Passed
Push — master ( 22202f...615a20 )
by David
02:36
created

StringValue::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DavidGarcia\ValueObject\Primitive;
6
7
use DavidGarcia\ValueObject\Exception\InvalidValueException;
8
9
class StringValue extends AbstractValue
10
{
11
    private string $value;
12
13 8
    private function __construct(string $value, bool $cache)
14
    {
15 8
        $this->value = $value;
16
17 8
        if ($cache) {
18 2
            self::cacheStore($value, $this);
19
        }
20 8
    }
21
22
    /**
23
     * Exposes the stored string value.
24
     *
25
     * @return string The string value
26
     */
27 4
    public function __toString(): string
28
    {
29 4
        return $this->getValue();
30
    }
31
32
    /**
33
     * Creates the value object.
34
     *
35
     * @param string $value The string value
36
     * @param bool   $cache Cache the value so we reuse the same object
37
     *
38
     * @throws InvalidValueException The initial validation of the value has failed
39
     *
40
     * @return StringValue The value object
41
     */
42 13
    public static function create(string $value, bool $cache = false): self
43
    {
44 13
        if ('' === trim($value)) {
45 1
            throw new InvalidValueException('String value cannot be empty');
46
        }
47
48 12
        $object = $cache ? parent::cacheRetrieve($value) : null;
49
50 12
        if (null === $object) {
51 8
            $object = new self($value, $cache);
52
        }
53
54 12
        return $object;
55
    }
56
57
    /**
58
     * Exposes the stored string value.
59
     *
60
     * @return string The string value
61
     */
62 8
    public function getValue(): string
63
    {
64 8
        return $this->value;
65
    }
66
67
    /**
68
     * Compares if the value of a given object matches with this object.
69
     *
70
     * @param StringValue $object The input object to be compared
71
     *
72
     * @return bool TRUE if the value matches; FALSE otherwise
73
     */
74 4
    public function equals(StringValue $object): bool
75
    {
76 4
        return $this->getValue() === $object->getValue();
77
    }
78
}
79