Completed
Push — master ( eaeb56...0fd03b )
by Philip
02:37
created

TwigExtensions::formatDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
/*
4
 * This file is part of the CRUDlex package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[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
namespace CRUDlex;
13
14
use Pimple\Container;
15
use Symfony\Component\Intl\Intl;
16
17
/**
18
 * Provides and setups the Twig extensions like filters.
19
 */
20
class TwigExtensions {
21
22
    /**
23
     * Formats the given time value to a timestring defined by the $pattern
24
     * parameter.
25
     *
26
     * If the value is false (like null), an empty string is
27
     * returned. Else, the value is tried to be parsed as datetime via the
28
     * given pattern. If that fails, it is tried to be parsed with the pattern
29
     * 'Y-m-d H:i:s'. If that fails, the value is returned unchanged. Else, it
30
     * is returned formatted with the given pattern. The effect is to shorten
31
     * 'Y-m-d H:i:s' to 'Y-m-d' for example.
32
     *
33
     * @param string $value
34
     * the value to be formatted
35
     * @param string $timezone
36
     * the timezone of the value
37
     * @param string $pattern
38
     * the pattern with which the value is parsed and formatted
39
     *
40
     * @return string
41
     * the formatted value
42
     */
43
    protected function formatTime($value, $timezone, $pattern) {
44
        if (!$value) {
45
            return '';
46
        }
47
        $result = \DateTime::createFromFormat($pattern, $value, new \DateTimeZone($timezone));
48
        if ($result === false) {
49
            $result = \DateTime::createFromFormat('Y-m-d H:i:s', $value, new \DateTimeZone($timezone));
50
        }
51
        if ($result === false) {
52
            return $value;
53
        }
54
        $result->setTimezone(new \DateTimeZone(date_default_timezone_get()));
55
        return $result->format($pattern);
56
    }
57
58
    /**
59
     * Registers all extensions.
60
     *
61
     * @param Container $app
62
     * the current application
63
     */
64
    public function registerTwigExtensions(Container $app) {
65
        $self = $this;
66
        $app->extend('twig', function(\Twig_Environment $twig) use ($self) {
67
            $twig->addFilter(new \Twig_SimpleFilter('arrayColumn', 'array_column'));
68
            $twig->addFilter(new \Twig_SimpleFilter('languageName', [$self, 'getLanguageName']));
69
            $twig->addFilter(new \Twig_SimpleFilter('float', [$self, 'formatFloat']));
70
            $twig->addFilter(new \Twig_SimpleFilter('basename', 'basename'));
71
            $twig->addFilter(new \Twig_SimpleFilter('formatDate', [$self, 'formatDate']));
72
            $twig->addFilter(new \Twig_SimpleFilter('formatDateTime', [$self, 'formatDateTime']));
73
            return $twig;
74
        });
75
    }
76
77
    /**
78
     * Gets a language name in the given language.
79
     *
80
     * @param string $language
81
     * the language code of the desired language name
82
     *
83
     * @return string
84
     * the language name in the given language or null if not available
85
     */
86
    public function getLanguageName($language) {
87
        return Intl::getLanguageBundle()->getLanguageName($language, $language, $language);
88
    }
89
90
    /**
91
     * Formats a float to not display in scientific notation.
92
     *
93
     * @param float $float
94
     * the float to format
95
     *
96
     * @return double|string
97
     * the formated float
98
     */
99
    public function formatFloat($float) {
100
101
        if (!$float) {
102
            return $float;
103
        }
104
105
        $zeroFraction = $float - floor($float) == 0 ? '0' : '';
106
107
        // We don't want values like 0.004 converted to  0.00400000000000000008
108
        if ($float > 0.0001) {
109
            return $float.($zeroFraction === '0' ? '.'.$zeroFraction : '');
110
        }
111
112
        // We don't want values like 0.00004 converted to its scientific notation 4.0E-5
113
        return rtrim(sprintf('%.20F', $float), '0').$zeroFraction;
114
    }
115
116
    /**
117
     * Formats the given value to a date of the format 'Y-m-d'.
118
     *
119
     * @param string $value
120
     * the value, might be of the format 'Y-m-d H:i' or 'Y-m-d'
121
     * @param boolean $isUTC
122
     * whether the given value is in UTC
123
     *
124
     * @return string
125
     * the formatted result or an empty string on null value
126
     */
127
    public function formatDate($value, $isUTC) {
128
        $timezone = $isUTC ? 'UTC' : date_default_timezone_get();
129
        return $this->formatTime($value, $timezone, 'Y-m-d');
130
    }
131
132
    /**
133
     * Formats the given value to a date of the format 'Y-m-d H:i'.
134
     *
135
     * @param string $value
136
     * the value, might be of the format 'Y-m-d H:i'
137
     * @param boolean $isUTC
138
     * whether the given value is in UTC
139
     *
140
     * @return string
141
     * the formatted result or an empty string on null value
142
     */
143
    public function formatDateTime($value, $isUTC) {
144
        $timezone = $isUTC ? 'UTC' : date_default_timezone_get();
145
        return $this->formatTime($value, $timezone, 'Y-m-d H:i');
146
    }
147
148
}
149