Passed
Push — master ( db3d0f...fd00a0 )
by Claudio
08:00
created

ValueObject::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Budgegeria\IntlSort\Comparator;
6
7
use Budgegeria\IntlSort\Exception\IntlSortException;
8
use Collator;
9
10
class ValueObject implements Comparable
11
{
12
    /**
13
     * @var Collator
14
     */
15
    private $collator;
16
17
    /**
18
     * @var string
19
     */
20
    private $methodOrPropertyName;
21
22
    /**
23
     * @var bool
24
     */
25
    private $isProperty;
26
27 26
    public function __construct(Collator $collator, string $name, bool $isProperty)
28
    {
29 26
        $this->collator = $collator;
30 26
        $this->methodOrPropertyName = $name;
31 26
        $this->isProperty = $isProperty;
32 26
    }
33
34
    /**
35
     * {@inheritDoc}
36
     */
37 24
    public function compare($value, $comparativeValue): int
38
    {
39
        try {
40 24
            $compared = $this->collator->compare(
41 24
                $this->callAccessor($value),
42 24
                $this->callAccessor($comparativeValue)
43
            );
44
45 22
            if ($this->collator->getErrorCode() !== 0) {
46 22
                throw IntlSortException::errorOnSort($this->collator->getErrorMessage());
47
            }
48 4
        } catch (\IntlException $e) {
49 2
            throw IntlSortException::errorOnSort($e->getMessage());
50
        }
51
52 20
        return $compared;
53
    }
54
55 24
    private function callAccessor(object $valueObject) : string
56
    {
57 24
        if ($this->isProperty) {
58 12
            return (string) $valueObject->{$this->methodOrPropertyName};
59
        }
60
61 12
        return (string) $valueObject->{$this->methodOrPropertyName}();
62
    }
63
}