StringValue   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 72
ccs 20
cts 20
cp 1
rs 10
c 1
b 0
f 0
wmc 9

5 Methods

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