| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\Utils; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; // Exit if accessed directly. |
| 7 |
} |
| 8 |
|
| 9 |
class Element_Position { |
| 10 |
|
| 11 |
const KIND_LAST = 'last'; |
| 12 |
const KIND_FIRST = 'first'; |
| 13 |
const KIND_INDEX = 'index'; |
| 14 |
const KIND_AFTER_TYPE = 'after_type'; |
| 15 |
const KIND_BEFORE_TYPE = 'before_type'; |
| 16 |
|
| 17 |
const KINDS = [ |
| 18 |
self::KIND_LAST, |
| 19 |
self::KIND_FIRST, |
| 20 |
self::KIND_INDEX, |
| 21 |
self::KIND_AFTER_TYPE, |
| 22 |
self::KIND_BEFORE_TYPE, |
| 23 |
]; |
| 24 |
|
| 25 |
private string $kind; |
| 26 |
|
| 27 |
/** |
| 28 |
* @var int|string|null |
| 29 |
*/ |
| 30 |
private $value; |
| 31 |
|
| 32 |
private function __construct( string $kind, $value = null ) { |
| 33 |
if ( ! in_array( $kind, self::KINDS, true ) ) { |
| 34 |
throw new \InvalidArgumentException( esc_html( "Invalid element position kind: {$kind}" ) ); |
| 35 |
} |
| 36 |
|
| 37 |
$this->kind = $kind; |
| 38 |
$this->value = $value; |
| 39 |
} |
| 40 |
|
| 41 |
public static function last(): self { |
| 42 |
return new self( self::KIND_LAST ); |
| 43 |
} |
| 44 |
|
| 45 |
public static function first(): self { |
| 46 |
return new self( self::KIND_FIRST ); |
| 47 |
} |
| 48 |
|
| 49 |
public static function at_index( int $index ): self { |
| 50 |
if ( $index < 0 ) { |
| 51 |
throw new \InvalidArgumentException( 'Element_Position: index must be >= 0.' ); |
| 52 |
} |
| 53 |
|
| 54 |
return new self( self::KIND_INDEX, $index ); |
| 55 |
} |
| 56 |
|
| 57 |
public static function after_type( string $element_type ): self { |
| 58 |
self::assert_non_empty_element_type( $element_type, 'after_type' ); |
| 59 |
|
| 60 |
return new self( self::KIND_AFTER_TYPE, $element_type ); |
| 61 |
} |
| 62 |
|
| 63 |
public static function before_type( string $element_type ): self { |
| 64 |
self::assert_non_empty_element_type( $element_type, 'before_type' ); |
| 65 |
|
| 66 |
return new self( self::KIND_BEFORE_TYPE, $element_type ); |
| 67 |
} |
| 68 |
|
| 69 |
private static function assert_non_empty_element_type( string $element_type, string $method ): void { |
| 70 |
if ( '' === trim( $element_type ) ) { |
| 71 |
throw new \InvalidArgumentException( |
| 72 |
esc_html( "Element_Position::{$method}: element_type must be a non-empty string." ) |
| 73 |
); |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
public function to_array(): array { |
| 78 |
return [ |
| 79 |
'kind' => $this->kind, |
| 80 |
'value' => $this->value, |
| 81 |
]; |
| 82 |
} |
| 83 |
} |
| 84 |
|