1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\Foundry; |
4
|
|
|
|
5
|
|
|
use Doctrine\Persistence\ObjectRepository; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* @author Kevin Bond <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
abstract class ModelFactory extends Factory |
11
|
|
|
{ |
12
|
46 |
|
private function __construct() |
13
|
|
|
{ |
14
|
46 |
|
parent::__construct(static::getClass()); |
15
|
46 |
|
} |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param array|callable|string $defaultAttributes If string, assumes state |
19
|
|
|
* @param string ...$states Optionally pass default states (these must be methods on your ObjectFactory with no arguments) |
20
|
|
|
*/ |
21
|
46 |
|
final public static function new($defaultAttributes = [], string ...$states): self |
22
|
|
|
{ |
23
|
|
|
// todo - is this too magical? |
24
|
46 |
|
if (\is_string($defaultAttributes)) { |
25
|
2 |
|
$states = \array_merge([$defaultAttributes], $states); |
26
|
2 |
|
$defaultAttributes = []; |
27
|
|
|
} |
28
|
|
|
|
29
|
46 |
|
$factory = new static(); |
30
|
|
|
$factory = $factory |
31
|
46 |
|
->withAttributes([$factory, 'getDefaults']) |
32
|
46 |
|
->withAttributes($defaultAttributes) |
33
|
46 |
|
->initialize() |
34
|
|
|
; |
35
|
|
|
|
36
|
46 |
|
foreach ($states as $state) { |
37
|
2 |
|
$factory = $factory->{$state}(); |
38
|
|
|
} |
39
|
|
|
|
40
|
46 |
|
return $factory; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Try and find existing object for the given $attributes. If not found, |
45
|
|
|
* instantiate and persist. |
46
|
|
|
* |
47
|
|
|
* @return Proxy|object |
48
|
|
|
*/ |
49
|
2 |
|
final public static function findOrCreate(array $attributes): object |
50
|
|
|
{ |
51
|
2 |
|
if ($found = self::repository(true)->find($attributes)) { |
52
|
2 |
|
return $found; |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
return self::new()->create($attributes); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return RepositoryProxy|ObjectRepository |
60
|
|
|
*/ |
61
|
10 |
|
final public static function repository(bool $proxy = true): ObjectRepository |
62
|
|
|
{ |
63
|
10 |
|
return PersistenceManager::repositoryFor(static::getClass(), $proxy); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Override to add default instantiator and default afterInstantiate/afterPersist events. |
68
|
|
|
*/ |
69
|
46 |
|
protected function initialize(): self |
70
|
|
|
{ |
71
|
46 |
|
return $this; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @param array|callable $attributes |
76
|
|
|
*/ |
77
|
4 |
|
final protected function addState($attributes = []): self |
78
|
|
|
{ |
79
|
4 |
|
return $this->withAttributes($attributes); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
abstract protected static function getClass(): string; |
83
|
|
|
|
84
|
|
|
abstract protected function getDefaults(): array; |
85
|
|
|
} |
86
|
|
|
|