Faktory::getFactory()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php namespace AdamWathan\Faktory;
2
3
use AdamWathan\Faktory\Factory\Factory;
4
use AdamWathan\Faktory\Factory\FactoryProxy;
5
use Closure;
6
7
class Faktory
8
{
9
    protected $factories = [];
10
11
    public function define($model, $name, $definitionCallback = null)
12
    {
13
        if ($name instanceof Closure) {
14
            $definitionCallback = $name;
15
            $name = $model;
16
        }
17
18
        $factory = Factory::make($model, $this);
19
        $this->addFactory($name, $factory);
20
        $definitionCallback($factory);
21
    }
22
23
    protected function addFactory($name, $factory)
24
    {
25
        $this->factories[$name] = $factory;
26
    }
27
28
    public function build($name, $attributes = [])
29
    {
30
        return $this->getFactory($name)->build($attributes);
31
    }
32
33
    public function create($name, $attributes = [])
34
    {
35
        return $this->getFactory($name)->create($attributes);
36
    }
37
38
    public function buildMany($name, $count, $attributes = [])
39
    {
40
        return $this->getFactory($name)->buildMany($count, $attributes);
41
    }
42
43
    public function createMany($name, $count, $attributes = [])
44
    {
45
        return $this->getFactory($name)->createMany($count, $attributes);
46
    }
47
48
    public function getFactory($name)
49
    {
50
        return $this->getProxyFactory($name);
51
    }
52
53
    protected function getProxyFactory($name)
54
    {
55
        return new FactoryProxy(function () use ($name) {
56
            return $this->fetchFactory($name);
57
        });
58
    }
59
60
    protected function fetchFactory($name)
61
    {
62
        if (! isset($this->factories[$name])) {
63
            throw new FactoryNotRegisteredException("'{$name}' is not a registered factory.");
64
        }
65
        return $this->factories[$name];
66
    }
67
}
68