Factory::instantiate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Zerg\Field;
4
5
/**
6
 * Field factory class. Instantiates fields by their declarations.
7
 *
8
 * @since 0.1
9
 * @package Zerg\Field
10
 */
11
class Factory
12
{
13
    /**
14
     * Create field instance by its declaration.
15
     *
16
     * @param array $declaration Field declaration.
17
     * @return AbstractField Field instance.
18
     * @throws ConfigurationException If invalid declaration is presented.
19
     */
20 21
    private static function instantiate(array $declaration)
21
    {
22 21
        $fieldType = array_shift($declaration);
23
24 21
        $class = "\\Zerg\\Field\\" . ucfirst(strtolower($fieldType));
25 21
        if (class_exists($class)) {
26 20
            $reflection = new \ReflectionClass($class);
27 20
            return $reflection->newInstanceArgs($declaration);
28
        }
29
30 1
        throw new ConfigurationException("Field {$fieldType} doesn't exist");
31
    }
32
33 22
    public static function get($array)
34
    {
35 22
        if (!is_array($array)) {
36 1
            throw new ConfigurationException('Unknown element declaration');
37
        }
38
39 21
        $isAssoc = array_keys(array_keys($array)) !== array_keys($array);
40
41 21
        if ($isAssoc || is_array(reset($array))) {
42 4
            $array = ['collection', $array];
43 4
        }
44
45 21
        return Factory::instantiate($array);
46
    }
47
}