Visited   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 60
rs 10
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A already() 0 3 1
A add() 0 8 2
A __construct() 0 4 1
A name() 0 3 1
A noneYet() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\EntityState\Internal;
5
6
use function array_merge as add;
7
use function array_search as search;
8
use function get_class as classOf;
9
use function gettype as typeOf;
10
use function in_array as has;
11
use function is_object as isObject;
12
13
/**
14
 * Visited list.
15
 *
16
 * @internal
17
 * @author Stratadox
18
 */
19
final class Visited
20
{
21
    private $visited;
22
    private $paths;
23
24
    private function __construct(array $visited, array $paths)
25
    {
26
        $this->visited = $visited;
27
        $this->paths = $paths;
28
    }
29
30
    /**
31
     * Produces an empty visited list.
32
     *
33
     * @return Visited The empty visited list.
34
     */
35
    public static function noneYet(): Visited
36
    {
37
        return new Visited([], []);
38
    }
39
40
    /**
41
     * Checks whether the value is already on the list.
42
     *
43
     * @param mixed $value The value to check for.
44
     * @return bool        Whether the value is on the list.
45
     */
46
    public function already($value): bool
47
    {
48
        return has($value, $this->visited, true);
49
    }
50
51
    /**
52
     * Retrieves the name associated with the visited value.
53
     *
54
     * @param mixed $value The value to find the property name for.
55
     * @return string      The name associated with the value.
56
     */
57
    public function name($value): string
58
    {
59
        return $this->paths[search($value, $this->visited)];
60
    }
61
62
    /**
63
     * Adds the value to the list of visited values.
64
     *
65
     * Also keeps a note on where to find it.
66
     *
67
     * @param mixed $value The value to mark as visited.
68
     * @param Name  $name  The name of the visited property.
69
     * @return Visited     The updated visited list.
70
     */
71
    public function add($value, Name $name): Visited
72
    {
73
        return new Visited(
74
            add($this->visited, [$value]),
75
            add($this->paths, [sprintf(
76
                '%s:%s',
77
                isObject($value) ? classOf($value) : typeOf($value),
78
               $name
79
           )])
80
        );
81
    }
82
}
83