Completed
Push — master ( 69f162...acb4bc )
by Sebastian
02:58
created

Date::hasDatePartsFromLocales()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/*
3
 * citeproc-php
4
 *
5
 * @link        http://github.com/seboettg/citeproc-php for the source repository
6
 * @copyright   Copyright (c) 2016 Sebastian Böttger.
7
 * @license     https://opensource.org/licenses/MIT
8
 */
9
10
namespace Seboettg\CiteProc\Rendering\Date;
11
12
use Seboettg\CiteProc\CiteProc;
13
use Seboettg\CiteProc\Exception\CiteProcException;
14
use Seboettg\CiteProc\Styles\AffixesTrait;
15
use Seboettg\CiteProc\Styles\DisplayTrait;
16
use Seboettg\CiteProc\Styles\FormattingTrait;
17
use Seboettg\CiteProc\Styles\TextCaseTrait;
18
use Seboettg\CiteProc\Util;
19
use Seboettg\Collection\ArrayList;
20
21
22
/**
23
 * Class Date
24
 * @package Seboettg\CiteProc\Rendering
25
 *
26
 * @author Sebastian Böttger <[email protected]>
27
 */
28
class Date
29
{
30
31
    use AffixesTrait,
32
        DisplayTrait,
33
        FormattingTrait,
34
        TextCaseTrait;
35
36
    // ymd
37
    const DATE_RANGE_STATE_NONE         = 0; // 000
38
    const DATE_RANGE_STATE_DAY          = 1; // 001
39
    const DATE_RANGE_STATE_MONTH        = 2; // 010
40
    const DATE_RANGE_STATE_MONTHDAY     = 3; // 011
41
    const DATE_RANGE_STATE_YEAR         = 4; // 100
42
    const DATE_RANGE_STATE_YEARDAY      = 5; // 101
43
    const DATE_RANGE_STATE_YEARMONTH    = 6; // 110
44
    const DATE_RANGE_STATE_YEARMONTHDAY = 7; // 111
45
46
    private static $localizedDateFormats = [
47
        'numeric',
48
        'text'
49
    ];
50
51
    /**
52
     * @var ArrayList
53
     */
54
    private $dateParts;
55
56
    /**
57
     * @var string
58
     */
59
    private $form = "";
60
61
    /**
62
     * @var string
63
     */
64
    private $variable = "";
65
66
    /**
67
     * @var string
68
     */
69
    private $datePartsAttribute = "";
70
71
    public function __construct(\SimpleXMLElement $node)
72
    {
73
        $this->dateParts = new ArrayList();
74
75
        /** @var \SimpleXMLElement $attribute */
76 View Code Duplication
        foreach ($node->attributes() as $attribute) {
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...
77
            switch ($attribute->getName()) {
78
                case 'form':
79
                    $this->form = (string) $attribute;
80
                    break;
81
                case 'variable':
82
                    $this->variable = (string) $attribute;
83
                    break;
84
                case 'date-parts':
85
                    $this->datePartsAttribute = (string) $attribute;
86
            }
87
        }
88
        /** @var \SimpleXMLElement $child */
89
        foreach ($node->children() as $child) {
90
            if ($child->getName() === "date-part") {
91
                $datePartName = (string) $child->attributes()["name"];
92
                $this->dateParts->set($this->form . "-" . $datePartName, Util\Factory::create($child));
93
            }
94
        }
95
96
        $this->initAffixesAttributes($node);
97
        $this->initDisplayAttributes($node);
98
        $this->initFormattingAttributes($node);
99
        $this->initTextCaseAttributes($node);
100
    }
101
102
    /**
103
     * @param $data
104
     * @return string
105
     */
106
    public function render($data)
107
    {
108
        $ret = "";
109
        $var = null;
0 ignored issues
show
Unused Code introduced by
$var is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
110
        if (isset($data->{$this->variable})) {
111
            $var = $data->{$this->variable};
112
        } else {
113
            return "";
114
        }
115
116
        if (!isset($data->{$this->variable}->{'date-parts'}) || empty($data->{$this->variable}->{'date-parts'})) {
117
            if (isset($data->{$this->variable}->raw) && !empty($data->{$this->variable}->raw)) {
118
                try {
119
                    // try to parse date parts from "raw" attribute
120
                    $var->{'date-parts'} = Util\Date::parseDateParts($data->{$this->variable});
121
                } catch (CiteProcException $e) {
122
                    if (!preg_match("/(\p{L}+)\s?([\-\-\&,])\s?(\p{L}+)/u", $data->{$this->variable}->raw)) {
123
                        return $this->addAffixes($this->format($this->applyTextCase($data->{$this->variable}->raw)));
124
                    }
125
                }
126
            } else {
127
                return "";
128
            }
129
        }
130
131
        $form = $this->form;
132
        $dateParts = explode("-", $this->datePartsAttribute);
133
134
        /* Localized date formats are selected with the optional form attribute, which must set to either “numeric”
135
        (for fully numeric formats, e.g. “12-15-2005”), or “text” (for formats with a non-numeric month, e.g.
136
        “December 15, 2005”). Localized date formats can be customized in two ways. First, the date-parts attribute may
137
        be used to show fewer date parts. The possible values are:
138
            - “year-month-day” - (default), renders the year, month and day
139
            - “year-month” - renders the year and month
140
            - “year” - renders the year */
141
142
        if ($this->dateParts->count() < 1 && in_array($form, self::$localizedDateFormats)) {
143
            if ($this->hasDatePartsFromLocales($form)) {
144
                $datePartsFromLocales = $this->getDatePartsFromLocales($form);
145
                array_filter($datePartsFromLocales, function (\SimpleXMLElement $item) use ($dateParts) {
146
                    return in_array($item["name"], $dateParts);
147
                });
148
149
                foreach ($datePartsFromLocales as $datePartNode) {
150
                    $datePart = $datePartNode["name"];
151
                    $this->dateParts->set("$form-$datePart", Util\Factory::create($datePartNode));
152
                }
153
            } else { //otherwise create default date parts
154
                foreach ($dateParts as $datePart) {
155
                    $this->dateParts->add("$form-$datePart", new DatePart(new \SimpleXMLElement('<date-part name="' . $datePart . '" form="' . $form . '" />')));
156
                }
157
            }
158
        }
159
160
161
        // No date-parts in date-part attribute defined, take into account that the defined date-part children will be used.
162
        if (empty($this->datePartsAttribute) && $this->dateParts->count() > 0) {
163
            /** @var DatePart $part */
164
            foreach ($this->dateParts as $part) {
165
                $dateParts[] = $part->getName();
166
            }
167
        }
168
169
        /* cs:date may have one or more cs:date-part child elements (see Date-part). The attributes set on
170
        these elements override those specified for the localized date formats (e.g. to get abbreviated months for all
171
        locales, the form attribute on the month-cs:date-part element can be set to “short”). These cs:date-part
172
        elements do not affect which, or in what order, date parts are rendered. Affixes, which are very
173
        locale-specific, are not allowed on these cs:date-part elements. */
174
175
        if ($this->dateParts->count() > 0) {
176
177
            if (isset($var->raw) && !preg_match("/(\p{L}+)\s?([\-\-\&,])\s?(\p{L}+)/u", $var->raw) && $this->dateParts->count() > 0) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
178
                //$var->{"date-parts"} = [];
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
179
            } else if (!isset($var->{'date-parts'})) { // ignore empty date-parts
180
                return "";
181
            }
182
183
            if (count($data->{$this->variable}->{'date-parts'}) === 1) {
184
                $data_ = $this->createDateTime($data->{$this->variable}->{'date-parts'});
185
                /** @var DatePart $datePart */
186
                foreach ($this->dateParts as $key => $datePart) {
187
                    list($f, $p) = explode("-", $key);
0 ignored issues
show
Unused Code introduced by
The assignment to $f is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
188
                    if (in_array($p, $dateParts)) {
189
                        $ret .= $datePart->render($data_[0], $this);
190
                    }
191
                }
192
            } else if (count($var->{'date-parts'}) === 2) { //date range
193
                $data_ = $this->createDateTime($var->{'date-parts'});
194
                $from = $data_[0];
195
                $to = $data_[1];
196
                $interval = $to->diff($from);
197
                $delim = "";
198
                $toRender = 0;
199
                if ($interval->y > 0) {
200
                    $toRender |= self::DATE_RANGE_STATE_YEAR;
201
                    $delim = $this->dateParts->get($this->form . "-year")->getRangeDelimiter();
202
                }
203
                if ($interval->m > 0 && $from->getMonth() - $to->getMonth() !== 0) {
204
                    $toRender |= self::DATE_RANGE_STATE_MONTH;
205
                    $delim = $this->dateParts->get($this->form . "-month")->getRangeDelimiter();
206
                }
207
                if ($interval->d > 0 && $from->getDay() - $to->getDay() !== 0) {
208
                    $toRender |= self::DATE_RANGE_STATE_DAY;
209
                    $delim = $this->dateParts->get($this->form . "-day")->getRangeDelimiter();
210
                }
211
212
                $ret = $this->renderDateRange($toRender, $from, $to, $delim);
213
            }
214
215
            if (isset($var->raw) && preg_match("/(\p{L}+)\s?([\-\-\&,])\s?(\p{L}+)/u", $var->raw, $matches)){
216
                return $matches[1].$matches[2].$matches[3];
217
            }
218
        }
219
        // fallback:
220
        // When there are no dateParts children, but date-parts attribute in date
221
        // render numeric
222
        else if (!empty($this->datePartsAttribute)) {
223
            $data = $this->createDateTime($var->{'date-parts'});
224
            $ret = $this->renderNumeric($data[0]);
225
        }
226
227
        return !empty($ret) ? $this->addAffixes($this->format($this->applyTextCase($ret))) : "";
228
    }
229
230
    private function renderNumeric(DateTime $date)
231
    {
232
        return $date->renderNumeric();
233
    }
234
235
    public function getForm()
236
    {
237
        return $this->form;
238
    }
239
240
    private function createDateTime($dates)
241
    {
242
        $data = [];
243
        foreach ($dates as $date) {
244
            if ($date[0] < 1000) {
245
                $dateTime = new DateTime(0,0,0);
0 ignored issues
show
Documentation introduced by
0 is of type integer, but the function expects a object<DateTimeZone>.

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...
246
                $dateTime->setDay(0)->setMonth(0)->setYear(0);
247
                $data[] = $dateTime;
248
            }
249
            $dateTime = new DateTime($date[0], array_key_exists(1, $date) ? $date[1] : 1, array_key_exists(2, $date) ? $date[2] : 1);
250
            if (!array_key_exists(1, $date)) {
251
                $dateTime->setMonth(0);
252
            }
253
            if (!array_key_exists(2, $date)) {
254
                $dateTime->setDay(0);
255
            }
256
            $data[] = $dateTime;
257
        }
258
259
        return $data;
260
    }
261
262
    /**
263
     * @param $differentParts
264
     * @param DateTime $from
265
     * @param DateTime $to
266
     * @param $delim
267
     * @return string
268
     */
269
    private function renderDateRange($differentParts, DateTime $from, DateTime $to, $delim)
270
    {
271
        $ret = "";
272
        switch ($differentParts) {
273
            case Date::DATE_RANGE_STATE_YEAR:
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
274
                foreach ($this->dateParts as $key => $datePart) {
275
                    if (strpos($key, "year") !== false) {
276
                        $ret .= $this->renderOneRangePart($datePart, $from, $to, $delim);
277
                    }
278
                    if (strpos($key, "month") !== false) {
279
                        $day = !empty($d = $from->getMonth()) ? $d : "";
280
                        $ret .= $day;
281
                    }
282 View Code Duplication
                    if (strpos($key, "day") !== false) {
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...
283
                        $day = !empty($d = $from->getDay()) ? $datePart->render($from, $this) : "";
284
                        $ret .= $day;
285
                    }
286
                }
287
                break;
288
            case Date::DATE_RANGE_STATE_MONTH:
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
289
                /**
290
                 * @var string $key
291
                 * @var DatePart $datePart
292
                 */
293
                foreach ($this->dateParts as $key => $datePart) {
294
                    if (strpos($key, "year") !== false) {
295
                        $ret .= $datePart->render($from, $this);
296
                    }
297
                    if (strpos($key, "month")) {
298
                        $ret .= $this->renderOneRangePart($datePart, $from, $to, $delim);
299
                    }
300 View Code Duplication
                    if (strpos($key, "day") !== false) {
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...
301
                        $day = !empty($d = $from->getDay()) ? $datePart->render($from, $this) : "";
302
                        $ret .= $day;
303
                    }
304
                }
305
                break;
306
            case Date::DATE_RANGE_STATE_DAY:
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
307
                /**
308
                 * @var string $key
309
                 * @var DatePart $datePart
310
                 */
311
                foreach ($this->dateParts as $key => $datePart) {
312
                    if (strpos($key, "year") !== false) {
313
                        $ret .= $datePart->render($from, $this);
314
                    }
315
                    if (strpos($key, "month") !== false) {
316
                        $ret .= $datePart->render($from, $this);
317
                    }
318
                    if (strpos($key, "day")) {
319
                        $ret .= $this->renderOneRangePart($datePart, $from, $to, $delim);
320
                    }
321
                }
322
                break;
323
            case Date::DATE_RANGE_STATE_YEARMONTHDAY:
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
324
                $i = 0;
325 View Code Duplication
                foreach ($this->dateParts as $datePart) {
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...
326
                    if ($i === $this->dateParts->count() - 1) {
327
                        $ret .= $datePart->renderPrefix();
328
                        $ret .= $datePart->renderWithoutAffixes($from, $this);
329
                    } else {
330
                        $ret .= $datePart->render($from, $this);
331
                    }
332
                    ++$i;
333
                }
334
                $ret .= $delim;
335
                $i = 0;
336 View Code Duplication
                foreach ($this->dateParts as $datePart) {
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...
337
                    if ($i == 0) {
338
                        $ret .= $datePart->renderWithoutAffixes($to, $this);
339
                        $ret .= $datePart->renderSuffix();
340
                    } else {
341
                        $ret .= $datePart->render($to, $this);
342
                    }
343
                    ++$i;
344
                }
345
                break;
346 View Code Duplication
            case Date::DATE_RANGE_STATE_YEARMONTH:
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...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
347
                $dp = $this->dateParts->toArray();
348
                $i = 0;
349
                $dateParts_ = [];
350
                array_walk($dp, function ($datePart, $key) use (&$i, &$dateParts_, $differentParts) {
351
                    if (strpos($key, "year") !== false || strpos($key, "month") !== false) {
352
                        $dateParts_["yearmonth"][] = $datePart;
353
                    }
354
                    if (strpos($key, "day") !== false) {
355
                        $dateParts_["day"] = $datePart;
356
                    }
357
                });
358
                break;
359 View Code Duplication
            case Date::DATE_RANGE_STATE_YEARDAY:
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...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
360
                $dp = $this->dateParts->toArray();
361
                $i = 0;
362
                $dateParts_ = [];
363
                array_walk($dp, function ($datePart, $key) use (&$i, &$dateParts_, $differentParts) {
364
                    if (strpos($key, "year") !== false || strpos($key, "day") !== false) {
365
                        $dateParts_["yearday"][] = $datePart;
366
                    }
367
                    if (strpos($key, "month") !== false) {
368
                        $dateParts_["month"] = $datePart;
369
                    }
370
                });
371
                break;
372 View Code Duplication
            case Date::DATE_RANGE_STATE_MONTHDAY:
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...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
373
                $dp = $this->dateParts->toArray();
374
                $i = 0;
375
                $dateParts_ = [];
376
                array_walk($dp, function ($datePart, $key) use (&$i, &$dateParts_, $differentParts) {
377
                    //$bit = sprintf("%03d", decbin($differentParts));
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
378
                    if (strpos($key, "month") !== false || strpos($key, "day") !== false) {
379
                        $dateParts_["monthday"][] = $datePart;
380
                    }
381
                    if (strpos($key, "year") !== false) {
382
                        $dateParts_["year"] = $datePart;
383
                    }
384
                });
385
                break;
386
        }
387
        switch ($differentParts) {
388
            case Date::DATE_RANGE_STATE_YEARMONTH:
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
389
            case Date::DATE_RANGE_STATE_YEARDAY:
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
390
            case Date::DATE_RANGE_STATE_MONTHDAY:
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
391
                /**
392
                 * @var $key
393
                 * @var DatePart $datePart */
394
                foreach ($dateParts_ as $key => $datePart) {
0 ignored issues
show
Bug introduced by
The variable $dateParts_ does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
395
                    if (is_array($datePart)) {
396
397
                        $f  = $datePart[0]->render($from, $this);
398
                        $f .= $datePart[1]->renderPrefix();
399
                        $f .= $datePart[1]->renderWithoutAffixes($from, $this);
400
                        $t  = $datePart[0]->renderWithoutAffixes($to, $this);
401
                        $t .= $datePart[0]->renderSuffix();
402
                        $t .= $datePart[1]->render($to, $this);
403
                        $ret .= $f . $delim . $t;
404
                    } else {
405
                        $ret .= $datePart->render($from, $this);
406
                    }
407
                }
408
                break;
409
        }
410
        return $ret;
411
    }
412
413
    /**
414
     * @param $datePart
415
     * @param $from
416
     * @param $to
417
     * @param $delim
418
     * @return string
419
     */
420
    protected function renderOneRangePart(DatePart $datePart, $from, $to, $delim)
421
    {
422
        $prefix = $datePart->renderPrefix();
423
        $from = $datePart->renderWithoutAffixes($from, $this);
424
        $to = $datePart->renderWithoutAffixes($to, $this);
425
        $suffix = !empty($to) ? $datePart->renderSuffix() : "";
426
        return $prefix.$from.$delim.$to.$suffix;
427
    }
428
429
    /**
430
     * @return bool
431
     */
432
    private function hasDatePartsFromLocales($format)
433
    {
434
        $dateXml = CiteProc::getContext()->getLocale()->getDateXml();
435
        return !empty($dateXml[$format]);
436
    }
437
438
    /**
439
     * @return array
440
     */
441
    private function getDatePartsFromLocales($format)
442
    {
443
        $ret = [];
444
        // date parts from locales
445
        $dateFromLocale_ = CiteProc::getContext()->getLocale()->getDateXml();
446
        $dateFromLocale = $dateFromLocale_[$format];
447
448
        // no custom date parts within the date element (this)?
449
        if (!empty($dateFromLocale)) {
450
451
            $dateForm = array_filter(is_array($dateFromLocale) ? $dateFromLocale : [$dateFromLocale], function ($element) use ($format) {
452
                /** @var \SimpleXMLElement $element */
453
                $dateForm = (string)$element->attributes()["form"];
454
                return $dateForm === $format;
455
            });
456
457
            //has dateForm from locale children (date-part elements)?
458
            $localeDate = array_pop($dateForm);
459
460
            if ($localeDate instanceof \SimpleXMLElement && $localeDate->count() > 0) {
461
                foreach ($localeDate as $child) {
462
                    $ret[] = $child;
463
                }
464
            }
465
        }
466
        return $ret;
467
    }
468
469
    /**
470
     * @return string
471
     */
472
    public function getVariable()
473
    {
474
        return $this->variable;
475
    }
476
}