soyhuce / array-factory
这是我创建的包array-factory
1.1.0
2024-03-08 13:52 UTC
Requires
- php: ^8.2
- illuminate/collections: ^10.0 || ^11.0
- illuminate/database: ^10.0 || ^11.0
- illuminate/pipeline: ^10.0 || ^11.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.10
- orchestra/testbench: ^8.0
- pestphp/pest: ^2.24
- phpstan/extension-installer: ^1.1
- phpstan/phpstan: ^1.10.41
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- phpunit/phpunit: ^10.4
- spatie/laravel-data: ^3.0 || ^4.0
README
在测试您的应用程序时,您可能需要编写相同的数据结构(列表、集合等)来填充模型或其他内容。这些通常在多个测试文件中重复。
类似于Laravel的Factory类,ArrayFactory允许生成和重用自定义数据结构,并在您的测试中复用。
安装
您可以通过composer安装此包
composer require --dev soyhuce/array-factory
使用
创建工厂
use Soyhuce\ArrayFactory; $factory = new ArrayFactory(['foo' => 'bar']); // from an array $factory = ArrayFactory::new(['foo' => 'bar']); // from static method new $factory = ArrayFactory::new(fn () => ['foo' => 'bar']); // with a callable $factory = ArrayFactory::new(fn () => ['foo' => faker()->word() ]); // using \Faker\Generator generation
使用它
$factory->createOne(); // ['foo' => 'bar'] $factory->createMany(['foo' => 'qux'], ['foo' => 'bar']) // [['foo' => 'qux'], ['foo' => 'bar']] $factory->count(2)->asCollection(); // Illuminate\Support\Collection([ ['foo' => 'bar'], ['foo' => 'bar'] ])
添加状态
您可能需要定义状态并在特定上下文中使用它。
$factory = new ArrayFactory( definition: ['foo' => 'bar'], states: [ 'qux' => ['foo' => 'qux'], ] ); $factory->createOne(); // ['foo' => 'bar'] $factory->state('qux')->createOne(); // ['foo' => 'qux']
添加自定义集合
您可以将数组转换为自定义集合。
$factory = new ArrayFactory( collection: FooCollection::class, ); $foo = FooFactory::new()->asCollection();
您还可以通过定义Spatie\LaravelData\Data类将数组转换为自定义数据对象。
添加自定义 \Spatie\LaravelData\Data
$factory = new ArrayFactory( data: FooData::class, ); $factory = FooFactory::new()->asData();
它允许以数据集合的形式获取多个结果
$datas = $factory->manyAsDataCollection(['id' => 2], ['id' => 3]); // Collection([FooData(id: 2), FooData(id: 3)])
创建扩展类
class FooFactory extends ArrayFactory { protected string $collection = FooCollection::class; protected string $data = FooData::class; public function definition(): array { return [ 'id' => 1, 'activated' => true, 'message' => faker()->sentence(), 'value' => 0, ]; } public function id(int $id): static { return $this->state(['id' => $id]); } public function activated(bool $activated = true): static { return $this->state(['activated' => $activated]); } }
然后,您可以在测试中简单使用它。
$foo1 = FooFactory::new()->createOne(); // ['id' => 1, 'activated' => true, 'value' => 0] $foo1 = FooFactory::new()->createOne(['value' => 1]]); // ['id' => 1, 'activated' => true, 'value' => 1] $foo2 = FooFactory::new()->id(2)->createOne(); // ['id' => 2, 'activated' => true, 'value' => 0] $foo3 = FooFactory::new()->activated(false)->createOne(); // ['id' => 1, 'activated' => false, 'value' => 0]
测试
运行测试。
composer test
运行所有预提交检查。
composer all
变更日志
请参阅变更日志以获取有关最近更改的更多信息。
安全漏洞
请参阅我们的安全策略了解如何报告安全漏洞。
致谢
许可协议
MIT许可协议(MIT)。请参阅许可文件以获取更多信息。