Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Zur aktuellen Revision | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
namespace Illuminate\Database\Eloquent\Factories;
4
 
5
use Closure;
6
use Faker\Generator;
7
use Illuminate\Container\Container;
8
use Illuminate\Contracts\Foundation\Application;
9
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
10
use Illuminate\Database\Eloquent\Model;
11
use Illuminate\Database\Eloquent\SoftDeletes;
12
use Illuminate\Support\Carbon;
13
use Illuminate\Support\Collection;
14
use Illuminate\Support\Enumerable;
15
use Illuminate\Support\Str;
16
use Illuminate\Support\Traits\Conditionable;
17
use Illuminate\Support\Traits\ForwardsCalls;
18
use Illuminate\Support\Traits\Macroable;
19
use Throwable;
20
 
21
/**
22
 * @template TModel of \Illuminate\Database\Eloquent\Model
23
 *
24
 * @method $this trashed()
25
 */
26
abstract class Factory
27
{
28
    use Conditionable, ForwardsCalls, Macroable {
29
        __call as macroCall;
30
    }
31
 
32
    /**
33
     * The name of the factory's corresponding model.
34
     *
35
     * @var class-string<\Illuminate\Database\Eloquent\Model|TModel>
36
     */
37
    protected $model;
38
 
39
    /**
40
     * The number of models that should be generated.
41
     *
42
     * @var int|null
43
     */
44
    protected $count;
45
 
46
    /**
47
     * The state transformations that will be applied to the model.
48
     *
49
     * @var \Illuminate\Support\Collection
50
     */
51
    protected $states;
52
 
53
    /**
54
     * The parent relationships that will be applied to the model.
55
     *
56
     * @var \Illuminate\Support\Collection
57
     */
58
    protected $has;
59
 
60
    /**
61
     * The child relationships that will be applied to the model.
62
     *
63
     * @var \Illuminate\Support\Collection
64
     */
65
    protected $for;
66
 
67
    /**
68
     * The model instances to always use when creating relationships.
69
     *
70
     * @var \Illuminate\Support\Collection
71
     */
72
    protected $recycle;
73
 
74
    /**
75
     * The "after making" callbacks that will be applied to the model.
76
     *
77
     * @var \Illuminate\Support\Collection
78
     */
79
    protected $afterMaking;
80
 
81
    /**
82
     * The "after creating" callbacks that will be applied to the model.
83
     *
84
     * @var \Illuminate\Support\Collection
85
     */
86
    protected $afterCreating;
87
 
88
    /**
89
     * The name of the database connection that will be used to create the models.
90
     *
91
     * @var string|null
92
     */
93
    protected $connection;
94
 
95
    /**
96
     * The current Faker instance.
97
     *
98
     * @var \Faker\Generator
99
     */
100
    protected $faker;
101
 
102
    /**
103
     * The default namespace where factories reside.
104
     *
105
     * @var string
106
     */
107
    protected static $namespace = 'Database\\Factories\\';
108
 
109
    /**
110
     * The default model name resolver.
111
     *
112
     * @var callable
113
     */
114
    protected static $modelNameResolver;
115
 
116
    /**
117
     * The factory name resolver.
118
     *
119
     * @var callable
120
     */
121
    protected static $factoryNameResolver;
122
 
123
    /**
124
     * Create a new factory instance.
125
     *
126
     * @param  int|null  $count
127
     * @param  \Illuminate\Support\Collection|null  $states
128
     * @param  \Illuminate\Support\Collection|null  $has
129
     * @param  \Illuminate\Support\Collection|null  $for
130
     * @param  \Illuminate\Support\Collection|null  $afterMaking
131
     * @param  \Illuminate\Support\Collection|null  $afterCreating
132
     * @param  string|null  $connection
133
     * @param  \Illuminate\Support\Collection|null  $recycle
134
     * @return void
135
     */
136
    public function __construct($count = null,
137
                                ?Collection $states = null,
138
                                ?Collection $has = null,
139
                                ?Collection $for = null,
140
                                ?Collection $afterMaking = null,
141
                                ?Collection $afterCreating = null,
142
                                $connection = null,
143
                                ?Collection $recycle = null)
144
    {
145
        $this->count = $count;
146
        $this->states = $states ?? new Collection;
147
        $this->has = $has ?? new Collection;
148
        $this->for = $for ?? new Collection;
149
        $this->afterMaking = $afterMaking ?? new Collection;
150
        $this->afterCreating = $afterCreating ?? new Collection;
151
        $this->connection = $connection;
152
        $this->recycle = $recycle ?? new Collection;
153
        $this->faker = $this->withFaker();
154
    }
155
 
156
    /**
157
     * Define the model's default state.
158
     *
159
     * @return array<string, mixed>
160
     */
161
    abstract public function definition();
162
 
163
    /**
164
     * Get a new factory instance for the given attributes.
165
     *
166
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
167
     * @return static
168
     */
169
    public static function new($attributes = [])
170
    {
171
        return (new static)->state($attributes)->configure();
172
    }
173
 
174
    /**
175
     * Get a new factory instance for the given number of models.
176
     *
177
     * @param  int  $count
178
     * @return static
179
     */
180
    public static function times(int $count)
181
    {
182
        return static::new()->count($count);
183
    }
184
 
185
    /**
186
     * Configure the factory.
187
     *
188
     * @return $this
189
     */
190
    public function configure()
191
    {
192
        return $this;
193
    }
194
 
195
    /**
196
     * Get the raw attributes generated by the factory.
197
     *
198
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
199
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
200
     * @return array<int|string, mixed>
201
     */
202
    public function raw($attributes = [], ?Model $parent = null)
203
    {
204
        if ($this->count === null) {
205
            return $this->state($attributes)->getExpandedAttributes($parent);
206
        }
207
 
208
        return array_map(function () use ($attributes, $parent) {
209
            return $this->state($attributes)->getExpandedAttributes($parent);
210
        }, range(1, $this->count));
211
    }
212
 
213
    /**
214
     * Create a single model and persist it to the database.
215
     *
216
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
217
     * @return \Illuminate\Database\Eloquent\Model|TModel
218
     */
219
    public function createOne($attributes = [])
220
    {
221
        return $this->count(null)->create($attributes);
222
    }
223
 
224
    /**
225
     * Create a single model and persist it to the database without dispatching any model events.
226
     *
227
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
228
     * @return \Illuminate\Database\Eloquent\Model|TModel
229
     */
230
    public function createOneQuietly($attributes = [])
231
    {
232
        return $this->count(null)->createQuietly($attributes);
233
    }
234
 
235
    /**
236
     * Create a collection of models and persist them to the database.
237
     *
238
     * @param  iterable<int, array<string, mixed>>  $records
239
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>
240
     */
241
    public function createMany(iterable $records)
242
    {
243
        return new EloquentCollection(
244
            collect($records)->map(function ($record) {
245
                return $this->state($record)->create();
246
            })
247
        );
248
    }
249
 
250
    /**
251
     * Create a collection of models and persist them to the database without dispatching any model events.
252
     *
253
     * @param  iterable<int, array<string, mixed>>  $records
254
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>
255
     */
256
    public function createManyQuietly(iterable $records)
257
    {
258
        return Model::withoutEvents(function () use ($records) {
259
            return $this->createMany($records);
260
        });
261
    }
262
 
263
    /**
264
     * Create a collection of models and persist them to the database.
265
     *
266
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
267
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
268
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>|\Illuminate\Database\Eloquent\Model|TModel
269
     */
270
    public function create($attributes = [], ?Model $parent = null)
271
    {
272
        if (! empty($attributes)) {
273
            return $this->state($attributes)->create([], $parent);
274
        }
275
 
276
        $results = $this->make($attributes, $parent);
277
 
278
        if ($results instanceof Model) {
279
            $this->store(collect([$results]));
280
 
281
            $this->callAfterCreating(collect([$results]), $parent);
282
        } else {
283
            $this->store($results);
284
 
285
            $this->callAfterCreating($results, $parent);
286
        }
287
 
288
        return $results;
289
    }
290
 
291
    /**
292
     * Create a collection of models and persist them to the database without dispatching any model events.
293
     *
294
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
295
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
296
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>|\Illuminate\Database\Eloquent\Model|TModel
297
     */
298
    public function createQuietly($attributes = [], ?Model $parent = null)
299
    {
300
        return Model::withoutEvents(function () use ($attributes, $parent) {
301
            return $this->create($attributes, $parent);
302
        });
303
    }
304
 
305
    /**
306
     * Create a callback that persists a model in the database when invoked.
307
     *
308
     * @param  array<string, mixed>  $attributes
309
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
310
     * @return \Closure(): (\Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>|\Illuminate\Database\Eloquent\Model|TModel)
311
     */
312
    public function lazy(array $attributes = [], ?Model $parent = null)
313
    {
314
        return fn () => $this->create($attributes, $parent);
315
    }
316
 
317
    /**
318
     * Set the connection name on the results and store them.
319
     *
320
     * @param  \Illuminate\Support\Collection  $results
321
     * @return void
322
     */
323
    protected function store(Collection $results)
324
    {
325
        $results->each(function ($model) {
326
            if (! isset($this->connection)) {
327
                $model->setConnection($model->newQueryWithoutScopes()->getConnection()->getName());
328
            }
329
 
330
            $model->save();
331
 
332
            foreach ($model->getRelations() as $name => $items) {
333
                if ($items instanceof Enumerable && $items->isEmpty()) {
334
                    $model->unsetRelation($name);
335
                }
336
            }
337
 
338
            $this->createChildren($model);
339
        });
340
    }
341
 
342
    /**
343
     * Create the children for the given model.
344
     *
345
     * @param  \Illuminate\Database\Eloquent\Model  $model
346
     * @return void
347
     */
348
    protected function createChildren(Model $model)
349
    {
350
        Model::unguarded(function () use ($model) {
351
            $this->has->each(function ($has) use ($model) {
352
                $has->recycle($this->recycle)->createFor($model);
353
            });
354
        });
355
    }
356
 
357
    /**
358
     * Make a single instance of the model.
359
     *
360
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
361
     * @return \Illuminate\Database\Eloquent\Model|TModel
362
     */
363
    public function makeOne($attributes = [])
364
    {
365
        return $this->count(null)->make($attributes);
366
    }
367
 
368
    /**
369
     * Create a collection of models.
370
     *
371
     * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
372
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
373
     * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>|\Illuminate\Database\Eloquent\Model|TModel
374
     */
375
    public function make($attributes = [], ?Model $parent = null)
376
    {
377
        if (! empty($attributes)) {
378
            return $this->state($attributes)->make([], $parent);
379
        }
380
 
381
        if ($this->count === null) {
382
            return tap($this->makeInstance($parent), function ($instance) {
383
                $this->callAfterMaking(collect([$instance]));
384
            });
385
        }
386
 
387
        if ($this->count < 1) {
388
            return $this->newModel()->newCollection();
389
        }
390
 
391
        $instances = $this->newModel()->newCollection(array_map(function () use ($parent) {
392
            return $this->makeInstance($parent);
393
        }, range(1, $this->count)));
394
 
395
        $this->callAfterMaking($instances);
396
 
397
        return $instances;
398
    }
399
 
400
    /**
401
     * Make an instance of the model with the given attributes.
402
     *
403
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
404
     * @return \Illuminate\Database\Eloquent\Model
405
     */
406
    protected function makeInstance(?Model $parent)
407
    {
408
        return Model::unguarded(function () use ($parent) {
409
            return tap($this->newModel($this->getExpandedAttributes($parent)), function ($instance) {
410
                if (isset($this->connection)) {
411
                    $instance->setConnection($this->connection);
412
                }
413
            });
414
        });
415
    }
416
 
417
    /**
418
     * Get a raw attributes array for the model.
419
     *
420
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
421
     * @return mixed
422
     */
423
    protected function getExpandedAttributes(?Model $parent)
424
    {
425
        return $this->expandAttributes($this->getRawAttributes($parent));
426
    }
427
 
428
    /**
429
     * Get the raw attributes for the model as an array.
430
     *
431
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
432
     * @return array
433
     */
434
    protected function getRawAttributes(?Model $parent)
435
    {
436
        return $this->states->pipe(function ($states) {
437
            return $this->for->isEmpty() ? $states : new Collection(array_merge([function () {
438
                return $this->parentResolvers();
439
            }], $states->all()));
440
        })->reduce(function ($carry, $state) use ($parent) {
441
            if ($state instanceof Closure) {
442
                $state = $state->bindTo($this);
443
            }
444
 
445
            return array_merge($carry, $state($carry, $parent));
446
        }, $this->definition());
447
    }
448
 
449
    /**
450
     * Create the parent relationship resolvers (as deferred Closures).
451
     *
452
     * @return array
453
     */
454
    protected function parentResolvers()
455
    {
456
        $model = $this->newModel();
457
 
458
        return $this->for->map(function (BelongsToRelationship $for) use ($model) {
459
            return $for->recycle($this->recycle)->attributesFor($model);
460
        })->collapse()->all();
461
    }
462
 
463
    /**
464
     * Expand all attributes to their underlying values.
465
     *
466
     * @param  array  $definition
467
     * @return array
468
     */
469
    protected function expandAttributes(array $definition)
470
    {
471
        return collect($definition)
472
            ->map($evaluateRelations = function ($attribute) {
473
                if ($attribute instanceof self) {
474
                    $attribute = $this->getRandomRecycledModel($attribute->modelName())
475
                        ?? $attribute->recycle($this->recycle)->create()->getKey();
476
                } elseif ($attribute instanceof Model) {
477
                    $attribute = $attribute->getKey();
478
                }
479
 
480
                return $attribute;
481
            })
482
            ->map(function ($attribute, $key) use (&$definition, $evaluateRelations) {
483
                if (is_callable($attribute) && ! is_string($attribute) && ! is_array($attribute)) {
484
                    $attribute = $attribute($definition);
485
                }
486
 
487
                $attribute = $evaluateRelations($attribute);
488
 
489
                $definition[$key] = $attribute;
490
 
491
                return $attribute;
492
            })
493
            ->all();
494
    }
495
 
496
    /**
497
     * Add a new state transformation to the model definition.
498
     *
499
     * @param  (callable(array<string, mixed>, \Illuminate\Database\Eloquent\Model|null): array<string, mixed>)|array<string, mixed>  $state
500
     * @return static
501
     */
502
    public function state($state)
503
    {
504
        return $this->newInstance([
505
            'states' => $this->states->concat([
506
                is_callable($state) ? $state : function () use ($state) {
507
                    return $state;
508
                },
509
            ]),
510
        ]);
511
    }
512
 
513
    /**
514
     * Set a single model attribute.
515
     *
516
     * @param  string|int  $key
517
     * @param  mixed  $value
518
     * @return static
519
     */
520
    public function set($key, $value)
521
    {
522
        return $this->state([$key => $value]);
523
    }
524
 
525
    /**
526
     * Add a new sequenced state transformation to the model definition.
527
     *
399 lars 528
     * @param  array  ...$sequence
148 lars 529
     * @return static
530
     */
531
    public function sequence(...$sequence)
532
    {
533
        return $this->state(new Sequence(...$sequence));
534
    }
535
 
536
    /**
537
     * Add a new sequenced state transformation to the model definition and update the pending creation count to the size of the sequence.
538
     *
399 lars 539
     * @param  array  ...$sequence
148 lars 540
     * @return static
541
     */
542
    public function forEachSequence(...$sequence)
543
    {
544
        return $this->state(new Sequence(...$sequence))->count(count($sequence));
545
    }
546
 
547
    /**
548
     * Add a new cross joined sequenced state transformation to the model definition.
549
     *
399 lars 550
     * @param  array  ...$sequence
148 lars 551
     * @return static
552
     */
553
    public function crossJoinSequence(...$sequence)
554
    {
555
        return $this->state(new CrossJoinSequence(...$sequence));
556
    }
557
 
558
    /**
559
     * Define a child relationship for the model.
560
     *
561
     * @param  \Illuminate\Database\Eloquent\Factories\Factory  $factory
562
     * @param  string|null  $relationship
563
     * @return static
564
     */
565
    public function has(self $factory, $relationship = null)
566
    {
567
        return $this->newInstance([
568
            'has' => $this->has->concat([new Relationship(
569
                $factory, $relationship ?? $this->guessRelationship($factory->modelName())
570
            )]),
571
        ]);
572
    }
573
 
574
    /**
575
     * Attempt to guess the relationship name for a "has" relationship.
576
     *
577
     * @param  string  $related
578
     * @return string
579
     */
580
    protected function guessRelationship(string $related)
581
    {
582
        $guess = Str::camel(Str::plural(class_basename($related)));
583
 
584
        return method_exists($this->modelName(), $guess) ? $guess : Str::singular($guess);
585
    }
586
 
587
    /**
588
     * Define an attached relationship for the model.
589
     *
590
     * @param  \Illuminate\Database\Eloquent\Factories\Factory|\Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array  $factory
591
     * @param  (callable(): array<string, mixed>)|array<string, mixed>  $pivot
592
     * @param  string|null  $relationship
593
     * @return static
594
     */
595
    public function hasAttached($factory, $pivot = [], $relationship = null)
596
    {
597
        return $this->newInstance([
598
            'has' => $this->has->concat([new BelongsToManyRelationship(
599
                $factory,
600
                $pivot,
601
                $relationship ?? Str::camel(Str::plural(class_basename(
602
                    $factory instanceof Factory
603
                        ? $factory->modelName()
604
                        : Collection::wrap($factory)->first()
605
                )))
606
            )]),
607
        ]);
608
    }
609
 
610
    /**
611
     * Define a parent relationship for the model.
612
     *
613
     * @param  \Illuminate\Database\Eloquent\Factories\Factory|\Illuminate\Database\Eloquent\Model  $factory
614
     * @param  string|null  $relationship
615
     * @return static
616
     */
617
    public function for($factory, $relationship = null)
618
    {
619
        return $this->newInstance(['for' => $this->for->concat([new BelongsToRelationship(
620
            $factory,
621
            $relationship ?? Str::camel(class_basename(
622
                $factory instanceof Factory ? $factory->modelName() : $factory
623
            ))
624
        )])]);
625
    }
626
 
627
    /**
628
     * Provide model instances to use instead of any nested factory calls when creating relationships.
629
     *
630
     * @param  \Illuminate\Database\Eloquent\Model|\Illuminate\Support\Collection|array  $model
631
     * @return static
632
     */
633
    public function recycle($model)
634
    {
635
        // Group provided models by the type and merge them into existing recycle collection
636
        return $this->newInstance([
637
            'recycle' => $this->recycle
638
                ->flatten()
639
                ->merge(
640
                    Collection::wrap($model instanceof Model ? func_get_args() : $model)
641
                        ->flatten()
642
                )->groupBy(fn ($model) => get_class($model)),
643
        ]);
644
    }
645
 
646
    /**
647
     * Retrieve a random model of a given type from previously provided models to recycle.
648
     *
649
     * @param  string  $modelClassName
650
     * @return \Illuminate\Database\Eloquent\Model|null
651
     */
652
    public function getRandomRecycledModel($modelClassName)
653
    {
654
        return $this->recycle->get($modelClassName)?->random();
655
    }
656
 
657
    /**
658
     * Add a new "after making" callback to the model definition.
659
     *
660
     * @param  \Closure(\Illuminate\Database\Eloquent\Model|TModel): mixed  $callback
661
     * @return static
662
     */
663
    public function afterMaking(Closure $callback)
664
    {
665
        return $this->newInstance(['afterMaking' => $this->afterMaking->concat([$callback])]);
666
    }
667
 
668
    /**
669
     * Add a new "after creating" callback to the model definition.
670
     *
671
     * @param  \Closure(\Illuminate\Database\Eloquent\Model|TModel): mixed  $callback
672
     * @return static
673
     */
674
    public function afterCreating(Closure $callback)
675
    {
676
        return $this->newInstance(['afterCreating' => $this->afterCreating->concat([$callback])]);
677
    }
678
 
679
    /**
680
     * Call the "after making" callbacks for the given model instances.
681
     *
682
     * @param  \Illuminate\Support\Collection  $instances
683
     * @return void
684
     */
685
    protected function callAfterMaking(Collection $instances)
686
    {
687
        $instances->each(function ($model) {
688
            $this->afterMaking->each(function ($callback) use ($model) {
689
                $callback($model);
690
            });
691
        });
692
    }
693
 
694
    /**
695
     * Call the "after creating" callbacks for the given model instances.
696
     *
697
     * @param  \Illuminate\Support\Collection  $instances
698
     * @param  \Illuminate\Database\Eloquent\Model|null  $parent
699
     * @return void
700
     */
701
    protected function callAfterCreating(Collection $instances, ?Model $parent = null)
702
    {
703
        $instances->each(function ($model) use ($parent) {
704
            $this->afterCreating->each(function ($callback) use ($model, $parent) {
705
                $callback($model, $parent);
706
            });
707
        });
708
    }
709
 
710
    /**
711
     * Specify how many models should be generated.
712
     *
713
     * @param  int|null  $count
714
     * @return static
715
     */
716
    public function count(?int $count)
717
    {
718
        return $this->newInstance(['count' => $count]);
719
    }
720
 
721
    /**
722
     * Specify the database connection that should be used to generate models.
723
     *
724
     * @param  string  $connection
725
     * @return static
726
     */
727
    public function connection(string $connection)
728
    {
729
        return $this->newInstance(['connection' => $connection]);
730
    }
731
 
732
    /**
733
     * Create a new instance of the factory builder with the given mutated properties.
734
     *
735
     * @param  array  $arguments
736
     * @return static
737
     */
738
    protected function newInstance(array $arguments = [])
739
    {
740
        return new static(...array_values(array_merge([
741
            'count' => $this->count,
742
            'states' => $this->states,
743
            'has' => $this->has,
744
            'for' => $this->for,
745
            'afterMaking' => $this->afterMaking,
746
            'afterCreating' => $this->afterCreating,
747
            'connection' => $this->connection,
748
            'recycle' => $this->recycle,
749
        ], $arguments)));
750
    }
751
 
752
    /**
753
     * Get a new model instance.
754
     *
755
     * @param  array<string, mixed>  $attributes
756
     * @return \Illuminate\Database\Eloquent\Model|TModel
757
     */
758
    public function newModel(array $attributes = [])
759
    {
760
        $model = $this->modelName();
761
 
762
        return new $model($attributes);
763
    }
764
 
765
    /**
766
     * Get the name of the model that is generated by the factory.
767
     *
768
     * @return class-string<\Illuminate\Database\Eloquent\Model|TModel>
769
     */
770
    public function modelName()
771
    {
772
        $resolver = static::$modelNameResolver ?? function (self $factory) {
773
            $namespacedFactoryBasename = Str::replaceLast(
774
                'Factory', '', Str::replaceFirst(static::$namespace, '', get_class($factory))
775
            );
776
 
777
            $factoryBasename = Str::replaceLast('Factory', '', class_basename($factory));
778
 
779
            $appNamespace = static::appNamespace();
780
 
781
            return class_exists($appNamespace.'Models\\'.$namespacedFactoryBasename)
782
                        ? $appNamespace.'Models\\'.$namespacedFactoryBasename
783
                        : $appNamespace.$factoryBasename;
784
        };
785
 
786
        return $this->model ?? $resolver($this);
787
    }
788
 
789
    /**
790
     * Specify the callback that should be invoked to guess model names based on factory names.
791
     *
792
     * @param  callable(self): class-string<\Illuminate\Database\Eloquent\Model|TModel>  $callback
793
     * @return void
794
     */
795
    public static function guessModelNamesUsing(callable $callback)
796
    {
797
        static::$modelNameResolver = $callback;
798
    }
799
 
800
    /**
801
     * Specify the default namespace that contains the application's model factories.
802
     *
803
     * @param  string  $namespace
804
     * @return void
805
     */
806
    public static function useNamespace(string $namespace)
807
    {
808
        static::$namespace = $namespace;
809
    }
810
 
811
    /**
812
     * Get a new factory instance for the given model name.
813
     *
814
     * @param  class-string<\Illuminate\Database\Eloquent\Model>  $modelName
815
     * @return \Illuminate\Database\Eloquent\Factories\Factory
816
     */
817
    public static function factoryForModel(string $modelName)
818
    {
819
        $factory = static::resolveFactoryName($modelName);
820
 
821
        return $factory::new();
822
    }
823
 
824
    /**
825
     * Specify the callback that should be invoked to guess factory names based on dynamic relationship names.
826
     *
827
     * @param  callable(class-string<\Illuminate\Database\Eloquent\Model>): class-string<\Illuminate\Database\Eloquent\Factories\Factory>  $callback
828
     * @return void
829
     */
830
    public static function guessFactoryNamesUsing(callable $callback)
831
    {
832
        static::$factoryNameResolver = $callback;
833
    }
834
 
835
    /**
836
     * Get a new Faker instance.
837
     *
838
     * @return \Faker\Generator
839
     */
840
    protected function withFaker()
841
    {
842
        return Container::getInstance()->make(Generator::class);
843
    }
844
 
845
    /**
846
     * Get the factory name for the given model name.
847
     *
848
     * @param  class-string<\Illuminate\Database\Eloquent\Model>  $modelName
849
     * @return class-string<\Illuminate\Database\Eloquent\Factories\Factory>
850
     */
851
    public static function resolveFactoryName(string $modelName)
852
    {
853
        $resolver = static::$factoryNameResolver ?? function (string $modelName) {
854
            $appNamespace = static::appNamespace();
855
 
856
            $modelName = Str::startsWith($modelName, $appNamespace.'Models\\')
857
                ? Str::after($modelName, $appNamespace.'Models\\')
858
                : Str::after($modelName, $appNamespace);
859
 
860
            return static::$namespace.$modelName.'Factory';
861
        };
862
 
863
        return $resolver($modelName);
864
    }
865
 
866
    /**
867
     * Get the application namespace for the application.
868
     *
869
     * @return string
870
     */
871
    protected static function appNamespace()
872
    {
873
        try {
874
            return Container::getInstance()
875
                            ->make(Application::class)
876
                            ->getNamespace();
877
        } catch (Throwable $e) {
878
            return 'App\\';
879
        }
880
    }
881
 
882
    /**
883
     * Proxy dynamic factory methods onto their proper methods.
884
     *
885
     * @param  string  $method
886
     * @param  array  $parameters
887
     * @return mixed
888
     */
889
    public function __call($method, $parameters)
890
    {
891
        if (static::hasMacro($method)) {
892
            return $this->macroCall($method, $parameters);
893
        }
894
 
895
        if ($method === 'trashed' && in_array(SoftDeletes::class, class_uses_recursive($this->modelName()))) {
896
            return $this->state([
897
                $this->newModel()->getDeletedAtColumn() => $parameters[0] ?? Carbon::now()->subDay(),
898
            ]);
899
        }
900
 
901
        if (! Str::startsWith($method, ['for', 'has'])) {
902
            static::throwBadMethodCallException($method);
903
        }
904
 
905
        $relationship = Str::camel(Str::substr($method, 3));
906
 
907
        $relatedModel = get_class($this->newModel()->{$relationship}()->getRelated());
908
 
909
        if (method_exists($relatedModel, 'newFactory')) {
910
            $factory = $relatedModel::newFactory() ?? static::factoryForModel($relatedModel);
911
        } else {
912
            $factory = static::factoryForModel($relatedModel);
913
        }
914
 
915
        if (str_starts_with($method, 'for')) {
916
            return $this->for($factory->state($parameters[0] ?? []), $relationship);
917
        } elseif (str_starts_with($method, 'has')) {
918
            return $this->has(
919
                $factory
920
                    ->count(is_numeric($parameters[0] ?? null) ? $parameters[0] : 1)
921
                    ->state((is_callable($parameters[0] ?? null) || is_array($parameters[0] ?? null)) ? $parameters[0] : ($parameters[1] ?? [])),
922
                $relationship
923
            );
924
        }
925
    }
926
}