Completed
Push — master ( 205cf7...842449 )
by Arnold
02:56
created

DateExtension::formatLocal()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 26
rs 8.439
cc 6
eloc 16
nc 7
nop 4
1
<?php
2
3
namespace Jasny\Twig;
4
5
/**
6
 * Format a date based on the current locale in Twig
7
 */
8
class DateExtension extends \Twig_Extension
9
{
10
    /**
11
     * Class constructor
12
     */
13
    public function __construct()
14
    {
15
        if (!extension_loaded('intl')) {
16
            throw new \Exception("The Date Twig extension requires the 'intl' PHP extension."); // @codeCoverageIgnore
17
        }
18
    }
19
20
    
21
    /**
22
     * Return extension name
23
     * 
24
     * @return string
25
     */
26
    public function getName()
27
    {
28
        return 'jasny/date';
29
    }
30
31
    /**
32
     * Callback for Twig to get all the filters.
33
     * 
34
     * @return \Twig_Filter[]
35
     */
36
    public function getFilters()
37
    {
38
        return [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array('localdate'... array($this, 'age'))); (array<string,Twig_SimpleFilter>) is incompatible with the return type declared by the interface Twig_ExtensionInterface::getFilters of type Twig_SimpleFilter[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
39
            'localdate' => new \Twig_SimpleFilter('localdate', [$this, 'localDate']),
40
            'localtime' => new \Twig_SimpleFilter('localtime', [$this, 'localTime']),
41
            'localdatetime' => new \Twig_SimpleFilter('localdatetime', [$this, 'localDateTime']),
42
            'duration' => new \Twig_SimpleFilter('duration', [$this, 'duration']),
43
            'age' => new \Twig_SimpleFilter('age', [$this, 'age']),
44
        ];
45
    }
46
47
    
48
    /**
49
     * Format the date/time value as a string based on the current locale
50
     * 
51
     * @param string $format    null, 'short', 'medium', 'long', 'full' or pattern
52
     * @param int    $calendar
53
     * @return array [format, pattern)
54
     */
55
    protected function getFormat($format, $calendar = \IntlDateFormatter::GREGORIAN)
56
    {
57
        if ($format === false) {
58
            return [\IntlDateFormatter::NONE, null];
59
        }
60
        
61
        $pattern = null;
62
        
63
        switch ($format) {
64
            case null:     $pattern = $this->getDefaultDatePattern($calendar); 
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
65
                           $format = \IntlDateFormatter::SHORT; break;
0 ignored issues
show
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
66
            case 'short':  $format = \IntlDateFormatter::SHORT;  break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
67
            case 'medium': $format = \IntlDateFormatter::MEDIUM; break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
68
            case 'long':   $format = \IntlDateFormatter::LONG;   break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
69
            case 'full':   $format = \IntlDateFormatter::FULL;   break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
70
            default:       $pattern = $format;
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
71
                           $format = \IntlDateFormatter::SHORT; break;
0 ignored issues
show
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
72
        }
73
        
74
        return [$format, $pattern];
75
    }
76
    
77
    /**
78
     * Default date pattern is short date pattern with 4 digit year
79
     * 
80
     * @param int $calendar
81
     * @return string
82
     */
83
    protected function getDefaultDatePattern($calendar=\IntlDateFormatter::GREGORIAN)
84
    {
85
        $pattern = \IntlDateFormatter::create(
86
            \Locale::getDefault(),
87
            \IntlDateFormatter::SHORT,
88
            \IntlDateFormatter::NONE,
89
            \IntlTimeZone::getGMT(),
90
            $calendar
91
        )->getPattern();
92
        
93
        return preg_replace('/\byy?\b/', 'yyyy', $pattern);
94
    }
95
96
    /**
97
     * Format the date and/or time value as a string based on the current locale
98
     * 
99
     * @param DateTime|int|string $date
100
     * @param string              $dateFormat  null, 'short', 'medium', 'long', 'full' or pattern
101
     * @param string              $timeFormat  null, 'short', 'medium', 'long', 'full' or pattern
102
     * @param string              $calendar    'gregorian' or 'traditional'
103
     * @return string
104
     */
105
    protected function formatLocal($date, $dateFormat, $timeFormat, $calendar = 'gregorian')
106
    {
107
        if (!isset($date)) {
108
            return null;
109
        }
110
        
111
        if (!$date instanceof \DateTime) {
112
            $date = is_int($date) ? \DateTime::createFromFormat('U', $date) : new \DateTime((string)$date);
113
        }
114
        
115
        $calendarConst = $calendar === 'traditional' ? \IntlDateFormatter::TRADITIONAL : \IntlDateFormatter::GREGORIAN;
116
        
117
        list($datetype, $pattern1) = $this->getFormat($dateFormat, $calendarConst);
118
        list($timetype, $pattern2) = $this->getFormat($timeFormat, $calendarConst);
119
        
120
        $df = new \IntlDateFormatter(
121
            \Locale::getDefault(),
122
            $datetype,
123
            $timetype,
124
            null,
125
            $calendarConst,
126
            $pattern1 ?: $pattern2
127
        );
128
        
129
        return $df->format($date->getTimestamp());
130
    }
131
132
    /**
133
     * Format the date value as a string based on the current locale
134
     * 
135
     * @param DateTime|int|string $date
136
     * @param string              $format    null, 'short', 'medium', 'long', 'full' or pattern
137
     * @param string              $calendar  'gregorian' or 'traditional'
138
     * @return string
139
     */
140
    public function localDate($date, $format = null, $calendar = 'gregorian')
141
    {
142
        return $this->formatLocal($date, $format, false, $calendar);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
143
    }
144
    
145
    /**
146
     * Format the time value as a string based on the current locale
147
     * 
148
     * @param DateTime|int|string $date
149
     * @param string              $format    'short', 'medium', 'long', 'full' or pattern
150
     * @param string              $calendar  'gregorian' or 'traditional'
151
     * @return string
152
     */
153
    public function localTime($date, $format='short', $calendar='gregorian')
154
    {
155
        return $this->formatLocal($date, false, $format, $calendar);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
156
    }
157
158
    /**
159
     * Format the date/time value as a string based on the current locale
160
     * 
161
     * @param DateTime|int|string $date
162
     * @param string              $format    date format, pattern or ['date'=>format, 'time'=>format)
163
     * @param string              $calendar  'gregorian' or 'traditional'
164
     * @return string
165
     */
166
    public function localDateTime($date, $format=null, $calendar='gregorian')
167
    {
168
        if (is_array($format) || !isset($format)) {
169
            $formatDate = null;
170
            $formatTime = 'short';
171
            
172
            extract((array)$format, EXTR_PREFIX_ALL, 'format');
0 ignored issues
show
Bug introduced by
(array) $format cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
173
        } else {
174
            $formatDate = $format;
175
            $formatTime = 'short';
176
        }
177
        
178
        return $this->formatLocal($date, $formatDate, $formatTime, $calendar);
179
    }
180
    
181
182
    /**
183
     * Split duration into seconds, minutes, hours, days, weeks and years.
184
     * 
185
     * @param int $seconds
186
     * @return array
187
     */
188
    protected function splitDuration($seconds, $max)
189
    {
190
        if ($max < 1 || $seconds < 60) {
191
            return [$seconds];
192
        }
193
        
194
        $minutes = floor($seconds / 60);
195
        $seconds = $seconds % 60;
196
        if ($max < 2 || $minutes < 60) {
197
            return [$seconds, $minutes];
198
        }
199
        
200
        $hours = floor($minutes / 60);
201
        $minutes = $minutes % 60;
202 View Code Duplication
        if ($max < 3 || $hours < 24) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
            return [$seconds, $minutes, $hours];
204
        }
205
        
206
        $days = floor($hours / 24);
207
        $hours = $hours % 24;
208 View Code Duplication
        if ($max < 4 || $days < 7) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209
            return [$seconds, $minutes, $hours, $days]; 
210
        }
211
        
212
        $weeks = floor($days / 7);
213
        $days = $days % 7;
214 View Code Duplication
        if ($max < 5 || $weeks < 52) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
215
            return [$seconds, $minutes, $hours, $days, $weeks];
216
        }
217
        
218
        $years = floor($weeks / 52);
219
        $weeks = $weeks % 52;
220
        return [$seconds, $minutes, $hours, $days, $weeks, $years];
221
    }
222
    
223
    /**
224
     * Calculate duration from seconds.
225
     * 1 year is seen as exactly 52 weeks.
226
     * 
227
     * Use null to skip a unit.
228
     * 
229
     * @param int    $seconds    Time in seconds
230
     * @param array  $units      Time units (seconds, minutes, hours, days, weeks, years)
231
     * @param string $separator
0 ignored issues
show
Bug introduced by
There is no parameter named $separator. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
232
     * @return string
233
     */
234
    public function duration($seconds, $units = ['s', 'm', 'h', 'd', 'w', 'y'], $seperator = ' ')
235
    {
236
        list($seconds, $minutes, $hours, $days, $weeks, $years) =
237
            $this->splitDuration($seconds, count($units)-1) + array_fill(0, 6, null);
238
        
239
        $duration = '';
240 View Code Duplication
        if (isset($years) && isset($units[5])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
241
            $duration .= $seperator . $years . $units[5];
242
        }
243
        
244 View Code Duplication
        if (isset($weeks) && isset($units[4])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
            $duration .= $seperator . $weeks . $units[4];
246
        }
247
        
248 View Code Duplication
        if (isset($days) && isset($units[3])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
249
            $duration .= $seperator . $days . $units[3];
250
        }
251
        
252 View Code Duplication
        if (isset($hours) && isset($units[2])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
253
            $duration .= $seperator . $hours . $units[2];
254
        }
255
        
256 View Code Duplication
        if (isset($minutes) && isset($units[1])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
257
            $duration .= $seperator . $minutes . $units[1];
258
        }
259
        
260 View Code Duplication
        if (isset($seconds) && isset($units[0])) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
261
            $duration .= $seperator . $seconds . $units[0];
262
        }
263
        
264
        return trim($duration, $seperator);
265
    }
266
267
    /**
268
     * Get the age (in years) based on a date.
269
     * 
270
     * @param DateTime|string $date
271
     * @return int
272
     */
273
    public function age($date)
274
    {
275
        if (!$date instanceof \DateTime) {
276
            $date = new \DateTime($date);
277
        }
278
        
279
        return $date->diff(new \DateTime())->format('%y');
280
    }
281
}
282