### Install Doctrine ORM and AliceBundle via Composer Source: https://github.com/theofidry/alicebundle/blob/master/README.md Composer commands to install Doctrine ORM package and AliceBundle as a development dependency. These are the foundational packages required for fixture management in Symfony applications. ```bash composer require doctrine-orm ``` ```bash composer require --dev hautelook/alice-bundle ``` -------------------------------- ### RecreateDatabaseTrait: On-the-Fly Schema Creation for In-Memory SQLite Source: https://github.com/theofidry/alicebundle/blob/master/README.md The RecreateDatabaseTrait is specifically designed for use with in-memory SQLite databases. It facilitates the creation of the database schema dynamically during tests, simplifying setup for environments that rely on temporary, file-less SQLite instances. ```php price: description: brand: '@brand_*' App\Entity\Brand: brand_{1..10}: name: foundedYear: ``` -------------------------------- ### Include Fixtures from Multiple Files Source: https://context7.com/theofidry/alicebundle/llms.txt Demonstrates how to organize and load fixtures from multiple YAML files using the `include` directive. This promotes modularity and maintainability for complex fixture sets. ```yaml # fixtures/main.yaml include: - 'users.yaml' - 'categories.yaml' - 'brands.yaml' - 'products.yaml' - '@AppBundle/Resources/fixtures/app_specific.yaml' - '@UserBundle/Resources/fixtures/user_roles.yaml' ``` -------------------------------- ### Configure Database Traits: Customizing Fixture Loading and Purging Source: https://github.com/theofidry/alicebundle/blob/master/README.md AliceBundle's database testing traits offer configuration options via protected static properties. These can be set in `setUpBeforeClass` to customize manager, bundles, fixture appending, purging strategy (TRUNCATE), and connection. ```php syntax. ```yaml # fixtures/parameters.yaml parameters: app.alice.parameters.parameter1: something app.alice.parameters.parameter2: something else ... ``` -------------------------------- ### Create Dummy Entity Fixture File in YAML Source: https://github.com/theofidry/alicebundle/blob/master/README.md YAML fixture file defining multiple Dummy entity instances with generated names and relationships to RelatedDummy entities. Uses Alice syntax for range expansion ({1..10}) and faker functions (). ```yaml # fixtures/dummy.yaml App\Entity\Dummy: dummy_{1..10}: name: related_dummy: '@related_dummy*' ``` -------------------------------- ### Create Custom File Locator for Fixture Ordering - PHP Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Implements a custom file locator that decorates the default locator to reorder fixture files before they are loaded. The locator receives bundles and environment parameters, retrieves files from the decorated locator, and returns them in a custom order. Note that file order only affects how fixture definitions are merged, not instantiation order which depends on fixture dependencies. ```php decoratedFixtureLocator = $decoratedFixtureLocator; } /** * Re-order the files found by the decorated finder. * * {@inheritdoc} */ public function locateFiles(array $bundles, string $environment): array { $files = $this->decoratedFixtureLocator->locateFiles($bundles, $environment); // TODO: order the files found in whatever order you want // Warning: the order will only affect how the fixture definitions are merged. Indeed the order in which they // are instantiated afterwards by nelmio/alice may change due to handling the fixture dependencies and // circular references. return $files; } } ``` -------------------------------- ### Define Fixtures with Factory and Parameters in YAML Source: https://context7.com/theofidry/alicebundle/llms.txt Create fixture definitions using YAML with factory support for instantiating objects with constructor parameters. Supports both single object creation with specific parameters and bulk generation with template syntax (e.g., {1..10}) for creating multiple related fixtures with variations. ```yaml App\Entity\User: admin_user: __factory: { '@App\Factory\UserFactory::create': ['admin@example.com', ['ROLE_ADMIN', 'ROLE_SUPER_ADMIN']] } regular_user_{1..10}: __factory: { '@App\Factory\UserFactory::create': [''] } ``` -------------------------------- ### Load Fixtures Using Hautelook Console Command Source: https://github.com/theofidry/alicebundle/blob/master/README.md Symfony console commands to load fixtures using Hautelook AliceBundle. The basic command loads all fixtures; the second option loads fixtures from specific bundles only. ```bash php bin/console hautelook:fixtures:load ``` ```bash php bin/console hautelook:fixtures:load -b MyFirstBundle -b MySecondBundle ``` -------------------------------- ### Organize Environment-Specific Fixtures Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Structure fixtures directory with environment-specific subdirectories. When running the hautelook:fixtures:load command with a specific environment, all fixtures from the root and environment-specific directories are loaded automatically. ```text . └── fixtures ├── environmentless-fixture1.yml ├── ... ├── dev │ ├── dev-fixture1.yml │ └── ... └── inte ├── prod-fixture1.yml └── ... ``` -------------------------------- ### Use Service Factories for Entity Construction Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Specify a service factory for entity instantiation using the __factory key with the '@service::method' syntax. This allows complex entity creation logic defined in services to be used during fixture loading, with support for passing parameters to the factory method. ```yaml # fixtures/dummy.yaml AppBundle\Entity\Dummy: dummy_0: __factory: { '@dummy_factory::create': [''] } ``` -------------------------------- ### Configure Fixture Paths and Root Directories Source: https://context7.com/theofidry/alicebundle/llms.txt Define the locations where Alice should search for fixture files and the root directories for resolving paths. This configuration is typically done in `config/packages/dev/hautelook_alice.yaml`. ```yaml hautelook_alice: # Paths relative to root directories where fixtures are located fixtures_path: - 'fixtures' - 'Resources/fixtures' # Root directories to search for fixtures root_dirs: - '%kernel.project_dir%' - '%kernel.project_dir%/src' ``` -------------------------------- ### Create Custom Loader for Fixture Persistence Ordering - PHP Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Implements a custom loader that decorates the default loader to control the order in which fixture objects are persisted to the database. The loader receives fixture files, parameters, and existing objects, delegates loading to the decorated loader, then reorders objects before returning them for persistence. ```php decoratedLoader = $decoratedLoader; } /** * Pre process, persist and post process each object loaded. * * {@inheritdoc} */ public function load(array $fixturesFiles, array $parameters = [], array $objects = [], PurgeMode $purgeMode = null): array { // We get the objects from the decorated loader $objects = $this->decoratedLoader->load($fixturesFiles, $parameters, $objects, $purgeMode); // TODO: re-order the objects we want them to be persisted return $objects; } } ``` -------------------------------- ### Configure Hautelook AliceBundle in YAML Source: https://github.com/theofidry/alicebundle/blob/master/README.md YAML configuration file for Hautelook AliceBundle specifying fixture paths and root directories. Defines where the bundle looks for fixture files relative to the project or bundle directory. ```yaml # config/packages/dev/hautelook_alice.yaml hautelook_alice: fixtures_path: 'fixtures' # Path to which to look for fixtures relative to the project directory or the bundle path. May be a string or an array of strings. root_dirs: - '%kernel.root_dir%' - '%kernel.project_dir%' ``` -------------------------------- ### Organize Environment-Specific Fixtures Source: https://context7.com/theofidry/alicebundle/llms.txt Structures fixture files by environment (dev, test, prod) and uses shared fixtures loaded across all environments. Enables selective data loading based on application context. ```yaml # fixtures/shared_users.yaml (loaded in all environments) App\Entity\User: admin_user: email: 'admin@example.com' roles: ['ROLE_ADMIN'] # fixtures/dev/dev_products.yaml (only in dev) App\Entity\Product: dev_product_{1..100}: name: price: ``` ```bash # Load environment-specific fixtures php bin/console hautelook:fixtures:load --env=dev php bin/console hautelook:fixtures:load --env=test ``` -------------------------------- ### Create RelatedDummy Entity Fixture File in YAML Source: https://github.com/theofidry/alicebundle/blob/master/README.md YAML fixture file defining multiple RelatedDummy entity instances with generated names. Demonstrates basic fixture structure with range expansion and faker data generation. ```yaml # fixtures/related_dummy.yaml App\Entity\RelatedDummy: related_dummy_{1..10}: name: ``` -------------------------------- ### Use Alice Parameters in Fixture Files Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Reference Alice parameters defined in parameters.yaml within fixture files using the <{app.alice.parameters.*}> syntax. Parameters can be used as simple property values or passed to functions. ```yaml # fixtures/dummy.yaml AppBundle\Entity\Dummy: dummy_0: name: <{app.alice.parameters.parameter1}> ``` ```yaml # fixtures/dummy.yaml AppBundle\Entity\Dummy: dummy_0: name: )> ``` -------------------------------- ### Register UserProcessor with Autoconfigure (YAML) Source: https://github.com/theofidry/alicebundle/blob/master/doc/alice-processors.md This snippet shows how to register a `UserProcessor` by relying on Symfony's autoconfiguration feature. It assumes `autoconfigure` is enabled at the default level. ```yaml #config/services.yaml services: _defaults: autoconfigure: true App\DataFixtures\Processor\UserProcessor: ~ ``` -------------------------------- ### Define Reusable Fixture Parameters Source: https://context7.com/theofidry/alicebundle/llms.txt Creates centralized parameter definitions in YAML for consistent data generation across multiple fixture files. Parameters support variable interpolation and reduce duplication. ```yaml # fixtures/parameters.yaml parameters: default_currency: 'USD' base_price: 100 test_email_domain: 'test.example.com' company_name: 'Acme Corporation' # fixtures/products.yaml App\Entity\Product: product_{1..20}: name: price: ', 500)>' currency: '<{default_currency}>' supplier: '<{company_name}>' # fixtures/users.yaml App\Entity\User: user_{1..30}: email: '@<{test_email_domain}>' company: '<{company_name}>' ``` -------------------------------- ### Register Custom Faker Provider as a Service (YAML) Source: https://github.com/theofidry/alicebundle/blob/master/doc/faker-providers.md This YAML configuration registers the custom PHP Faker provider as a service. It uses the `nelmio_alice.faker.provider` tag to make it available to Nelmio Alice. This method requires explicit tagging. ```yaml # config/services.yaml services: AppBundle\DataFixtures\Faker\Provider\FooProvider: tags: [ { name: nelmio_alice.faker.provider } ] ``` -------------------------------- ### Register UserProcessor without Autoconfigure (YAML) Source: https://github.com/theofidry/alicebundle/blob/master/doc/alice-processors.md This snippet demonstrates manual registration of a `UserProcessor` service when autoconfiguration is disabled. It explicitly assigns the `fidry_alice_data_fixtures.processor` tag. ```yaml #config/services.yaml services: App\DataFixtures\Processor\UserProcessor: tags: [ { name: fidry_alice_data_fixtures.processor } ] ``` -------------------------------- ### Configure Test Database Settings with RefreshDatabaseTrait Source: https://context7.com/theofidry/alicebundle/llms.txt Configures fixture loading behavior through static properties in test classes including Doctrine manager selection, bundle filtering, append mode, truncate strategy, and database connection specification. ```php request('GET', '/'); $this->assertResponseIsSuccessful(); } } ``` -------------------------------- ### Register Custom Faker Provider and Use in Fixtures Source: https://context7.com/theofidry/alicebundle/llms.txt Register the custom Faker provider as a Symfony service and reference its methods in fixture definitions using angle bracket syntax. This allows generating product fixtures with realistic SKUs, categories, brands, and prices using custom provider methods. ```yaml # config/services.yaml services: App\DataFixtures\Faker\Provider\ProductProvider: tags: [ { name: nelmio_alice.faker.provider } ] # fixtures/products_with_custom_provider.yaml App\Entity\Product: product_{1..50}: name: '' sku: '' category: '' brand: '' price: '' ``` -------------------------------- ### Implement Processor for Object Transformation Before Persistence Source: https://context7.com/theofidry/alicebundle/llms.txt Create a processor implementing ProcessorInterface to transform objects in preProcess hook before persistence. Useful for hashing passwords, setting default timestamps, or other business logic. The postProcess hook handles cleanup after persistence, such as erasing sensitive credentials. ```php getPlainPassword()) { $hashedPassword = $this->passwordHasher->hashPassword( $object, $plainPassword ); $object->setPassword($hashedPassword); } // Set default values if (!$object->getCreatedAt()) { $object->setCreatedAt(new \DateTime()); } } public function postProcess(string $id, object $object): void { if (!$object instanceof User) { return; } // Clear sensitive data after persistence $object->eraseCredentials(); } } ``` -------------------------------- ### Create Fixture Validation Processor - PHP Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Implements a custom processor that validates fixtures using Symfony's Validator component before they are persisted. The processor checks each object during the preProcess phase and throws a DomainException with detailed violation information if validation fails. The postProcess method is left empty for custom post-validation logic if needed. ```php validator->validate($object); if ($violations->count() > 0) { $message = sprintf("Error when validating fixture %s, violation(s) detected:\n%s", $id, $violations); throw new DomainException($message); } } public function postProcess(string $id, object $object): void { } } ``` -------------------------------- ### Register Processor and Apply to Fixtures Source: https://context7.com/theofidry/alicebundle/llms.txt Register the processor as a Symfony service with fidry_alice_data_fixtures.processor tag. Define fixtures with plaintext sensitive data that will be transformed by the processor before persistence without modifying the fixture definition. ```yaml # config/services.yaml services: App\DataFixtures\Processor\UserProcessor: tags: [ { name: fidry_alice_data_fixtures.processor } ] # fixtures/users_with_processor.yaml App\Entity\User: user_{1..20}: email: '' plainPassword: 'password123' # Will be hashed by processor roles: ['ROLE_USER'] ``` -------------------------------- ### Create Custom Faker Provider for Domain Data Source: https://context7.com/theofidry/alicebundle/llms.txt Extend Faker\Provider\Base to implement domain-specific data generators for custom business logic. Providers can return static selections or generate dynamic values using Faker's built-in methods. Register providers as Symfony services with nelmio_alice.faker.provider tag for integration with Alice fixtures. ```php generator->bothify('??-####-??')); } public function productPrice(float $min = 10, float $max = 1000): float { return round($this->generator->randomFloat(2, $min, $max), 2); } } ``` -------------------------------- ### Register Custom File Locator in Symfony Services - YAML Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Configures the Symfony service container to register the custom file locator and replace the default hautelook_alice.locator service. The custom locator decorates the environmentless locator to maintain existing functionality while adding custom ordering logic. ```yaml # config/services.yaml services: Acme\Alice\Locator\CustomOrderFilesLocator: arguments: - '@hautelook_alice.locator.environmentless' # Decorates the currently used file locator # Replaces the default file locator used hautelook_alice.locator: '@Acme\Alice\Locator\CustomOrderFilesLocator' ``` -------------------------------- ### ReloadDatabaseTrait: Purge and Reload Fixtures for External Processes (e.g., Panther) Source: https://github.com/theofidry/alicebundle/blob/master/README.md The ReloadDatabaseTrait is suitable for scenarios where transactional rollbacks are not feasible, such as when using Panther, which operates in a separate process. This trait purges the database and reloads fixtures before each test, ensuring a clean state for tests involving external database interactions. ```php request('GET', '/my-news'); $form = $crawler->filter('#post-comment')->form(['new-comment' => 'Symfony is so cool!']); $client->submit($form); } } ``` -------------------------------- ### Register AliceBundle in Symfony AppKernel Source: https://github.com/theofidry/alicebundle/blob/master/README.md PHP code to register Doctrine, NelmioAlice, and Hautelook AliceBundle in the Symfony kernel for non-Flex architectures. Bundles are conditionally loaded in dev and test environments only. ```php getEnvironment(), ['dev', 'test'])) { //... $bundles[] = new Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle(); $bundles[] = new Fidry\AliceDataFixtures\Bridge\Symfony\FidryAliceDataFixturesBundle(); $bundles[] = new Hautelook\AliceBundle\HautelookAliceBundle(); } return $bundles; } ``` -------------------------------- ### Define Entity Relationships and References in Fixtures Source: https://context7.com/theofidry/alicebundle/llms.txt Illustrates how to define relationships between entities using Alice's reference system in YAML fixture files. References are denoted by `@` followed by the entity's reference name. ```yaml # fixtures/brands.yaml App\Entity\Brand: brand_apple: name: 'Apple' country: 'USA' brand_samsung: name: 'Samsung' country: 'South Korea' # fixtures/products.yaml App\Entity\Product: iphone: name: 'iPhone 15' price: 999.99 brand: '@brand_apple' # Specific reference product_{1..20}: name: '' price: '' brand: '@brand_*' # Random brand reference samsung_products_{1..10}: name: 'Galaxy ' price: '' brand: '@brand_samsung' ``` -------------------------------- ### Implement Service Factory Pattern for Fixture Objects Source: https://context7.com/theofidry/alicebundle/llms.txt Creates complex objects in fixtures using Symfony service factories for encapsulated business logic and dependency injection. Factory services must be marked public in service configuration. ```php setEmail($email); $user->setRoles($roles ?: ['ROLE_USER']); $user->setPassword(password_hash('password123', PASSWORD_BCRYPT)); $user->setCreatedAt(new \DateTime()); return $user; } } ``` ```yaml # config/services.yaml services: App\Factory\UserFactory: public: true ``` -------------------------------- ### Register Custom Faker Provider with Autoconfiguration (YAML) Source: https://github.com/theofidry/alicebundle/blob/master/doc/faker-providers.md If autoconfiguration is enabled in your Symfony project and the provider extends `Faker\Provider\Base`, you can omit the explicit tag. Nelmio Alice will automatically discover and register it. This simplifies the service definition. ```yaml # config/services.yaml services: AppBundle\DataFixtures\Faker\Provider\FooProvider: ~ ``` -------------------------------- ### Declare Custom Faker Provider in PHP Source: https://github.com/theofidry/alicebundle/blob/master/doc/faker-providers.md This PHP code defines a custom Faker provider class. It should be placed in the appropriate bundle or application directory. This provider can then be registered as a service. ```php syntax. These parameters are available for fixture configuration but are not injected back into the application ParameterBag. ```yaml # fixtures/dummy.yaml AppBundle\Entity\Dummy: dummy_0: locale: <{framework.validation.enabled}> ``` -------------------------------- ### PHPUnit Test with RefreshDatabaseTrait (PHP) Source: https://context7.com/theofidry/alicebundle/llms.txt Shows how to use `RefreshDatabaseTrait` in PHPUnit tests. This trait loads fixtures once and wraps each test in a database transaction that automatically rolls back, optimizing performance for functional tests. ```php request('POST', '/api/products', [], [], ['CONTENT_TYPE' => 'application/json'], json_encode([ 'name' => 'New Product', 'price' => 99.99, 'description' => 'A great product' ]) ); $this->assertResponseIsSuccessful(); // Transaction rolls back automatically after test } public function testListProducts(): void { $client = static::createClient(); // New transaction starts for this test $client->request('GET', '/api/products'); $this->assertResponseIsSuccessful(); $data = json_decode($client->getResponse()->getContent(), true); $this->assertGreaterThan(0, count($data)); // Transaction rolls back automatically } } ``` -------------------------------- ### RecreateDatabaseTrait for SQLite In-Memory Database Testing Source: https://context7.com/theofidry/alicebundle/llms.txt Implements PHPUnit trait that automatically drops and recreates database schema before each test execution. Ideal for isolated in-memory SQLite databases. Dependencies include Hautelook AliceBundle and Symfony FrameworkBundle KernelTestCase. ```php getContainer() ->get('doctrine') ->getRepository(\App\Entity\Product::class); $expensiveProducts = $repository->findBy( [], ['price' => 'DESC'], 10 ); $this->assertNotEmpty($expensiveProducts); $this->assertGreaterThanOrEqual(100, $expensiveProducts[0]->getPrice()); } } ``` -------------------------------- ### Register Custom Loader in Symfony Services - YAML Source: https://github.com/theofidry/alicebundle/blob/master/doc/advanced-usage.md Configures the Symfony service container to decorate the fidry_alice_data_fixtures.loader.simple service with the custom loader. This intercepts objects after they are loaded from fixture files but before they are persisted to the database. ```yaml # config/services.yaml services: Acme\Alice\Loader\CustomOrderLoader: decorates: 'fidry_alice_data_fixtures.loader.simple' arguments: - '@Acme\Alice\Loader\CustomOrderLoader.inner' ``` -------------------------------- ### Panther Test with ReloadDatabaseTrait (PHP) Source: https://context7.com/theofidry/alicebundle/llms.txt Demonstrates the use of `ReloadDatabaseTrait` for Panther tests. This trait purges and reloads fixtures before each test, which is essential for tests running in separate processes like those executed by Panther. ```php request('GET', '/products'); $link = $crawler->selectLink('Buy Now')->first()->link(); $client->click($link); $client->waitFor('#checkout-form'); $this->assertSelectorTextContains('h1', 'Checkout'); // Database will be purged again for next test } } ``` -------------------------------- ### Use Custom Faker Provider in Fixtures (YAML) Source: https://github.com/theofidry/alicebundle/blob/master/doc/faker-providers.md This YAML snippet demonstrates how to use the registered custom Faker provider within a Nelmio Alice fixture file. The custom provider function `foo()` is called with an argument to generate the 'name' property for an entity. ```yaml # fixtures/orm/dummy.yml (Sf4) # or app/Resources/fixtures/orm/dummy.yml AppBundle\Entity\Dummy: brand{1..10}: name: ``` -------------------------------- ### Validate Fixtures with Validation Processor Source: https://context7.com/theofidry/alicebundle/llms.txt Implement a processor using Symfony's ValidatorInterface to enforce constraint validation before persistence. Collects all violations and throws a DomainException with detailed error messages including property path and constraint message for each violation found. ```php validator->validate($object); if ($violations->count() > 0) { $errors = []; foreach ($violations as $violation) { $errors[] = sprintf( '%s: %s', $violation->getPropertyPath(), $violation->getMessage() ); } throw new DomainException(sprintf( "Validation failed for fixture '%s':\n- %s", $id, implode("\n- ", $errors) )); } } public function postProcess(string $id, object $object): void { // No post-processing needed } } ``` -------------------------------- ### Access Symfony Container Parameters in Fixtures Source: https://context7.com/theofidry/alicebundle/llms.txt Integrates Symfony kernel parameters directly into fixture definitions for environment-aware configuration including locale, environment mode, and debug status. ```yaml # fixtures/config_aware.yaml App\Entity\Setting: setting_locale: key: 'default_locale' value: '<{kernel.default_locale}>' setting_env: key: 'environment' value: '<{kernel.environment}>' setting_debug: key: 'debug_mode' value: '<{kernel.debug}>' ``` -------------------------------- ### RefreshDatabaseTrait: Transactional Database Reset for PHPUnit Tests Source: https://github.com/theofidry/alicebundle/blob/master/README.md The RefreshDatabaseTrait enhances PHPUnit tests by wrapping each test in a database transaction. This ensures the database is reset to a known state after each test by rolling back the transaction, improving performance by loading fixtures only once. It's ideal for standard Symfony WebTestCase tests. ```php request('GET', '/my-news'); $form = $crawler->filter('#post-comment')->form(['new-comment' => 'Symfony is so cool!']); $client->submit($form); // At the end of this test, the transaction will be rolled back (even if the test fails) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.