diff --git a/composer.json b/composer.json index dc8ce122..b5d764c1 100644 --- a/composer.json +++ b/composer.json @@ -27,6 +27,7 @@ "cycle/schema-migrations-generator": "^2.0", "cycle/schema-renderer": "^1.2", "cycle/schema-builder": "^2.7", + "cycle/schema-provider": "^1.0", "psr/event-dispatcher": "^1.0", "psr/simple-cache": "^2.0|^3.0", "spiral/attributes": "^2.7|^3.0", @@ -44,6 +45,7 @@ "roave/infection-static-analysis-plugin": "^1.25", "spatie/phpunit-watcher": "^1.23", "vimeo/psalm": "^4.30|^5.7", + "yiisoft/definitions": "^3.2", "yiisoft/test-support": "^3.0" }, "autoload": { diff --git a/config/di.php b/config/di.php index 0ad76aa6..1e7c4e44 100644 --- a/config/di.php +++ b/config/di.php @@ -12,8 +12,15 @@ use Cycle\ORM\ORMInterface; use Cycle\ORM\Schema; use Cycle\ORM\SchemaInterface; +use Cycle\Schema\Provider\FromFilesSchemaProvider; +use Cycle\Schema\Provider\PhpFileSchemaProvider; +use Cycle\Schema\Provider\SchemaProviderInterface; +use Cycle\Schema\Provider\Support\SchemaProviderPipeline; use Psr\Container\ContainerInterface; use Spiral\Core\FactoryInterface as SpiralFactoryInterface; +use Spiral\Files\FilesInterface; +use Yiisoft\Aliases\Aliases; +use Yiisoft\Definitions\DynamicReference; use Yiisoft\Definitions\Reference; use Yiisoft\Yii\Cycle\Exception\SchemaWasNotProvidedException; use Yiisoft\Yii\Cycle\Factory\CycleDynamicFactory; @@ -21,9 +28,7 @@ use Yiisoft\Yii\Cycle\Factory\OrmFactory; use Yiisoft\Yii\Cycle\Schema\Conveyor\CompositeSchemaConveyor; use Yiisoft\Yii\Cycle\Schema\Conveyor\MetadataSchemaConveyor; -use Yiisoft\Yii\Cycle\Schema\Provider\Support\SchemaProviderPipeline; use Yiisoft\Yii\Cycle\Schema\SchemaConveyorInterface; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; /** * @var array $params @@ -71,6 +76,21 @@ return (new SchemaProviderPipeline($container))->withConfig($params['yiisoft/yii-cycle']['schema-providers']); }, + // FromFilesSchemaProvider + FromFilesSchemaProvider::class => static function (Aliases $aliases) { + return new FromFilesSchemaProvider(static fn (string $path): string => $aliases->get($path)); + }, + + // PhpFileSchemaProvider + PhpFileSchemaProvider::class => [ + '__construct()' => [ + DynamicReference::to( + static fn (Aliases $aliases): \Closure => static fn (string $path): string => $aliases->get($path) + ), + Reference::optional(FilesInterface::class), + ], + ], + // Schema Conveyor SchemaConveyorInterface::class => static function (ContainerInterface $container) use (&$params) { /** @var SchemaConveyorInterface $conveyor */ diff --git a/config/params.php b/config/params.php index 1eb958bc..3f98d4f7 100644 --- a/config/params.php +++ b/config/params.php @@ -2,10 +2,11 @@ declare(strict_types=1); +use Cycle\Schema\Provider\SchemaProviderInterface; +use Cycle\Schema\Provider\Support\SchemaProviderPipeline; use Yiisoft\Yii\Cycle\Command\Schema; use Yiisoft\Yii\Cycle\Command\Migration; use Yiisoft\Yii\Cycle\Schema\Conveyor\CompositeSchemaConveyor; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; return [ // Console commands @@ -44,7 +45,7 @@ ], /** - * SchemaProvider list for {@see \Yiisoft\Yii\Cycle\Schema\Provider\Support\SchemaProviderPipeline} + * SchemaProvider list for {@see SchemaProviderPipeline} * Array of classname and {@see SchemaProviderInterface} object. * You can configure providers if you pass classname as key and parameters as array: * [ diff --git a/docs/en/reading-schema.md b/docs/en/reading-schema.md index a3344478..8f238753 100644 --- a/docs/en/reading-schema.md +++ b/docs/en/reading-schema.md @@ -7,10 +7,10 @@ Since a schema is built from an array of a certain structure, we can store it ei You can display currently used schema by executing `cycle/schema` command. In `yii-cycle` package schema can be built from multiple sources represented by multiple providers implementing -`SchemaProviderInterface`. +`Cycle\Schema\Provider\SchemaProviderInterface`. -In order to use multiple schema providers in turn, grouping `SchemaProviderPipeline` provider is used. -You can configure this provider in `schema-providers` section of a `config/params.php` file. +In order to use multiple schema providers in turn, grouping `Cycle\Schema\Provider\Support\SchemaProviderPipeline` +provider is used. You can configure this provider in `schema-providers` section of a `config/params.php` file. Arrage schema providers in such an order, that caching providers are at the top of the list, and origin schema providers at the end. @@ -30,14 +30,14 @@ using annotations it is a good idea to use schema cache. ## Schema cache -Reading and writing a schema from and to cache happens in `SimpleCacheSchemaProvider`. +Reading and writing a schema from and to cache happens in `Cycle\Schema\Provider\SimpleCacheSchemaProvider`. Place it to the beginning of providers list to make the process of obtaining a schema significantly faster. ## File-based schema If you want to avoid annotations, you can describe a schema in a PHP file. -Use `FromFilesSchemaProvider` to load a schema: +Use `Cycle\Schema\Provider\FromFilesSchemaProvider` to load a schema: ```php # config/common.php @@ -45,7 +45,7 @@ Use `FromFilesSchemaProvider` to load a schema: 'yiisoft/yii-cycle' => [ // ... 'schema-providers' => [ - \Yiisoft\Yii\Cycle\Schema\Provider\FromFilesSchemaProvider::class => [ + \Cycle\Schema\Provider\FromFilesSchemaProvider::class => [ 'files' => '@runtime/schema.php' ] ], @@ -88,7 +88,7 @@ But in case of loading multiple files, it may take extra time to merge them. ## Building DB schema from different providers -To merge schema parts obtained from different providers, use `MergeSchemaProvider`. +To merge schema parts obtained from different providers, use `Cycle\Schema\Provider\MergeSchemaProvider`. ```php # runtime/schema.php @@ -97,11 +97,11 @@ return [ 'yiisoft/yii-cycle' => [ // ... 'schema-providers' => [ - \Yiisoft\Yii\Cycle\Schema\Provider\Support\MergeSchemaProvider::class => [ + \Cycle\Schema\Provider\MergeSchemaProvider::class => [ // You can specify the provider class as the key and the configuration as the value. - \Yiisoft\Yii\Cycle\Schema\Provider\FromFilesSchemaProvider::class => ['files' => ['@src/schema.php']], + \Cycle\Schema\Provider\FromFilesSchemaProvider::class => ['files' => ['@src/schema.php']], // The provider and its configuration can be passed as an array. - [\Yiisoft\Yii\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class, ['key' => 'cycle-schema']], + [\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class, ['key' => 'cycle-schema']], // When defining the dependency as a string, make sure the container provides // the already configured provider. \Yiisoft\Yii\Cycle\Schema\Provider\FromConveyorSchemaProvider::class, @@ -132,8 +132,8 @@ migrations based on them. For production use schema could be moved into a file. ### `PhpFileSchemaProvider` Provider -Unlike `FromFilesSchemaProvider`, the `PhpFileSchemaProvider` works with only one file. but, `PhpFileSchemaProvider` -can not only read schema, but also save it. +Unlike `FromFilesSchemaProvider`, the `Cycle\Schema\Provider\PhpFileSchemaProvider` works with only one file. but, +`PhpFileSchemaProvider` can not only read schema, but also save it. In the mode of reading and writing a schema file, the `PhpFileSchemaProvider` provider works similarly to the cache, with the only difference is that saved result (schema file), can be saved in codebase. diff --git a/docs/es/reading-schema.md b/docs/es/reading-schema.md index 1db12274..184f860e 100644 --- a/docs/es/reading-schema.md +++ b/docs/es/reading-schema.md @@ -7,10 +7,10 @@ Dado que el esquema se construye a partir de un arreglo con una estructura defin Puede mostrar el esquema utilizado actualmente ejecutando el comando `cycle/schema`. En el paquete `yiisoft/yii-cycle` el esquema puede ser construido desde múltiples fuentes representadas por múltiples proveedores que implementan -`SchemaProviderInterface`. +`Cycle\Schema\Provider\SchemaProviderInterface`. -Para utilizar varios proveedores de esquemas, se utiliza el proveedor `SchemaProviderPipeline` de agrupación. -Puede configurar este proveedor en la sección `schema-providers` en el archivo `config/params.php`. +Para utilizar varios proveedores de esquemas, se utiliza el proveedor `Cycle\Schema\Provider\Support\SchemaProviderPipeline` +de agrupación. Puede configurar este proveedor en la sección `schema-providers` en el archivo `config/params.php`. Los proveedores de esquemas deben estar organizados de la siguiente manera, los proveedores de caché deben estar al principio de la lista y los proveedores de esquemas de origen al final. @@ -29,14 +29,14 @@ usar anotaciones es una buena idea usar el caché de esquemas. ## Esquemas desde caché -La lectura y escritura de un esquema desde y hacia la caché ocurre en `SimpleCacheSchemaProvider`. +La lectura y escritura de un esquema desde y hacia la caché ocurre en `Cycle\Schema\Provider\SimpleCacheSchemaProvider`. Debe indicarse al principio de la lista de proveedores para que el proceso de obtención de un esquema sea significativamente más rápido. ## Esquemas basados en archivos Si quiere evitar las anotaciones, puede describir un esquema en un archivo PHP. -Utilice `FromFilesSchemaProvider` para cargar un esquema: +Utilice `Cycle\Schema\Provider\FromFilesSchemaProvider` para cargar un esquema: ```php # config/common.php @@ -44,7 +44,7 @@ Utilice `FromFilesSchemaProvider` para cargar un esquema: 'yiisoft/yii-cycle' => [ // ... 'schema-providers' => [ - \Yiisoft\Yii\Cycle\Schema\Provider\FromFilesSchemaProvider::class => [ + \Cycle\Schema\Provider\FromFilesSchemaProvider::class => [ 'files' => '@runtime/schema.php' ] ], @@ -87,7 +87,7 @@ En el caso de que se carguen varios archivos, puede tardar más tiempo en fusion ## Construir el esquema de la base de datos a partir de diferentes proveedores -Para fusionar partes del esquema obtenidas de diferentes proveedores, utilice `MergeSchemaProvider`. +Para fusionar partes del esquema obtenidas de diferentes proveedores, utilice `Cycle\Schema\Provider\MergeSchemaProvider`. ```php # runtime/schema.php @@ -96,11 +96,11 @@ return [ 'yiisoft/yii-cycle' => [ // ... 'schema-providers' => [ - \Yiisoft\Yii\Cycle\Schema\Provider\Support\MergeSchemaProvider::class => [ + \Cycle\Schema\Provider\MergeSchemaProvider::class => [ // Puede especificar la clase de proveedor como clave y la configuración como valor. - \Yiisoft\Yii\Cycle\Schema\Provider\FromFilesSchemaProvider::class => ['files' => ['@src/schema.php']], + \Cycle\Schema\Provider\FromFilesSchemaProvider::class => ['files' => ['@src/schema.php']], // El proveedor y su configuración pueden pasarse como un array. - [\Yiisoft\Yii\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class, ['key' => 'cycle-schema']], + [\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class, ['key' => 'cycle-schema']], // Al definir la dependencia como una cadena, asegúrese de que el contenedor proporciona // el proveedor ya configurado. \Yiisoft\Yii\Cycle\Schema\Provider\FromConveyorSchemaProvider::class, @@ -130,8 +130,8 @@ migraciones basadas en ellas. Para el uso en producción, el esquema puede ser t ### Provider `PhpFileSchemaProvider` -A diferencia de `FromFilesSchemaProvider`, el archivo `PhpFileSchemaProvider` trabaja con un solo archivo de esquema `PhpFileSchemaProvider` -no sólo puede leer el esquema, sino también guardarlo. +A diferencia de `FromFilesSchemaProvider`, el archivo `Cycle\Schema\Provider\PhpFileSchemaProvider` trabaja con un solo +archivo de esquema `PhpFileSchemaProvider` no sólo puede leer el esquema, sino también guardarlo. En el modo de lectura y escritura un archivo de esquema que utilice el proveedor `PhpFileSchemaProvider`, funcionara de forma similar a la caché, con la única diferencia que el resultado guardado (archivo de esquema), puede ser guardado en codebase. diff --git a/docs/ru/reading-schema.md b/docs/ru/reading-schema.md index 6845e3c7..5caf2353 100644 --- a/docs/ru/reading-schema.md +++ b/docs/ru/reading-schema.md @@ -8,12 +8,12 @@ Cycle ORM в своей работе полагается на схему — о Посмотреть используемую в вашем проекте схему вы можете с помощью консольной команды `cycle/schema`. В пакете `yii-cycle` схему из разных источников предоставляют разные поставщики, реализующие интерфейс -`SchemaProviderInterface`. +`Cycle\Schema\Provider\SchemaProviderInterface`. Для того, чтобы последовательно использовать несколько поставщиков схемы, используется группирующий поставщик -`SchemaProviderPipeline`, который можно сконфигурировать в секции `schema-providers` файла `config/params.php`. -Выстраивайте поставщиков схемы в таком порядке, чтобы кеширующие поставщики были в начале списка, а первичные источники -схемы в конце. +`Cycle\Schema\Provider\Support\SchemaProviderPipeline`, который можно сконфигурировать в секции `schema-providers` +файла `config/params.php`. Выстраивайте поставщиков схемы в таком порядке, чтобы кеширующие поставщики были в начале +списка, а первичные источники схемы в конце. ## Схема из аннотаций сущностей @@ -30,14 +30,14 @@ Cycle ORM в своей работе полагается на схему — о ## Кеширование схемы -Запись и чтение схемы в кеш осуществляет поставщик `SimpleCacheSchemaProvider`. +Запись и чтение схемы в кеш осуществляет поставщик `Cycle\Schema\Provider\SimpleCacheSchemaProvider`. Разместите его в начале списка поставщиков, чтобы значительно ускорить процесс получения схемы. ## Схема в файле Если вы желаете избежать использования аннотаций для описания схемы, то можно описать её в PHP-файле. -Воспользуйтесь поставщиком `FromFilesSchemaProvider` для загрузки схемы из PHP-файла: +Воспользуйтесь поставщиком `Cycle\Schema\Provider\FromFilesSchemaProvider` для загрузки схемы из PHP-файла: ```php # Файл config/common.php @@ -46,7 +46,7 @@ return [ 'yiisoft/yii-cycle' => [ // ... 'schema-providers' => [ - \Yiisoft\Yii\Cycle\Schema\Provider\FromFilesSchemaProvider::class => [ + \Cycle\Schema\Provider\FromFilesSchemaProvider::class => [ 'files' => ['@runtime/schema.php'] ] ], @@ -91,7 +91,7 @@ return [ ## Сборка схемы по частям из разных поставщиков -Для того, чтобы объединить получаемые из разных поставщиков части схемы в одну, используйте `MergeSchemaProvider`. +Для того, чтобы объединить получаемые из разных поставщиков части схемы в одну, используйте `Cycle\Schema\Provider\MergeSchemaProvider`. ```php # Файл config/common.php @@ -100,11 +100,11 @@ return [ 'yiisoft/yii-cycle' => [ // ... 'schema-providers' => [ - \Yiisoft\Yii\Cycle\Schema\Provider\Support\MergeSchemaProvider::class => [ + \Cycle\Schema\Provider\MergeSchemaProvider::class => [ // Вы можете указать класс поставщика в качестве ключа, а конфигурацию в качестве значения. - \Yiisoft\Yii\Cycle\Schema\Provider\FromFilesSchemaProvider::class => ['files' => ['@src/schema.php']], + \Cycle\Schema\Provider\FromFilesSchemaProvider::class => ['files' => ['@src/schema.php']], // Поставщик и его конфигурация могут быть переданы в виде массива. - [\Yiisoft\Yii\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class, ['key' => 'cycle-schema']], + [\Cycle\Schema\Provider\SimpleCacheSchemaProvider::class, ['key' => 'cycle-schema']], // При указании зависимости в виде строки убедитесь, что контейнер предоставит // уже сконфигурированного поставщика. \Yiisoft\Yii\Cycle\Schema\Provider\FromConveyorSchemaProvider::class, @@ -136,8 +136,8 @@ cycle/schema/php @runtime/schema.php ### Поставщик PhpFileSchemaProvider -В отличие от `FromFilesSchemaProvider`, поставщик `PhpFileSchemaProvider` работает только с одним файлом. Но схему он -может не только читать, но и записывать. +В отличие от `FromFilesSchemaProvider`, поставщик `Cycle\Schema\Provider\PhpFileSchemaProvider` работает только с одним +файлом. Но схему он может не только читать, но и записывать. В режиме чтения и записи файла схемы, поставщик `PhpFileSchemaProvider` работает аналогично кешу. В режиме только записи схема из поставщика, следующего за `PhpFileSchemaProvider`, только записывается в файл. diff --git a/src/Command/CycleDependencyProxy.php b/src/Command/CycleDependencyProxy.php index dffbc807..4f9a558d 100644 --- a/src/Command/CycleDependencyProxy.php +++ b/src/Command/CycleDependencyProxy.php @@ -9,9 +9,9 @@ use Cycle\Migrations\Migrator; use Cycle\ORM\ORMInterface; use Cycle\ORM\SchemaInterface; +use Cycle\Schema\Provider\SchemaProviderInterface; use Psr\Container\ContainerInterface; use Yiisoft\Yii\Cycle\Schema\SchemaConveyorInterface; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; final class CycleDependencyProxy { diff --git a/src/Exception/CumulativeException.php b/src/Exception/CumulativeException.php deleted file mode 100644 index 4f38d42b..00000000 --- a/src/Exception/CumulativeException.php +++ /dev/null @@ -1,48 +0,0 @@ -exceptions = $exceptions; - $count = count($exceptions); - $message = $count === 1 ? 'One exception was thrown.' : $count . ' exceptions were thrown.'; - parent::__construct($message . $this->getMessageDetails()); - } - - /** - * @return Throwable[] - */ - public function getExceptions(): array - { - return $this->exceptions; - } - - private function getMessageDetails(): string - { - $result = ''; - $num = 0; - foreach ($this->exceptions as $exception) { - $result .= sprintf( - "\n\n%d) %s:%s\n[%s] #%d: %s", - ++$num, - $exception->getFile(), - $exception->getLine(), - get_class($exception), - $exception->getCode(), - $exception->getMessage() - ); - } - return $result; - } -} diff --git a/src/Exception/DuplicateRoleException.php b/src/Exception/DuplicateRoleException.php deleted file mode 100644 index e4d29fcf..00000000 --- a/src/Exception/DuplicateRoleException.php +++ /dev/null @@ -1,26 +0,0 @@ -schemaProvider = $schemaProvider; + public function __construct( + private SchemaProviderInterface $schemaProvider, + ) { } public function onAfterMigrate(AfterMigrate $event): void diff --git a/src/Logger/StdoutQueryLogger.php b/src/Logger/StdoutQueryLogger.php index ccbd2299..7f142063 100644 --- a/src/Logger/StdoutQueryLogger.php +++ b/src/Logger/StdoutQueryLogger.php @@ -15,6 +15,7 @@ * @package Yiisoft\Yii\Cycle\Logger * * @deprecated In the future StdoutLogger will be removed (when we will have debug-tools) + * @codeCoverageIgnore */ class StdoutQueryLogger implements LoggerInterface { diff --git a/src/Schema/Provider/FromConveyorSchemaProvider.php b/src/Schema/Provider/FromConveyorSchemaProvider.php index fbaaca08..ca395c96 100644 --- a/src/Schema/Provider/FromConveyorSchemaProvider.php +++ b/src/Schema/Provider/FromConveyorSchemaProvider.php @@ -8,14 +8,12 @@ use Cycle\Database\DatabaseProviderInterface; use Cycle\Schema\Compiler; use Cycle\Schema\GeneratorInterface; +use Cycle\Schema\Provider\SchemaProviderInterface; use Cycle\Schema\Registry; use Yiisoft\Yii\Cycle\Schema\SchemaConveyorInterface; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; final class FromConveyorSchemaProvider implements SchemaProviderInterface { - private SchemaConveyorInterface $conveyor; - private DatabaseProviderInterface $dbal; /** * Additional generators when reading Schema * @@ -23,10 +21,10 @@ final class FromConveyorSchemaProvider implements SchemaProviderInterface */ private array $generators = []; - public function __construct(SchemaConveyorInterface $conveyor, DatabaseProviderInterface $dbal) - { - $this->conveyor = $conveyor; - $this->dbal = $dbal; + public function __construct( + private SchemaConveyorInterface $conveyor, + private DatabaseProviderInterface $dbal, + ) { } public function withConfig(array $config): self diff --git a/src/Schema/Provider/FromFilesSchemaProvider.php b/src/Schema/Provider/FromFilesSchemaProvider.php deleted file mode 100644 index 3a5b5cc8..00000000 --- a/src/Schema/Provider/FromFilesSchemaProvider.php +++ /dev/null @@ -1,106 +0,0 @@ - Schema files */ - private array $files = []; - - /** @var bool Throw exception if file not found */ - private bool $strict = false; - - private Aliases $aliases; - - public function __construct(Aliases $aliases) - { - $this->aliases = $aliases; - } - - public function withConfig(array $config): self - { - $files = $config['files'] ?? []; - if (!is_array($files)) { - throw new InvalidArgumentException('The "files" parameter must be an array.'); - } - if (count($files) === 0) { - throw new InvalidArgumentException('Schema file list is not set.'); - } - - $strict = $config['strict'] ?? $this->strict; - if (!is_bool($strict)) { - throw new InvalidArgumentException('The "strict" parameter must be a boolean.'); - } - - $files = array_map( - function ($file) { - if (!is_string($file)) { - throw new InvalidArgumentException('The "files" parameter must contain string values.'); - } - return $this->aliases->get($file); - }, - $files - ); - - $new = clone $this; - $new->files = $files; - $new->strict = $strict; - return $new; - } - - public function read(?SchemaProviderInterface $nextProvider = null): ?array - { - $schema = (new SchemaMerger())->merge(...$this->readFiles()); - - return $schema !== null || $nextProvider === null ? $schema : $nextProvider->read(); - } - - public function clear(): bool - { - return false; - } - - /** - * Read schema from each file - * - * @return Generator - */ - private function readFiles(): Generator - { - foreach ($this->files as $path) { - $path = \str_replace('\\', '/', $path); - if (!Glob::isDynamic($path)) { - yield $this->loadFile($path); - continue; - } - foreach (new GlobIterator($path) as $file) { - yield $this->loadFile($file); - } - } - } - - private function loadFile(string $path): ?array - { - $isFile = is_file($path); - - if (!$isFile && $this->strict) { - throw new SchemaFileNotFoundException($path); - } - - return $isFile ? require $path : null; - } -} diff --git a/src/Schema/Provider/PhpFileSchemaProvider.php b/src/Schema/Provider/PhpFileSchemaProvider.php deleted file mode 100644 index 2ef9831a..00000000 --- a/src/Schema/Provider/PhpFileSchemaProvider.php +++ /dev/null @@ -1,107 +0,0 @@ -aliases = $aliases; - } - - public function withConfig(array $config): self - { - $new = clone $this; - - // required option - if ($this->file === '' && !array_key_exists('file', $config)) { - throw new \InvalidArgumentException('The "file" parameter is required.'); - } - $new->file = $this->aliases->get($config['file']); - - $new->mode = $config['mode'] ?? $this->mode; - - return $new; - } - - public function read(?SchemaProviderInterface $nextProvider = null): ?array - { - if (!$this->isReadable()) { - if ($nextProvider === null) { - throw new RuntimeException(__CLASS__ . ' can not read schema.'); - } - $schema = null; - } else { - $schema = !is_file($this->file) ? null : (include $this->file); - } - - if ($schema !== null || $nextProvider === null) { - return $schema; - } - - $schema = $nextProvider->read(); - if ($schema !== null) { - $this->write($schema); - } - return $schema; - } - - private function write(array $schema): bool - { - if (basename($this->file) === '') { - throw new RuntimeException('The "file" parameter must not be empty.'); - } - $dirname = dirname($this->file); - if ($dirname !== '' && !is_dir($dirname)) { - mkdir($dirname, 0777, true); - } - - $content = (new PhpSchemaRenderer())->render($schema); - file_put_contents($this->file, $content, LOCK_EX); - return true; - } - - private function removeFile(): void - { - if (!file_exists($this->file)) { - return; - } - if (!is_file($this->file)) { - throw new RuntimeException("`$this->file` is not a file."); - } - if (!is_writable($this->file)) { - throw new RuntimeException("File `$this->file` is not writeable."); - } - unlink($this->file); - } - - public function clear(): bool - { - try { - $this->removeFile(); - } catch (\Throwable $e) { - return false; - } - return true; - } - - private function isReadable(): bool - { - return $this->mode !== self::MODE_WRITE_ONLY; - } -} diff --git a/src/Schema/Provider/SimpleCacheSchemaProvider.php b/src/Schema/Provider/SimpleCacheSchemaProvider.php deleted file mode 100644 index cee4912b..00000000 --- a/src/Schema/Provider/SimpleCacheSchemaProvider.php +++ /dev/null @@ -1,59 +0,0 @@ -cache = $cache; - } - - public function withConfig(array $config): self - { - $new = clone $this; - $new->key = $config['key'] ?? self::DEFAULT_KEY; - return $new; - } - - public function read(?SchemaProviderInterface $nextProvider = null): ?array - { - $schema = $this->cache->get($this->key); - - if ($schema !== null || $nextProvider === null) { - return $schema; - } - - $schema = $nextProvider->read(); - if ($schema !== null) { - $this->write($schema); - } - return $schema; - } - - public function clear(): bool - { - if (!$this->cache->has($this->key)) { - return true; - } - $result = $this->cache->delete($this->key); - if ($result === false) { - throw new \RuntimeException("Unable to delete \"{$this->key}\" from cache."); - } - return true; - } - - private function write(array $schema): bool - { - return $this->cache->set($this->key, $schema); - } -} diff --git a/src/Schema/Provider/Support/BaseProviderCollector.php b/src/Schema/Provider/Support/BaseProviderCollector.php deleted file mode 100644 index 21967848..00000000 --- a/src/Schema/Provider/Support/BaseProviderCollector.php +++ /dev/null @@ -1,83 +0,0 @@ -|null */ - protected ?SplFixedArray $providers = null; - private ContainerInterface $container; - - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } - - /** - * @return $this - * - * @psalm-immutable - */ - public function withConfig(array $config): self - { - $new = clone $this; - $new->providers = $this->createSequence($new->container, $config); - return $new; - } - - public function clear(): bool - { - if ($this->providers === null) { - throw new RuntimeException(self::class . ' is not configured.'); - } - $exceptions = []; - $result = false; - foreach ($this->providers as $provider) { - try { - $result = $provider->clear() || $result; - } catch (\Throwable $e) { - $exceptions[] = $e; - } - } - if (count($exceptions)) { - throw new CumulativeException(...$exceptions); - } - return $result; - } - - private function createSequence(ContainerInterface $container, array $providers): SplFixedArray - { - $size = count($providers); - $stack = new SplFixedArray($size); - $nextProvider = null; - foreach (array_reverse($providers) as $key => $definition) { - $config = []; - if (is_array($definition)) { - if (is_string($key)) { - $config = $definition; - $definition = $key; - } else { - $config = $definition[1] ?? []; - $definition = $definition[0]; - } - } - $nextProvider = (new DeferredSchemaProviderDecorator( - $container, - $definition, - static::IS_SEQUENCE_PIPELINE ? $nextProvider : null - ))->withConfig($config); - $stack[--$size] = $nextProvider; - } - return $stack; - } -} diff --git a/src/Schema/Provider/Support/DeferredSchemaProviderDecorator.php b/src/Schema/Provider/Support/DeferredSchemaProviderDecorator.php deleted file mode 100644 index 9a5be3fa..00000000 --- a/src/Schema/Provider/Support/DeferredSchemaProviderDecorator.php +++ /dev/null @@ -1,87 +0,0 @@ -provider = $provider; - $this->container = $container; - $this->nextProvider = $nextProvider; - } - - public function withConfig(array $config): self - { - $provider = !$this->resolved && count($this->config) === 0 ? $this->provider : $this->getProvider(); - $new = new self($this->container, $provider, $this->nextProvider); - $new->config = $config; - return $new; - } - - public function read(?SchemaProviderInterface $nextProvider = null): ?array - { - $nextProvider ??= $this->latestProvider; - if ($nextProvider !== null && $this->nextProvider !== null) { - $nextProvider = $this->nextProvider->withLatestProvider($nextProvider); - } else { - $nextProvider = $this->nextProvider ?? $nextProvider; - } - return $this->getProvider()->read($nextProvider); - } - - public function clear(): bool - { - return $this->getProvider()->clear(); - } - - /** - * @psalm-suppress InvalidReturnType,InvalidReturnStatement - */ - private function getProvider(): SchemaProviderInterface - { - if ($this->resolved) { - return $this->provider; - } - $provider = $this->provider; - if (is_string($provider)) { - $provider = $this->container->get($provider); - } - if (!$provider instanceof SchemaProviderInterface) { - throw new BadDeclarationException('Provider', SchemaProviderInterface::class, $provider); - } - $this->provider = count($this->config) > 0 ? $provider->withConfig($this->config) : $provider; - $this->resolved = true; - return $this->provider; - } - - private function withLatestProvider(SchemaProviderInterface $provider): self - { - // resolve provider - $this->getProvider(); - $new = clone $this; - $new->latestProvider = $provider; - return $new; - } -} diff --git a/src/Schema/Provider/Support/MergeSchemaProvider.php b/src/Schema/Provider/Support/MergeSchemaProvider.php deleted file mode 100644 index 15949fee..00000000 --- a/src/Schema/Provider/Support/MergeSchemaProvider.php +++ /dev/null @@ -1,35 +0,0 @@ -providers === null) { - throw new RuntimeException(self::class . ' is not configured.'); - } - $parts = []; - foreach ($this->providers as $provider) { - $parts[] = $provider->read(); - } - - $schema = (new SchemaMerger())->merge(...$parts); - - if ($schema !== null || $nextProvider === null) { - return $schema; - } - return $nextProvider->read(); - } -} diff --git a/src/Schema/Provider/Support/SchemaMerger.php b/src/Schema/Provider/Support/SchemaMerger.php deleted file mode 100644 index 441e76b0..00000000 --- a/src/Schema/Provider/Support/SchemaMerger.php +++ /dev/null @@ -1,40 +0,0 @@ - $body) { - if (!is_string($role)) { - $schema[] = $body; - continue; - } - if (array_key_exists($role, $schema)) { - if ($schema[$role] === $body) { - continue; - } - throw new DuplicateRoleException($role); - } - $schema[$role] = $body; - } - } - - return $schema; - } -} diff --git a/src/Schema/Provider/Support/SchemaProviderPipeline.php b/src/Schema/Provider/Support/SchemaProviderPipeline.php deleted file mode 100644 index ab330ef5..00000000 --- a/src/Schema/Provider/Support/SchemaProviderPipeline.php +++ /dev/null @@ -1,26 +0,0 @@ -providers === null) { - throw new RuntimeException(self::class . ' is not configured.'); - } - if ($this->providers->count() === 0) { - return $nextProvider === null ? null : $nextProvider->read(); - } - return $this->providers[0]->read($nextProvider); - } -} diff --git a/src/Schema/SchemaProviderInterface.php b/src/Schema/SchemaProviderInterface.php deleted file mode 100644 index 10da9ddc..00000000 --- a/src/Schema/SchemaProviderInterface.php +++ /dev/null @@ -1,22 +0,0 @@ -createMock(SchemaInterface::class); + $schema->expects($this->any())->method('getRoles')->willReturn(['foo', 'bar']); + $schema->expects($this->any())->method('define')->willReturnCallback( + fn (string $role, int $property): ?string => $property === SchemaInterface::ROLE ? $role : null + ); + + $container = new SimpleContainer([SchemaInterface::class => $schema]); + $promise = new CycleDependencyProxy($container); + $command = new SchemaPhpCommand(new Aliases(), $promise); + + $this->expectException(\RuntimeException::class); + $command->run(new ArrayInput(['file' => $file]), $this->output); + } } diff --git a/tests/Command/Schema/SchemaRebuildCommandTest.php b/tests/Command/Schema/SchemaRebuildCommandTest.php index e0ee7ea3..ce07d5fe 100644 --- a/tests/Command/Schema/SchemaRebuildCommandTest.php +++ b/tests/Command/Schema/SchemaRebuildCommandTest.php @@ -4,6 +4,7 @@ namespace Yiisoft\Yii\Cycle\Tests\Command\Schema; +use Cycle\Schema\Provider\SchemaProviderInterface; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; @@ -11,7 +12,6 @@ use Yiisoft\Yii\Console\ExitCode; use Yiisoft\Yii\Cycle\Command\CycleDependencyProxy; use Yiisoft\Yii\Cycle\Command\Schema\SchemaRebuildCommand; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; final class SchemaRebuildCommandTest extends TestCase { diff --git a/tests/Feature/Schema/Provider/BaseSchemaProvider.php b/tests/Feature/Schema/Provider/BaseSchemaProvider.php index 961e48e5..bf063e76 100644 --- a/tests/Feature/Schema/Provider/BaseSchemaProvider.php +++ b/tests/Feature/Schema/Provider/BaseSchemaProvider.php @@ -5,8 +5,8 @@ namespace Yiisoft\Yii\Cycle\Tests\Feature\Schema\Provider; use Cycle\ORM\SchemaInterface as Schema; +use Cycle\Schema\Provider\SchemaProviderInterface; use PHPUnit\Framework\TestCase; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; use Yiisoft\Yii\Cycle\Tests\Feature\Schema\Stub\ArraySchemaProvider; abstract class BaseSchemaProvider extends TestCase diff --git a/tests/Feature/Schema/Provider/FromConveyorSchemaProviderTest.php b/tests/Feature/Schema/Provider/FromConveyorSchemaProviderTest.php index 39f2aebe..ef0c315f 100644 --- a/tests/Feature/Schema/Provider/FromConveyorSchemaProviderTest.php +++ b/tests/Feature/Schema/Provider/FromConveyorSchemaProviderTest.php @@ -10,6 +10,7 @@ use Cycle\Database\DatabaseManager; use Cycle\Database\DatabaseProviderInterface; use Cycle\ORM\Mapper\Mapper; +use Cycle\ORM\Schema\GeneratedField; use Cycle\ORM\SchemaInterface; use Cycle\ORM\Select\Repository; use Cycle\ORM\Select\Source; @@ -23,12 +24,12 @@ use Cycle\Schema\Generator\ResetTables; use Cycle\Schema\Generator\ValidateEntities; use Cycle\Schema\GeneratorInterface; +use Cycle\Schema\Provider\SchemaProviderInterface; use Yiisoft\Aliases\Aliases; use Yiisoft\Test\Support\Container\SimpleContainer; use Yiisoft\Yii\Cycle\Schema\Conveyor\AttributedSchemaConveyor; use Yiisoft\Yii\Cycle\Schema\Provider\FromConveyorSchemaProvider; use Yiisoft\Yii\Cycle\Schema\SchemaConveyorInterface; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; use Yiisoft\Yii\Cycle\Tests\Feature\Schema\Provider\Stub\FakePost; use Yiisoft\Yii\Cycle\Tests\Feature\Schema\Stub\ArraySchemaProvider; @@ -110,6 +111,9 @@ public function testReadFromConveyor(): void SchemaInterface::TYPECAST => ['id' => 'int', 'createdAt' => 'datetime'], SchemaInterface::SCHEMA => [], SchemaInterface::TYPECAST_HANDLER => null, + SchemaInterface::GENERATED_FIELDS => [ + 'id' => GeneratedField::ON_INSERT, + ], ], ], $provider->read()); } diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/FromFilesSchemaProviderTest.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/FromFilesSchemaProviderTest.php deleted file mode 100644 index aecaefef..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/FromFilesSchemaProviderTest.php +++ /dev/null @@ -1,217 +0,0 @@ - ['@dir/schema1.php']]; - protected const READ_CONFIG_SCHEMA = ['user' => []]; - - public static function EmptyConfigProvider(): array - { - return [ - [ - [], - ], - [ - ['files' => []], - ], - ]; - } - - /** - * @dataProvider EmptyConfigProvider - */ - public function testWithConfigEmpty(array $config): void - { - $schemaProvider = $this->createSchemaProvider(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Schema file list is not set.'); - $schemaProvider->withConfig($config); - } - - public function testWithConfigInvalidFiles(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "files" parameter must be an array.'); - $schemaProvider->withConfig(['files' => '@dir/schema1.php']); - } - - public static function FileListBadValuesProvider(): array - { - return [ - [null], - [42], - [STDIN], - [[]], - [new \SplFileInfo(__FILE__)], - ]; - } - - /** - * @dataProvider FileListBadValuesProvider - */ - public function testWithConfigInvalidValueInFileList($value): void - { - $schemaProvider = $this->createSchemaProvider(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "files" parameter must contain string values.'); - $schemaProvider->withConfig(['files' => [$value]]); - } - - public function testWithConfigInvalidStrict(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "strict" parameter must be a boolean.'); - $schemaProvider->withConfig([ - 'files' => ['@dir/schema1.php'], - 'strict' => 1, - ]); - } - - public function testWithConfig(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $data = $schemaProvider - ->withConfig(['files' => ['@dir/schema1.php']]) - ->read(); - - $this->assertSame([ - 'user' => [], - ], $data); - } - - public function testWithConfigFilesNotExists(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $data = $schemaProvider - ->withConfig(['files' => ['@dir/schema-not-exists.php']]) - ->read(); - - $this->assertNull($data); - } - - public function testWithConfigFilesEmpty(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $data = $schemaProvider - ->withConfig(['files' => ['@dir/schema-empty.php']]) - ->read(); - - $this->assertSame([], $data); - } - - public function testWithConfigStrictFilesNotExists(): void - { - $schemaProvider = $this - ->createSchemaProvider() - ->withConfig([ - 'files' => [ - '@dir/schema1.php', - '@dir/schema-not-exists.php', - ], - 'strict' => true, - ]); - - $this->expectException(SchemaFileNotFoundException::class); - $schemaProvider->read(); - } - - public function testRead(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $data = $schemaProvider - ->withConfig([ - 'files' => [ - '@dir/schema1.php', - '@dir/schema-not-exists.php', // not exists files should be silent in non strict mode - '@dir/schema2.php', - ], - ]) - ->read(); - - $this->assertSame([ - 'user' => [], - 'post' => [Schema::DATABASE => 'postgres'], - 'comment' => [], - ], $data); - } - - public function testReadEmpty(): void - { - $schemaProvider = $this->createSchemaProvider(); - $this->assertNull($schemaProvider->read()); - } - - public function testReadDuplicateRoles(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $this->expectException(DuplicateRoleException::class); - $this->expectExceptionMessage('The "post" role already exists in the DB schema.'); - $schemaProvider - ->withConfig([ - 'files' => [ - '@dir/schema2.php', - '@dir/schema2-duplicate.php', - ], - ]) - ->read(); - } - - public function testReadWildcard(): void - { - $schemaProvider = $this->createSchemaProvider(); - - $data = $schemaProvider - ->withConfig([ - 'strict' => true, - 'files' => [ - '@dir/schema[12].php', - '@dir/*/*.php', // no files found - '@dir/**/level3*.php', - ], - ]) - ->read(); - - $this->assertArrayHasKey('user', $data); - $this->assertArrayHasKey('post', $data); - $this->assertArrayHasKey('level3-schema', $data); - $this->assertArrayHasKey('level3-1-schema', $data); - $this->assertArrayHasKey('level3-2-schema', $data); - $this->assertArrayNotHasKey('level2-schema', $data); - } - - public function testClear(): void - { - $schemaProvider = $this->createSchemaProvider(); - $this->assertFalse($schemaProvider->clear()); - } - - protected function createSchemaProvider(array $config = null): FromFilesSchemaProvider - { - $aliases = new Aliases(['@dir' => __DIR__ . '/files']); - $provider = new FromFilesSchemaProvider($aliases); - return $config === null ? $provider : $provider->withConfig($config); - } -} diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-1-schema.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-1-schema.php deleted file mode 100644 index 3acf6da9..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-1-schema.php +++ /dev/null @@ -1,7 +0,0 @@ - [], -]; diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-2-schema.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-2-schema.php deleted file mode 100644 index de933f47..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-2-schema.php +++ /dev/null @@ -1,7 +0,0 @@ - [], -]; diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-schema.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-schema.php deleted file mode 100644 index 26c46d3e..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level-3/level3-schema.php +++ /dev/null @@ -1,7 +0,0 @@ - [], -]; diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level2-schema.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level2-schema.php deleted file mode 100644 index 8c418149..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/level1/level2/level2-schema.php +++ /dev/null @@ -1,7 +0,0 @@ - [], -]; diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema-empty.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema-empty.php deleted file mode 100644 index 0dae23de..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema-empty.php +++ /dev/null @@ -1,5 +0,0 @@ - [], -]; diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema2-duplicate.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema2-duplicate.php deleted file mode 100644 index 26b1948b..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema2-duplicate.php +++ /dev/null @@ -1,10 +0,0 @@ - [], - 'post' => [Schema::DATABASE => 'default'], -]; diff --git a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema2.php b/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema2.php deleted file mode 100644 index 5893a9c2..00000000 --- a/tests/Feature/Schema/Provider/FromFilesSchemaProvider/files/schema2.php +++ /dev/null @@ -1,10 +0,0 @@ - [Schema::DATABASE => 'postgres'], - 'comment' => [], -]; diff --git a/tests/Feature/Schema/Provider/PhpFileSchemaProvider/PhpFileSchemaProviderTest.php b/tests/Feature/Schema/Provider/PhpFileSchemaProvider/PhpFileSchemaProviderTest.php deleted file mode 100644 index b2553ffb..00000000 --- a/tests/Feature/Schema/Provider/PhpFileSchemaProvider/PhpFileSchemaProviderTest.php +++ /dev/null @@ -1,165 +0,0 @@ - '@dir/simple_schema.php']; - protected const READ_CONFIG_SCHEMA = ['user' => []]; - private const WRITE_CONFIG = ['file' => self::TMP_FILE]; - private const WRITE_ONLY_CONFIG = ['file' => self::TMP_FILE, 'mode' => PhpFileSchemaProvider::MODE_WRITE_ONLY]; - private const TMP_FILE = __DIR__ . '/files/write.php'; - - protected function setUp(): void - { - $this->removeTmpFile(); - } - - protected function tearDown(): void - { - $this->removeTmpFile(); - } - - public function testReadFromNextProvider(): void - { - $provider1 = $this->createSchemaProvider(self::WRITE_CONFIG); - $provider2 = new ArraySchemaProvider(self::READ_CONFIG_SCHEMA); - - $result = $provider1->read($provider2); - - $this->assertSame(self::READ_CONFIG_SCHEMA, $result); - } - - public function testDefaultState(): void - { - $provider = $this->createSchemaProvider(); - - $this->assertNull($provider->read()); - } - - public function testWithConfigWithoutRequiredParams(): void - { - $this->expectException(InvalidArgumentException::class); - - $this->createSchemaProvider([]); - } - - public function testWithConfigWithBadParams(): void - { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessageMatches('/parameter must not be empty/'); - - $nextProvider = new ArraySchemaProvider(self::READ_CONFIG_SCHEMA); - - $this->createSchemaProvider(null)->read($nextProvider); - } - - public function testModeWriteOnlyWithoutSchemaFromNextProvider(): void - { - $provider = $this->createSchemaProvider(self::WRITE_ONLY_CONFIG); - $nextProvider = new ArraySchemaProvider(null); - - $this->assertNull($provider->read($nextProvider)); - $this->assertFileDoesNotExist(self::TMP_FILE, 'Empty schema file is created.'); - } - - public function testModeWriteOnlyWithSchemaFromNextProvider(): void - { - $provider = $this->createSchemaProvider(self::WRITE_ONLY_CONFIG); - $nextProvider = new ArraySchemaProvider(self::READ_CONFIG_SCHEMA); - $this->assertSame(self::READ_CONFIG_SCHEMA, $provider->read($nextProvider)); - $this->assertFileExists(self::TMP_FILE, 'Schema file is not created.'); - } - - public function testModeWriteOnlyWithoutNextProviderException(): void - { - $config = self::READ_CONFIG; - $config['mode'] = PhpFileSchemaProvider::MODE_WRITE_ONLY; - $provider = $this->createSchemaProvider($config); - - $this->expectException(RuntimeException::class); - - $provider->read(); - } - - public function testModeWriteOnlyExceptionOnRead(): void - { - $config = self::READ_CONFIG; - $config['mode'] = PhpFileSchemaProvider::MODE_WRITE_ONLY; - $provider = $this->createSchemaProvider($config); - - $this->expectException(RuntimeException::class); - - $provider->read(); - } - - public function testClear(): void - { - $this->prepareTmpFile(); - $provider = $this->createSchemaProvider(self::WRITE_CONFIG); - - $result = $provider->clear(); - - $this->assertTrue($result); - $this->assertFileDoesNotExist(self::TMP_FILE); - } - - public function testClearNotExistingFile(): void - { - $provider = $this->createSchemaProvider(self::WRITE_CONFIG); - - $result = $provider->clear(); - - $this->assertTrue($result); - } - - public function testClearNotAFile(): void - { - $provider = $this->createSchemaProvider(['file' => '@dir']); - - $result = $provider->clear(); - - $this->assertFalse($result); - } - - public function testPrepareTmpFile(): void - { - $this->prepareTmpFile(); - $this->assertFileExists(self::TMP_FILE); - } - - public function testRemoveTmpFile(): void - { - $this->prepareTmpFile(); - $this->removeTmpFile(); - $this->assertFileDoesNotExist(self::TMP_FILE); - } - - private function prepareTmpFile(): void - { - file_put_contents(self::TMP_FILE, ' __DIR__ . '/files']); - $provider = new PhpFileSchemaProvider($aliases); - return $config === null ? $provider : $provider->withConfig($config); - } -} diff --git a/tests/Feature/Schema/Provider/PhpFileSchemaProvider/files/simple_schema.php b/tests/Feature/Schema/Provider/PhpFileSchemaProvider/files/simple_schema.php deleted file mode 100644 index 7fca98db..00000000 --- a/tests/Feature/Schema/Provider/PhpFileSchemaProvider/files/simple_schema.php +++ /dev/null @@ -1,7 +0,0 @@ - [], -]; diff --git a/tests/Feature/Schema/Provider/SimpleCacheSchemaProviderTest.php b/tests/Feature/Schema/Provider/SimpleCacheSchemaProviderTest.php deleted file mode 100644 index 1ad71a89..00000000 --- a/tests/Feature/Schema/Provider/SimpleCacheSchemaProviderTest.php +++ /dev/null @@ -1,97 +0,0 @@ - self::CACHE_KEY]; - private const CACHE_KEY = 'test-cycle-schema-cache-key'; - - private SimpleCacheActionLogger $cacheService; - - public function testDefaultState(): void - { - $provider = $this->createSchemaProvider(); - - $this->assertNull($provider->read()); - $this->assertTrue($this->cacheService->has(self::CACHE_KEY)); - } - - public function testClear(): void - { - $provider = $this->createSchemaProvider(self::READ_CONFIG); - - $result = $provider->clear(); - - $this->assertTrue($result); - $this->assertSame([ - [Action::HAS, self::CACHE_KEY], - [Action::DELETE, self::CACHE_KEY], - ], $this->cacheService->getActionKeyList()); - $this->assertFalse($this->cacheService->has(self::CACHE_KEY)); - } - - public function testClearNotExistingKey(): void - { - $key = 'key-not-exists'; - $provider = $this->createSchemaProvider(['key' => $key]); - - $result = $provider->clear(); - - $this->assertTrue($result); - $this->assertSame([[Action::HAS, $key]], $this->cacheService->getActionKeyList()); - } - - public function testClearWithCacheOnDeleteError(): void - { - $provider = $this->createSchemaProvider(self::READ_CONFIG); - $this->cacheService->getCacheService()->returnOnDelete = false; - - $this->expectException(RuntimeException::class); - - $provider->clear(); - } - - public function testWriteOnReadFromNextProvider(): void - { - $key = 'key-not-exists'; - $provider = $this->createSchemaProvider(['key' => $key]); - $nextProvider = new ArraySchemaProvider(self::READ_CONFIG_SCHEMA); - - $result = $provider->read($nextProvider); - $this->assertSame( - [[Action::GET, $key], [Action::SET, $key]], - $this->cacheService->getActionKeyList() - ); - $this->assertSame(self::READ_CONFIG_SCHEMA, $result); - $this->assertSame(self::READ_CONFIG_SCHEMA, $this->cacheService->get($key)); - } - - private function prepareCacheService(): void - { - $this->cacheService = new SimpleCacheActionLogger( - new MemorySimpleCache(), - [self::CACHE_KEY => self::READ_CONFIG_SCHEMA] - ); - } - - protected function setUp(): void - { - $this->prepareCacheService(); - } - - protected function createSchemaProvider(array $config = null): SimpleCacheSchemaProvider - { - $provider = new SimpleCacheSchemaProvider($this->cacheService); - return $config === null ? $provider : $provider->withConfig($config); - } -} diff --git a/tests/Feature/Schema/Provider/Support/BaseProviderCollector.php b/tests/Feature/Schema/Provider/Support/BaseProviderCollector.php deleted file mode 100644 index 1731dfc7..00000000 --- a/tests/Feature/Schema/Provider/Support/BaseProviderCollector.php +++ /dev/null @@ -1,261 +0,0 @@ - [ - Schema::ENTITY => \stdClass::class, - Schema::MAPPER => \stdClass::class, - ], - ]; - - protected ContainerInterface $container; - - protected function setUp(): void - { - $this->prepareContainer(); - } - - protected function prepareContainer(array $definitions = []): ContainerInterface - { - return $this->container = new SimpleContainer(array_merge([ - ArraySchemaProvider::class => new ArraySchemaProvider(), - 'BadSchemaProvider' => new \stdClass(), - ], $definitions)); - } - - // Definition resolving test - - public function testProviderFromString(): void - { - $this->prepareContainer(['provider' => new ArraySchemaProvider(self::READ_CONFIG_SCHEMA)]); - - $provider = $this->createSchemaProvider(['provider']); - - $this->assertSame(self::READ_CONFIG_SCHEMA, $provider->read()); - } - - public function testProviderFromArray(): void - { - $this->prepareContainer(['provider' => new ArraySchemaProvider(self::READ_CONFIG_SCHEMA)]); - $newSchema = self::ANOTHER_SCHEMA; - - $provider = $this->createSchemaProvider(['provider' => $newSchema]); - - $this->assertSame($newSchema, $provider->read()); - } - - public function testIgnoreStringKeyIfDefinitionIsNotArray(): void - { - $this->prepareContainer(['provider' => new ArraySchemaProvider(self::READ_CONFIG_SCHEMA)]); - - $provider = $this->createSchemaProvider(['provider' => new ArraySchemaProvider(self::ANOTHER_SCHEMA)]); - - $this->assertSame(self::ANOTHER_SCHEMA, $provider->read()); - } - - public function testProviderAsObject(): void - { - $provider = $this->createSchemaProvider([new ArraySchemaProvider(self::READ_CONFIG_SCHEMA)]); - - $this->assertSame(self::READ_CONFIG_SCHEMA, $provider->read()); - } - - public function testProviderAsBadClassObject(): void - { - $provider = $this->createSchemaProvider(['BadSchemaProvider']); - - $this->expectException(BadDeclarationException::class); - - $provider->read(); - } - - // Clear test - - public function testClearWithoutProviders(): void - { - $provider = $this->createSchemaProvider([]); - - $result = $provider->clear(); - - // exception was not thrown - $this->assertFalse($result); - } - - public function testClearNotConfigured(): void - { - $provider = $this->createSchemaProvider(null); - - $this->expectException(RuntimeException::class); - - $provider->clear(); - } - - public function testClearResultFalse(): void - { - $provider1 = (new ConfigurableSchemaProvider(self::ANOTHER_SCHEMA)) - ->withConfig([ConfigurableSchemaProvider::OPTION_CLEARABLE => false]); - $provider2 = (new ConfigurableSchemaProvider(self::ANOTHER_SCHEMA)) - ->withConfig([ConfigurableSchemaProvider::OPTION_CLEARABLE => false]); - $provider3 = (new ConfigurableSchemaProvider(self::ANOTHER_SCHEMA)) - ->withConfig([ConfigurableSchemaProvider::OPTION_CLEARABLE => false]); - - $provider = $this->createSchemaProvider([$provider1, $provider2, $provider3]); - - $result = $provider->clear(); - - // exception was not thrown - $this->assertFalse($result); - } - - public function testClearResultTrue(): void - { - $provider1 = (new ConfigurableSchemaProvider(self::ANOTHER_SCHEMA)) - ->withConfig([ConfigurableSchemaProvider::OPTION_CLEARABLE => false]); - $provider2 = (new ConfigurableSchemaProvider(self::ANOTHER_SCHEMA)) - ->withConfig([ConfigurableSchemaProvider::OPTION_CLEARABLE => true]); - $provider3 = (new ConfigurableSchemaProvider(self::ANOTHER_SCHEMA)) - ->withConfig([ConfigurableSchemaProvider::OPTION_CLEARABLE => false]); - - $provider = $this->createSchemaProvider([$provider1, $provider2, $provider3]); - - $result = $provider->clear(); - - // exception was not thrown - $this->assertTrue($result); - } - - public function testClearAllProvidersIndependentFromWriteable(): void - { - $writeable = new ArraySchemaProvider(self::READ_CONFIG_SCHEMA); - $origin = new SameOriginProvider([]); - $notReadable = $origin->withConfig([]); - $notWriteable1 = (new SameOriginProvider(self::READ_CONFIG_SCHEMA)) - ->withConfig([SameOriginProvider::OPTION_WRITABLE => false]); - $notWriteable2 = (new SameOriginProvider(self::ANOTHER_SCHEMA)) - ->withConfig([SameOriginProvider::OPTION_CLEARABLE => false]); - - $provider = $this->createSchemaProvider([$writeable, $notWriteable1, $notReadable, $notWriteable2]); - - $provider->clear(); - - $this->assertNull($writeable->read()); - $this->assertNull($notWriteable1->read()); - $this->assertNull($origin->read()); - $this->assertSame(self::ANOTHER_SCHEMA, $notWriteable2->read()); - } - - public function testClearWithException(): void - { - $provider1 = (new SameOriginProvider(self::READ_CONFIG_SCHEMA)) - ->withConfig([SameOriginProvider::EXCEPTION_ON_CLEAR => true]); - $provider2 = new ArraySchemaProvider(self::ANOTHER_SCHEMA); - $provider3 = new ArraySchemaProvider(self::ANOTHER_SCHEMA); - $provider = $this->createSchemaProvider([$provider1, $provider2, $provider3]); - - $this->expectException(CumulativeException::class); - - try { - $provider->clear(); - } catch (\Throwable $e) { - throw $e; - } finally { - // first provider throws exception - $this->assertSame(self::READ_CONFIG_SCHEMA, $provider1->read()); - // next provider will be cleared - $this->assertNull($provider2->read()); - // last provider will be cleared - $this->assertNull($provider3->read()); - } - } - - // Reading test - - public function testReadNotConfigured(): void - { - $provider = $this->createSchemaProvider(null); - - $this->expectException(RuntimeException::class); - - $provider->read(); - } - - public function testReadWithoutProviders(): void - { - $provider = $this->createSchemaProvider([]); - - $this->assertNull($provider->read()); - } - - public function testReadWithException(): void - { - $this->prepareContainer([ - 'withoutSchema' => (new SameOriginProvider(self::READ_CONFIG_SCHEMA)) - ->withConfig([SameOriginProvider::EXCEPTION_ON_READ => true]), - ]); - - $this->expectException(RuntimeException::class); - - $this->createSchemaProvider(['withoutSchema'])->read(); - } - - public function testReadFromOneProvider(): void - { - $provider = $this->createSchemaProvider([new ArraySchemaProvider(self::READ_CONFIG_SCHEMA)]); - - $schema = $provider->read(); - - $this->assertSame(self::READ_CONFIG_SCHEMA, $schema); - } - - public function testReadingOrderWithNullIgnoring(): void - { - $this->prepareContainer([ - 'withSchema' => new ArraySchemaProvider(self::READ_CONFIG_SCHEMA), - 'withoutSchema' => new ArraySchemaProvider(null), - ]); - - $provider = $this->createSchemaProvider(['withoutSchema', 'withSchema']); - - $this->assertNotNull($provider->read()); - } - - public function testReadWithAlternativeProvider(): void - { - $provider = $this->createSchemaProvider([ - new ArraySchemaProvider(), - new ArraySchemaProvider(), - new ArraySchemaProvider(), - ]); - - $schema1 = $provider->read(); - $schema2 = $provider->read(new ArraySchemaProvider(self::READ_CONFIG_SCHEMA)); - - $this->assertNull($schema1); - $this->assertSame(self::READ_CONFIG_SCHEMA, $schema2); - } - - public function testReadWithoutProvidersButWithAlternativeProvider(): void - { - $provider = $this->createSchemaProvider(); - - $schema2 = $provider->read(new ArraySchemaProvider(self::READ_CONFIG_SCHEMA)); - - $this->assertSame(self::READ_CONFIG_SCHEMA, $schema2); - } -} diff --git a/tests/Feature/Schema/Provider/Support/DeferredSchemaProviderDecoratorTest.php b/tests/Feature/Schema/Provider/Support/DeferredSchemaProviderDecoratorTest.php deleted file mode 100644 index 56e118dd..00000000 --- a/tests/Feature/Schema/Provider/Support/DeferredSchemaProviderDecoratorTest.php +++ /dev/null @@ -1,111 +0,0 @@ - [ - Schema::ENTITY => \stdClass::class, - Schema::MAPPER => \stdClass::class, - ], - ]; - protected const ALIASES = [ - '@test' => 'test', - ]; - - protected ContainerInterface $container; - - public function testReadWithLatestProvider() - { - $provider1 = new ArraySchemaProvider(null); - $provider2 = new ArraySchemaProvider(null); - $latestProvider = new ArraySchemaProvider(self::ANOTHER_SCHEMA); - - $deferred1 = $this->createSchemaProvider(null, $provider1); - $deferred2 = $this->createSchemaProvider(null, $provider2, $deferred1); - - $result = $deferred2->read($latestProvider); - - $this->assertSame(self::ANOTHER_SCHEMA, $result); - $this->assertSame(self::ANOTHER_SCHEMA, $provider1->read()); - $this->assertSame(self::ANOTHER_SCHEMA, $provider2->read()); - } - - public function testNextDeferredProviderImmutabilityOnReadWithLatestProvider() - { - $this->prepareContainer([ - SameOriginProvider::class => (new SameOriginProvider(null)) - ->withConfig([SameOriginProvider::OPTION_WRITABLE => false]), - ]); - $latestProvider = new ArraySchemaProvider(self::ANOTHER_SCHEMA); - - $deferred1 = $this->createSchemaProvider(null, SameOriginProvider::class); - $deferred2 = $this->createSchemaProvider(null, SameOriginProvider::class, $deferred1); - - $result1 = $deferred2->read($latestProvider); - $result2 = $deferred2->read(); - - $this->assertSame(self::ANOTHER_SCHEMA, $result1); - $this->assertNull($result2); - } - - public function testUseSameProviderIfLatestProviderIsExists() - { - $provider1 = new ConfigurableSchemaProvider(null); - $this->prepareContainer([ConfigurableSchemaProvider::class => $provider1]); - $latestProvider = new ArraySchemaProvider(self::ANOTHER_SCHEMA); - - $deferred1 = $this->createSchemaProvider( - [ConfigurableSchemaProvider::OPTION_WRITABLE => true], - ConfigurableSchemaProvider::class - ); - $deferred2 = $this->createSchemaProvider(null, null, $deferred1); - - $result1 = $deferred2->read($latestProvider); - $result2 = $deferred1->read(); - - $this->assertSame(self::ANOTHER_SCHEMA, $result1); - $this->assertSame(self::ANOTHER_SCHEMA, $result2); - } - - protected function setUp(): void - { - $this->prepareContainer(); - } - - protected function prepareContainer(array $definitions = []): ContainerInterface - { - return $this->container = new SimpleContainer(array_merge([ - ArraySchemaProvider::class => new ArraySchemaProvider(self::ANOTHER_SCHEMA), - ], $definitions)); - } - - /** - * @param SchemaProviderInterface|string|null $provider - */ - protected function createSchemaProvider( - ?array $config = null, - $provider = null, - ?DeferredSchemaProviderDecorator $nextProvider = null - ): DeferredSchemaProviderDecorator { - if ($provider === null) { - $provider = new ArraySchemaProvider(self::DEFAULT_SCHEMA); - } - $provider = new DeferredSchemaProviderDecorator($this->container, $provider, $nextProvider); - return $config === null ? $provider : $provider->withConfig($config); - } -} diff --git a/tests/Feature/Schema/Provider/Support/MergeSchemaProviderTest.php b/tests/Feature/Schema/Provider/Support/MergeSchemaProviderTest.php deleted file mode 100644 index 5c0d7513..00000000 --- a/tests/Feature/Schema/Provider/Support/MergeSchemaProviderTest.php +++ /dev/null @@ -1,53 +0,0 @@ - [ - Schema::ENTITY => \stdClass::class, - Schema::MAPPER => \stdClass::class, - ], - ]; - protected const SCHEMA_CONFLICT = [ - 'post' => [ - Schema::ENTITY => \stdClass::class, - Schema::DATABASE => 'default', - ], - ]; - - protected function createSchemaProvider(?array $config = []): MergeSchemaProvider - { - $provider = new MergeSchemaProvider($this->container); - return $config === null ? $provider : $provider->withConfig($config); - } - - public function testMergeSameValueConflict(): void - { - $provider = $this->createSchemaProvider([...self::READ_CONFIG, new ArraySchemaProvider(self::SCHEMA_PART_1)]); - $schema = $provider->read(); - self::assertSame(self::READ_CONFIG_SCHEMA, $schema); - } - - public function testMergeDifferentValueConflict(): void - { - $this->expectException(DuplicateRoleException::class); - - $provider = $this->createSchemaProvider([...self::READ_CONFIG, new ArraySchemaProvider(self::SCHEMA_CONFLICT)]); - $provider->read(); - } -} diff --git a/tests/Feature/Schema/Provider/Support/SchemaMergerTest.php b/tests/Feature/Schema/Provider/Support/SchemaMergerTest.php deleted file mode 100644 index d022eff6..00000000 --- a/tests/Feature/Schema/Provider/Support/SchemaMergerTest.php +++ /dev/null @@ -1,59 +0,0 @@ -createMerger()->merge(null, null); - - $this->assertNull($result); - } - - public function testMergeNullAndEmptyArray(): void - { - $result = $this->createMerger()->merge(null, []); - - $this->assertSame([], $result); - } - - public function testMergeDifferentRoles(): void - { - $result = $this->createMerger()->merge(['user' => []], ['post' => []], []); - - $this->assertSame(['user' => [], 'post' => []], $result); - } - - public function testMergeSameRoles(): void - { - $result = $this->createMerger()->merge(['user' => []], ['post' => [], 'user' => [], 'tag' => []]); - - $this->assertSame(['user' => [], 'post' => [], 'tag' => []], $result); - } - - public function testMergeConflictRoles(): void - { - $this->expectException(DuplicateRoleException::class); - - $this->createMerger()->merge(['user' => []], ['post' => [], 'user' => ['']]); - } - - public function testMergeNumericKeys(): void - { - $result = $this->createMerger()->merge([['foo'], ['bar']], [['bar'], ['baz']]); - - $this->assertSame([['foo'], ['bar'], ['bar'], ['baz']], $result); - } -} diff --git a/tests/Feature/Schema/Provider/Support/SchemaProviderPipelineTest.php b/tests/Feature/Schema/Provider/Support/SchemaProviderPipelineTest.php deleted file mode 100644 index ae07a213..00000000 --- a/tests/Feature/Schema/Provider/Support/SchemaProviderPipelineTest.php +++ /dev/null @@ -1,35 +0,0 @@ - self::READ_CONFIG_SCHEMA, - ]; - - protected function createSchemaProvider(?array $config = []): SchemaProviderPipeline - { - $provider = new SchemaProviderPipeline($this->container); - return $config === null ? $provider : $provider->withConfig($config); - } - - // Reading test - - public function testShortCircuitInstantiation(): void - { - $this->prepareContainer([ - 'goodProvider' => new ArraySchemaProvider(self::READ_CONFIG_SCHEMA), - 'badProvider' => 'not an object', - ]); - - $provider = $this->createSchemaProvider(['goodProvider', 'badProvider', 'undefined provider']); - - $this->assertSame(self::READ_CONFIG_SCHEMA, $provider->read()); - } -} diff --git a/tests/Feature/Schema/Stub/ArraySchemaProvider.php b/tests/Feature/Schema/Stub/ArraySchemaProvider.php index 0cc54828..a00c28d5 100644 --- a/tests/Feature/Schema/Stub/ArraySchemaProvider.php +++ b/tests/Feature/Schema/Stub/ArraySchemaProvider.php @@ -4,7 +4,7 @@ namespace Yiisoft\Yii\Cycle\Tests\Feature\Schema\Stub; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; +use Cycle\Schema\Provider\SchemaProviderInterface; final class ArraySchemaProvider implements SchemaProviderInterface { @@ -17,8 +17,6 @@ public function __construct(array $schema = null) /** * @param array $config will replace the schema - * - * @return $this */ public function withConfig(array $config): self { @@ -32,7 +30,7 @@ public function read(?SchemaProviderInterface $nextProvider = null): ?array if ($this->schema !== null) { return $this->schema; } - $this->schema = $nextProvider === null ? null : $nextProvider->read(); + $this->schema = $nextProvider?->read(); return $this->schema; } diff --git a/tests/Feature/Schema/Stub/ConfigurableSchemaProvider.php b/tests/Feature/Schema/Stub/ConfigurableSchemaProvider.php deleted file mode 100644 index 000dc0fd..00000000 --- a/tests/Feature/Schema/Stub/ConfigurableSchemaProvider.php +++ /dev/null @@ -1,99 +0,0 @@ -schema = $schema; - } - - public function withConfig(array $config): self - { - $new = clone $this; - if (array_key_exists(self::OPTION_WRITABLE, $config)) { - $new->writable = $config[self::OPTION_WRITABLE]; - } - if (array_key_exists(self::OPTION_CLEARABLE, $config)) { - $new->clearable = $config[self::OPTION_CLEARABLE]; - } - if (array_key_exists(self::EXCEPTION_ON_READ, $config)) { - $new->exceptionOnRead = $config[self::EXCEPTION_ON_READ]; - } - if (array_key_exists(self::EXCEPTION_ON_WRITE, $config)) { - $new->exceptionOnWrite = $config[self::EXCEPTION_ON_WRITE]; - } - if (array_key_exists(self::EXCEPTION_ON_CLEAR, $config)) { - $new->exceptionOnClear = $config[self::EXCEPTION_ON_CLEAR]; - } - return $new; - } - - public function isWritable(): bool - { - return $this->writable; - } - - public function isExceptionOnRead(): bool - { - return $this->exceptionOnRead; - } - - public function read(?SchemaProviderInterface $nextProvider = null): ?array - { - if ($this->exceptionOnRead) { - throw new \RuntimeException('Schema cannot be read.'); - } - if ($this->schema !== null) { - return $this->schema; - } - $schema = $nextProvider === null ? null : $nextProvider->read(); - if ($schema !== null) { - $this->write($schema); - } - return $schema; - } - - public function write(array $schema): bool - { - if ($this->exceptionOnWrite) { - throw new \RuntimeException('Schema cannot be written.'); - } - if (!$this->writable) { - return false; - } - $this->schema = $schema; - return true; - } - - public function clear(): bool - { - if ($this->exceptionOnClear) { - throw new \RuntimeException('Schema cannot be cleared.'); - } - if (!$this->clearable) { - return false; - } - $this->schema = null; - return true; - } -} diff --git a/tests/Feature/Schema/Stub/SameOriginProvider.php b/tests/Feature/Schema/Stub/SameOriginProvider.php deleted file mode 100644 index 7ce84be5..00000000 --- a/tests/Feature/Schema/Stub/SameOriginProvider.php +++ /dev/null @@ -1,15 +0,0 @@ -schema = &$this->schema; - return $new; - } -} diff --git a/tests/Unit/Exception/CumulativeExceptionTest.php b/tests/Unit/Exception/CumulativeExceptionTest.php deleted file mode 100644 index 3beae7ed..00000000 --- a/tests/Unit/Exception/CumulativeExceptionTest.php +++ /dev/null @@ -1,77 +0,0 @@ -prepareException(); - - $this->assertInstanceOf(Throwable::class, $exception); - $this->assertSame('0 exceptions were thrown.', $exception->getMessage()); - $this->assertSame(0, $exception->getCode()); - } - - public function testGetExceptions(): void - { - $list = [ - new \RuntimeException(), - new \Exception(), - new \InvalidArgumentException(), - ]; - - $exception = $this->prepareException(...$list); - - $this->assertSame($list, $exception->getExceptions()); - } - - public function testGetMessageWithOneException(): void - { - $list = [ - new \RuntimeException('Foo message.', 42), - ]; - - $exception = $this->prepareException(...$list); - - $this->assertIsInt(strpos($exception->getMessage(), '[RuntimeException] #42: Foo message.')); - $this->assertMatchesRegularExpression('/One exception was thrown\\./', $exception->getMessage()); - } - - public function testGetMessageWithMultipleExceptions(): void - { - $list = [ - new \RuntimeException('Foo message.', 42), - new \Exception('Bar message.'), - new \InvalidArgumentException('Baz message.'), - ]; - - $exception = $this->prepareException(...$list); - - $this->assertMatchesRegularExpression('/3 exceptions were thrown\\./', $exception->getMessage()); - - $this->assertMatchesRegularExpression( - '/\\n1\\) [^\\n]++\\n\\[RuntimeException\\] \\#42\\: Foo message\\./', - $exception->getMessage() - ); - $this->assertMatchesRegularExpression( - '/\\n2\\) [^\\n]++\\n\\[Exception] #0: Bar message./', - $exception->getMessage() - ); - $this->assertMatchesRegularExpression( - '/\\n3\\) [^\\n]++\\n\\[InvalidArgumentException] #0: Baz message./', - $exception->getMessage() - ); - } -} diff --git a/tests/Unit/Exception/DuplicateRoleExceptionTest.php b/tests/Unit/Exception/DuplicateRoleExceptionTest.php deleted file mode 100644 index 8c83a62f..00000000 --- a/tests/Unit/Exception/DuplicateRoleExceptionTest.php +++ /dev/null @@ -1,40 +0,0 @@ -prepareException(); - - $this->assertInstanceOf(\Throwable::class, $exception); - $this->assertSame( - 'The "' . self::DEFAULT_ROLE . '" role already exists in the DB schema.', - $exception->getMessage() - ); - $this->assertSame(0, $exception->getCode()); - } - - public function testFriendly(): void - { - $exception = $this->prepareException(); - - $this->assertInstanceOf(FriendlyExceptionInterface::class, $exception); - $this->assertNotEmpty($exception->getName()); - $this->assertNotEmpty($exception->getSolution()); - } -} diff --git a/tests/Unit/Exception/SchemaFileNotFoundExceptionTest.php b/tests/Unit/Exception/SchemaFileNotFoundExceptionTest.php deleted file mode 100644 index 7c47406d..00000000 --- a/tests/Unit/Exception/SchemaFileNotFoundExceptionTest.php +++ /dev/null @@ -1,37 +0,0 @@ -prepareException(); - - $this->assertInstanceOf(\Throwable::class, $exception); - $this->assertSame('Schema file "' . self::DEFAULT_FILENAME . '" not found.', $exception->getMessage()); - $this->assertSame(0, $exception->getCode()); - } - - public function testFriendly(): void - { - $exception = $this->prepareException(); - - $this->assertInstanceOf(FriendlyExceptionInterface::class, $exception); - $this->assertNotEmpty($exception->getName()); - $this->assertNotEmpty($exception->getSolution()); - } -} diff --git a/tests/Unit/Listener/MigrationListenerTest.php b/tests/Unit/Listener/MigrationListenerTest.php index 97f0aead..4e9de57c 100644 --- a/tests/Unit/Listener/MigrationListenerTest.php +++ b/tests/Unit/Listener/MigrationListenerTest.php @@ -4,15 +4,15 @@ namespace Yiisoft\Yii\Cycle\Tests\Unit\Listener; +use Cycle\Schema\Provider\SchemaProviderInterface; +use Cycle\Schema\Provider\Support\SchemaProviderPipeline; use PHPUnit\Framework\TestCase; use Yiisoft\Test\Support\Container\SimpleContainer; use Yiisoft\Yii\Cycle\Event\AfterMigrate; use Yiisoft\Yii\Cycle\Listener\MigrationListener; -use Yiisoft\Yii\Cycle\Schema\Provider\Support\SchemaProviderPipeline; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; use Yiisoft\Yii\Cycle\Tests\Unit\Listener\Stub\CallingSpyProvider; -class MigrationListenerTest extends TestCase +final class MigrationListenerTest extends TestCase { private function prepareSchemaProvider(array $providers = []): SchemaProviderInterface { diff --git a/tests/Unit/Listener/Stub/CallingSpyProvider.php b/tests/Unit/Listener/Stub/CallingSpyProvider.php index 51a99e33..87a31213 100644 --- a/tests/Unit/Listener/Stub/CallingSpyProvider.php +++ b/tests/Unit/Listener/Stub/CallingSpyProvider.php @@ -4,7 +4,7 @@ namespace Yiisoft\Yii\Cycle\Tests\Unit\Listener\Stub; -use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface; +use Cycle\Schema\Provider\SchemaProviderInterface; class CallingSpyProvider implements SchemaProviderInterface { diff --git a/tests/Unit/Schema/Provider/FromConveyorSchemaProviderTest.php b/tests/Unit/Schema/Provider/FromConveyorSchemaProviderTest.php new file mode 100644 index 00000000..31341827 --- /dev/null +++ b/tests/Unit/Schema/Provider/FromConveyorSchemaProviderTest.php @@ -0,0 +1,43 @@ +createMock(GeneratorInterface::class); + + $conveyor = $this->createMock(SchemaConveyorInterface::class); + $conveyor + ->expects($this->once()) + ->method('addGenerator') + ->with(SchemaConveyorInterface::STAGE_USERLAND, $generator); + + $provider = new FromConveyorSchemaProvider( + $conveyor, + $this->createMock(DatabaseProviderInterface::class) + ); + $provider = $provider->withConfig(['generators' => [$generator]]); + + $provider->read(); + } + + public function testClear(): void + { + $provider = new FromConveyorSchemaProvider( + $this->createMock(SchemaConveyorInterface::class), + $this->createMock(DatabaseProviderInterface::class) + ); + + $this->assertFalse($provider->clear()); + } +}