diff --git a/composer.json b/composer.json index 86fcdf1..62174c2 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "phpstan/phpstan": "^1.9", "phpstan/phpstan-phpunit": "^1.3", "phpunit/phpunit": "^10.1", - "rector/rector": "^0.16", + "rector/rector": "^0.17.7", "soosyze/php-cs-fixer-config": "^1.0" }, "suggest": { diff --git a/rector.php b/rector.php index 5ecca38..e018f89 100644 --- a/rector.php +++ b/rector.php @@ -18,12 +18,12 @@ ]); // is your PHP version different from the one your refactor to? [default: your PHP version], uses PHP_VERSION_ID format - $rectorConfig->phpVersion(PhpVersion::PHP_80); + $rectorConfig->phpVersion(PhpVersion::PHP_81); // Define what rule sets will be applied $rectorConfig->sets([ SetList::CODE_QUALITY, - SetList::PHP_80, + SetList::PHP_81, SetList::DEAD_CODE, SetList::TYPE_DECLARATION ]); diff --git a/src/Command.php b/src/Command.php new file mode 100644 index 0000000..fe4c03b --- /dev/null +++ b/src/Command.php @@ -0,0 +1,17 @@ + + */ +class Command +{ + public function __construct(readonly public string $name) + { + } +} diff --git a/src/Command/DropCommand.php b/src/Command/DropCommand.php new file mode 100644 index 0000000..852b01e --- /dev/null +++ b/src/Command/DropCommand.php @@ -0,0 +1,30 @@ + + */ +final class DropCommand extends Command +{ + public function __construct(readonly public string $name) + { + } + + /** + * {@inheritdoc} + */ + public function getExecutionType(): TableExecutionType + { + return TableExecutionType::Drop; + } +} diff --git a/src/Command/RenameCommand.php b/src/Command/RenameCommand.php new file mode 100644 index 0000000..53a08f1 --- /dev/null +++ b/src/Command/RenameCommand.php @@ -0,0 +1,30 @@ + + */ +final class RenameCommand extends Command +{ + public function __construct(public readonly string $name, public readonly string $to) + { + } + + /** + * {@inheritdoc} + */ + public function getExecutionType(): TableExecutionType + { + return TableExecutionType::Rename; + } +} diff --git a/src/Concern/Field/ThrowInvalidType.php b/src/Concern/Field/ThrowInvalidType.php new file mode 100644 index 0000000..0d9f812 --- /dev/null +++ b/src/Concern/Field/ThrowInvalidType.php @@ -0,0 +1,32 @@ + + */ +trait ThrowInvalidType +{ + /** + * @throws \InvalidArgumentException + */ + public function throwInvalidType(mixed $value): never + { + throw new \InvalidArgumentException( + sprintf( + 'The value of the %s field must be of type %s: %s given.', + $this->name, + $this->getType()->realType(), + gettype($value) + ) + ); + } +} diff --git a/src/Concern/Field/TryOrGetDate.php b/src/Concern/Field/TryOrGetDate.php new file mode 100644 index 0000000..662f73e --- /dev/null +++ b/src/Concern/Field/TryOrGetDate.php @@ -0,0 +1,65 @@ + + */ +trait TryOrGetDate +{ + use ThrowInvalidType; + + private CurentDefaultType $currentDefault; + + public function tryOrGetValue(mixed $value): string + { + if (!\is_string($value)) { + $this->throwInvalidType($value); + } + + /** @var string $value */ + if (strtolower($value) === $this->currentDefault->value) { + return $this->currentDefault->value; + } + if (($timestamp = strtotime($value))) { + return date($this->currentDefault->format(), $timestamp); + } + + throw new ColumnsValueException( + sprintf('The value of the %s field must be a valid date: %s given', $this->name, $value) + ); + } + + /** + * {@inheritdoc} + */ + public function getValueDefault(): bool|float|int|string|null + { + if ($this->valueDefault !== null) { + if ($this->valueDefault === $this->currentDefault->value) { + return date($this->currentDefault->format(), time()); + } + + /* Si les variables magiques ne sont pas utilisé alors la vrais valeur par defaut est retourné. */ + return $this->valueDefault; + } + if ($this->isNullable) { + return null; + } + + throw new ColumnsValueException( + sprintf('%s not nullable or not default.', $this->name) + ); + } +} diff --git a/src/Concern/Field/TryOrGetString.php b/src/Concern/Field/TryOrGetString.php new file mode 100644 index 0000000..1e3d210 --- /dev/null +++ b/src/Concern/Field/TryOrGetString.php @@ -0,0 +1,44 @@ + + */ +trait TryOrGetString +{ + use ThrowInvalidType; + + /** + * {@inheritdoc} + */ + public function tryOrGetValue(mixed $value): string + { + if (!\is_string($value)) { + $this->throwInvalidType($value); + } + + /** @var string $value */ + if (strlen($value) > $this->length) { + throw new \LengthException( + sprintf( + 'The value of the %s field must be less than or equal to %s characters: %s given', + $this->name, + $this->length, + strlen($value) + ) + ); + } + + return $value; + } +} diff --git a/src/Driver.php b/src/Driver.php index e14d94c..95c17dd 100644 --- a/src/Driver.php +++ b/src/Driver.php @@ -20,7 +20,7 @@ */ abstract class Driver implements DriverInterface { - const DS = DIRECTORY_SEPARATOR; + public final const DS = DIRECTORY_SEPARATOR; /** * Déclenche une exception si l'extension du fichier n'est pas chargée. diff --git a/src/Enum/CurentDefaultType.php b/src/Enum/CurentDefaultType.php new file mode 100644 index 0000000..361ab87 --- /dev/null +++ b/src/Enum/CurentDefaultType.php @@ -0,0 +1,26 @@ + + */ +enum CurentDefaultType: string +{ + case Date = 'current_date'; + case DateTime = 'current_datetime'; + + public function format(): string + { + return match ($this) { + self::Date => 'Y-m-d', + self::DateTime => 'Y-m-d H:i:s', + }; + } +} diff --git a/src/Enum/FieldType.php b/src/Enum/FieldType.php new file mode 100644 index 0000000..d622b3b --- /dev/null +++ b/src/Enum/FieldType.php @@ -0,0 +1,61 @@ + + */ +enum FieldType: string +{ + case Boolean = 'boolean'; + case Char = 'char'; + case DateTime = 'datetime'; + case Date = 'date'; + case Float = 'float'; + case Increment = 'increments'; + case Int = 'integer'; + case String = 'string'; + case Text = 'text'; + + private const TEXT_TYPES = [self::Text, self::String, self::Char]; + + private const DATE_TYPES = [self::Date, self::DateTime, self::Int]; + + private const NUMBER_TYPES = [self::Float, self::Increment, self::Int]; + + public function realType(): string + { + return match ($this) { + self::Boolean => 'boolean', + self::Char => 'string', + self::DateTime => 'string', + self::Date => 'string', + self::Float => 'float', + self::Int => 'integer', + self::Increment => 'integer', + self::String => 'string', + self::Text => 'string', + }; + } + + public function isModify(FieldType $newType): bool + { + return match ($this) { + self::Boolean => in_array($newType, [self::Boolean, ...self::TEXT_TYPES]), + self::Char => in_array($newType, self::TEXT_TYPES), + self::DateTime => in_array($newType, self::DATE_TYPES), + self::Date => in_array($newType, self::DATE_TYPES), + self::Float => in_array($newType, self::NUMBER_TYPES), + self::Int => in_array($newType, self::NUMBER_TYPES), + self::Increment => in_array($newType, self::NUMBER_TYPES), + self::String => in_array($newType, self::TEXT_TYPES), + self::Text => in_array($newType, self::TEXT_TYPES), + }; + } +} diff --git a/src/Field.php b/src/Field.php index 22d2f67..0f8b703 100644 --- a/src/Field.php +++ b/src/Field.php @@ -8,6 +8,7 @@ namespace Soosyze\Queryflatfile; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Enum\TableExecutionType; use Soosyze\Queryflatfile\Exception\TableBuilder\ColumnsValueException; use Soosyze\Queryflatfile\Exception\TableBuilder\TableBuilderException; @@ -22,18 +23,15 @@ * default?: null|scalar, * length?: int, * nullable?: bool, - * opt?: TableExecutionType, * type: string, * unsigned?: bool, * } */ abstract class Field { - public const TYPE = ''; - protected const INVALID_ARGUMENT_MESSAGE = 'The value of the %s field must be of type %s: %s given.'; - protected null|bool|string|int|float $valueDefault = null; + protected bool|float|int|string|null $valueDefault = null; protected TableExecutionType $opt = TableExecutionType::Create; @@ -41,15 +39,12 @@ abstract class Field protected bool $isNullable = false; - public function __construct(protected string $name) + public function __construct(readonly public string $name) { } /** * Enregistre un commentaire. - * - * - * @return $this */ public function comment(string $comment): self { @@ -60,8 +55,6 @@ public function comment(string $comment): self /** * Enregistre le champ comme acceptant la valeur NULL. - * - * @return $this */ public function nullable(): self { @@ -71,24 +64,11 @@ public function nullable(): self } /** - * Enregistre une valeur par défaut au champ précédent. - * Lève une exception si la valeur par défaut ne correspond pas au type de valeur passée en paramètre. + * Associe une valeur par défaut au champ. * - * @throws ColumnsValueException + * @throws \InvalidArgumentException */ - abstract public function tryOrGetValue( - null|bool|string|int|float $value - ): null|bool|string|int|float; - - /** - * Enregistre une valeur par défaut au champ précédent. - * Lève une exception si la valeur par défaut ne correspond pas au type de valeur passée en paramètre. - * - * @throws TableBuilderException - * - * @return $this - */ - public function valueDefault(null|bool|string|int|float $value) + public function valueDefault(mixed $value): self { $this->valueDefault = $this->tryOrGetValue($value); @@ -100,18 +80,17 @@ public function valueDefault(null|bool|string|int|float $value) * * @throws ColumnsValueException */ - public function getValueDefault(): null|bool|string|int|float + public function getValueDefault(): bool|float|int|string|null { if ($this->valueDefault !== null) { return $this->valueDefault; } - if ($this->isNullable) { - return null; - } - throw new ColumnsValueException( - sprintf('%s not nullable or not default.', $this->name) - ); + return $this->isNullable + ? null + : throw new ColumnsValueException( + sprintf('%s not nullable or not default.', $this->name) + ); } /** @@ -125,46 +104,42 @@ public function modify(): void /** * Retourne le nom de l'opération du champ. */ - public function getOpt(): TableExecutionType + public function getExecutionType(): TableExecutionType { return $this->opt; } - /** - * Retourne le nom du champ. - */ - public function getName(): string - { - return $this->name; - } - - public function setName(string $name): self - { - $this->name = $name; - - return $this; - } - /** * Retourne les données du champ. * - * * @phpstan-return FieldToArray */ public function toArray(): array { - $data[ 'type' ] = static::TYPE; + $data['type'] = $this->getType()->value; if ($this->isNullable) { - $data[ 'nullable' ] = $this->isNullable; + $data['nullable'] = $this->isNullable; } if ($this->comment !== null) { - $data[ '_comment' ] = $this->comment; + $data['_comment'] = $this->comment; } if ($this->valueDefault !== null) { - $data[ 'default' ] = $this->valueDefault; + $data['default'] = $this->valueDefault; } return $data; } + + /** + * Retourne le type du champ. + */ + abstract public function getType(): FieldType; + + /** + * Test si la valeur passé en paramètre correspond au type du champ. + * + * @throws \InvalidArgumentException + */ + abstract public function tryOrGetValue(mixed $value): bool|float|int|string|null; } diff --git a/src/Field/BoolType.php b/src/Field/BoolType.php index 7116316..787ea6d 100644 --- a/src/Field/BoolType.php +++ b/src/Field/BoolType.php @@ -8,24 +8,32 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\ThrowInvalidType; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Field; /** * @author Mathieu NOËL */ -class BoolType extends Field +final class BoolType extends Field { - public const TYPE = 'boolean'; + use ThrowInvalidType; /** * {@inheritdoc} */ - public function tryOrGetValue(null|bool|string|int|float $value): bool + public function getType(): FieldType + { + return FieldType::Boolean; + } + + /** + * {@inheritdoc} + */ + public function tryOrGetValue(mixed $value): bool { if (!\is_bool($value)) { - throw new \InvalidArgumentException( - sprintf(self::INVALID_ARGUMENT_MESSAGE, $this->name, self::TYPE, gettype($value)) - ); + $this->throwInvalidType($value); } return $value; diff --git a/src/Field/CharType.php b/src/Field/CharType.php index 321b440..6ed70fd 100644 --- a/src/Field/CharType.php +++ b/src/Field/CharType.php @@ -8,12 +8,24 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\TryOrGetString; +use Soosyze\Queryflatfile\Enum\FieldType; +use Soosyze\Queryflatfile\Field; + /** * @author Mathieu NOËL */ -class CharType extends StringType +final class CharType extends Field { - public const TYPE = 'char'; + use TryOrGetString; protected int $length = 1; + + /** + * {@inheritdoc} + */ + public function getType(): FieldType + { + return FieldType::Char; + } } diff --git a/src/Field/DateTimeType.php b/src/Field/DateTimeType.php index ed25c78..1a9b18b 100644 --- a/src/Field/DateTimeType.php +++ b/src/Field/DateTimeType.php @@ -8,61 +8,28 @@ namespace Soosyze\Queryflatfile\Field; -use Soosyze\Queryflatfile\Exception\TableBuilder\ColumnsValueException; +use Soosyze\Queryflatfile\Concern\Field\TryOrGetDate; +use Soosyze\Queryflatfile\Enum\CurentDefaultType; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Field; /** * @author Mathieu NOËL */ -class DateTimeType extends Field +final class DateTimeType extends Field { - public const CURRENT_DEFAULT = 'current_datetime'; + use TryOrGetDate; - public const TYPE = 'datetime'; - - protected const FORMAT = 'Y-m-d H:i:s'; - - /** - * {@inheritdoc} - */ - public function tryOrGetValue(null|bool|string|int|float $value): string + public function __construct(readonly public string $name) { - if (!\is_string($value)) { - throw new \InvalidArgumentException( - sprintf(self::INVALID_ARGUMENT_MESSAGE, $this->name, 'string', gettype($value)) - ); - } - if (strtolower($value) === static::CURRENT_DEFAULT) { - return static::CURRENT_DEFAULT; - } - if (($timestamp = strtotime($value))) { - return date(static::FORMAT, $timestamp); - } - - throw new ColumnsValueException( - sprintf('The value of the %s field must be a valid date: %s given', $this->name, $value) - ); + $this->currentDefault = CurentDefaultType::DateTime; } /** * {@inheritdoc} */ - public function getValueDefault(): null|bool|string|int|float + public function getType(): FieldType { - if ($this->valueDefault !== null) { - if ($this->valueDefault === static::CURRENT_DEFAULT) { - return date(static::FORMAT, time()); - } - - /* Si les variables magiques ne sont pas utilisé alors la vrais valeur par defaut est retourné. */ - return $this->valueDefault; - } - if ($this->isNullable) { - return null; - } - - throw new ColumnsValueException( - sprintf('%s not nullable or not default.', $this->name) - ); + return FieldType::DateTime; } } diff --git a/src/Field/DateType.php b/src/Field/DateType.php index 132366c..16a2fb3 100644 --- a/src/Field/DateType.php +++ b/src/Field/DateType.php @@ -8,14 +8,28 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\TryOrGetDate; +use Soosyze\Queryflatfile\Enum\CurentDefaultType; +use Soosyze\Queryflatfile\Enum\FieldType; +use Soosyze\Queryflatfile\Field; + /** * @author Mathieu NOËL */ -class DateType extends DateTimeType +final class DateType extends Field { - public const CURRENT_DEFAULT = 'current_date'; + use TryOrGetDate; - public const TYPE = 'date'; + public function __construct(readonly public string $name) + { + $this->currentDefault = CurentDefaultType::Date; + } - protected const FORMAT = 'Y-m-d'; + /** + * {@inheritdoc} + */ + public function getType(): FieldType + { + return FieldType::Date; + } } diff --git a/src/Field/DropType.php b/src/Field/DropType.php deleted file mode 100644 index 9c944df..0000000 --- a/src/Field/DropType.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class DropType extends Field -{ - protected TableExecutionType $opt = TableExecutionType::Drop; - - public function tryOrGetValue(null|bool|string|int|float $value): null|bool|string|int|float - { - return null; - } - - /** - * {@inheritdoc} - */ - public function toArray(): array - { - $data = parent::toArray(); - $data[ 'opt' ] = $this->opt; - - return $data; - } -} diff --git a/src/Field/FloatType.php b/src/Field/FloatType.php index 14ed6d9..12882c5 100644 --- a/src/Field/FloatType.php +++ b/src/Field/FloatType.php @@ -8,24 +8,32 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\ThrowInvalidType; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Field; /** * @author Mathieu NOËL */ -class FloatType extends Field +final class FloatType extends Field { - public const TYPE = 'float'; + use ThrowInvalidType; /** * {@inheritdoc} */ - public function tryOrGetValue(null|bool|string|int|float $value): float + public function getType(): FieldType + { + return FieldType::Float; + } + + /** + * {@inheritdoc} + */ + public function tryOrGetValue(mixed $value): float { if (!\is_float($value)) { - throw new \InvalidArgumentException( - sprintf(self::INVALID_ARGUMENT_MESSAGE, $this->name, self::TYPE, gettype($value)) - ); + $this->throwInvalidType($value); } return $value; diff --git a/src/Field/IncrementType.php b/src/Field/IncrementType.php index b8336ba..457f36e 100644 --- a/src/Field/IncrementType.php +++ b/src/Field/IncrementType.php @@ -8,25 +8,33 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\ThrowInvalidType; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Exception\TableBuilder\ColumnsValueException; use Soosyze\Queryflatfile\Field; /** * @author Mathieu NOËL */ -class IncrementType extends Field +final class IncrementType extends Field { - public const TYPE = 'increments'; + use ThrowInvalidType; /** * {@inheritdoc} */ - public function tryOrGetValue(null|bool|string|int|float $value): int + public function getType(): FieldType + { + return FieldType::Increment; + } + + /** + * {@inheritdoc} + */ + public function tryOrGetValue(mixed $value): int { if (!\is_int($value)) { - throw new \InvalidArgumentException( - sprintf(self::INVALID_ARGUMENT_MESSAGE, $this->name, 'integer', gettype($value)) - ); + $this->throwInvalidType($value); } return $value; @@ -34,20 +42,16 @@ public function tryOrGetValue(null|bool|string|int|float $value): int /** * @throws ColumnsValueException - * - * @return never */ - public function getValueDefault(): null|bool|string|int|float + public function getValueDefault(): never { throw new ColumnsValueException('An incremental type column can not have a default value.'); } /** * @throws ColumnsValueException - * - * @return never */ - public function valueDefault(null|bool|string|int|float $value): null|bool|string|int|float + public function valueDefault(mixed $value): never { throw new ColumnsValueException('An incremental type column can not have a default value.'); } diff --git a/src/Field/IntType.php b/src/Field/IntType.php index 4506c3b..7af49f2 100644 --- a/src/Field/IntType.php +++ b/src/Field/IntType.php @@ -8,26 +8,34 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\ThrowInvalidType; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Field; /** * @author Mathieu NOËL */ -class IntType extends Field +final class IntType extends Field { - public const TYPE = 'integer'; + use ThrowInvalidType; private bool $isUnsigned = false; /** * {@inheritdoc} */ - public function tryOrGetValue(null|bool|string|int|float $value): int + public function getType(): FieldType + { + return FieldType::Int; + } + + /** + * {@inheritdoc} + */ + public function tryOrGetValue(mixed $value): int { if (!\is_int($value)) { - throw new \InvalidArgumentException( - sprintf(self::INVALID_ARGUMENT_MESSAGE, $this->name, self::TYPE, gettype($value)) - ); + $this->throwInvalidType($value); } return $value; diff --git a/src/Field/RenameType.php b/src/Field/RenameType.php deleted file mode 100644 index eb6e74b..0000000 --- a/src/Field/RenameType.php +++ /dev/null @@ -1,53 +0,0 @@ - - */ -class RenameType extends Field -{ - protected TableExecutionType $opt = TableExecutionType::Rename; - - public function __construct(string $name, protected string $to) - { - parent::__construct($name); - } - - /** - * {@inheritdoc} - */ - public function tryOrGetValue(null|bool|string|int|float $value): null|bool|string|int|float - { - return null; - } - - /** - * {@inheritdoc} - */ - public function getTo(): string - { - return $this->to; - } - - /** - * {@inheritdoc} - */ - public function toArray(): array - { - $data = parent::toArray(); - $data[ 'opt' ] = $this->opt; - $data[ 'to' ] = $this->to; - - return $data; - } -} diff --git a/src/Field/StringType.php b/src/Field/StringType.php index 81ef6d1..dc08ac1 100644 --- a/src/Field/StringType.php +++ b/src/Field/StringType.php @@ -8,43 +8,30 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\TryOrGetString; +use Soosyze\Queryflatfile\Enum\FieldType; +use Soosyze\Queryflatfile\Field; + /** * @author Mathieu NOËL */ -class StringType extends TextType +final class StringType extends Field { - public const TYPE = 'string'; - - protected int $length; + use TryOrGetString; - public function __construct(string $name, int $length) + public function __construct(readonly public string $name, protected int $length) { - if ($length < 0) { + if ($length <= 0) { throw new \InvalidArgumentException('The length passed in parameter is not of numeric type.'); } - parent::__construct($name); - $this->length = $length; } /** * {@inheritdoc} */ - public function tryOrGetValue(null|bool|string|int|float $value): string + public function getType(): FieldType { - $str = parent::tryOrGetValue($value); - - if (strlen($str) > $this->length) { - throw new \LengthException( - sprintf( - 'The value of the %s field must be less than or equal to %s characters: %s given', - $this->name, - $this->length, - strlen($str) - ) - ); - } - - return $str; + return FieldType::String; } /** diff --git a/src/Field/TextType.php b/src/Field/TextType.php index d8d8334..f606f38 100644 --- a/src/Field/TextType.php +++ b/src/Field/TextType.php @@ -8,24 +8,32 @@ namespace Soosyze\Queryflatfile\Field; +use Soosyze\Queryflatfile\Concern\Field\ThrowInvalidType; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Field; /** * @author Mathieu NOËL */ -class TextType extends Field +final class TextType extends Field { - public const TYPE = 'text'; + use ThrowInvalidType; /** * {@inheritdoc} */ - public function tryOrGetValue(null|bool|string|int|float $value): string + public function getType(): FieldType + { + return FieldType::Text; + } + + /** + * {@inheritdoc} + */ + public function tryOrGetValue(mixed $value): string { if (!\is_string($value)) { - throw new \InvalidArgumentException( - sprintf(self::INVALID_ARGUMENT_MESSAGE, $this->name, 'string', gettype($value)) - ); + $this->throwInvalidType($value); } return $value; diff --git a/src/Request.php b/src/Request.php index f0db2e0..65464ae 100644 --- a/src/Request.php +++ b/src/Request.php @@ -349,7 +349,7 @@ protected function executeOrderBy(array &$data, array $orderBy): void } $sorted = $a[ $field ] > $b[ $field ] - ? 1 * $order->value + ? $order->value : -1 * $order->value; if ($sorted !== 0) { @@ -511,10 +511,10 @@ private function selectToString(): string $output = trim($output, ', ') . ' '; } if ($this->limit !== 0) { - $output .= sprintf('LIMIT %d ', (string) $this->limit); + $output .= sprintf('LIMIT %d ', $this->limit); } if ($this->offset !== 0) { - $output .= sprintf('OFFSET %d ', (string) $this->offset); + $output .= sprintf('OFFSET %d ', $this->offset); } return trim($output) . ';'; @@ -578,7 +578,7 @@ private function loadAllFieldsSchema(): void */ private function tryFrom(): void { - if (empty($this->from)) { + if ($this->from === '') { throw new TableNotFoundException(); } } diff --git a/src/Schema.php b/src/Schema.php index c0f7b92..e60da4d 100644 --- a/src/Schema.php +++ b/src/Schema.php @@ -10,6 +10,8 @@ namespace Soosyze\Queryflatfile; +use Soosyze\Queryflatfile\Command\DropCommand; +use Soosyze\Queryflatfile\Command\RenameCommand; use Soosyze\Queryflatfile\DriverInterface; use Soosyze\Queryflatfile\Enum\TableExecutionType; use Soosyze\Queryflatfile\Exception\Exception; @@ -295,18 +297,21 @@ public function alterTable(string $tableName, callable $callback): self $tableData = $this->read($tableName); foreach ($tableBuilder->getFields() as $field) { - if ($field->getOpt() === TableExecutionType::Create) { - self::tryFieldAdd($tableSchema, $field); + if ($field->getExecutionType() === TableExecutionType::Create) { + $this->tryFieldAdd($tableSchema, $field); self::add($tableSchema, $field, $tableData); - } elseif ($field->getOpt() === TableExecutionType::Rename) { - self::tryFieldRename($tableSchema, $field); - self::rename($tableSchema, $field, $tableData); - } elseif ($field->getOpt() === TableExecutionType::Modify) { - self::tryFieldModify($tableSchema, $field); + } elseif ($field->getExecutionType() === TableExecutionType::Modify) { + $this->tryFieldModify($tableSchema, $field); self::modify($tableSchema, $field, $tableData); - } elseif ($field->getOpt() === TableExecutionType::Drop) { - self::tryFieldDrop($tableSchema, $field); - self::drop($tableSchema, $field, $tableData); + } + } + foreach($tableBuilder->getCommands() as $command) { + if ($command instanceof RenameCommand) { + $this->tryFieldRename($tableSchema, $command); + self::rename($tableSchema, $command, $tableData); + } elseif ($command instanceof DropCommand) { + $this->tryFieldDrop($tableSchema, $command); + self::drop($tableSchema, $command, $tableData); } } @@ -474,7 +479,7 @@ protected static function add( } foreach ($tableData as &$data) { - $data[ $field->getName() ] = $increment === null + $data[ $field->name ] = $increment === null ? $valueDefault : ++$increment; } @@ -496,7 +501,7 @@ protected static function modify( Field $field, array &$tableData ): void { - $oldField = $table->getField($field->getName()); + $oldField = $table->getField($field->name); $table->addField($field); @@ -504,7 +509,7 @@ protected static function modify( * Si la modification ne concerne pas le type, la mise à jour des données ne se fait pas. * Exemple: rendre un champ nullable ne doit écraser les données présentent en table. */ - if ($oldField::TYPE === $field::TYPE) { + if ($oldField->getType() === $field->getType()) { return; } @@ -515,7 +520,7 @@ protected static function modify( try { $valueDefault = $field->getValueDefault(); foreach ($tableData as &$data) { - $data[ $field->getName() ] = $valueDefault; + $data[ $field->name ] = $valueDefault; } } catch (ColumnsValueException | \InvalidArgumentException) { } @@ -528,43 +533,43 @@ protected static function modify( /** * Renomme un champ dans les paramètre de la table et ses données. * - * @param Table $table Schéma de la table. - * @param RenameType $fieldRename champ à renommer - * @param array $tableData Les données de la table. + * @param Table $table Schéma de la table. + * @param RenameCommand $command champ à renommer + * @param array $tableData Les données de la table. */ protected static function rename( Table &$table, - RenameType $fieldRename, + RenameCommand $command, array &$tableData ): void { - $table->renameField($fieldRename->getName(), $fieldRename->getTo()); + $table->renameField($command->name, $command->to); foreach ($tableData as &$data) { - $data[ $fieldRename->getTo() ] = $data[ $fieldRename->getName() ]; - unset($data[ $fieldRename->getName() ]); + $data[ $command->to ] = $data[ $command->name ]; + unset($data[ $command->name ]); } } /** * Supprime un champ dans les paramètre de la table et ses données. * - * @param Table $table Schéma de la table. - * @param DropType $fieldDrop Champ à supprimer - * @param array $tableData Les données de la table. + * @param Table $table Schéma de la table. + * @param DropCommand $command Champ à supprimer + * @param array $tableData Les données de la table. */ protected static function drop( Table &$table, - DropType $fieldDrop, + DropCommand $command, array &$tableData ): void { foreach (array_keys($tableData) as $key) { - unset($tableData[ $key ][ $fieldDrop->getName() ]); + unset($tableData[ $key ][ $command->name ]); } - if ($table->getField($fieldDrop->getName()) instanceof IncrementType) { + if ($table->getField($command->name) instanceof IncrementType) { $table->setIncrement(null); } - $table->unsetField($fieldDrop->getName()); + $table->unsetField($command->name); } /** @@ -606,15 +611,15 @@ protected static function tableBuilder(string $tableName, ?callable $callback = * @throws Exception * @throws ColumnsNotFoundException */ - private static function tryFieldAdd(Table $tableSchema, Field $field): void + private function tryFieldAdd(Table $tableSchema, Field $field): void { /* Si un champ est ajouté il ne doit pas exister dans le schéma. */ - if ($tableSchema->hasField($field->getName())) { + if ($tableSchema->hasField($field->name)) { throw new Exception( sprintf( '%s field does not exists in %s table.', - $field->getName(), - $tableSchema->getName() + $field->name, + $tableSchema->name ) ); } @@ -622,7 +627,7 @@ private static function tryFieldAdd(Table $tableSchema, Field $field): void throw new ColumnsValueException( sprintf( 'The %s table can not have multiple incremental values.', - $tableSchema->getName() + $tableSchema->name ) ); } @@ -638,14 +643,14 @@ private static function tryFieldAdd(Table $tableSchema, Field $field): void * @throws ColumnsValueException * @throws Exception */ - private static function tryFieldModify(Table $tableSchema, Field $field): void + private function tryFieldModify(Table $tableSchema, Field $field): void { - if (!$tableSchema->hasField($field->getName())) { + if (!$tableSchema->hasField($field->name)) { throw new Exception( sprintf( '%s field does not exists in %s table.', - $field->getName(), - $tableSchema->getName() + $field->name, + $tableSchema->name ) ); } @@ -653,28 +658,23 @@ private static function tryFieldModify(Table $tableSchema, Field $field): void throw new ColumnsValueException( sprintf( 'The %s table can not have multiple incremental values.', - $tableSchema->getName() + $tableSchema->name ) ); } - $fieldOld = $tableSchema->getField($field->getName()); + $fieldOld = $tableSchema->getField($field->name); + $typeFieldOld = $fieldOld->getType(); + $typeField = $field->getType(); /* Si le type change, les données présents doivent être d'un type équivalent. */ - $modifyNumber = in_array($field::TYPE, [ 'integer', 'float', 'increments' ]) && - !in_array($fieldOld::TYPE, [ 'integer', 'float', 'increments' ]); - $modifyString = in_array($field::TYPE, [ 'text', 'string', 'char' ]) && - !in_array($fieldOld::TYPE, [ 'text', 'string', 'char' ]); - $modifyDate = in_array($field::TYPE, [ 'date', 'datetime' ]) && - !in_array($fieldOld::TYPE, [ 'date', 'datetime', 'string', 'text' ]); - - if ($modifyString || $modifyNumber || $modifyDate) { + if (!$typeFieldOld->isModify($typeField)) { throw new Exception( sprintf( 'The %s column type %s can not be changed with the %s type.', - $field->getName(), - $fieldOld::TYPE, - $field::TYPE + $field->name, + $typeFieldOld->value, + $typeField->value ) ); } @@ -683,23 +683,23 @@ private static function tryFieldModify(Table $tableSchema, Field $field): void /** * Vérifie si les opérations de renommage du champ sont conformes. * - * @param Table $table Le schéma de la table. - * @param RenameType $field Champ à renommer. + * @param Table $table Le schéma de la table. + * @param RenameCommand $command Champ à renommer. * * @throws ColumnsNotFoundException * @throws Exception */ - private static function tryFieldRename(Table $table, RenameType $field): void + private function tryFieldRename(Table $table, RenameCommand $command): void { - if (!$table->hasField($field->getName())) { + if (!$table->hasField($command->name)) { throw new ColumnsNotFoundException( - sprintf('%s field does not exists in %s table.', $field->getName(), $table->getName()) + sprintf('%s field does not exists in %s table.', $command->name, $table->name) ); } /* Si le champ à renommer existe dans le schema. */ - if ($table->hasField($field->getTo())) { + if ($table->hasField($command->to)) { throw new Exception( - sprintf('%s field does exists in %s table.', $field->getName(), $table->getName()) + sprintf('%s field does exists in %s table.', $command->name, $table->name) ); } } @@ -707,16 +707,16 @@ private static function tryFieldRename(Table $table, RenameType $field): void /** * Vérifie si les opérations de suppression du champ sont conformes. * - * @param Table $table Le schéma de la table. - * @param DropType $field Champ à supprimer + * @param Table $table Le schéma de la table. + * @param DropCommand $command Champ à supprimer * * @throws ColumnsNotFoundException */ - private static function tryFieldDrop(Table $table, DropType $field): void + private function tryFieldDrop(Table $table, DropCommand $command): void { - if (!$table->hasField($field->getName())) { + if (!$table->hasField($command->name)) { throw new ColumnsNotFoundException( - sprintf('%s field does not exists in %s table.', $field->getName(), $table->getName()) + sprintf('%s field does not exists in %s table.', $command->name, $table->name) ); } } diff --git a/src/Table.php b/src/Table.php index 840b476..03a3112 100644 --- a/src/Table.php +++ b/src/Table.php @@ -13,10 +13,8 @@ /** * @author Mathieu NOËL * - * @phpstan-import-type FieldToArray from Field - * * @phpstan-type TableToArray array{ - * fields: array, + * fields: array, * increments?: int|null * } */ @@ -30,33 +28,52 @@ final class Table protected array $fields = []; /** - * La valeur des champs incrémentaux. + * Les champs et leurs paramètres. + * + * @var array + */ + private array $commands = []; + + /** + * La valeur du champ incrémentaux. */ private ?int $increment = null; - public function __construct(protected string $name) + public function __construct(public readonly string $name) { } + public function addCommand(Command $command): void + { + $this->commands[$command->name] = $command; + } + + /** + * @return array + */ + public function getCommands(): array + { + return $this->commands; + } + /** * Ajoute un nouveau champ. - * - * @param Field $field Champ. */ public function addField(Field $field): void { if ($field instanceof IncrementType) { - $this->increment = 0; + $this->increment = is_int($this->increment) + ? throw new \InvalidArgumentException('Only one incremental column is allowed per table.') + : 0; } - $this->fields[ $field->getName() ] = $field; + $this->fields[$field->name] = $field; } public function getField(string $name): Field { - return isset($this->fields[ $name ]) - ? $this->fields[ $name ] - : throw new \Exception(); + return $this->fields[$name] + ?? throw new \InvalidArgumentException('Field does not exist'); } /** @@ -64,30 +81,31 @@ public function getField(string $name): Field */ public function getFieldOrPut(Field $field): Field { - if (isset($this->fields[$field->getName()])) { - return $this->fields[$field->getName()]; + if (isset($this->fields[$field->name])) { + return $this->fields[$field->name]; } $this->addField($field); - return $this->fields[$field->getName()]; + return $this->fields[$field->name]; } + /** + * @return array + */ public function getFields(): array { return $this->fields; } + /** + * @return string[] + */ public function getFieldsName(): array { return array_keys($this->fields); } - public function getName(): string - { - return $this->name; - } - public function getIncrement(): ?int { return $this->increment; @@ -105,9 +123,8 @@ public function hasIncrement(): bool public function renameField(string $from, string $to): void { - $this->fields[ $to ] = $this->fields[ $from ]; + $this->fields[ $to ] = $this->getField($from); unset($this->fields[ $from ]); - $this->fields[ $to ]->setName($to); } public function setIncrement(?int $increment): void @@ -122,15 +139,15 @@ public function setIncrement(?int $increment): void */ public function toArray(): array { - $fields = []; + $table['fields'] = []; foreach ($this->fields as $name => $field) { - $fields[ $name ] = $field->toArray(); + $table['fields'][$name] = $field->toArray(); + } + if ($this->increment !== null) { + $table['increments'] = $this->increment; } - return [ - 'fields' => $fields, - 'increments' => $this->increment - ]; + return $table; } public function unsetField(string $name): void diff --git a/src/TableAlter.php b/src/TableAlter.php index b4fc073..cbfdb62 100644 --- a/src/TableAlter.php +++ b/src/TableAlter.php @@ -8,8 +8,8 @@ namespace Soosyze\Queryflatfile; -use Soosyze\Queryflatfile\Field\DropType; -use Soosyze\Queryflatfile\Field\RenameType; +use Soosyze\Queryflatfile\Command\DropCommand; +use Soosyze\Queryflatfile\Command\RenameCommand; /** * Pattern fluent pour la création et configuration des types de données. @@ -25,7 +25,7 @@ class TableAlter extends TableBuilder */ public function dropColumn(string $name): void { - $this->table->addField(new DropType($name)); + $this->table->addCommand(new DropCommand($name)); } /** @@ -36,6 +36,6 @@ public function dropColumn(string $name): void */ public function renameColumn(string $from, string $to): void { - $this->table->addField(new RenameType($from, $to)); + $this->table->addCommand(new RenameCommand($from, $to)); } } diff --git a/src/TableBuilder.php b/src/TableBuilder.php index 902d104..073bab4 100644 --- a/src/TableBuilder.php +++ b/src/TableBuilder.php @@ -8,6 +8,7 @@ namespace Soosyze\Queryflatfile; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Exception\TableBuilder\TableBuilderException; use Soosyze\Queryflatfile\Field\BoolType; use Soosyze\Queryflatfile\Field\CharType; @@ -50,14 +51,13 @@ public function boolean(string $name): Field * Enregistre un champ de type `char` avec une limite de taille par défaut de un caractère. * http://php.net/language.types.string * - * @param string $name Nom du champ - * @param int $length longueur maximum de la chaine. + * @param string $name Nom du champ * * @throws TableBuilderException */ - public function char(string $name, int $length = 1): Field + public function char(string $name): Field { - return $this->table->getFieldOrPut(new CharType($name, $length)); + return $this->table->getFieldOrPut(new CharType($name)); } /** @@ -98,14 +98,10 @@ public function float(string $name): Field * http://php.net/manual/fr/language.types.integer.php * * @param string $name nom du champ - * - * @throws TableBuilderException */ public function increments(string $name): Field { - return $this->table->getIncrement() !== null - ? throw new TableBuilderException('Only one incremental column is allowed per table.') - : $this->table->getFieldOrPut(new IncrementType($name)); + return $this->table->getFieldOrPut(new IncrementType($name)); } /** @@ -160,7 +156,7 @@ public function getTable(): Table * Créer une table à partir d'un tableau de données. * * @param string $table Nom de la table. - * @param array $data Donnaées pour créer une table. + * @param array $data Données pour créer une table. * * @phpstan-param TableToArray $data * @@ -169,34 +165,23 @@ public function getTable(): Table public static function createTableFromArray(string $table, array $data): Table { $tableBuilder = new self($table); - foreach ($data[ 'fields' ] as $name => $value) { - switch ($value[ 'type' ]) { - case BoolType::TYPE: - case DateType::TYPE: - case DateTimeType::TYPE: - case FloatType::TYPE: - case IncrementType::TYPE: - case TextType::TYPE: - $field = $tableBuilder->{$value[ 'type' ]}($name); - - break; - case CharType::TYPE: - case StringType::TYPE: - $field = $tableBuilder->{$value[ 'type' ]}($name, $value[ 'length' ] ?? 0); - - break; - case IntType::TYPE: - $field = $tableBuilder->{$value[ 'type' ]}($name); - - if (isset($value[ 'unsigned' ])) { - $field->unsigned(); - } - - break; - default: - throw new TableBuilderException(sprintf('Type %s not supported.', $value[ 'type' ])); + foreach ($data['fields'] as $name => $value) { + $field = match (FieldType::tryFrom($value['type'])) { + FieldType::Boolean => new BoolType($name), + FieldType::Char => new CharType($name), + FieldType::Date => new DateType($name), + FieldType::DateTime => new DateTimeType($name), + FieldType::Float => new FloatType($name), + FieldType::Increment => new IncrementType($name), + FieldType::Int => new IntType($name), + FieldType::String => new StringType($name, $value['length'] ?? 255), + FieldType::Text => new TextType($name), + default => throw new TableBuilderException("Type {$value['type']} not supported.") + }; + + if (isset($value['unsigned']) && $field instanceof IntType) { + $field->unsigned(); } - if (isset($value[ 'nullable' ])) { $field->nullable(); } @@ -206,6 +191,7 @@ public static function createTableFromArray(string $table, array $data): Table if (isset($value[ '_comment' ])) { $field->comment($value[ '_comment' ]); } + $tableBuilder->table->addField($field); } $tableBuilder->table->setIncrement($data[ 'increments' ] ?? null); diff --git a/tests/Fixtures/builder/schema.json b/tests/Fixtures/builder/schema.json index 4a2d3ec..849f830 100644 --- a/tests/Fixtures/builder/schema.json +++ b/tests/Fixtures/builder/schema.json @@ -25,8 +25,7 @@ "id_role": { "type": "integer" } - }, - "increments": null + } }, "role": { "fields": { diff --git a/tests/Fixtures/request/schema.json b/tests/Fixtures/request/schema.json index 4a2d3ec..849f830 100644 --- a/tests/Fixtures/request/schema.json +++ b/tests/Fixtures/request/schema.json @@ -25,8 +25,7 @@ "id_role": { "type": "integer" } - }, - "increments": null + } }, "role": { "fields": { diff --git a/tests/Unit/RequestTest.php b/tests/Unit/RequestTest.php index 5a5e69b..1642bcc 100644 --- a/tests/Unit/RequestTest.php +++ b/tests/Unit/RequestTest.php @@ -1296,8 +1296,7 @@ public function testLeftJoin(): void ->leftJoin('role', 'id_role', '=', 'role.id_role'); self::assertEquals( - 'SELECT id, name, firstname, labelle FROM user ' - . 'LEFT JOIN user_role ON id = \'user_role.id_user\' ' + 'SELECT id, name, firstname, labelle FROM user LEFT JOIN user_role ON id = \'user_role.id_user\' ' . 'LEFT JOIN role ON id_role = \'role.id_role\';', (string) $data ); @@ -1326,8 +1325,7 @@ public function testLeftJoinWhere(): void ->where('labelle', '=', 'Admin'); self::assertEquals( - 'SELECT id, name, firstname FROM user ' - . 'LEFT JOIN user_role ON id = \'user_role.id_user\' ' + 'SELECT id, name, firstname FROM user LEFT JOIN user_role ON id = \'user_role.id_user\' ' . 'LEFT JOIN role ON id_role = \'role.id_role\' ' . 'WHERE labelle = \'Admin\';', (string) $data @@ -1353,8 +1351,7 @@ public function testLeftJoinGroup(): void ->where('labelle', '=', 'Admin'); self::assertEquals( - 'SELECT id, name, firstname FROM user ' - . 'LEFT JOIN user_role ON id = \'user_role.id_user\' ' + 'SELECT id, name, firstname FROM user LEFT JOIN user_role ON id = \'user_role.id_user\' ' . 'LEFT JOIN role ON id_role = \'role.id_role\' ' . 'WHERE labelle = \'Admin\';', (string) $data @@ -1382,8 +1379,7 @@ public function testLeftJoinGroupMultiple(): void ->where('labelle', '=', 'Admin'); self::assertEquals( - 'SELECT id, name, firstname, labelle FROM user ' - . 'LEFT JOIN user_role ON id = \'user_role.id_user\' ' + 'SELECT id, name, firstname, labelle FROM user LEFT JOIN user_role ON id = \'user_role.id_user\' ' . 'LEFT JOIN role ON (id_role = \'role.id_role\') ' . 'WHERE labelle = \'Admin\';', (string) $data @@ -1433,8 +1429,7 @@ public function testLeftJoinExceptionColumn(): void $this->expectException(ColumnsNotFoundException::class); $this->expectExceptionMessage( 'Column foo is absent: ' - . 'SELECT id, name, firstname FROM user ' - . 'LEFT JOIN user_role ON foo == \'user_role.id_user\' ' + . 'SELECT id, name, firstname FROM user LEFT JOIN user_role ON foo == \'user_role.id_user\' ' . 'LEFT JOIN role ON id_role == \'role.id\' ' . 'WHERE labelle = \'Admin\' ' . 'LIMIT 1;' @@ -1573,8 +1568,7 @@ public function testUnionAllMultiple(): void ->unionAll($union); self::assertEquals( - 'SELECT name, firstname FROM user ' - . 'UNION ALL ' + 'SELECT name, firstname FROM user UNION ALL ' . 'SELECT name, firstname FROM user WHERE id BETWEEN 1 AND 5;', (string) $data ); diff --git a/tests/Unit/SchemaJsonTest.php b/tests/Unit/SchemaJsonTest.php index 3f4b798..61bef88 100644 --- a/tests/Unit/SchemaJsonTest.php +++ b/tests/Unit/SchemaJsonTest.php @@ -87,7 +87,6 @@ public function testGetSchema(): void 'value_i' => [ 'type' => 'integer' ], 'value_s' => [ 'type' => 'string', 'length' => 255 ] ], - 'increments' => null ] ], $schema @@ -279,7 +278,6 @@ public function testAlterTableModify(): void 'value_i' => [ 'type' => 'float', 'default' => 1.0 ], 'value_s' => [ 'type' => 'string', 'length' => 255, 'nullable' => true ] ], - 'increments' => null ], $this->bdd->getTableSchema('test_second')->toArray() ); @@ -331,7 +329,6 @@ public function testAlterTableDrop(): void 'fields' => [ 'name' => [ 'type' => 'string', 'length' => 255 ] ], - 'increments' => null ], $this->bdd->getTableSchema('test')->toArray() ); diff --git a/tests/Unit/TableAlterTest.php b/tests/Unit/TableAlterTest.php index 401e585..ccc9097 100644 --- a/tests/Unit/TableAlterTest.php +++ b/tests/Unit/TableAlterTest.php @@ -2,7 +2,6 @@ namespace Soosyze\Queryflatfile\Tests\Unit; -use Soosyze\Queryflatfile\Enum\TableExecutionType; use Soosyze\Queryflatfile\TableAlter; class TableAlterTest extends \PHPUnit\Framework\TestCase @@ -19,12 +18,7 @@ public function testDrop(): void $this->object->dropColumn('0'); self::assertEquals( - [ - 'fields' => [ - '0' => [ 'type' => '', 'opt' => TableExecutionType::Drop ] - ], - 'increments' => null - ], + ['fields' => []], $this->object->getTable()->toArray() ); } @@ -34,12 +28,7 @@ public function testRename(): void $this->object->renameColumn('0', '1'); self::assertEquals( - [ - 'fields' => [ - '0' => [ 'type' => '', 'opt' => TableExecutionType::Rename, 'to' => '1' ] - ], - 'increments' => null - ], + ['fields' => []], $this->object->getTable()->toArray() ); } @@ -50,10 +39,9 @@ public function testModify(): void self::assertEquals( [ - 'fields' => [ - '0' => [ 'type' => 'char', 'length' => 1 ] + 'fields' => [ + '0' => [ 'type' => 'char' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); diff --git a/tests/Unit/TableBuilderTest.php b/tests/Unit/TableBuilderTest.php index 9f3fca9..56da8cc 100644 --- a/tests/Unit/TableBuilderTest.php +++ b/tests/Unit/TableBuilderTest.php @@ -2,7 +2,9 @@ namespace Soosyze\Queryflatfile\Tests\Unit; +use Soosyze\Queryflatfile\Enum\FieldType; use Soosyze\Queryflatfile\Exception\TableBuilder\ColumnsValueException; +use Soosyze\Queryflatfile\Field; use Soosyze\Queryflatfile\TableBuilder; class TableBuilderTest extends \PHPUnit\Framework\TestCase @@ -42,29 +44,19 @@ public function testIncrementsException(): void public function testChar(): void { $this->object->char('id'); - $this->object->char('id2', 2); + $this->object->char('id2'); self::assertEquals( [ 'fields' => [ - 'id' => [ 'type' => 'char', 'length' => 1 ], - 'id2' => [ 'type' => 'char', 'length' => 2 ] + 'id' => [ 'type' => 'char' ], + 'id2' => [ 'type' => 'char' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); } - public function testCharException(): void - { - $this->expectException(\Exception::class); - $this->expectExceptionMessage( - 'The length passed in parameter is not of numeric type.' - ); - $this->object->char('id2', -1); - } - public function testText(): void { $this->object->text('id'); @@ -74,7 +66,6 @@ public function testText(): void 'fields' => [ 'id' => [ 'type' => 'text' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -91,7 +82,6 @@ public function testString(): void 'id' => [ 'type' => 'string', 'length' => 255 ], 'id2' => [ 'type' => 'string', 'length' => 256 ], ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -115,7 +105,6 @@ public function testInteger(): void 'fields' => [ 'id' => [ 'type' => 'integer' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -130,7 +119,6 @@ public function testFloat(): void 'fields' => [ 'id' => [ 'type' => 'float' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -145,7 +133,6 @@ public function testBoolean(): void 'fields' => [ 'id' => [ 'type' => 'boolean' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -160,7 +147,6 @@ public function testDate(): void 'fields' => [ 'id' => [ 'type' => 'date' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -175,7 +161,6 @@ public function testDatetime(): void 'fields' => [ 'id' => [ 'type' => 'datetime' ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -197,7 +182,7 @@ public function testNullable(): void [ 'fields' => [ '0' => [ 'type' => 'increments', 'nullable' => true ], - '1' => [ 'type' => 'char', 'length' => 1, 'nullable' => true ], + '1' => [ 'type' => 'char', 'nullable' => true ], '2' => [ 'type' => 'text', 'nullable' => true ], '3' => [ 'type' => 'string', 'length' => 255, 'nullable' => true ], '4' => [ 'type' => 'integer', 'nullable' => true ], @@ -245,7 +230,6 @@ public function testUnsigned(): void 'fields' => [ 'id' => [ 'type' => 'integer', 'unsigned' => true ] ], - 'increments' => null ], $this->object->getTable()->toArray() ); @@ -260,7 +244,7 @@ public function testComment(): void 'fields' => [ 'id' => [ 'type' => 'increments', '_comment' => 'identifiant' ] ], - 'increments' => null + 'increments' => 0 ], $this->object->getTable()->toArray() ); @@ -284,7 +268,7 @@ public function testValueDefault(): void [ 'fields' => [ '0' => [ 'type' => 'increments' ], - '1' => [ 'type' => 'char', 'length' => 1, 'default' => 'a' ], + '1' => [ 'type' => 'char', 'default' => 'a' ], '2' => [ 'type' => 'text', 'default' => 'test' ], '3' => [ 'type' => 'string', 'length' => 255, 'default' => 'test' ], '4' => [ 'type' => 'integer', 'default' => 1 ], @@ -311,7 +295,7 @@ public function testValueDefault(): void * @dataProvider getValueDefaultExceptionProvider */ public function testValueDefaulException( - string $method, + FieldType $fieldType, mixed $valueDefault, string $exceptionClass, string $exceptionMessage @@ -320,61 +304,61 @@ public function testValueDefaulException( $this->expectException($exceptionClass); $this->expectExceptionMessage($exceptionMessage); - $tableBuilder->$method('0')->valueDefault($valueDefault); + $tableBuilder->{$fieldType->value}('0')->valueDefault($valueDefault); } public static function getValueDefaultExceptionProvider(): \Generator { yield [ - 'boolean', 1, + FieldType::Boolean, 1, \InvalidArgumentException::class, 'The value of the 0 field must be of type boolean: integer given.' ]; yield [ - 'char', 1, + FieldType::Char, 1, \InvalidArgumentException::class, 'The value of the 0 field must be of type string: integer given.' ]; yield [ - 'char', 'error', + FieldType::Char, 'error', \LengthException::class, 'The value of the 0 field must be less than or equal to 1 characters: 5 given' ]; yield [ - 'date', 1, + FieldType::Date, 1, \InvalidArgumentException::class, 'The value of the 0 field must be of type string: integer given.' ]; yield [ - 'date', '1', + FieldType::Date, '1', ColumnsValueException::class, 'The value of the 0 field must be a valid date: 1 given' ]; yield [ - 'datetime', 1, + FieldType::DateTime, 1, \InvalidArgumentException::class, 'The value of the 0 field must be of type string: integer given.' ]; yield [ - 'datetime', '1', + FieldType::DateTime, '1', ColumnsValueException::class, 'The value of the 0 field must be a valid date: 1 given' ]; yield [ - 'float', '1', + FieldType::Float, '1', \InvalidArgumentException::class, 'The value of the 0 field must be of type float: string given.' ]; yield [ - 'increments', 2, + FieldType::Increment, 2, \Exception::class, 'An incremental type column can not have a default value.' ]; yield [ - 'integer', '1', + FieldType::Int, '1', \InvalidArgumentException::class, 'The value of the 0 field must be of type integer: string given.' ]; yield [ - 'string', 1, + FieldType::String, 1, \InvalidArgumentException::class, 'The value of the 0 field must be of type string: integer given.' ]; yield [ - 'string', str_repeat('0', 256), + FieldType::String, str_repeat('0', 256), \LengthException::class, 'The value of the 0 field must be less than or equal to 255 characters: 256 given' ]; yield [ - 'text', 1, + FieldType::Text, 1, \InvalidArgumentException::class, 'The value of the 0 field must be of type string: integer given.' ]; } @@ -385,7 +369,7 @@ public function testCreateTableFromArray(): void $this->object->char('field_1')->valueDefault('a'); $this->object->text('field_2')->valueDefault('test'); $this->object->string('field_3')->valueDefault('test'); - $this->object->integer('field_4')->valueDefault(1)->unsigned(); + $this->object->integer('field_4')->unsigned()->valueDefault(1); $this->object->float('field_5')->valueDefault(1.1); $this->object->boolean('field_6')->valueDefault(true); $this->object->date('field_7')->valueDefault('2017-11-26'); @@ -397,7 +381,7 @@ public function testCreateTableFromArray(): void 'test' => [ 'fields' => [ 'field_0' => [ 'type' => 'increments' ], - 'field_1' => [ 'type' => 'char', 'length' => 1, 'default' => 'a' ], + 'field_1' => [ 'type' => 'char', 'default' => 'a' ], 'field_2' => [ 'type' => 'text', 'default' => 'test' ], 'field_3' => [ 'type' => 'string', 'length' => 255, 'default' => 'test' ], 'field_4' => [ 'type' => 'integer', 'default' => 1, 'unsigned' => true ],