### Install Nelmio Alice with Composer Source: https://github.com/nelmio/alice/blob/main/README.md Install the nelmio/alice package as a development dependency using Composer. ```bash composer require --dev nelmio/alice ``` -------------------------------- ### PHP Fixture Example Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md An example of a PHP file structure for defining entities and their properties, similar to the YAML format. ```php [ 'user{1..10}' => [ 'username' => '', 'fullname' => ' ', 'birthDate' => '', 'email' => '', 'favoriteNumber' => '50%? ', ], ], \Nelmio\Entity\Group::class => [ 'group1' => [ 'name' => 'Admins', 'owner' => '@user1', 'members' => 'x @user*', 'created' => '', 'updated' => '', ], ], ]; ``` -------------------------------- ### YAML Fixture Example Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md An example of a YAML file structure for defining entities and their properties with data generation rules. ```yaml Nelmio\Entity\User: user{1..10}: username: '' fullname: ' ' birthDate: '' email: '' favoriteNumber: '50%? ' Nelmio\Entity\Group: group1: name: Admins owner: '@user1' members: 'x @user*' created: '' updated: '' ``` -------------------------------- ### Custom Dummy Instantiator Implementation Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Implement a custom instantiator to control how fixtures are created. This example shows how to conditionally instantiate a specific class or delegate to a decorated instantiator. ```php instantiator = $decoratedInstantiator; } /** * @inheritdoc */ public function instantiate( FixtureInterface $fixture, ResolvedFixtureSet $fixtureSet, GenerationContext $context ): ResolvedFixtureSet { if ('App\Dummy' === $fixture->getClassName()) { $instance = new Dummy(); $objects = $fixtureSet->getObjects()->with( new SimpleObject( $fixture->getId(), $instance ) ); return $fixtureSet->withObjects($objects); } return $this->instantiator->instantiate($fixture, $fixtureSet, $context); } } ``` -------------------------------- ### YAML Identity Function with Variables and References Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Shows how the identity function can be used with existing variables and references to other fixtures. The example implies access to previously defined data. ```yaml # Example with variables and references stdClass: dummy1: foo: '<($current)>' ``` -------------------------------- ### Dynamic Parameters with Runtime Resolution Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Use dynamic parameters that resolve values at runtime based on context, such as the current entity being generated. This example uses `` to dynamically set usernames. ```yaml parameters: username_alice: Alice username_bob: Bob Nelmio\Entity\User: user_{alice, bob}: username: '<{username_}>' # Will be 'Alice' for 'user_alice' and 'Bob' for 'user_bob' ``` -------------------------------- ### Call Methods on Objects Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Call methods on objects during fixture creation by specifying the method name followed by an array of arguments. This allows for dynamic object manipulation and setup. ```yaml user: __construct: false username: "John Doe" methodName: [arg1, arg2] ``` -------------------------------- ### YAML Non-Template Fixture Extension Result (Alice 3.x) Source: https://github.com/nelmio/alice/blob/main/UPGRADE.md This example shows the output when attempting to extend a non-template fixture in Alice 3.x, illustrating how the derived fixture overrides the base. ```yaml dummy_A: #stdClass { +var: 'A' } dummy_B: #stdClass { +var1: 'foo' +var2: 'bar' } ``` -------------------------------- ### YAML Non-Template Fixture Extension Result (Alice 2.x) Source: https://github.com/nelmio/alice/blob/main/UPGRADE.md This example shows the output in Alice 2.x when extending a non-template fixture, contrasting with the behavior in Alice 3.x where the derived fixture overrides the base. ```yaml dummy_A: #stdClass { +var1: 'foo' +var2: 'bar' +var: 'A' } dummy_B: #stdClass { +var1: 'foo' +var2: 'bar' } ``` -------------------------------- ### Static Parameters in YAML Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Define static parameters in YAML to be used across multiple entity definitions. Parameters are enclosed in angle brackets `<>`. This example shows setting a domain name parameter. ```yaml parameters: ebay_domain_name: ebay.us Nelmio\Entity\Shop: shop{1..10}: domain: '<{ebay_domain_name}>' # or domain: '<($ebay_domain_name)>' ``` -------------------------------- ### Escaping @-signs for Literal Strings Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Escape `@`-signs with a backslash (`\@`) to create literal strings that start with `@`. This prevents them from being interpreted as references. ```yaml message: "\@username is not a valid username." ``` -------------------------------- ### Implement Custom Property Hydrator Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Create a custom PropertyHydrator by extending the default SymfonyPropertyAccessorHydrator to add specific logic for hydrating object properties. This example shows how to intercept and modify the 'key' property. ```php hydrator = $decoratedPropertyHydrator; } /** * @inheritdoc */ public function hydrate(ObjectInterface $object, Property $property, GenerationContext $context): ObjectInterface { if ('key' === $property->getName()) { $instance = $object->getInstance()->withKey($property->getValue()); return new SimpleObject($object->getId(), $instance); } return $this->hydrator->hydrate($object, $property, $context); } } ``` -------------------------------- ### Method Arguments in PHP Equivalent Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Illustrates the PHP equivalent of the YAML configuration for method arguments with parameters and references, showing how the structure translates. ```php [ 'parameters' => [ 'foo' => 'bar', ], Nelmio\Entity\Dummy::class => [ 'dummy{1..10}' => [ '__calls' => [ 'setLocation' => [ 'arg0' => '<{foo}>', 'arg1' => '$arg0', 500, '$3', ], ], ], ], ], ``` -------------------------------- ### Load Fixture from File using NativeLoader Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md Demonstrates how to use the NativeLoader to load data from a YAML or PHP fixture file. ```php $loader = new Nelmio\Alice\Loader\NativeLoader(); $objectSet = $loader->loadFile(__DIR__.'/fixtures.yml'); // or $objectSet = $loader->loadFile(__DIR__.'/fixtures.php'); ``` -------------------------------- ### Parameters in Constructor Arguments (PHP Equivalent) Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md This PHP array structure demonstrates how parameters and arguments are represented when using Nelmio Alice, mirroring the YAML configuration for constructor arguments. ```php [ 'parameters' => [ 'foo' => 'bar', ], Nelmio\Entity\Dummy::class => [ 'dummy{1..10}' => [ '__construct' => [ 'arg0' => '<{foo}>', 'arg1' => '$arg0', 500, '$3', ], ], ], ], ``` -------------------------------- ### Inject Parameters and Objects with NativeLoader Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md Illustrates how to inject custom parameters and existing objects into the data loading process. ```php $loader = new Nelmio\Alice\Loader\NativeLoader(); $objectSet = $loader->loadData( [ \Nelmio\Entity\Group::class => [ 'group1' => [ 'name' => '<{name}>', 'owner' => '@user1', ], ], ], ['name' => 'Admins'], ['user1' => $user1] ); ``` -------------------------------- ### Include Fixture Files Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Use the 'include' key to merge external fixture files. Content in the main file takes precedence over included files in case of duplicate keys. ```yaml include: - relative/path/to/file.yml - /absolute/path/to/another/file.yml Nelmio\Entity\User: user1 (extends user, extends user_young): name: '' lastname: '' city: '' ``` ```yaml Nelmio\Entity\User: user (template): username: '' age: '' ``` ```yaml Nelmio\Entity\User: user_young (template): age: '' ``` -------------------------------- ### Provide Basic Progress Information with Logger Option Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Configure a logger option, which can be a callable or a PSR-3 logger, to receive basic progress information during the loading process. This aids in monitoring and debugging. ```yaml loader.options: logger: '@my_logger' ``` -------------------------------- ### Load Multiple Files Successively with NativeLoader Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md Demonstrates loading multiple files sequentially, passing parameters and objects from one load to the next. ```php $loader = new Nelmio\Alice\Loader\NativeLoader(); $objectSet = $loader->loadFile(__DIR__.'/users.yml'); $objectSet = $loader->loadFile( __DIR__.'/groups.yml', $objectSet->getParameters(), $objectSet->getObjects() ); ``` -------------------------------- ### Use Identity Provider as Syntactic Sugar Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md The syntax `<($whatever)>` is a shorthand for ``, providing a more concise way to evaluate expressions. ```yaml Nelmio\Entity\User: user1: favoriteNumber: '' user2: username: '<($favoriteNumber * @user1->favoriteNumber)>' ``` -------------------------------- ### YAML Reference Syntax Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Shows various ways to reference other fixtures using the '@ref' notation, including wildcards, lists, and dynamic references using functions. ```yaml stdClass: dummy: reference: '@user' ``` -------------------------------- ### YAML Parameters for Class Instantiation Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Use parameters defined in YAML to dynamically set class properties. This allows for configuration-driven object creation. ```yaml parameters: foo: value Acme\ClassName: property: <{foo}> ``` -------------------------------- ### Method Arguments with Parameters and References Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Use parameters and references within method arguments. Parameters like '<{foo}>' are resolved from the 'parameters' section, and '$arg0' references previous arguments within the same call. ```yaml parameters: foo: bar Nelmio\Entity\Dummy: dummy{1..10}: __calls: - setLocation: arg0: '<{foo}>' arg1: '$arg0' # will be resolved info 'bar' 3: 500 # the numerical key here is just a random number as in YAML you cannot mix keys with array values 4: '$3' # `3` here refers to the *third* argument, i.e. 500 ``` -------------------------------- ### Load Data Array using NativeLoader Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md Shows how to load data directly from a PHP array using the NativeLoader. ```php $loader = new Nelmio\Alice\Loader\NativeLoader(); $objectSet = $loader->loadData([ \Nelmio\Entity\User::class => [ 'user{1..10}' => [ 'username' => '', 'fullname' => ' ', 'birthDate' => '', 'email' => '', 'favoriteNumber' => '50%? ', ], ], \Nelmio\Entity\Group::class => [ 'group1' => [ 'name' => 'Admins', 'owner' => '@user1', 'members' => 'x @user*', 'created' => '', 'updated' => '', ], ], ]); ``` -------------------------------- ### YAML Property Reference Syntax Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Illustrates how to reference properties of other objects using the '@ref->prop' syntax. This allows accessing specific attributes of referenced fixtures. ```yaml stdClass: dummy: propertyName: '@user1->name' ``` -------------------------------- ### YAML Parameters and Escaped Expressions Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Demonstrates how to use parameters and escaped expressions in YAML configuration. The escaped expression '\<{foo}>' is treated as a literal string. ```yaml parameters: foo: 'bar' stdClass: dummy: foo: '<{foo}>' escapedFoo: '\<{foo}>' ``` -------------------------------- ### PHP Class with addX Method (Deprecated) Source: https://github.com/nelmio/alice/blob/main/UPGRADE.md In Alice 3.x, `addX()` methods are no longer supported unless a corresponding `removeX()` method is defined. A setter for the collection must be defined if `removeX()` is not present. ```php class Recipe // no longer supported public function addServing(Serving $serving) { // … } // the setter must be defined public function setServings(iterable $servings) { // … } } ``` -------------------------------- ### YAML Array Syntax Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Illustrates the syntax for defining regular and string arrays. String arrays allow elements to be evaluated expressions, useful for referencing other data. ```yaml # String array example stdClass: dummy: items: '\[@user*->name]' ``` -------------------------------- ### Use Static Factory Method (Named Constructor) Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Call a static factory method instead of the constructor. Specify the method name and its arguments within the `__factory` key. Deprecated for `__construct` since 3.0.0. ```yaml Nelmio\Entity\User: user1: __factory: { create: [''] } ``` -------------------------------- ### YAML Fixture Extended Notations Source: https://github.com/nelmio/alice/blob/main/UPGRADE.md The fixture extended notations have been hardened in Alice 3.x. The correct syntax expected for extending fixtures is now more restrictive. ```yaml user{1..10} user_{alice, bob} admin (template) user {extends admin} ``` -------------------------------- ### YAML Optional Value Syntax Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Demonstrates the syntax for defining optional values using the D%? X: Y pattern. This allows for conditional assignment of values based on a probability D. ```yaml stdClass: dummy: optionalValue: '50%? foo: bar' ``` -------------------------------- ### Define Template Fixtures for Inheritance Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Use the '(template)' flag to define base fixtures that can be extended. Template instances are not persisted and serve as blueprints for other fixtures. ```yaml Nelmio\Entity\User: user_bare (template): username: '' user_full (template, extends user_bare): name: '' lastname: '' city: '' ``` -------------------------------- ### Reference All Fixtures with Wildcard Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Use a wildcard '*' to reference all fixtures matching a pattern. This is useful for creating related entities, like UserDetails for all generated Users. ```yaml Nelmio\Entity\User: user_{1..10}: username: '' Nelmio\Entity\UserDetail: userdetail_{@user_*}: # is going to generate `userdetail_user_1`, `userdetail_user_2`, ..., `userdetail_user_10` user: email: '' ``` -------------------------------- ### Generate Users with a List of Values Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Specifies a list of values for username and fullname, using the function to populate them. ```yaml Nelmio\Entity\User: user_{alice, bob}: username: '' fullname: '' birthDate: 1980-10-10 email: '\@example.org' favoriteNumber: 42 ``` -------------------------------- ### Fixture Inheritance with Template and Extends Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Define base fixtures using `(template)` and inherit from them using `(extends NAME)`. This promotes reusability and reduces redundancy in fixture definitions. ```yaml (template) User: username: "" (extends User) Admin: roles: [ROLE_ADMIN] ``` -------------------------------- ### Include Other YAML Fixture Files Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Incorporate definitions from other YAML fixture files using a top-level `include` array. This helps organize large fixture sets. ```yaml include: - ./users.yml - ./products.yml ``` -------------------------------- ### Pass references to providers Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md References can be passed as arguments to providers, allowing dynamic value generation based on other fixtures. ```yaml Nelmio\Entity\Group: group1: owner: '' group2: owner: 'owner, 200)>' ``` -------------------------------- ### Multi and Random References with Properties Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Combine multi-references (e.g., `5x`) with random references (`*`) and properties to create complex relationships between objects. This allows for generating multiple related objects with specific property targeting. ```yaml users: 5x @user* username: "" email: "" posts: 3x @post title: "" author: @users.0 ``` -------------------------------- ### Pass Constructor Arguments Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Provide arguments to the constructor of a class when creating an object. This ensures that objects are initialized with the necessary parameters. ```yaml user: __construct: ["John Doe", 30] username: "John Doe" age: 30 ``` -------------------------------- ### Specify Constructor Arguments Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Define mandatory constructor arguments for an entity. Ensure the arguments are correctly formatted and available. ```yaml Nelmio\Entity\User: user1: __construct: [''] ``` -------------------------------- ### Use Identity Provider for Expressions Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md The `` provider evaluates its argument and returns the result, allowing for arithmetic operations and PHP expressions. It also supports references and variables. ```yaml Nelmio\Entity\User: user1: favoriteNumber: '' user2: username: 'favoriteNumber)>' ``` -------------------------------- ### YAML Function Calls and Nested Functions Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Shows how to use PHP functions like strtolower and implode within the expression language. Nested function calls are supported, and escaped function syntax '\' is used for literal strings. ```yaml stdClass: dummy: functionValue: '' nestedFunctionValue: ']))>)> \ ``` -------------------------------- ### Use Factory Method from Another Class Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Call a static factory method from a different class by providing the fully qualified class name. Ensure the factory method and its arguments are correctly specified. ```yaml Nelmio\Entity\User: user1: __factory: { 'Nelmio\User\UserFactory::create': [''] } ``` -------------------------------- ### Define User and Group Fixtures in YAML Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md This YAML structure defines multiple user and group objects with their respective properties. It's a static way to declare fixtures. ```yaml Nelmio\Entity\User: user0: username: bob fullname: Bob birthDate: 1980-10-10 email: bob@example.org favoriteNumber: 42 user1: username: alice fullname: Alice birthDate: 1978-07-12 email: alice@example.org favoriteNumber: 27 Nelmio\Entity\Group: group1: name: Admins ``` -------------------------------- ### Generate Users with Sequential IDs Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Defines a range to generate ten user fixtures with IDs from user1 to user10. ```yaml Nelmio\Entity\User: user{1..10}: username: bob fullname: Bob birthDate: 1980-10-10 email: bob@example.org favoriteNumber: 42 ``` -------------------------------- ### Create Value Objects with (local) Flag Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Use the `(local)` flag for classes and objects to create value objects that should not be persisted. This is useful for temporary or non-persistent data structures. ```yaml address: (local) App\Entity\Address street: "123 Main St" ``` -------------------------------- ### Use Identity Provider with PHP Expressions Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md The `` provider can evaluate arbitrary PHP expressions, including object instantiation. ```yaml Nelmio\Entity\User: user1: birthDate: '' ``` -------------------------------- ### Workaround for Dynamic Parameters in Alice 3.x Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md In Alice 3.x, parameters are not evaluated dynamically. Use this workaround by defining parameters under `stdClass` to achieve a similar effect to older versions, though be mindful of potential unintended side effects like shared IDs. ```yaml stdClass: parameters: shop_id: '' Nelmio\Entity\Shop: shop{1..10}: id: '@parameters->shop_id' ``` -------------------------------- ### Define User Fixtures in PHP Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md This PHP array structure defines user fixtures, similar to the YAML format but using PHP syntax. It's useful for defining fixtures programmatically. ```php [ 'user1' => [ 'username' => 'bob', 'fullname' => 'Bob', ], 'user2' => [ 'username' => 'alice', 'fullname' => 'Alice', ], ], ]; ``` -------------------------------- ### YAML Identity Function for Simple Evaluation Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Illustrates the use of the identity function '<(X)>' for evaluating PHP expressions. This is a shortcut for and can be used for simple type casting or evaluation. ```yaml # Simple example stdClass: dummy: foo: '<(strtolower("BAR"))>' ``` -------------------------------- ### Load Entities from a File Source: https://github.com/nelmio/alice/blob/main/README.md Use the NativeLoader to load entity data from a YAML file and obtain an object set. ```php $loader = new Nelmio\Alice\Loader\NativeLoader(); $objectSet = $loader->loadFile(__DIR__.'/fixtures.yml'); ``` -------------------------------- ### Reference Object Properties Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Reference an object's properties using the `@reference->property` syntax. This allows you to link objects and reuse existing data within your fixtures. ```yaml user: username: "John Doe" profile: user: @user username_from_profile: @user->username ``` -------------------------------- ### Reference Properties with Variables Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Reference other properties using PHP's $variable notation to ensure data consistency, such as making sure an update date is after a creation date. ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group1: name: Admins owner: '@user1' members: 'x @user*' created: '' updated: '' ``` -------------------------------- ### Create Multiple Objects with Enums Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Use enums to create multiple objects with named variations, similar to fixture ranges but with explicit names. This allows for structured generation of related objects. ```yaml user_type: - admin - editor - viewer User: '@user_type' ``` -------------------------------- ### Call Methods During Fixture Generation Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Call methods on entities during fixture generation by specifying the method name and an array of arguments. This is an alternative to setting properties directly. ```yaml Nelmio\Entity\User: user1: username: '' __calls: - setLocation: [40.689269, -74.044737] ``` -------------------------------- ### Reference with fixture ranges Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md Use '' within fixture ranges to link objects to corresponding entities, like assigning owners to groups. ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group{1..10}: owner: '@user' ``` -------------------------------- ### YAML Non-Template Fixture Extension (Deprecated) Source: https://github.com/nelmio/alice/blob/main/UPGRADE.md It is no longer possible to extend from a non-template fixture in Alice 3.x. Attempting to do so will result in the derived fixture definition completely overriding the base fixture. ```yaml stdClass: dummy_{A, B}: var1: 'foo' var2: 'bar' dummy_A: # This fixture definition will completely override the 'dummy_A' derived from 'dummy_{A, B}' var: 'A' ``` -------------------------------- ### Evaluate PHP Expressions with Identity Faker Provider Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Use the `` (aliased as `<()>`) faker provider to evaluate PHP expressions directly within your fixture definitions. This allows for dynamic value generation based on arbitrary logic. ```yaml user: name: age: <(20 + 10)> ``` -------------------------------- ### Define User Fixture in JSON Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md This JSON structure defines a user fixture with a specific property. It offers an alternative to YAML and PHP for fixture definition. ```json { "Nelmio\\Alice\\support\\models\\User": { "user0": { "fullname": "John Doe" } } } ``` -------------------------------- ### Configure NelmioAliceBundle in Symfony Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md Customize NelmioAliceBundle settings in your Symfony configuration file. Options include setting the default locale for Faker, a seed for consistent data generation, blacklisting PHP functions to use Faker formatters, and setting recursion limits for value resolution. ```yaml # app/config/config_dev.yml nelmio_alice: locale: 'en_US' # Default locale for the Faker Generator seed: 1 # Value used to make sure Faker generates data consistently across # runs, set to null to disable. functions_blacklist: # Some Faker formatter may have the same name as PHP - 'current' # native functions. PHP functions have the priority, # so if you want to use a Faker formatter instead, # blacklist this function here loading_limit: 5 # Alice may do some recursion to resolve certain values. # This parameter defines a limit which will stop the # resolution once reached. max_unique_values_retry: 150 # Maximum number of time Alice can try to # generate a unique value before stopping and # failing. ``` -------------------------------- ### Generate Users with Gaps in IDs Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Uses a range with a step argument to generate users with IDs user1, user3, user5, user7, and user9. ```yaml Nelmio\Entity\User: user{1..10, 2}: username: bob fullname: Bob birthDate: 1980-10-10 email: bob@example.org favoriteNumber: 42 ``` -------------------------------- ### Parameters in Constructor Arguments Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Parameters can be used within constructor arguments. Arguments can also be referenced as parameters within the same scope. Note the use of numerical keys in YAML to represent array indices. ```yaml parameters: foo: bar Nelmio\Entity\Dummy: dummy{1..10}: __construct: arg0: '<{foo}>' arg1: '$arg0' # will be resolved info 'bar' 3: 500 # the numerical key here is just a random number as in YAML you cannot mix keys with array values 4: '$3' # `3` here refers to the *third* argument, i.e. 500 ``` -------------------------------- ### Handle Optional Data with Probability Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Make fields optional by using the `50%? value : empty value` notation. This allows for probabilistic assignment of values, similar to a ternary operator. If `null` is acceptable, the empty value can be omitted. ```yaml Nelmio\Entity\User: user{1..10}: username: '' fullname: ' ' birthDate: '' email: '' favoriteNumber: '50%? ' ``` -------------------------------- ### Method Arguments with Flags Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Specify flags for method arguments, such as 'unique', to control how arguments are generated or used. This allows for more dynamic argument assignment. ```yaml Nelmio\Entity\User: user{1..10}: username: '' __calls: - setLocation: 0 (unique): '' 1 (unique): '' ``` -------------------------------- ### Define multiple references Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md Use an array of references for a fixed set of related objects, or specify a count with 'Nx @objectName*' for a variable number. ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group1: name: Admins owner: '@user1' members: ['@user2', '@user3'] ``` ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group1: name: Admins owner: '@user1' members: '5x @user*' ``` ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group{1..10}: members: '@user{1..10}' ``` -------------------------------- ### Reference object property or method Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md Access properties or call methods on referenced objects using '@objectName->property' or '@objectName->method()'. ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group1: name: Admins owner: '@user1->username' ``` -------------------------------- ### Perform Type Casting with Faker Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md Use built-in PHP functions like `intval` and `boolval` via Faker syntax for type casting. It is recommended to use PHP internals directly. ```yaml stdClass: dummy{1..2}: intval: boolval: ``` -------------------------------- ### Extend Base Fixtures with '(extends)' Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Use the '(extends)' flag to inherit properties from a template fixture. This allows for defining common structures in a base template and specializing them in derived fixtures. ```yaml Nelmio\Entity\User: user (template): username: '' age: '' user1 (extends user): name: '' lastname: '' city: '' age: '' ``` -------------------------------- ### Generate Randomized User Data with Faker Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md Use Faker data providers within YAML to generate randomized data for entities. Arguments can be passed to Faker providers just like function calls. ```yaml Nelmio\Entity\User: user{1..10}: username: '' fullname: ' ' birthDate: '' email: '' favoriteNumber: '' ``` -------------------------------- ### Self reference Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md Use '@self' to refer to the current fixture instance being defined. -------------------------------- ### References within Faker Provider Calls Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Reference other objects or their properties within faker provider calls using `@-references`. This allows for dynamic data linking between fixtures. ```yaml user: username: "" friend: ``` -------------------------------- ### Reference a specific object Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md Use '@objectName' to reference a specific fixture instance. Ensure fixture names adhere to allowed characters. ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group1: name: Admins owner: '@user1' ``` -------------------------------- ### Composite Parameters in YAML Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Combine multiple parameters into a single composite parameter. This allows for more complex string constructions by referencing other defined parameters. ```yaml parameters: key1: NaN key2: Bat composite: '<{key1}> <{key2}>!' Nelmio\Entity\User: user0: username: '<{composite}>' # 'NaN Bat!' ``` -------------------------------- ### Optional Method Calls with Probability Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Make method calls optional by specifying a probability. The method will only be called if the random chance meets the specified percentage. ```yaml Nelmio\Entity\User: user1: username: '' __calls: - setLocation (80%?): [40.689269, -74.044737] ``` -------------------------------- ### Reference a random object Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md Use a wildcard '*' with '@objectName*' to reference any object matching the pattern, or '' for random selection by ID. ```yaml Nelmio\Entity\User: # ... Nelmio\Entity\Group: group1: name: Admins owner: '@user*' ``` ```yaml Nelmio\Entity\Group: group1: owner: '@user' ``` -------------------------------- ### Pass References to Faker Providers Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Pass references to other objects or values as arguments to faker provider calls. This enables dynamic data generation based on existing entities. ```yaml user: username: "" friend: ``` -------------------------------- ### Register Custom Faker Provider in Symfony Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md Configuration for registering a custom Faker provider in Symfony using service tags. This ensures Alice can utilize the custom provider for data generation. ```yaml # config/services.yaml services: _defaults: autowire: true autoconfigure: true App\Faker\Provider\JobProvider: ~ ``` ```yaml # config/services.yaml services: App\Faker\Provider\JobProvider: arguments: - '@Faker\Generator' tags: [ { name: nelmio_alice.faker.provider } ] ``` -------------------------------- ### Custom Job Faker Provider Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md Defines a custom Faker provider class 'JobProvider' that generates random job titles and abbreviations. This class extends Faker's Base provider and can be registered with Alice. ```php [ 'Audience Recognition', 'Big Data', 'Bitcoin', '...', 'Video Experience', 'Wearables', 'Webinar', ], 'lastname' => [ 'Advocate', 'Amplifier', 'Architect', '...', 'Warlock', 'Watchman', 'Wizard', ], 'fullname' => [ 'Conductor of Datafication', 'Crowd-Funder-in-Residence', 'Quantified-Self-in-Residence', '...', 'Tech-Svengali-in-Residence', 'Tech-Wizard-in-Residence', 'Thought-Leader-in-Residence', ], ]; /** * Sources: {@link http://sos.uhrs.indiana.edu/Job_Code_Title_Abbreviation_List.htm} * * @var array List of job abbreviations. */ const ABBREVIATION_PROVIDER = [ 'ABATE', 'ACAD', 'ACCT', '...', 'WCTR', 'WSTRN', 'WKR', ]; /** * @return string Random job title. */ public function jobTitle() { $names = [ sprintf( '%s %s', self::randomElement(self::TITLE_PROVIDER['firstname']), self::randomElement(self::TITLE_PROVIDER['lastname']) ), self::randomElement(self::TITLE_PROVIDER['fullname']), ]; return self::randomElement($names); } /** * @return string Random job abbreviation title */ public function jobAbbreviation() { return self::randomElement(self::ABBREVIATION_PROVIDER); } } ``` -------------------------------- ### Custom Setter for All Properties Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Define a special `__set` property to specify a custom setter method that will be used for all properties of a class. This allows for centralized property manipulation. ```yaml Acme\ClassName: __set: "customSetter" property1: value1 property2: value2 ``` -------------------------------- ### Create Objects with Non-Numeric IDs Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Fetch objects by ID even when the IDs are not numeric. This provides flexibility when dealing with various identifier types. ```yaml product: Product id: "abc-123" name: "Example Product" ``` -------------------------------- ### Decorate Property Accessor with Symfony DI Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Use Symfony's DI to decorate the default property accessor, allowing for custom logic like reflection-based property setting. ```yaml services: app.fixtures.reflection_property_accessor: class: Nelmio\Alice\PropertyAccess\ReflectionPropertyAccessor public: false decorates: nelmio_alice.property_accessor decoration_priority: -10 arguments: ['@app.fixtures.reflection_property_accessor.inner'] ``` -------------------------------- ### Modify Objects Before Persistence with ProcessorInterface Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Implement `ProcessorInterface` to modify objects before they are persisted. This allows for custom logic to be applied to objects during the loading process. ```php namespace App\Processor; use Nelmio\Alice\ProcessorInterface; use stdClass; class MyProcessor implements ProcessorInterface { public function process(std::object $object): void { // Modify the object here } } ``` -------------------------------- ### Register NelmioAliceBundle in Symfony Kernel Source: https://github.com/nelmio/alice/blob/main/doc/getting-started.md Add the NelmioAliceBundle to your application's kernel to enable its features. This is typically done within the `registerBundles` method, conditional on the environment being 'dev' or 'test'. ```php getEnvironment(), ['dev', 'test'])) { //... $bundles[] = new Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle(); } return $bundles; } ``` -------------------------------- ### Reference a Specific Fixture Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Reference a single, specifically named fixture. The `` function will hold the value of the referenced fixture. ```yaml Nelmio\Entity\User: user_bob: username: 'bob' Nelmio\Entity\UserDetail: userdetail_{@user_bob}: user: # holds `@user_bob` email: 'bob@test.de' ``` -------------------------------- ### YAML Custom Method Call Syntax Source: https://github.com/nelmio/alice/blob/main/UPGRADE.md Calls to custom methods (not setters) must not be placed under the `__calls` key in YAML fixture definitions. This syntax is no longer supported. ```yaml User: user_{A, B}: __calls: - markAsInvited: [] ``` -------------------------------- ### Instantiate Object Without Constructor Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Use `__construct: false` to instantiate an object without executing its constructor. This is useful when constructor logic is not needed for fixture creation. ```yaml Nelmio\Entity\User: user1: __construct: false ``` -------------------------------- ### Declare Unique Constructor Argument Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Specify the `(unique)` flag for a constructor argument to ensure that the values passed for this argument are unique across generated entities. This is applied by appending `(unique)` to the argument's index or name. ```yaml Nelmio\Entity\User: user{1..10}: __construct: 0 (unique): '' ``` -------------------------------- ### YAML Identity Function with Current Value Source: https://github.com/nelmio/alice/blob/main/doc/advanced-guide.md Demonstrates using the identity function '<($current)>' to access the current value within a loop or sequence. This is useful when generating sequences of data. ```yaml # Example with current stdClass: dummy{1..2}: foo: '<($current)>' ``` -------------------------------- ### Multiple Inheritance and Value Overriding Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Fixtures can extend multiple templates. Properties from later 'extends' declarations override those from earlier ones. Explicitly defined properties in the fixture itself always take precedence. ```yaml Nelmio\Entity\User: user (template): username: '' age: '' user_young (template): age: '' user1 (extends user, extends user_young): username: user1 name: '' lastname: '' city: '' ``` -------------------------------- ### Use Current Value in Collections Source: https://github.com/nelmio/alice/blob/main/doc/customizing-data-generation.md The `` faker provider returns the current value within a collection context. It is equivalent to using the '$current' variable. ```yaml stdClass: dummy{1..2}: currentValue: # is equivalent to '$current' ``` -------------------------------- ### Self-Reference with @self Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Use `@self` to reference the current object being created, similar to `$this` in PHP. This is useful for setting properties that refer to the object itself. ```yaml user: username: "" manager: @self ``` -------------------------------- ### Bypass Constructors Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Prevent the constructor from being called when creating an object by setting `__construct: false`. This is useful when you want to set properties directly without constructor logic. ```yaml user: __construct: false username: "John Doe" ``` -------------------------------- ### Reference object ID Source: https://github.com/nelmio/alice/blob/main/doc/relations-handling.md Reference an object's ID using '@objectName->id'. This is useful when IDs are generated upon creation. ```yaml # fixture_group.yml Nelmio\Entity\Group: group1: name: Admins owner: '@user1->id' ``` -------------------------------- ### Mark Fields as Unique for Random Values Source: https://github.com/nelmio/alice/blob/main/CHANGELOG.md Mark fields as unique to ensure that random values generated for them are distinct. This is useful for fields like usernames or email addresses. ```yaml user: username: ")" ``` -------------------------------- ### Declare Unique Property in Entity Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md Use the `(unique)` flag after the property name to ensure generated values for this property are unique across all instances of the entity within the fixture set. This is useful for fields like usernames or email addresses. ```yaml Nelmio\Entity\User: user{1..10}: username (unique): '' ``` -------------------------------- ### Access Nested Object Properties Source: https://github.com/nelmio/alice/blob/main/doc/fixtures-refactoring.md Access properties of nested objects using '@self->propertyName.nestedProperty' notation. This allows referencing data from related objects within the same fixture. ```yaml Nelmio\Entity\User: user1: # ... created: '' Nelmio\Entity\Group: group1: # ... created_by: '@user1' created: 'created_by.created, "now")>' updated: '' ``` -------------------------------- ### Unique Constraint on Array Property Source: https://github.com/nelmio/alice/blob/main/doc/complete-reference.md When applied to an array property, the `(unique)` flag ensures that the *values within* the array are unique for each entity. It does not prevent duplicate array properties across different entities if the array content is identical. ```yaml Nelmio\Entity\User: friends{1..2}: username (unique): '' user{1..2}: friends (unique): '@friends*' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.