Stringifier::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * This file is part of byrokrat\autogiro.
5
 *
6
 * byrokrat\autogiro is free software: you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * byrokrat\autogiro is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with byrokrat\autogiro. If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 * Copyright 2016-21 Hannes Forsgård
20
 */
21
22
declare(strict_types=1);
23
24
namespace byrokrat\autogiro\Xml;
25
26
use Money\Money;
27
use Money\MoneyFormatter;
28
29
/**
30
 * Helper class to cast values to string
31
 */
32
class Stringifier
33
{
34
    /**
35
     * Arrays cast value
36
     */
37
    public const ARRAY_VALUE = 'ARRAY_VALUE';
38
39
    /**
40
     * Object cast value
41
     */
42
    public const OBJECT_VALUE = 'OBJECT_VALUE';
43
44
    /**
45
     * @var MoneyFormatter
46
     */
47
    private $moneyFormatter;
48
49
    public function __construct(MoneyFormatter $moneyFormatter)
50
    {
51
        $this->moneyFormatter = $moneyFormatter;
52
    }
53
54
    /**
55
     * Cast value to string
56
     *
57
     * @param mixed $value
58
     */
59
    public function stringify($value): string
60
    {
61
        if ($value instanceof \DateTimeInterface) {
62
            return $value->format('Y-m-d');
63
        }
64
65
        if ($value instanceof Money) {
66
            return $this->moneyFormatter->format($value);
67
        }
68
69
        if (is_array($value)) {
70
            return self::ARRAY_VALUE;
71
        }
72
73
        if (is_object($value) && !method_exists($value, '__tostring')) {
74
            return self::OBJECT_VALUE;
75
        }
76
77
        return (string)$value;
78
    }
79
}
80