diff --git a/src/ColumnDefinition.php b/src/ColumnDefinition.php index ddb8062..e48e4ad 100644 --- a/src/ColumnDefinition.php +++ b/src/ColumnDefinition.php @@ -3,16 +3,24 @@ namespace ipl\Orm; use InvalidArgumentException; -use LogicException; +use ipl\Stdlib\Filter\Condition; +use ipl\Stdlib\Filter\Like; +use ipl\Stdlib\Filter\Unlike; class ColumnDefinition { /** @var string The name of the column */ protected $name; + /** @var ?string The data type of the column */ + protected $type; + /** @var ?string The label of the column */ protected $label; + /** @var ?array The values allowed for this column */ + protected $allowedValues; + /** * Create a new column definition * @@ -33,6 +41,30 @@ public function getName(): string return $this->name; } + /** + * Get the data type of the column + * + * @return ?string + */ + public function getType(): ?string + { + return $this->type; + } + + /** + * Set the data type of the column + * + * @param ?string $type + * + * @return $this + */ + public function setType(?string $type): self + { + $this->type = $type; + + return $this; + } + /** * Get the column label * @@ -57,6 +89,73 @@ public function setLabel(?string $label): self return $this; } + /** + * Get the allowed values for this column + * + * @return ?array + */ + public function getAllowedValues(): ?array + { + return $this->allowedValues; + } + + /** + * Set the allowed values for this column + * + * @param ?array $values + * + * @return $this + */ + public function setAllowedValues(?array $values): self + { + $this->allowedValues = $values; + + return $this; + } + + /** + * Get whether the given filter's value is valid + * + * @param Condition $filter + * + * @return bool + */ + public function isValidValue(Condition $filter): bool + { + if ($filter instanceof Like || $filter instanceof Unlike) { + return true; + } + + switch ($this->type) { + case 'number': + if (! is_numeric($filter->getValue())) { + return false; + } + + break; + } + + if (empty($this->allowedValues)) { + return true; + } + + return isset($this->allowedValues[$filter->getValue()]); + } + + /** + * Get the given value's label + * + * Returns the value itself if there's no label available + * + * @param string $value + * + * @return string + */ + public function getValueLabel(string $value): string + { + return $this->allowedValues[$value] ?? $value; + } + /** * Create a new column definition based on the given options * @@ -71,10 +170,22 @@ public static function fromArray(array $options): self } $self = new static($options['name']); + + if (isset($options['type'])) { + $self->setType($options['type']); + } + if (isset($options['label'])) { $self->setLabel($options['label']); } + // min (number start, datetime range start) + // max (number end, string length, datetime range end) + + if (isset($options['allowed_values'])) { + $self->setAllowedValues($options['allowed_values']); + } + return $self; } }