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