Repository: makeabledk/laravel-factory-enhanced Branch: master Commit: 7293219b1378 Files: 32 Total size: 78.5 KB Directory structure: gitextract_r60zc_y7/ ├── .github/ │ └── workflows/ │ └── test.yml ├── .gitignore ├── .styleci.yml ├── CONTRIBUTING.md ├── LICENSE.md ├── composer.json ├── phpunit.xml ├── readme.md ├── src/ │ ├── ArgumentParser.php │ ├── Concerns/ │ │ ├── EnhancedCount.php │ │ ├── EnhancedRelationships.php │ │ └── EnhancedSequence.php │ ├── Factory.php │ ├── FactoryServiceProvider.php │ ├── HasFactory.php │ ├── RelationRequest.php │ └── helpers.php └── tests/ ├── Feature/ │ ├── FactoryTest.php │ ├── RelationsTest.php │ └── StateTest.php ├── Stubs/ │ ├── Company.php │ ├── Customer.php │ ├── Department.php │ ├── HasFactory.php │ ├── Image.php │ └── User.php ├── TestCase.php └── database/ ├── factories/ │ ├── CompanyFactory.php │ ├── CustomerFactory.php │ ├── DepartmentFactory.php │ └── UserFactory.php └── migrations/ └── 2018_04_27_000000_create_test_tables.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/test.yml ================================================ name: Run tests on: push: pull_request: jobs: test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: php: [ 8.1, 8.2, 8.3, 8.4, 8.5 ] laravel: [ 10.*, 11.*, 12.*, 13.* ] dependency-version: [ prefer-lowest, prefer-stable ] exclude: - php: 8.1 laravel: 11.* - php: 8.1 laravel: 12.* - php: 8.1 laravel: 13.* - php: 8.2 laravel: 13.* name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} steps: - name: Checkout code uses: actions/checkout@v1 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick coverage: none - name: Install dependencies run: | composer require "laravel/framework:${{ matrix.laravel }}" --no-interaction --no-update composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction - name: Execute tests run: vendor/bin/phpunit ================================================ FILE: .gitignore ================================================ build composer.phar composer.lock vendor .php_cs.cache .phpunit.result.cache .phpunit.cache ================================================ FILE: .styleci.yml ================================================ preset: laravel ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing We accept contributions via Pull Requests on [Github](https://github.com/makeable/laravel-production-seeding). ## Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - see **fixing styles** section - **Add tests** - Your patch must include tests of the added functionality. See **Running tests** section - **Document any change in behaviour** - Make sure the `README.md` and `CHANGELOG.md` are kept up-to-date. - **Create feature branches** - Don't ask us to pull from your master branch. ## Fixing styles ``` bash $ composer style ``` ## Running Tests ``` bash $ composer test ``` **Happy coding**! ================================================ FILE: LICENSE.md ================================================ Attribution-ShareAlike 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ================================================ FILE: composer.json ================================================ { "name": "makeabledk/laravel-factory-enhanced", "license": "CC-BY-SA-4.0", "autoload": { "psr-4": { "Makeable\\LaravelFactory\\": "src/" }, "files": [ "src/helpers.php" ] }, "require": { "php": "^8.1", "illuminate/database": "^10.0|^11.0|^12.0|^13.0", "illuminate/support": "^10.0|^11.0|^12.0|^13.0" }, "require-dev": { "fakerphp/faker": "^1.21", "laravel/laravel": "^10.0|^11.0|^12.0|^13.0", "mockery/mockery": "^1.5", "phpunit/phpunit": "^10.5.17|^11.0" }, "autoload-dev": { "psr-4": { "Makeable\\LaravelFactory\\Tests\\": "tests/", "Makeable\\LaravelFactory\\Tests\\Database\\Factories\\": "tests/database/factories" } }, "extra": { "laravel": { "providers": [ "Makeable\\LaravelFactory\\FactoryServiceProvider" ] } }, "config": { "sort-packages": true }, "scripts": { "test": "./vendor/bin/phpunit" }, "minimum-stability": "dev", "prefer-stable": true } ================================================ FILE: phpunit.xml ================================================ ./tests/ src/ ================================================ FILE: readme.md ================================================ ![Laravel Factory Enhanced - Supercharge your tests](https://raw.githubusercontent.com/makeabledk/laravel-factory-enhanced/master/banner-1.png) # Laravel Factory Enhanced 🔥 [![Latest Version on Packagist](https://img.shields.io/packagist/v/makeabledk/laravel-factory-enhanced.svg)](https://packagist.org/packages/makeabledk/laravel-factory-enhanced) [![Build Status](https://img.shields.io/github/workflow/status/makeabledk/laravel-factory-enhanced/Run%20tests?label=Tests)](https://github.com/makeabledk/laravel-factory-enhanced/actions) [![StyleCI](https://styleci.io/repos/117680722/shield?branch=master)](https://styleci.io/repos/117680722) Bring the magic of eloquent relationships into the Laravel Factory. Traditionally if you wanted to factory a team with some users, you'd have to manually create the individual team and users and then tie them together afterwards. This can easily lead to very verbose tests. **Laravel 7.x and earlier** ```php $team = factory(Team::class)->create(); $users = factory(User::class)->times(2)->create(); foreach ($users as $user) { factory(TeamMember::class)->create([ 'team_id' => $team, 'user_id' => $user, 'role' => 'admin' ]); } ``` **Laravel 8.0 and later** ```php $team = Team::factory() ->hasAttached( User::factory()->count(2), ['role' => 'admin'] ) ->create(); ``` **Laravel Factory Enhanced** ```php $team = Team::factory() ->with(2, 'users', ['pivot.role' => 'admin']) ->create(); ``` ## Installation You may install the package via composer ```bash composer require makeabledk/laravel-factory-enhanced ``` ### Versions **Laravel 8+ class based factories** Version 4 and later of this package is compatible with the new class-based syntax introduced with Laravel 8. **Pre-Laravel 7 factories** Version 3 and earlier of this package is compatible with the legacy `$factory->define()` syntax. Please find docs here [v3 documentation](https://github.com/makeabledk/laravel-factory-enhanced/tree/3.x): ## Upgrade guide to v4 The majority of the refactoring needed to upgrade to v4 of this package, lies in rewriting factories to be compatible with Laravel class-based factories. If you use [Laravel Shift](https://laravelshift.com) when upgrading to Laravel 8, a lot of this work will be automated, and you will be well on you way. ### Rewriting to class based factories Please use [Laravel Shift](https://laravelshift.com) for upgrading Laravel versions, or refer to the [official documentation](https://laravel.com/docs/8.x/database-testing) on how to write factories using the class-based approach. ### Applying states Replace all occurrences of `->state('some-state')` with `->someState()` in your test suite. ### Presets The concept of presets which was introduced by this package may now simply be rewritten to states. As such, replace all occurrences of `->preset('some-preset')` with `->somePreset()` in your test suite. ### Times method Replace all occurrences of `->times(x)` with `->count(x)` in your test suite. ### Factory helper syntax This change is completely optional. If you wish, you may change all occurrence of `factory(SomeModel::class)` to `SomeModel::factory()` in your test suite. _If you choose to do so_, remember to add `use \Makeable\LaravelFactory\Factory;` to all models. ### Other breaking changes The `odds()` method has been removed from the Factory instance. ## Usage Once the package is installed, your factories should extend `Makeable\LaravelFactory\Factory` rather than the native Laravel `Factory` class. Additionally, please make sure to use the corresponding `Makeable\LaravelFactory\HasFactory` trait on your models. For example: **app/Models/User.php** ```php with(3, 'sites')->create(); ``` Note that you may still use any native functionality that you are used to, such as states and attributes: ```php Server::factory()->online()->with(3, 'sites')->create([ 'name' => 'production-1' ]); ``` ### Multiple relationships You are free to specify multiple relationships on the same factory. Given our previous `Server` model has another relationship called `team` (belongs-to), you may do: ```php Server::factory() ->with('team') ->with(3, 'sites') ->create(); ``` Now you would have `1 team` that has `1 server` which has `3 sites`. ### Nested relationships Moving on to the more advanced use-cases, you may also do nested relationships. For instance we could rewrite our example from before using nesting: ```php Team::factory() ->with(3, 'servers.sites') ->create(); ``` Please note that the count '3' applies to *the final relationship*, in this case `sites`. If you are wanting 2 servers each of which has 3 sites, you may write it as following: ```php Team::factory() ->with(2, 'servers') ->with(3, 'servers.sites') ->create(); ``` ### States in relationships Just as you may specify pre-defined states on the factoring model ([see official documentation](https://laravel.com/docs/master/database-testing#factory-states)), you may also apply the very same states on the relation. ```php Team::factory() ->with(2, 'online', 'servers') ->create(); ``` You may finding yourself wanting a relationship in multiple states. In this case you may use the `andWith()` method. ```php Team::factory() ->with(2, 'online', 'servers') ->andWith(1, 'offline', 'servers') ->create(); ``` By using the `andWith` we will create a 'clean cut', so that no further calls to `with` can interfere with relations specified prior to the `andWith`. In the above example any further nesting of relations will apply to the 'offline' server. ```php Team::factory() ->with(2, 'online', 'servers') ->andWith(1, 'offline', 'servers') ->with(3, 'servers.sites') ->create(); ``` The above example will create 1x team that has - 2x online servers - 1x offline servers with 3 sites ### Filling attributes in relationships You may fill attributes on a relationship by passing them as an argument to the `with()` method. ```php factory(Team::class) ->with(2, 'servers', ['name' => 'laravel.com']) ->create(); ``` If the relation is a belongs-to-many relationship, you may also fill attributes on the pivot model by prefixing the attribute name with `pivot.`. ```php Team::factory() ->with(2, 'users', ['pivot.role' => 'admin']) ->create(); ``` ### Using apply() All of the above examples of how you might configure a relationship using the `with()` method, can also be applied on the base model using the `apply()` method. For example: ```php Server::factory() ->apply(2, 'online', ['name' => 'laravel.com']) ->with(3, 'mysql', 'databases') ->create(); ``` This would create 2 online servers each with 3 mysql databases. In fact, by using the `HasFactory` trait from this package, you can even pass these arguments to the `::factory()` method itself: ```php Server::factory(2, 'online', ['name' => 'laravel.com']) ->with(3, 'mysql', 'databases') ->create(); ``` ### Using closures for customization In addition to passing *count* and *state* directly into the `with` function, you may also pass a closure that will receive the `FactoryBuilder` instance directly. In the closure you can do everything you are used to on the `FactoryBuilder` - including nesting further relationships should you wish to. ```php Team::factory() ->with('servers', fn (ServerFactory $servers) => $servers ->count(2) ->active() ->with(3, 'sites') ) ->create(); ``` ### Factoring models with no defined factory Traditionally trying to use `Model::factory()` on a model with no defined factory would throw an exception. Not anymore! After installing this package, you are completely free to use the static `Model::factory()` method on any Eloquent model that uses the `Makeable\LaravelFactory\HasFactory` trait. Furthermore, this package brings back the good old `factory(Model::class)` helper function which you may use on any model, whether or not the model has a defined factory or uses the `HasFactory` trait. **Example** ```php factory(2, Server::class)->with(1, 'sites')->create(); ``` ## Available methods These are the provided methods on the `Factory` instance in addition to the core methods. - apply - fill - fillPivot (only applicable on BelongsToMany - pipe - tap - with - andWith ## Testing You can run the tests with: ```bash composer test ``` ## Contributing We are happy to receive pull requests for additional functionality. Please see [CONTRIBUTING](CONTRIBUTING.md) for details. ## Credits - [Rasmus Christoffer Nielsen](https://github.com/rasmuscnielsen) - [All Contributors](../../contributors) ## License Attribution-ShareAlike 4.0 International. Please see [License File](LICENSE.md) for more information. ================================================ FILE: src/ArgumentParser.php ================================================ reduce(function (Factory $factory, $arg) { if (is_null($arg)) { return $factory; } if (is_numeric($arg)) { return $factory->count($arg); } if (is_array($arg) && ! isset($arg[0])) { return static::fill($factory, $arg); } if ($arg instanceof Model) { return $factory->for($arg); } if (is_callable($arg) && ! is_string($arg)) { return $factory->tap($arg); } if (is_string($arg) || (is_array($arg) && is_string($arg[0]))) { return collect($arg)->reduce(fn ($factory, $method) => call_user_func([$factory, $method]), $factory); } throw new \InvalidArgumentException('Unexpected argument: '.$arg); }, $factory); } protected static function fill(Factory $factory, array $attributes): Factory { $pivotAttributes = []; foreach ($attributes as $attribute => $value) { if (Str::startsWith($attribute, 'pivot.')) { $pivotAttributes[Str::after($attribute, 'pivot.')] = $value; Arr::forget($attributes, $attribute); } } return $factory ->fill($attributes) ->fillPivot($pivotAttributes); } } ================================================ FILE: src/Concerns/EnhancedCount.php ================================================ newInstance(['count' => $count]); } public function make($attributes = [], ?Model $parent = null) { return $this->withCalculatedCount(fn () => parent::make($attributes, $parent)); } public function raw($attributes = [], ?Model $parent = null) { return $this->withCalculatedCount(fn () => parent::raw($attributes, $parent)); } protected function withCalculatedCount(\Closure $callback) { $backup = $this->count; if (is_callable($this->count)) { $this->count = call_user_func($this->count); } return tap($callback(), fn () => $this->count = $backup); } } ================================================ FILE: src/Concerns/EnhancedRelationships.php ================================================ loadRelation( new RelationRequest($this->model, $this->currentBatch, $args) ); } /** * Build relations in a new batch. Multiple batches can be * created on the same relation, so that ie. multiple * has-many relations can be configured differently. * * @param mixed ...$args * @return static */ public function andWith(...$args): self { return $this->newBatch()->with(...$args); } /** * Load a RelationRequest onto current FactoryBuilder. * * @param \Makeable\LaravelFactory\RelationRequest $request * @return \Makeable\LaravelFactory\Concerns\EnhancedRelationships */ public function loadRelation(RelationRequest $request): self { $related = $this->pushRelatedFactory($request); // Recursively create factories until no further nesting. if ($request->hasNesting()) { $this->pushRelatedFactory($request, $related->loadRelation($request->createNestedRequest())); return $this; } // Apply the request onto the final relationship factory. $this->pushRelatedFactory($request, $related->apply(...$request->arguments)); return $this; } protected function pushRelatedFactory(RelationRequest $request, ?self $factory = null): Factory { $path = implode('.', [ $request->loadMethod(), $request->getRelationName(), $request->batch, ]); $factory = $factory ?? data_get($this->relations, $path) ?? static::factoryForModel($request->getRelatedClass()); return tap($factory, fn () => data_set($this->relations, $path, $factory)); } protected function withRelationsApplied(Closure $callback) { $self = $this; foreach ($this->relations as $method => $relations) { foreach ($relations as $relationship => $factories) { foreach ($factories as $batch => $factory) { if ($factory->count === 0) { continue; } if ($method === 'for') { $factory = $factory->count(null); } if ($this->connection) { $factory = $factory->connection($this->connection); } $args = $method === RelationRequest::BelongsToMany ? [$factory, $factory->mergedPivotAttributes(), $relationship] : [$factory, $relationship]; $self = $self->$method(...$args); } } } return call_user_func($callback->bindTo($self)); } protected function mergedPivotAttributes(): Closure { return function (Model $model) { return collect($this->pivot)->reduce(function ($merged, $pivot) use ($model) { return array_merge($merged, is_callable($pivot) ? call_user_func($pivot, $model) : $pivot); }, []); }; } protected function newBatch(): self { $this->currentBatch++; return $this; } // Core method overwrites protected function createChildren(Model $model) { $this->withRelationsApplied(fn () => parent::createChildren($model)); } protected function getRawAttributes(?Model $parent) { return $this->withRelationsApplied(fn () => parent::getRawAttributes($parent)); } } ================================================ FILE: src/Concerns/EnhancedSequence.php ================================================ $value()->count(null)->raw(); }; } return $value; }, $values); $sequence = new Sequence(...$values); return $this->state(function () use ($sequence) { return ($attributes = $sequence()) instanceof \Closure ? $attributes() : $attributes; }); } } ================================================ FILE: src/Factory.php ================================================ tap(fn ($factory) => $factory->model = $modelName); } public function apply(...$args): self { return ArgumentParser::apply(collect($args), $this); } public function definition() { return []; } public function fill($attributes): self { return $this->state($attributes); } public function fillPivot($attributes): self { return $this->newInstance()->tap(fn (self $factory) => array_push($factory->pivot, $attributes)); } public function pipe(callable $callback): self { return call_user_func($callback, $this); } public function tap($callback = null): self { $this->mutating = true; call_user_func($callback, $this); $this->mutating = false; return $this; } protected function newInstance(array $arguments = []) { if ($this->mutating) { foreach ($arguments as $argument => $value) { $this->$argument = $value; } return $this; } return parent::newInstance($arguments)->tap(function (self $factory) { $factory->relations = $this->relations; $factory->pivot = $this->pivot; $factory->model = $this->model; }); } } ================================================ FILE: src/FactoryServiceProvider.php ================================================ apply(...$parameters); } } ================================================ FILE: src/RelationRequest.php ================================================ model, $this->batch, $this->arguments] = [$model, $batch, collect($arguments)]; $this->extractRelationFromArguments(); $this->failOnMissingRelation(); } /** * Create a new relationship request for nested relations. * * @return RelationRequest */ public function createNestedRequest() { return new static( $this->getRelatedClass(), $this->batch, $this->arguments->values()->push($this->getNestedPath()) ); } /** * Get the nested path beyond immediate relation. * * @param string|null $path * @return string */ public function getNestedPath($path = null) { $nested = explode('.', $path ?: $this->path); array_shift($nested); return implode('.', $nested); } /** * Get the class name of the related eloquent model. * * @return string */ public function getRelatedClass() { return get_class($this->getRelation()->getRelated()); } protected function getRelation() { $relation = $this->getRelationName(); return $this->cachedRelation ??= $this->newModel()->$relation(); } /** * Get the name of the immediate relation. * * @param string|null $path * @return mixed */ public function getRelationName($path = null) { $nested = explode('.', $path ?: $this->path); return array_shift($nested); } public function loadMethod() { if ($this->getRelation() instanceof BelongsToMany) { return static::BelongsToMany; } if ($this->getRelation() instanceof BelongsTo) { return static::BelongsTo; } if ($this->getRelation() instanceof HasOneOrMany) { return static::HasMany; } throw new BadMethodCallException('Unsupported relation type '.get_class($this->getRelation())); } /** * Check if has nesting. * * @return bool */ public function hasNesting() { return strpos($this->path, '.') !== false; } /** * Loop through arguments to detect a relation name. */ protected function extractRelationFromArguments() { $this->arguments = $this->arguments->reject(function ($arg) { if ($match = (is_string($arg) && $this->isValidRelation($arg))) { $this->path = $arg; } return $match; }); } /** * Check if a string represents a valid relation path. * * @param $path * @return bool */ protected function isValidRelation($path) { $model = $this->newModel(); $relation = $this->getRelationName($path); return method_exists($model, $relation) && $model->$relation() instanceof Relation; } /** * @return Model */ protected function newModel() { return new $this->model; } /** * Fail build with a readable exception message. */ protected function failOnMissingRelation() { if (! $this->path) { throw new BadMethodCallException( 'No matching relations could be found on model ['.$this->model.']. '. 'Following possible relation names was checked: '. ( ($testedRelations = $this->getPossiblyIntendedRelationships())->isEmpty() ? '[NO POSSIBLE RELATION NAMES FOUND]' : '['.$testedRelations->implode(', ').']' ) ); } } /** * Give the developer a readable list of possibly arguments * that they might have intended could be a relation, * but was invalid. Helpful for debugging purposes. * * @return Collection */ protected function getPossiblyIntendedRelationships() { return $this->arguments ->filter(function ($arg) { return is_string($arg) || is_null($arg); }) ->map(function ($arg) { return is_null($arg) ? 'NULL' : "'".$arg."'"; }); } } ================================================ FILE: src/helpers.php ================================================ apply(...$arguments); } } } namespace Makeable\LaravelFactory { use Illuminate\Database\Eloquent\Model; function count($count) { return fn (Factory $factory) => $factory->count($count); } function fill($attributes) { return fn (Factory $factory) => $factory->fill($attributes); } function inherit(...$attributes) { return fn (Factory $factory) => $factory->fill(function ($attrs, Model $parent) use ($attributes) { return $parent->only($attributes); }); } function sequence(...$sequence) { return fn (Factory $factory) => $factory->sequence(...$sequence); } } ================================================ FILE: tests/Feature/FactoryTest.php ================================================ assertInstanceOf(User::class, User::factory()->create()); } /** @test **/ public function it_creates_models_without_prior_definitions() { $this->assertInstanceOf(Customer::class, Customer::factory()->create()); } /** @test **/ public function it_creates_models_even_when_no_factory_exists() { $this->assertInstanceOf(Image::class, Image::factory()->create([ 'imageable_type' => 'Foo', 'imageable_id' => 1, ])); } /** @test **/ public function it_creates_models_on_a_custom_connection() { $company = Company::factory() ->connection('secondary') ->create(['name' => 'Evil corp']); $this->assertNull(Company::query()->where('name', 'Evil corp')->first()); $this->assertEquals($company->id, Company::on('secondary')->where('name', 'Evil corp')->first()->id); } /** @test **/ public function it_makes_models_on_a_custom_connection() { $company = Company::factory() ->connection('secondary') ->make(['name' => 'Evil corp']); $this->assertEquals('secondary', $company->getConnectionName()); } /** @test **/ public function it_supports_giving_a_closure_as_count() { $companies = Company::factory()->count(new Sequence(1, 2)); $this->assertEquals(1, $companies->make()->count()); $this->assertEquals(2, $companies->make()->count()); } // /** @test **/ // public function it_applies_closures_when_a_condition_is_met() // { // $createTwice = function ($builder) { // $builder->times(2); // }; // // $this->assertInstanceOf(User::class, User::factory()->when(false, $createTwice)->create()); // $this->assertInstanceOf(Collection::class, User::factory()->when(true, $createTwice)->create()); // } // // /** @test **/ // public function it_applies_closures_given_certain_odds() // { // $createTwice = function ($builder) { // $builder->times(2); // }; // // // With decimal // $this->assertInstanceOf(User::class, User::factory()->odds(0 / 1, $createTwice)->create()); // $this->assertInstanceOf(Collection::class, User::factory()->odds(1 / 1, $createTwice)->create()); // // // With 0-100 // $this->assertInstanceOf(User::class, User::factory()->odds(0, $createTwice)->create()); // $this->assertInstanceOf(Collection::class, User::factory()->odds(100, $createTwice)->create()); // // // With string percentage // $this->assertInstanceOf(User::class, User::factory()->odds('0%', $createTwice)->create()); // $this->assertInstanceOf(Collection::class, User::factory()->odds('100%', $createTwice)->create()); // } /** @test **/ public function a_builder_can_be_tapped() { $createTwice = function ($builder) { $builder->count(2); }; $this->assertInstanceOf(Collection::class, User::factory()->tap($createTwice)->create()); } /** @test **/ public function it_executes_defined_after_callbacks() { $factory = Department::factory() ->afterMaking(function ($department) { $department->forceFill(['active' => 1]); }) ->afterCreating(function ($department) { $department->forceFill(['flagship' => 1]); }); $this->assertEquals(1, ($made = $factory->make())->active); $this->assertEquals(0, $made->flagship); $this->assertEquals(1, ($created = $factory->create())->active); $this->assertEquals(1, $created->flagship); } // /** @test **/ // public function regression_it_doesnt_throw_missing_state_exception_when_has_after_callback() // { // )->factory((Department::class, 'undefined-state', function ($department) { // $department->forceFill(['name' => 'HQ']); // }); // // $this->assertEquals('HQ', Department::factory())->state('undefined-state')->make()->name); // // unset(app(StateManager::class)->afterMaking[Company::class]); // } // /** @test **/ // public function regression_it_passes_inline_attributes_to_definitions() // { // $factory = $this->factory(); // $factory->defineAs(Customer::class, 'special', function (Generator $faker, array $attributes) { // $this->assertEquals('bar', $attributes['foo']); // // return []; // }); // // $customer = $factory->of(Customer::class, 'special')->make(['foo' => 'bar']); // // $this->assertEquals('bar', $customer->foo); // // unset($factory[Customer::class]['special']); // } /** @test **/ public function regression_it_ignores_callables_when_expanding_attributes() { $company = Company::factory()->create([ 'tags' => ['Storage', 'Data'], ]); $this->assertEquals(['Storage', 'Data'], $company->tags); } /** @test **/ public function regression_it_expands_closures_in_definition_attributes() { $company = Company::factory()->withOwner()->create(); $this->assertInstanceOf(User::class, $company->owner); } } ================================================ FILE: tests/Feature/RelationsTest.php ================================================ with('owner') ->create(); $this->assertInstanceOf(Company::class, $company); $this->assertEquals(1, $company->owner->id); } /** @test **/ public function it_creates_models_with_has_many_relations() { $company = Company::factory() ->with(2, 'departments') ->create(); $this->assertInstanceOf(Company::class, $company); $this->assertInstanceOf(Department::class, $company->departments->first()); $this->assertEquals(2, $company->departments->count()); } /** @test **/ public function it_creates_models_with_morph_many_relations() { $company = Company::factory() ->with('logo') ->create(); $this->assertInstanceOf(Company::class, $company); $this->assertInstanceOf(Image::class, $company->logo); } /** @test **/ public function it_creates_models_with_belongs_to_many_relations() { $department = Department::factory() ->with(2, 'employees') ->create(); $this->assertInstanceOf(User::class, $department->employees->first()); $this->assertEquals(2, $department->employees->count()); } /** @test **/ public function it_creates_models_with_multiple_relations() { $company = Company::factory() ->with('owner') ->with(2, 'departments') ->create(); $this->assertInstanceOf(User::class, $company->owner); $this->assertInstanceOf(Department::class, $company->departments->first()); } // FUNCTIONALITY AND BEHAVIOR /** @test **/ public function it_creates_related_models_on_the_same_connection() { $queries = []; DB::listen(function (QueryExecuted $e) use (&$queries) { $queries[$e->connectionName][] = $e->sql; }); Company::factory() ->connection('secondary') ->for(User::factory(), 'owner') ->with('owner') // belongs-to ->with(1, 'departments') // has-many ->with(1, 'departments.employees') // belongs-to-many ->create(); $this->assertNull(data_get($queries, 'primary')); $this->assertCount(5, data_get($queries, 'secondary')); $company = Company::on('secondary')->with('owner', 'departments.employees')->latest()->first(); $this->assertInstanceOf(User::class, $company->owner); $this->assertEquals(1, $company->departments->count()); $this->assertEquals(1, $company->departments->first()->employees->count()); } /** @test **/ public function the_same_relation_can_be_created_multiple_times_using_andWith() { $company = Company::factory() ->with('owner') ->with(1, 'departments') ->andWith(1, 'departments.manager') ->create(); $this->assertEquals(2, $company->departments->count()); $this->assertNull($company->departments->first()->manager); $this->assertInstanceOf(User::class, $company->departments->last()->manager); } /** @test **/ public function additional_attributes_can_be_passed_inline_for_relations() { $company = Company::factory() ->with(1, 'departments', ['active' => 1]) ->with('departments.manager', ['password' => 'foobar']) ->create(); $this->assertEquals(1, $company->departments->first()->active); $this->assertEquals('foobar', $company->departments->first()->manager->password); } /** @test **/ public function it_throws_a_bad_method_call_on_missing_relations() { $this->expectException(\BadMethodCallException::class); $this->expectExceptionMessageMatches('/invalidRelation/'); Company::factory()->with(1, 'invalidRelation')->create(); } /** @test **/ public function it_accepts_pivot_attributes_on_belongs_to_many_relations() { $department = Department::factory()->with(1, 'employees', function ($employee) { return $employee->fillPivot(['started_at' => '2019-01-01 00:00:00']); })->create(); $employees = $department->employees()->withPivot('started_at')->get(); $this->assertEquals('2019-01-01 00:00:00', $employees->first()->pivot->started_at); $this->assertEquals(1, $employees->count()); } /** @test **/ public function it_accepts_closures_as_pivot_attributes_and_they_will_evaluate_on_each_model() { [$i, $dates] = [0, [now()->subMonth(), now()->subDay()]]; $department = Department::factory() ->with(2, 'employees', function ($employee) use ($dates, &$i) { return $employee->fillPivot(function (Department $department) use ($dates, &$i) { return ['started_at' => $dates[$i++]]; }); })->create(); $employees = $department->employees()->withPivot('started_at')->get(); $this->assertEquals(2, $employees->count()); $this->assertEquals($dates[0]->toDateTimeString(), $employees->get(0)->pivot->started_at); $this->assertEquals($dates[1]->toDateTimeString(), $employees->get(1)->pivot->started_at); } /** @test **/ public function regression_null_arguments_will_parse_as_state_and_then_ignored() { $company = Company::factory() ->with(1, 'departments', null) ->create(); $this->assertEquals(1, $company->departments->count()); } /** @test **/ public function regression_parent_model_is_available_as_second_argument() { // Laravel syntax $company = Company::factory() ->has( Department::factory() ->count(2) ->state(function (array $attributes, Company $company) { return ['name' => $company->name.': Department']; }) ) ->create(); $this->assertStringContainsString($company->name, $company->departments->first()->name); // Enhanced syntax $company = Company::factory() ->with(2, 'departments', function ($builder) { $builder->fill(fn ($department, $company) => ['name' => $company->name.': Department']); }) ->create(); $this->assertStringContainsString($company->name, $company->departments->first()->name); } // NESTED RELATIONS /** @test **/ public function it_creates_models_with_nested_relations() { $company = Company::factory() ->with('owner') ->with('departments.manager') ->create(); $this->assertEquals(1, $company->departments->count()); $this->assertInstanceOf(User::class, $company->departments->first()->manager); } /** @test **/ public function nested_relations_can_be_built_by_closures() { $company = Company::factory() ->with('departments', function (Factory $departments) { return $departments ->fill(['name' => 'foo']) ->count(2) ->with('manager'); }) ->create(); $this->assertEquals(2, $company->departments->count()); $this->assertEquals('foo', $company->departments->first()->name); $this->assertInstanceOf(User::class, $company->departments->first()->manager); $this->assertNotEquals( $company->departments->get(0)->manager->id, $company->departments->get(1)->manager->id ); } /** @test **/ public function nested_relations_can_be_specified_separate_function_calls() { $company = Company::factory() ->with('owner') ->with(1, 'departments') ->with(1, 'departments.manager') ->create(); $this->assertEquals(1, $company->departments->count()); $this->assertInstanceOf(User::class, $company->departments->first()->manager); } /** @test **/ public function it_accepts_model_instances_as_for_belongs_to() { // Using apply $company = Company::factory()->create(); $department = Department::factory()->apply($company)->create(); $this->assertEquals($company->id, $department->company_id); // Using with $company = Company::factory()->create(); $manager = User::factory() ->with(1, 'departments', $company) ->create(); $this->assertEquals($company->id, $manager->departments->first()->company_id); } // HELPER FUNCTIONS /** @test **/ public function count_helper_may_be_used_for_dynamic_expressions() { $companies = Company::factory() ->count(2) ->with(count(new Sequence(1, 2)), 'departments') ->create(); $this->assertEquals(1, $companies->first()->departments->count()); $this->assertEquals(2, $companies->last()->departments->count()); } /** @test **/ public function fill_helper_may_be_used_to_access_parent() { $company = Company::factory() ->with(1, 'departments', fill(fn ($attributes, Company $parent) => ['name' => $parent->name])) ->create(); $this->assertEquals($company->name, $company->departments->first()->name); } /** @test **/ public function inherit_helper_may_be_used_to_fill_attributes_from_parent() { $company = Company::factory() ->with(1, 'departments', inherit('name')) ->create(); $this->assertEquals($company->name, $company->departments->first()->name); } /** @test **/ public function sequence_helper_may_be_used_to_apply_different_states() { $company = Company::factory() ->with(2, 'customers', sequence('happy', 'unhappy')) ->create(); $this->assertEquals(5, $company->customers->first()->satisfaction); $this->assertEquals(1, $company->customers->last()->satisfaction); } /** @test **/ public function regression_it_doesnt_create_belongs_to_relations_when_given_a_count_of_zero() { $company = Company::factory() ->with(0, 'owner') ->create(); $this->assertInstanceOf(Company::class, $company); $this->assertNull($company->owner); } } ================================================ FILE: tests/Feature/StateTest.php ================================================ happy()->create(); $this->assertEquals(5, $customer->satisfaction); } /** @test **/ public function it_filters_null_args() { $customer = Customer::factory()->apply(null)->create(); $this->assertInstanceOf(Customer::class, $customer); } /** @test **/ public function it_throws_exception_when_missing_state() { $this->expectException(\BadMethodCallException::class); Customer::factory()->foobar()->create(); } /** @test **/ public function multiple_states_can_be_passed_for_relations_inline_individually() { $company = Company::factory() ->with(1, 'active', 'flagship', 'departments') ->create(); $this->assertEquals(1, $company->departments->count()); $this->assertEquals(1, $company->departments->first()->active); $this->assertEquals(1, $company->departments->first()->flagship); } /** @test **/ public function multiple_states_can_be_passed_for_relations_inline_as_array() { $company = Company::factory() ->with(1, ['active', 'flagship'], 'departments') ->create(); $this->assertEquals(1, $company->departments->count()); $this->assertEquals(1, $company->departments->first()->active); $this->assertEquals(1, $company->departments->first()->flagship); } /** @test **/ public function it_can_apply_what_was_formerly_know_as_a_preset() { $company = Company::factory()->startup()->create(); $this->assertEquals(1, $company->departments->count()); $this->assertEquals(1, $company->departments->first()->employees->count()); } /** @test **/ public function presets_can_be_passed_for_relations_inline() { $company = Company::factory() ->with(1, 'mediumSized', 'departments') ->create(); $this->assertEquals(1, $company->departments->count()); $this->assertEquals(4, $company->departments->first()->employees->count()); $this->assertInstanceOf(User::class, $company->departments->first()->manager); } /** @test **/ public function regression_states_works_with_nested_relations() { $company = Company::factory() ->with(1, 'active', 'departments') ->with(2, 'departments.employees') ->create(); $this->assertEquals(1, $company->departments->count()); $this->assertEquals(2, $company->departments->first()->employees->count()); $this->assertEquals(1, $company->departments->first()->active); } /** @test **/ public function sequence_accepts_state_names() { $customer = Customer::factory()->sequence('happy', 'unhappy', ['satisfaction' => 3]); $this->assertEquals(5, $customer->make()->satisfaction); $this->assertEquals(1, $customer->make()->satisfaction); $this->assertEquals(3, $customer->make()->satisfaction); } } ================================================ FILE: tests/Stubs/Company.php ================================================ 'array', ]; public function customers() { return $this->hasMany(Customer::class); } public function departments() { return $this->hasMany(Department::class); } public function logo() { return $this->morphOne(Image::class, 'imageable'); } public function owner() { return $this->belongsTo(User::class, 'owner_id'); } } ================================================ FILE: tests/Stubs/Customer.php ================================================ belongsTo(Company::class); } public function employees() { return $this->belongsToMany(User::class, 'employees'); } public function manager() { return $this->belongsTo(User::class, 'manager_id'); } } ================================================ FILE: tests/Stubs/HasFactory.php ================================================ morphTo(); } } ================================================ FILE: tests/Stubs/User.php ================================================ 'datetime', ]; public function departments() { return $this->hasMany(Department::class, 'manager_id'); } } ================================================ FILE: tests/TestCase.php ================================================ make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap(); $app->register(FactoryServiceProvider::class); $app->useDatabasePath(__DIR__.'/database'); $app['config']->set('database.default', 'primary'); $app['config']->set('database.connections.primary', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); $app['config']->set('database.connections.secondary', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); return $app; } /** * @param null $class * @return Factory */ protected function factory($class = null) { return Factory::factoryForModel($class); } } ================================================ FILE: tests/database/factories/CompanyFactory.php ================================================ $this->faker->company, ]; } public function startup() { return $this ->with(1, 'departments') ->with(1, 'departments.employees'); } public function withOwner() { return $this->state([ 'owner_id' => function () { return User::factory()->create()->id; }, ]); } } ================================================ FILE: tests/database/factories/CustomerFactory.php ================================================ state([ 'satisfaction' => 5, ]); } public function unhappy() { return $this->state([ 'satisfaction' => 1, ]); } } ================================================ FILE: tests/database/factories/DepartmentFactory.php ================================================ $this->faker->company, ]; } public function active() { return $this->state([ 'active' => 1, ]); } public function flagship() { return $this->state([ 'flagship' => 1, ]); } public function mediumSized() { return $this ->with(1, 'manager') ->with(4, 'employees'); } } ================================================ FILE: tests/database/factories/UserFactory.php ================================================ $this->faker->name, 'email' => $this->faker->unique()->safeEmail, 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password ]; } } ================================================ FILE: tests/database/migrations/2018_04_27_000000_create_test_tables.php ================================================ createTables('primary'); $this->createTables('secondary'); } protected function createTables($connection) { Schema::connection($connection)->create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->string('remember_token', 100)->nullable(); $table->timestamps(); }); Schema::connection($connection)->create('companies', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('owner_id')->nullable(); $table->string('name'); $table->text('tags')->nullable(); $table->timestamps(); }); Schema::connection($connection)->create('customers', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('company_id')->nullable(); $table->integer('satisfaction')->nullable(); $table->timestamps(); }); Schema::connection($connection)->create('departments', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('company_id')->nullable(); $table->unsignedInteger('manager_id')->nullable(); $table->tinyInteger('active')->default(0); $table->tinyInteger('flagship')->default(0); $table->string('name'); $table->timestamps(); }); Schema::connection($connection)->create('employees', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('department_id'); $table->unsignedInteger('user_id'); $table->timestamp('started_at')->nullable(); $table->timestamps(); }); Schema::connection($connection)->create('images', function (Blueprint $table) { $table->increments('id'); $table->morphs('imageable'); $table->timestamps(); }); Schema::connection($connection)->dropIfExists('users'); Schema::connection($connection)->create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamp('email_verified_at')->nullable(); $table->rememberToken(); $table->timestamps(); }); } }