Completed
Push — master ( 4fb1d6...a24b8d )
by Oscar
01:43
created

FieldFactory::getClassName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace SimpleCrud\Fields;
5
6
use SimpleCrud\Table;
7
8
/**
9
 * Class to create instances of a field.
10
 */
11
final class FieldFactory implements FieldFactoryInterface
12
{
13
    private $className;
14
    private $types = [];
15
    private $names = [];
16
    private $config = [];
17
18
    public function __construct(string $className, array $types = [], array $names = [], array $config = [])
19
    {
20
        $this->className = $className;
21
        $this->types = $types;
22
        $this->names = $names;
23
        $this->config = $config;
24
    }
25
26
    public function getClassName(): string
27
    {
28
        return $this->className;
29
    }
30
31
    public function addTypes(string ...$types): self
32
    {
33
        $this->types = array_merge($this->types, $types);
34
        return $this;
35
    }
36
37
    public function getTypes(): array
38
    {
39
        return $this->types;
40
    }
41
42
    public function addNames(string ...$names): self
43
    {
44
        $this->names = array_merge($this->names, $names);
45
        return $this;
46
    }
47
48
    public function getNames(): array
49
    {
50
        return $this->names;
51
    }
52
53
    public function addConfig(array $config): self
54
    {
55
        $this->config = $config + $this->config;
56
        return $this;
57
    }
58
59
    public function getConfig(): array
60
    {
61
        return $this->config;
62
    }
63
64
    public function create(Table $table, array $info): ?Field
65
    {
66
        if (!$this->matches($info['name'], $info['type'])) {
67
            return null;
68
        }
69
70
        $className = $this->className;
71
        $field = new $className($table, $info);
72
73
        foreach ($this->config as $name => $value) {
74
            $field->setConfig($name, $value);
75
        }
76
77
        return $field;
78
    }
79
80
    private function matches(string $fieldName, string $fieldType): bool
81
    {
82
        foreach ($this->names as $name) {
83
            if ($fieldName === $name || ($name[0] === '/' && preg_match($name, $fieldName))) {
84
                return true;
85
            }
86
        }
87
88
        return in_array($fieldType, $this->types);
89
    }
90
}
91