Completed
Push — master ( ab5447...1cc941 )
by Jesse
02:05
created

Mapper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
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\Mapping;
11
use Stratadox\Hydration\MapsObject;
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 hydrator() : Hydrates
44
    {
45
        return MappedHydrator::fromThis($this->map());
46
    }
47
48
    public function map() : MapsObject
49
    {
50
        $class = $this->name;
51
        $properties = [];
52
        foreach ($this->properties as $name => $instruction) {
53
            $properties[] = $instruction->followFor($name);
54
        }
55
        return Mapping::ofThe($class, ...$properties);
56
    }
57
58
    private function add(
59
        string $property,
60
        InstructsHowToMap $instruction = null
61
    ) : array
62
    {
63
        return $this->properties + [$property => $instruction ?: Is::string()];
64
    }
65
}
66