BasicCondition.php
95 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\FieldsAPI\Conditions; |
| 4 | |
| 5 | use Give\Framework\Exceptions\Primitives\InvalidArgumentException; |
| 6 | |
| 7 | /** |
| 8 | * @since 2.13.0 |
| 9 | */ |
| 10 | class BasicCondition extends Condition { |
| 11 | |
| 12 | const OPERATORS = [ '=', '!=', '>', '>=', '<', '<=' ]; |
| 13 | |
| 14 | const BOOLEANS = [ 'and', 'or' ]; |
| 15 | |
| 16 | /** @var string */ |
| 17 | const TYPE = 'basic'; |
| 18 | |
| 19 | /** @var string */ |
| 20 | public $field; |
| 21 | |
| 22 | /** @var mixed */ |
| 23 | public $value; |
| 24 | |
| 25 | /** @var string */ |
| 26 | public $operator; |
| 27 | |
| 28 | /** @var string */ |
| 29 | public $boolean; |
| 30 | |
| 31 | /** |
| 32 | * Create a new BasicCondition. |
| 33 | * |
| 34 | * @since 2.13.0 |
| 35 | * |
| 36 | * @param string $field |
| 37 | * @param string $operator |
| 38 | * @param mixed $value |
| 39 | * @param string $boolean |
| 40 | */ |
| 41 | public function __construct( $field, $operator, $value, $boolean = 'and' ) { |
| 42 | if ( $this->invalidOperator( $operator ) ) { |
| 43 | throw new InvalidArgumentException( "Invalid operator: $operator. Must be one of: " . implode( ', ', static::OPERATORS ) ); |
| 44 | } |
| 45 | |
| 46 | if ( $this->invalidBoolean( $boolean ) ) { |
| 47 | throw new InvalidArgumentException( "Invalid boolean: $boolean. Must be one of: " . implode( ', ', static::BOOLEANS ) ); |
| 48 | } |
| 49 | |
| 50 | $this->field = $field; |
| 51 | $this->operator = $operator; |
| 52 | $this->value = $value; |
| 53 | $this->boolean = $boolean; |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Check if the provided operator is invalid. |
| 58 | * |
| 59 | * @since 2.13.0 |
| 60 | * |
| 61 | * @param string $operator |
| 62 | * |
| 63 | * @return bool |
| 64 | */ |
| 65 | protected function invalidOperator( $operator ) { |
| 66 | return ! in_array( $operator, static::OPERATORS, true ); |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Check if the provided boolean is invalid. |
| 71 | * |
| 72 | * @since 2.13.0 |
| 73 | * |
| 74 | * @param $boolean |
| 75 | * |
| 76 | * @return bool |
| 77 | */ |
| 78 | protected function invalidBoolean( $boolean ) { |
| 79 | return ! in_array( $boolean, static::BOOLEANS, true ); |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * {@inheritDoc} |
| 84 | */ |
| 85 | public function jsonSerialize() { |
| 86 | return [ |
| 87 | 'type' => static::TYPE, |
| 88 | 'field' => $this->field, |
| 89 | 'value' => $this->value, |
| 90 | 'operator' => $this->operator, |
| 91 | 'boolean' => $this->boolean, |
| 92 | ]; |
| 93 | } |
| 94 | } |
| 95 |