Completed
Push — master ( 35993a...8e7e6b )
by Jesse
02:55
created

Mapper::add()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 1
nop 2
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stratadox\Hydration\Mapper;
6
7
use Stratadox\Hydration\Hydrates;
8
use Stratadox\Hydration\Hydrator\MappedHydrator;
9
use Stratadox\Hydration\Mapper\Instruction\Is;
10
use Stratadox\Hydration\Mapping\Properties;
11
use Stratadox\Hydration\MapsProperties;
12
13
/**
14
 * Produces a mapping object.
15
 *
16
 * @package Stratadox\Hydrate
17
 * @author Stratadox
18
 */
19
final class Mapper implements MakesMap
20
{
21
    private $name;
22
    private $properties;
23
24
    private function __construct(string $name, array $properties = [])
25
    {
26
        $this->name = $name;
27
        $this->properties = $properties;
28
    }
29
30
    public static function forThe(string $className) : self
31
    {
32
        return new self($className);
33
    }
34
35
    public function property(
36
        string $property,
37
        InstructsHowToMap $instruction = null
38
    ) : MakesMap
39
    {
40
        return new self($this->name, $this->add($property, $instruction));
41
    }
42
43
    public function finish() : Hydrates
44
    {
45
        $class = $this->name;
46
        $properties = [];
47
        foreach ($this->properties as $name => $instruction) {
48
            $properties[] = $instruction->followFor($name);
49
        }
50
        return MappedHydrator::forThe($class, Properties::map(...$properties));
51
    }
52
53
    private function add(
54
        string $property,
55
        InstructsHowToMap $instruction = null
56
    ) : array
57
    {
58
        return $this->properties + [$property => $instruction ?: Is::string()];
59
    }
60
}
61