*/ private static array $saving = array(); /** * Orders with an allowed refund or payment under way, counted. * * @var array */ private static array $orders = array(); /** * Objects whose save was vetoed. Weak: an id freed with its object must * not carry a veto to the next object given it. * * @var \WeakMap|null */ private static ?\WeakMap $vetoed = null; /** * An allowed save of this object has started. * * @param object $data The object. */ public static function saving( object $data ): void { self::$saving[ spl_object_id( $data ) ] = $data; } /** * That save finished. Only a save this class started is ended. * * @param object $data The object. */ public static function saved( object $data ): void { unset( self::$saving[ spl_object_id( $data ) ] ); } /** * Whether this very object is mid-save under a cover - a nested save of * it, or a retry after its save threw. Either way the cover is dropped: * the caller decides again. * * @param object $data The object. */ public static function restart( object $data ): void { unset( self::$saving[ spl_object_id( $data ) ] ); } /** * An allowed refund or payment on an order has started. * * @param int $order_id The order. */ public static function order( int $order_id ): void { self::$orders[ $order_id ] = ( self::$orders[ $order_id ] ?? 0 ) + 1; } /** * That refund or payment ended, done or failed. * * @param int $order_id The order. */ public static function order_done( int $order_id ): void { if ( isset( self::$orders[ $order_id ] ) && --self::$orders[ $order_id ] <= 0 ) { unset( self::$orders[ $order_id ] ); } } /** * Whether a write to this target is a consequence of one already * allowed: an object being saved with that id, or an order whose refund * or payment is under way. * * @param string $type Entity type. * @param int $id Object id. */ public static function covers( string $type, int $id ): bool { if ( 'order' === $type && isset( self::$orders[ $id ] ) ) { return true; } foreach ( self::$saving as $data ) { if ( CrudBackstop::type_of( $data ) === $type && is_callable( array( $data, 'get_id' ) ) && (int) $data->get_id() === $id && $id > 0 ) { return true; } } return false; } /** * Whether any allowed refund or payment is under way: the stock it * moves is its consequence. */ public static function any_order(): bool { return array() !== self::$orders; } /** * Mark an object's save vetoed. * * @param object $data The object. */ public static function veto( object $data ): void { self::$vetoed ??= new \WeakMap(); self::$vetoed[ $data ] = true; self::saved( $data ); } /** * Whether this object's save was vetoed earlier in the request. * * @param object $data The object. */ public static function was_vetoed( object $data ): bool { return null !== self::$vetoed && isset( self::$vetoed[ $data ] ); } /** * Forget everything (a new request; tests). */ public static function reset(): void { self::$saving = array(); self::$orders = array(); self::$vetoed = null; } }