CreatePolymorphic   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 14
dl 0
loc 49
c 0
b 0
f 0
rs 10
ccs 13
cts 13
cp 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A create() 0 19 6
1
<?php
2
/**
3
 * File was created 17.05.2016 06:20
4
 */
5
6
namespace PeekAndPoke\Component\Creator;
7
8
9
/**
10
 * @author Karsten J. Gerber <[email protected]>
11
 */
12
class CreatePolymorphic implements Creator
13
{
14
    /** @var Creator[] */
15
    private $mapping;
16
    /** @var string */
17
    private $discriminator;
18
    /** @var Creator */
19
    private $defaultCreator;
20
21
    /**
22
     * CreatePolymorphic constructor.
23
     *
24
     * @param Creator[] $mapping        Key is defining the class, value is the creator for this class
25
     * @param string    $discriminator  The name of the field to look for when deciding which class to create
26
     * @param Creator   $defaultCreator The default creator to use when nothing is found in the mapping
27
     */
28 9
    public function __construct(array $mapping, $discriminator, Creator $defaultCreator)
29
    {
30 9
        $this->mapping        = $mapping;
31 9
        $this->discriminator  = $discriminator;
32 9
        $this->defaultCreator = $defaultCreator;
33 9
    }
34
35
    /**
36
     * Creates a new instance
37
     *
38
     * @param mixed $data
39
     *
40
     * @return mixed
41
     */
42 9
    public function create($data = null)
43
    {
44 9
        if (! \is_array($data) && ! $data instanceof \ArrayAccess) {
45 1
            return null;
46
        }
47
48
        // is the discriminator present
49 8
        if (isset($data[$this->discriminator])) {
50
            // get the value
51 5
            $type = $data[$this->discriminator];
52
53
            // do we know how to map this one
54 5
            if ($type !== null && isset($this->mapping[$type])) {
55 4
                return $this->mapping[$type]->create($data);
56
            }
57
        }
58
59
        // map to the default
60 4
        return $this->defaultCreator->create($data);
61
    }
62
}
63