marty/mcfly

Marty McFly - 返回未来,编写您的Symfony fixtures

2.2.0 2024-05-05 20:35 UTC

This package is auto-updated.

Last update: 2024-09-05 21:22:12 UTC


README

Marty MacFly - 返回未来,编写您的Symfony fixtures Marty MacFly 允许您快速轻松地创建 fixtures,以简化 Symfony 的开发和测试。

主要功能

安装

需要 PHP 8.0+ 和 Composer

composer req --dev Marty/McFly

您需要为每个实体创建一个 fixtures 文件,并扩展 Marty\McFly\Fixture 而不是 Doctrine\Bundle\FixturesBundle\Fixture

<?php
// src/DataFixtures/CompanyFixtures.php

namespace App\DataFixtures;

use Doctrine\Persistence\ObjectManager;
use Marty\McFly\Fixture;

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        // $product = new Product();
        // $manager->persist($product);

        $manager->flush();
    }
}

添加 Marty\McFly\Fixture 时,必须遵循 Marty\McFly\Interface\CreateInterface 接口,并添加一个 generate() 函数。

⚠️ 在 v1 和 v2 之间,将 create() 函数重命名为 generate() 以避免破坏性更改。虽然 create() 函数仍然兼容,但建议迁移到 generate() 以利用新功能。

<?php
// src/DataFixtures/CompanyFixtures.php

namespace App\DataFixtures;

use Doctrine\Persistence\ObjectManager;
use Marty\McFly\Fixture;

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        // $this->generate();

        $manager->flush();
    }

    public function generate(?array $properties = null, array|string|null $references = null): object
    {
        // TODO: Implement generate() method.
        throw new \RuntimeException("The generate() method is not implemented.");
    }
}

配置您的模板(generate() 是一个工厂,无需设置器或 _construct 与 Reflection 一起工作)

<?php
// src/DataFixtures/CompanyFixtures.php

namespace App\DataFixtures;

use App\Entity\Company;
use Doctrine\Persistence\ObjectManager;
use Marty\McFly\Fixture;

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        // Create a random Company, persist it (for database), and automatically add a reference to use it in other fixtures.
        $this->generate();

        // Create 10 randoms Companies to "Paris" (Since 2.0)
        $this->generateMany(10, [
            'city' => 'Paris',
            'postalCode' => '75000'
        ]);

        // Finally, flush to the database
        $manager->flush();
    }

    public function generate(?array $properties = null, array|string|null $references = null): object
    {
        return $this->createAndSave(Company::class, $properties,
            [
                'name'       => self::$faker->company(),
                'address'    => self::$faker->address(),
                'city'       => self::$faker->city(),
                'postalCode' => self::$faker->postcode(),
            ],
            $references
        );
    }

}

配置您的模板:替代样式(如果您有设置器)

<?php
// src/DataFixtures/CompanyFixtures.php

namespace App\DataFixtures;

use App\Entity\Company;
use Doctrine\Persistence\ObjectManager;
use Marty\McFly\Fixture;

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        // Create a random Company, persist it (for database), and automatically add a reference to use it in other fixtures.
        $this->generate();

        // Alternative : Create 10 randoms Companies to "Paris" with setter
        for ($i=0 ; $i<10 ; $i++) {
            $this->generate()
                ->setCity('Paris')
                ->setPostalCode('75000');
        }

        // Finally, flush to the database
        $manager->flush();
    }

    public function generate(?array $properties = null, array|string|null $references = null): object
    {
        $company = (new Company())
            ->setName(self::getFaker()->company())
            ->setAddress(self::getFaker()->address())
            ->setCity(self::getFaker()->city())
            ->setPostalCode(self::getFaker()->postcode());

        $this->save($company, $references);

        return $company;
    }
}

使用方法

创建一个随机实体

<?php

// ...

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        // Create a random Company
        $this->generate();

        // Finally, flush to the database
        $manager->flush();
    }

    // ... generate() definition
}

仅通过设置必要的属性创建一个实体(推荐样式)。

<?php

// ...

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        // Create a random Company to "Paris"
        $this->generate([
            'city'       => 'Paris',
            'postalCode' => '75000',
        ]);

        // Finally, flush to the database
        $manager->flush();
    }

    // ... generate() definition
}

仅通过设置必要的属性创建一个实体(替代样式)。

⚠️ 使用此语法,实体在创建后会进行更改。

<?php

// ...

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        // Create a random Company to "Paris"
        $this->generate()
            ->setCity('Paris')
            ->setPostalCode('75000');

        // Finally, flush to the database
        $manager->flush();
    }

    // ... generate() definition
}

同时定制某些属性创建多个实体。

<?php

// ...

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {

        // Create 10 random Company to "Paris"
        $this->generateMany(10, [
            'city'       => 'Paris',
            'postalCode' => '75000',
        ]);

        // Finally, flush to the database
        $manager->flush();
    }

    // ... generate() definition
}

同时定制某些属性,并为每个元素生成随机值的多个实体。

<?php

// ...

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {

        // Create 10 random Company to "Paris"
        $this->generateMany(10, function() {
            return [
                'city'       => 'Paris',
                'postalCode' => self::$faker->randomElement(['75000', '75100', '75200']),
            ];
        });

        // Finally, flush to the database
        $manager->flush();
    }

    // ... generate() definition
}

同时定制某些属性(替代)

<?php

// ...

class CompanyFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {

        // Create 10 random Company to "Paris"
        for ($i=0 ; $i<10 ; $i++) {
            $this->generate()
                ->setCity('Hill Valley')
            ;
        }

        // Finally, flush to the database
        $manager->flush();
    }

    // ... generate() definition
}

依赖

<?php

namespace App\DataFixtures;

use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Marty\McFly\Fixture;
use App\Entity\Company;

class UserFixture extends Fixture implements DependentFixtureInterface
{

    public function load(ObjectManager $manager): void
    {
        // Use this function to loop through all companies and create users for them.
        /** @var array<Company> $companies */
        $companies = $this->getReferencesByClass(Company::class);

        // Need a random company? Use this method.
        /** @var Company $company */
        $company = $this->getRandomReferenceByClass(Company::class);

    }

    public function create(string|array $references = null): User
    {
        // You can also use it in the template to add a default random company.
        /** @var Company $company */
        $company = $this->getRandomReferenceByClass(Company::class);

        // ..
    }

    public function getDependencies(): array
    {
        return [
            CompanyFixture::class,
        ];
    }
}

引用、计数器、枚举和随机值

<?php
// --

class InvoiceFixture extends Fixture implements DependentFixtureInterface
{

    // --

    public function generate(?array $properties = null, array|string|null $references = null): Invoice
    {
        $invoice = $this->createAndSave(Invoice::class, $properties,
            [
                'createdAt' => new DateTimeImmutable(),
                'number'    => InvoiceFixture::count(),                                 // the current number, auto-incrementation on save()
                'user'      => $this->getRandomReferenceByClass(User::class),           // a random User
                'status'    => self::randomValue(Status::cases()),                      // randomly a value of Status Enum,
                'confirmed' => self::randomValue([True, False]),                        // randomly True or False
                'comment'   => self::randomValue([null, self::getFaker()->sentence()]), // Add random sentence or randomly NULL
                'product'
            ],
            $references
        );

        // Add RandomProduct
        for ($i=0 ; $i<10 ; $i++) {
            /** @var Product $product */
            $randomProduct = $this->getRandomReferenceByClass(Product::class);
            $invoice->addProduct($randomProduct);
        }

        return $invoice;
    }

    // --
}

致谢

  • Arnaud Lemercier 基于 Wixiweb

许可

Marty MacFly 在 MIT 许可证 (MIT) 下授权。