-
Notifications
You must be signed in to change notification settings - Fork 5
/
FactoryMuffin.php
55 lines (47 loc) · 1.82 KB
/
FactoryMuffin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
namespace saada\FactoryMuffin;
use League\FactoryMuffin\Exceptions\ModelException;
use League\FactoryMuffin\Exceptions\ModelNotFoundException;
use League\FactoryMuffin\FactoryMuffin as LeagueFactoryMuffin;
class FactoryMuffin extends LeagueFactoryMuffin
{
/**
* @param array $models ex: [ Model1::className(), Model2::className() ]
* @throws ModelException
* @throws ModelNotFoundException
* @throws \League\FactoryMuffin\Exceptions\DefinitionAlreadyDefinedException
*/
public function __construct($models = [])
{
parent::__construct(new ModelStoreYii());
if (!empty($models)) {
$this->loadModelDefinitions($models);
}
}
/**
* Go into each model and add its implementation of definitions() into FactoryMuffin
* @param array $models ex: [ Model1::className(), Model2::className() ]
* @return void
*/
public function loadModelDefinitions($models)
{
// load model definitions
if (empty($models) || !is_array($models)) {
throw new ModelNotFoundException(self::class, 'Models should be passed as an array of class names!');
}
foreach ($models as $model) {
/** @var FactoryInterface $model */
if (!in_array(FactoryInterface::class, class_implements($model))) {
throw new ModelException($model, 'Could not find interface implementation: ' . FactoryInterface::class);
}
$fmModel = $this->define($model);
$definitions = $model::definitions();
if (!empty($definitions[0]) and is_array($definitions[0])) {
$fmModel->setDefinitions($definitions[0]);
if (!empty($definitions[1])) {
$fmModel->setCallback($definitions[1]);
}
}
}
}
}