RoughDate::__toString()   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
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of RoughDate library.
5
 *
6
 * (c) Marek Matulka <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Mareg\RoughDate;
15
16
use Mareg\RoughDate\Helper\StringDateNormalizer;
17
use Mareg\RoughDate\Helper\StringDateFormatter;
18
19
final class RoughDate implements \JsonSerializable
20
{
21
    const DEFAULT_DATE_FORMAT = 'Y-m-d';
22
23
    /**
24
     * @var string
25
     */
26
    private $date;
27
28
    /**
29
     * @param string $dateString
30
     */
31
    private function __construct(string $dateString)
32
    {
33
        $this->date = $dateString;
34
    }
35
36
    /**
37
     * @param string $string
38
     *
39
     * @return RoughDate
40
     */
41
    public static function fromString(string $string): RoughDate
42
    {
43
        $noramlizer = new StringDateNormalizer();
44
45
        return new RoughDate($noramlizer->normalize($string));
46
    }
47
48
    /**
49
     * @param \DateTimeInterface $dateTime
50
     *
51
     * @return RoughDate
52
     */
53
    public static function fromDateTime(\DateTimeInterface $dateTime): RoughDate
54
    {
55
        return new RoughDate($dateTime->format(self::DEFAULT_DATE_FORMAT));
56
    }
57
58
    /**
59
     * @return string
60
     */
61
    public function __toString(): string
62
    {
63
        return $this->format();
64
    }
65
66
    /**
67
     * @param string $format
68
     *
69
     * @return string
70
     */
71
    public function format(string $format = self::DEFAULT_DATE_FORMAT): string
72
    {
73
        $formatter = StringDateFormatter::fromString($this->date);
74
75
        return $formatter->format($format);
76
    }
77
78
    /**
79
     * @return string
80
     */
81
    public function jsonSerialize(): string
82
    {
83
        return $this->format();
84
    }
85
}
86