master 7293219b1378 cached
32 files
78.5 KB
18.8k tokens
131 symbols
1 requests
Download .txt
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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" bootstrap="vendor/autoload.php" colors="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
  <testsuites>
    <testsuite name="Package Test Suite">
      <directory>./tests/</directory>
    </testsuite>
  </testsuites>
  <php>
    <ini name="display_errors" value="1"/>
    <env name="APP_ENV" value="testing"/>
    <server name="BCRYPT_ROUNDS" value="4"/>
    <server name="CACHE_DRIVER" value="array"/>
    <server name="MAIL_DRIVER" value="array"/>
    <server name="QUEUE_CONNECTION" value="sync"/>
    <server name="SESSION_DRIVER" value="array"/>
  </php>
  <source>
    <include>
      <directory suffix=".php">src/</directory>
    </include>
  </source>
</phpunit>


================================================
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
<?php

namespace App\Models;

use Makeable\LaravelFactory\HasFactory;

class User 
{
    use HasFactory;
    
    // ...
}
```

**database/factories/UserFactory.php**

```php
<?php

namespace Database\Factories;

use Makeable\LaravelFactory\Factory;

class UserFactory extends Factory
{
    public function definition()
    {
        return [
            // ...
        ];
    }
}
```

You may now use all the native Laravel features you are used to, along with the additional functionality this package provides.

If you're not familiar with Laravel factories, please refer to the official documentation: https://laravel.com/docs/master/database-testing

### Simple relationships

You may use the enhanced factory to create any additional relationships defined on the model.

Example: A `Server` model with a `sites()` relationship (has-many)

```php
Server::factory()->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
================================================
<?php

namespace Makeable\LaravelFactory;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class ArgumentParser
{
    public static function apply(Collection $arguments, Factory $factory): Factory
    {
        return $arguments->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
================================================
<?php

namespace Makeable\LaravelFactory\Concerns;

use Illuminate\Database\Eloquent\Model;

trait EnhancedCount
{
    /**
     * Overwrite core method to allow closures.
     *
     * @param  int|callable|null  $count
     * @return $this
     */
    public function count($count): self
    {
        return $this->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
================================================
<?php

namespace Makeable\LaravelFactory\Concerns;

use Closure;
use Illuminate\Database\Eloquent\Model;
use Makeable\LaravelFactory\Factory;
use Makeable\LaravelFactory\RelationRequest;

trait EnhancedRelationships
{
    protected int $currentBatch = 0;

    protected array $relations = [];

    protected array $pivot = [];

    /**
     * Build the model with specified relations.
     *
     * @param  mixed  ...$args
     * @return static
     */
    public function with(...$args): self
    {
        return $this->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
================================================
<?php

namespace Makeable\LaravelFactory\Concerns;

use Illuminate\Database\Eloquent\Factories\Sequence;

trait EnhancedSequence
{
    /**
     * Support a "method name" string given as sequence value.
     * It will invoke the method on the Factory and grab
     * any attributes the method has applied.
     */
    public function sequence(...$values): self
    {
        $values = array_map(function ($value) {
            if (is_string($value) && method_exists($this, $value)) {
                return function () use ($value) {
                    return (new static)->$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
================================================
<?php

namespace Makeable\LaravelFactory;

use Makeable\LaravelFactory\Concerns\EnhancedCount;
use Makeable\LaravelFactory\Concerns\EnhancedRelationships;
use Makeable\LaravelFactory\Concerns\EnhancedSequence;

class Factory extends \Illuminate\Database\Eloquent\Factories\Factory
{
    use EnhancedCount,
        EnhancedRelationships,
        EnhancedSequence;

    protected bool $mutating = false;

    public static function factoryForModel($modelName): self
    {
        if (method_exists($modelName, 'newFactory') && ($factory = $modelName::newFactory())) {
            return $factory;
        }

        $factory = static::resolveFactoryName($modelName);

        if (is_string($factory) && class_exists($factory)) {
            return $factory::new();
        }

        return Factory::new()->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
================================================
<?php

namespace Makeable\LaravelFactory;

use Illuminate\Support\ServiceProvider;

class FactoryServiceProvider extends ServiceProvider
{
    //
}


================================================
FILE: src/HasFactory.php
================================================
<?php

namespace Makeable\LaravelFactory;

trait HasFactory
{
    /**
     * Get a new factory instance for the model.
     *
     * @param  mixed  $parameters
     * @return \Makeable\LaravelFactory\Factory
     */
    public static function factory(...$parameters)
    {
        return Factory::factoryForModel(static::class)->apply(...$parameters);
    }
}


================================================
FILE: src/RelationRequest.php
================================================
<?php

namespace Makeable\LaravelFactory;

use BadMethodCallException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;

class RelationRequest
{
    public const HasMany = 'has';
    public const BelongsToMany = 'hasAttached';
    public const BelongsTo = 'for';

    /**
     * The parent model requesting relations.
     */
    protected string $model;

    public int $batch;

    public Collection $arguments;

    protected ?Relation $cachedRelation;

    /**
     * The (possibly nested) relations path.
     *
     * @var string
     */
    public $path;

    /**
     * Create a new relationship request.
     *
     * @param  $model
     * @param  $batch
     * @param  mixed  $arguments
     */
    public function __construct($model, $batch, $arguments)
    {
        [$this->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
================================================
<?php

namespace {
    if (! function_exists('factory')) {
        function factory($model, ...$arguments)
        {
            return \Makeable\LaravelFactory\Factory::factoryForModel($model)->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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Feature;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\Sequence;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Makeable\LaravelFactory\Tests\Stubs\Company;
use Makeable\LaravelFactory\Tests\Stubs\Customer;
use Makeable\LaravelFactory\Tests\Stubs\Department;
use Makeable\LaravelFactory\Tests\Stubs\Image;
use Makeable\LaravelFactory\Tests\Stubs\User;
use Makeable\LaravelFactory\Tests\TestCase;

class FactoryTest extends TestCase
{
    use RefreshDatabase;

    /** @test **/
    public function it_creates_models_with_no_relations()
    {
        $this->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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Feature;

use Illuminate\Database\Eloquent\Factories\Sequence;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Makeable\LaravelFactory\Factory;
use Makeable\LaravelFactory\Tests\Stubs\Company;
use Makeable\LaravelFactory\Tests\Stubs\Department;
use Makeable\LaravelFactory\Tests\Stubs\Image;
use Makeable\LaravelFactory\Tests\Stubs\User;
use Makeable\LaravelFactory\Tests\TestCase;

use function Makeable\LaravelFactory\count;
use function Makeable\LaravelFactory\fill;
use function Makeable\LaravelFactory\inherit;
use function Makeable\LaravelFactory\sequence;

class RelationsTest extends TestCase
{
    use RefreshDatabase;

    // DIFFERENT RELATIONSHIP TYPES

    /** @test **/
    public function it_creates_models_with_belongs_to_relations()
    {
        $company = Company::factory()
            ->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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Makeable\LaravelFactory\Tests\Stubs\Company;
use Makeable\LaravelFactory\Tests\Stubs\Customer;
use Makeable\LaravelFactory\Tests\Stubs\User;
use Makeable\LaravelFactory\Tests\TestCase;

class StateTest extends TestCase
{
    use RefreshDatabase;

    /** @test **/
    public function it_can_apply_a_state()
    {
        $customer = Customer::factory()->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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Stubs;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    use HasFactory;

    protected $casts = [
        'tags' => '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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Stubs;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    use HasFactory;
}


================================================
FILE: tests/Stubs/Department.php
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Stubs;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
    use HasFactory;

    public function company()
    {
        return $this->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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Stubs;

trait HasFactory
{
    use \Makeable\LaravelFactory\HasFactory;

    /**
     * Create a new factory instance for the model.
     *
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    protected static function newFactory()
    {
        $name = '\\Makeable\\LaravelFactory\\Tests\\Database\\Factories\\'.class_basename(static::class).'Factory';

        if (class_exists($name)) {
            return new $name;
        }
    }
}


================================================
FILE: tests/Stubs/Image.php
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Stubs;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;

    public function imageable()
    {
        return $this->morphTo();
    }
}


================================================
FILE: tests/Stubs/User.php
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Stubs;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasFactory;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function departments()
    {
        return $this->hasMany(Department::class, 'manager_id');
    }
}


================================================
FILE: tests/TestCase.php
================================================
<?php

namespace Makeable\LaravelFactory\Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Makeable\LaravelFactory\Factory;
use Makeable\LaravelFactory\FactoryServiceProvider;

class TestCase extends BaseTestCase
{
    protected $connectionsToTransact = [
        'primary',
        'secondary',
    ];

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        /** @var \Illuminate\Foundation\Application $app */
        $app = require __DIR__.'/../vendor/laravel/laravel/bootstrap/app.php';
        $app->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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Database\Factories;

use App\Models\User;
use Makeable\LaravelFactory\Factory;
use Makeable\LaravelFactory\Tests\Stubs\Company;

class CompanyFactory extends Factory
{
    protected $model = Company::class;

    public function definition()
    {
        return [
            'name' => $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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Database\Factories;

use Makeable\LaravelFactory\Factory;
use Makeable\LaravelFactory\Tests\Stubs\Customer;

class CustomerFactory extends Factory
{
    protected $model = Customer::class;

    public function happy()
    {
        return $this->state([
            'satisfaction' => 5,
        ]);
    }

    public function unhappy()
    {
        return $this->state([
            'satisfaction' => 1,
        ]);
    }
}


================================================
FILE: tests/database/factories/DepartmentFactory.php
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Database\Factories;

use Makeable\LaravelFactory\Factory;
use Makeable\LaravelFactory\Tests\Stubs\Department;

class DepartmentFactory extends Factory
{
    protected $model = Department::class;

    public function definition()
    {
        return [
            'name' => $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
================================================
<?php

namespace Makeable\LaravelFactory\Tests\Database\Factories;

use Makeable\LaravelFactory\Factory;
use Makeable\LaravelFactory\Tests\Stubs\User;

class UserFactory extends Factory
{
    protected $model = User::class;

    public function definition()
    {
        return [
            'name' => $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
================================================
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTestTables extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        $this->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();
        });
    }
}
Download .txt
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
Download .txt
SYMBOL INDEX (131 symbols across 24 files)

FILE: src/ArgumentParser.php
  class ArgumentParser (line 10) | class ArgumentParser
    method apply (line 12) | public static function apply(Collection $arguments, Factory $factory):...
    method fill (line 43) | protected static function fill(Factory $factory, array $attributes): F...

FILE: src/Concerns/EnhancedCount.php
  type EnhancedCount (line 7) | trait EnhancedCount
    method count (line 15) | public function count($count): self
    method make (line 20) | public function make($attributes = [], ?Model $parent = null)
    method raw (line 25) | public function raw($attributes = [], ?Model $parent = null)
    method withCalculatedCount (line 30) | protected function withCalculatedCount(\Closure $callback)

FILE: src/Concerns/EnhancedRelationships.php
  type EnhancedRelationships (line 10) | trait EnhancedRelationships
    method with (line 24) | public function with(...$args): self
    method andWith (line 39) | public function andWith(...$args): self
    method loadRelation (line 50) | public function loadRelation(RelationRequest $request): self
    method pushRelatedFactory (line 67) | protected function pushRelatedFactory(RelationRequest $request, ?self ...
    method withRelationsApplied (line 82) | protected function withRelationsApplied(Closure $callback)
    method mergedPivotAttributes (line 113) | protected function mergedPivotAttributes(): Closure
    method newBatch (line 122) | protected function newBatch(): self
    method createChildren (line 131) | protected function createChildren(Model $model)
    method getRawAttributes (line 136) | protected function getRawAttributes(?Model $parent)

FILE: src/Concerns/EnhancedSequence.php
  type EnhancedSequence (line 7) | trait EnhancedSequence
    method sequence (line 14) | public function sequence(...$values): self

FILE: src/Factory.php
  class Factory (line 9) | class Factory extends \Illuminate\Database\Eloquent\Factories\Factory
    method factoryForModel (line 17) | public static function factoryForModel($modelName): self
    method apply (line 32) | public function apply(...$args): self
    method definition (line 37) | public function definition()
    method fill (line 42) | public function fill($attributes): self
    method fillPivot (line 47) | public function fillPivot($attributes): self
    method pipe (line 52) | public function pipe(callable $callback): self
    method tap (line 57) | public function tap($callback = null): self
    method newInstance (line 68) | protected function newInstance(array $arguments = [])

FILE: src/FactoryServiceProvider.php
  class FactoryServiceProvider (line 7) | class FactoryServiceProvider extends ServiceProvider

FILE: src/HasFactory.php
  type HasFactory (line 5) | trait HasFactory
    method factory (line 13) | public static function factory(...$parameters)

FILE: src/RelationRequest.php
  class RelationRequest (line 13) | class RelationRequest
    method __construct (line 44) | public function __construct($model, $batch, $arguments)
    method createNestedRequest (line 57) | public function createNestedRequest()
    method getNestedPath (line 72) | public function getNestedPath($path = null)
    method getRelatedClass (line 86) | public function getRelatedClass()
    method getRelation (line 91) | protected function getRelation()
    method getRelationName (line 104) | public function getRelationName($path = null)
    method loadMethod (line 111) | public function loadMethod()
    method hasNesting (line 133) | public function hasNesting()
    method extractRelationFromArguments (line 141) | protected function extractRelationFromArguments()
    method isValidRelation (line 158) | protected function isValidRelation($path)
    method newModel (line 169) | protected function newModel()
    method failOnMissingRelation (line 177) | protected function failOnMissingRelation()
    method getPossiblyIntendedRelationships (line 199) | protected function getPossiblyIntendedRelationships()

FILE: src/helpers.php
  function factory (line 5) | function factory($model, ...$arguments)
  function count (line 15) | function count($count)
  function fill (line 20) | function fill($attributes)
  function inherit (line 25) | function inherit(...$attributes)
  function sequence (line 32) | function sequence(...$sequence)

FILE: tests/Feature/FactoryTest.php
  class FactoryTest (line 15) | class FactoryTest extends TestCase
    method it_creates_models_with_no_relations (line 20) | public function it_creates_models_with_no_relations()
    method it_creates_models_without_prior_definitions (line 26) | public function it_creates_models_without_prior_definitions()
    method it_creates_models_even_when_no_factory_exists (line 32) | public function it_creates_models_even_when_no_factory_exists()
    method it_creates_models_on_a_custom_connection (line 41) | public function it_creates_models_on_a_custom_connection()
    method it_makes_models_on_a_custom_connection (line 52) | public function it_makes_models_on_a_custom_connection()
    method it_supports_giving_a_closure_as_count (line 62) | public function it_supports_giving_a_closure_as_count()
    method a_builder_can_be_tapped (line 102) | public function a_builder_can_be_tapped()
    method it_executes_defined_after_callbacks (line 112) | public function it_executes_defined_after_callbacks()
    method regression_it_ignores_callables_when_expanding_attributes (line 159) | public function regression_it_ignores_callables_when_expanding_attribu...
    method regression_it_expands_closures_in_definition_attributes (line 169) | public function regression_it_expands_closures_in_definition_attributes()

FILE: tests/Feature/RelationsTest.php
  class RelationsTest (line 21) | class RelationsTest extends TestCase
    method it_creates_models_with_belongs_to_relations (line 28) | public function it_creates_models_with_belongs_to_relations()
    method it_creates_models_with_has_many_relations (line 39) | public function it_creates_models_with_has_many_relations()
    method it_creates_models_with_morph_many_relations (line 51) | public function it_creates_models_with_morph_many_relations()
    method it_creates_models_with_belongs_to_many_relations (line 62) | public function it_creates_models_with_belongs_to_many_relations()
    method it_creates_models_with_multiple_relations (line 73) | public function it_creates_models_with_multiple_relations()
    method it_creates_related_models_on_the_same_connection (line 87) | public function it_creates_related_models_on_the_same_connection()
    method the_same_relation_can_be_created_multiple_times_using_andWith (line 114) | public function the_same_relation_can_be_created_multiple_times_using_...
    method additional_attributes_can_be_passed_inline_for_relations (line 128) | public function additional_attributes_can_be_passed_inline_for_relatio...
    method it_throws_a_bad_method_call_on_missing_relations (line 140) | public function it_throws_a_bad_method_call_on_missing_relations()
    method it_accepts_pivot_attributes_on_belongs_to_many_relations (line 148) | public function it_accepts_pivot_attributes_on_belongs_to_many_relatio...
    method it_accepts_closures_as_pivot_attributes_and_they_will_evaluate_on_each_model (line 161) | public function it_accepts_closures_as_pivot_attributes_and_they_will_...
    method regression_null_arguments_will_parse_as_state_and_then_ignored (line 180) | public function regression_null_arguments_will_parse_as_state_and_then...
    method regression_parent_model_is_available_as_second_argument (line 190) | public function regression_parent_model_is_available_as_second_argument()
    method it_creates_models_with_nested_relations (line 218) | public function it_creates_models_with_nested_relations()
    method nested_relations_can_be_built_by_closures (line 230) | public function nested_relations_can_be_built_by_closures()
    method nested_relations_can_be_specified_separate_function_calls (line 251) | public function nested_relations_can_be_specified_separate_function_ca...
    method it_accepts_model_instances_as_for_belongs_to (line 264) | public function it_accepts_model_instances_as_for_belongs_to()
    method count_helper_may_be_used_for_dynamic_expressions (line 282) | public function count_helper_may_be_used_for_dynamic_expressions()
    method fill_helper_may_be_used_to_access_parent (line 294) | public function fill_helper_may_be_used_to_access_parent()
    method inherit_helper_may_be_used_to_fill_attributes_from_parent (line 304) | public function inherit_helper_may_be_used_to_fill_attributes_from_par...
    method sequence_helper_may_be_used_to_apply_different_states (line 314) | public function sequence_helper_may_be_used_to_apply_different_states()
    method regression_it_doesnt_create_belongs_to_relations_when_given_a_count_of_zero (line 325) | public function regression_it_doesnt_create_belongs_to_relations_when_...

FILE: tests/Feature/StateTest.php
  class StateTest (line 11) | class StateTest extends TestCase
    method it_can_apply_a_state (line 16) | public function it_can_apply_a_state()
    method it_filters_null_args (line 24) | public function it_filters_null_args()
    method it_throws_exception_when_missing_state (line 32) | public function it_throws_exception_when_missing_state()
    method multiple_states_can_be_passed_for_relations_inline_individually (line 40) | public function multiple_states_can_be_passed_for_relations_inline_ind...
    method multiple_states_can_be_passed_for_relations_inline_as_array (line 52) | public function multiple_states_can_be_passed_for_relations_inline_as_...
    method it_can_apply_what_was_formerly_know_as_a_preset (line 64) | public function it_can_apply_what_was_formerly_know_as_a_preset()
    method presets_can_be_passed_for_relations_inline (line 73) | public function presets_can_be_passed_for_relations_inline()
    method regression_states_works_with_nested_relations (line 85) | public function regression_states_works_with_nested_relations()
    method sequence_accepts_state_names (line 98) | public function sequence_accepts_state_names()

FILE: tests/Stubs/Company.php
  class Company (line 7) | class Company extends Model
    method customers (line 15) | public function customers()
    method departments (line 20) | public function departments()
    method logo (line 25) | public function logo()
    method owner (line 30) | public function owner()

FILE: tests/Stubs/Customer.php
  class Customer (line 7) | class Customer extends Model

FILE: tests/Stubs/Department.php
  class Department (line 7) | class Department extends Model
    method company (line 11) | public function company()
    method employees (line 16) | public function employees()
    method manager (line 21) | public function manager()

FILE: tests/Stubs/HasFactory.php
  type HasFactory (line 5) | trait HasFactory
    method newFactory (line 14) | protected static function newFactory()

FILE: tests/Stubs/Image.php
  class Image (line 7) | class Image extends Model
    method imageable (line 11) | public function imageable()

FILE: tests/Stubs/User.php
  class User (line 7) | class User extends Authenticatable
    method departments (line 23) | public function departments()

FILE: tests/TestCase.php
  class TestCase (line 9) | class TestCase extends BaseTestCase
    method createApplication (line 21) | public function createApplication()
    method factory (line 48) | protected function factory($class = null)

FILE: tests/database/factories/CompanyFactory.php
  class CompanyFactory (line 9) | class CompanyFactory extends Factory
    method definition (line 13) | public function definition()
    method startup (line 20) | public function startup()
    method withOwner (line 27) | public function withOwner()

FILE: tests/database/factories/CustomerFactory.php
  class CustomerFactory (line 8) | class CustomerFactory extends Factory
    method happy (line 12) | public function happy()
    method unhappy (line 19) | public function unhappy()

FILE: tests/database/factories/DepartmentFactory.php
  class DepartmentFactory (line 8) | class DepartmentFactory extends Factory
    method definition (line 12) | public function definition()
    method active (line 19) | public function active()
    method flagship (line 26) | public function flagship()
    method mediumSized (line 33) | public function mediumSized()

FILE: tests/database/factories/UserFactory.php
  class UserFactory (line 8) | class UserFactory extends Factory
    method definition (line 12) | public function definition()

FILE: tests/database/migrations/2018_04_27_000000_create_test_tables.php
  class CreateTestTables (line 7) | class CreateTestTables extends Migration
    method up (line 12) | public function up()
    method createTables (line 18) | protected function createTables($connection)
Condensed preview — 32 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (85K chars).
[
  {
    "path": ".github/workflows/test.yml",
    "chars": 1233,
    "preview": "name: Run tests\n\non:\n  push:\n  pull_request:\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: f"
  },
  {
    "path": ".gitignore",
    "chars": 92,
    "preview": "build\ncomposer.phar\ncomposer.lock\nvendor\n.php_cs.cache\n.phpunit.result.cache\n.phpunit.cache\n"
  },
  {
    "path": ".styleci.yml",
    "chars": 15,
    "preview": "preset: laravel"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 712,
    "preview": "# Contributing\n\nWe accept contributions via Pull Requests on [Github](https://github.com/makeable/laravel-production-see"
  },
  {
    "path": "LICENSE.md",
    "chars": 20132,
    "preview": "Attribution-ShareAlike 4.0 International\n\n=======================================================================\n\nCreat"
  },
  {
    "path": "composer.json",
    "chars": 1155,
    "preview": "{\n    \"name\": \"makeabledk/laravel-factory-enhanced\",\n    \"license\": \"CC-BY-SA-4.0\",\n    \"autoload\": {\n        \"psr-4\": {"
  },
  {
    "path": "phpunit.xml",
    "chars": 938,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" backupGlobals=\"fal"
  },
  {
    "path": "readme.md",
    "chars": 9789,
    "preview": "![Laravel Factory Enhanced - Supercharge your tests](https://raw.githubusercontent.com/makeabledk/laravel-factory-enhanc"
  },
  {
    "path": "src/ArgumentParser.php",
    "chars": 1689,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Arr;\nuse Illum"
  },
  {
    "path": "src/Concerns/EnhancedCount.php",
    "chars": 974,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Concerns;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\ntrait EnhancedCount\n{\n    /"
  },
  {
    "path": "src/Concerns/EnhancedRelationships.php",
    "chars": 4070,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Concerns;\n\nuse Closure;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Makeable\\La"
  },
  {
    "path": "src/Concerns/EnhancedSequence.php",
    "chars": 942,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Concerns;\n\nuse Illuminate\\Database\\Eloquent\\Factories\\Sequence;\n\ntrait Enhanced"
  },
  {
    "path": "src/Factory.php",
    "chars": 2105,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory;\n\nuse Makeable\\LaravelFactory\\Concerns\\EnhancedCount;\nuse Makeable\\LaravelFacto"
  },
  {
    "path": "src/FactoryServiceProvider.php",
    "chars": 148,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory;\n\nuse Illuminate\\Support\\ServiceProvider;\n\nclass FactoryServiceProvider extends"
  },
  {
    "path": "src/HasFactory.php",
    "chars": 360,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory;\n\ntrait HasFactory\n{\n    /**\n     * Get a new factory instance for the model.\n "
  },
  {
    "path": "src/RelationRequest.php",
    "chars": 5236,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory;\n\nuse BadMethodCallException;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illum"
  },
  {
    "path": "src/helpers.php",
    "chars": 876,
    "preview": "<?php\n\nnamespace {\n    if (! function_exists('factory')) {\n        function factory($model, ...$arguments)\n        {\n   "
  },
  {
    "path": "tests/Feature/FactoryTest.php",
    "chars": 5906,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Feature;\n\nuse Illuminate\\Database\\Eloquent\\Collection;\nuse Illuminate\\Dat"
  },
  {
    "path": "tests/Feature/RelationsTest.php",
    "chars": 11405,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Feature;\n\nuse Illuminate\\Database\\Eloquent\\Factories\\Sequence;\nuse Illumi"
  },
  {
    "path": "tests/Feature/StateTest.php",
    "chars": 3458,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Feature;\n\nuse Illuminate\\Foundation\\Testing\\RefreshDatabase;\nuse Makeable"
  },
  {
    "path": "tests/Stubs/Company.php",
    "chars": 596,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Stubs;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Company extends Mo"
  },
  {
    "path": "tests/Stubs/Customer.php",
    "chars": 149,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Stubs;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Customer extends M"
  },
  {
    "path": "tests/Stubs/Department.php",
    "chars": 454,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Stubs;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Department extends"
  },
  {
    "path": "tests/Stubs/HasFactory.php",
    "chars": 507,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Stubs;\n\ntrait HasFactory\n{\n    use \\Makeable\\LaravelFactory\\HasFactory;\n\n"
  },
  {
    "path": "tests/Stubs/Image.php",
    "chars": 224,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Stubs;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Image extends Mode"
  },
  {
    "path": "tests/Stubs/User.php",
    "chars": 503,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Stubs;\n\nuse Illuminate\\Foundation\\Auth\\User as Authenticatable;\n\nclass Us"
  },
  {
    "path": "tests/TestCase.php",
    "chars": 1417,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests;\n\nuse Illuminate\\Foundation\\Testing\\TestCase as BaseTestCase;\nuse Makeabl"
  },
  {
    "path": "tests/database/factories/CompanyFactory.php",
    "chars": 720,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Database\\Factories;\n\nuse App\\Models\\User;\nuse Makeable\\LaravelFactory\\Fac"
  },
  {
    "path": "tests/database/factories/CustomerFactory.php",
    "chars": 472,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Database\\Factories;\n\nuse Makeable\\LaravelFactory\\Factory;\nuse Makeable\\La"
  },
  {
    "path": "tests/database/factories/DepartmentFactory.php",
    "chars": 726,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Database\\Factories;\n\nuse Makeable\\LaravelFactory\\Factory;\nuse Makeable\\La"
  },
  {
    "path": "tests/database/factories/UserFactory.php",
    "chars": 502,
    "preview": "<?php\n\nnamespace Makeable\\LaravelFactory\\Tests\\Database\\Factories;\n\nuse Makeable\\LaravelFactory\\Factory;\nuse Makeable\\La"
  },
  {
    "path": "tests/database/migrations/2018_04_27_000000_create_test_tables.php",
    "chars": 2901,
    "preview": "<?php\n\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Support\\Fa"
  }
]

About this extraction

This page contains the full source code of the makeabledk/laravel-factory-enhanced GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 32 files (78.5 KB), approximately 18.8k tokens, and a symbol index with 131 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!