Passed
Push — master ( 790382...9b34f8 )
by Mark
09:58
created

DateValue::evaluate()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 21
nc 13
nop 1
dl 0
loc 35
ccs 22
cts 22
cp 1
crap 8
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel;
4
5
use DateTimeImmutable;
6
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
7
use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper;
8
9
class DateValue
10
{
11
    /**
12
     * DATEVALUE.
13
     *
14
     * Returns a value that represents a particular date.
15
     * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
16
     * value.
17
     *
18
     * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
19
     * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way.
20
     *
21
     * Excel Function:
22
     *        DATEVALUE(dateValue)
23
     *
24
     * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
25
     *                                    For example, "1/30/2008" or "30-Jan-2008" are text strings within
26
     *                                    quotation marks that represent dates. Using the default date
27
     *                                    system in Excel for Windows, date_text must represent a date from
28
     *                                    January 1, 1900, to December 31, 9999. Using the default date
29
     *                                    system in Excel for the Macintosh, date_text must represent a date
30
     *                                    from January 1, 1904, to December 31, 9999. DATEVALUE returns the
31
     *                                    #VALUE! error value if date_text is out of this range.
32
     *
33
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
34
     *                        depending on the value of the ReturnDateType flag
35
     */
36 1086
    public static function fromString($dateValue)
37
    {
38 1086
        $dti = new DateTimeImmutable();
39 1086
        $baseYear = SharedDateHelper::getExcelCalendar();
40 1086
        $dateValue = trim(Functions::flattenSingleValue($dateValue), '"');
41
        //    Strip any ordinals because they're allowed in Excel (English only)
42 1086
        $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue) ?? '';
43
        //    Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
44 1086
        $dateValue = str_replace(['/', '.', '-', '  '], ' ', $dateValue);
45
46 1086
        $yearFound = false;
47 1086
        $t1 = explode(' ', $dateValue);
48 1086
        $t = '';
49 1086
        foreach ($t1 as &$t) {
50 1086
            if ((is_numeric($t)) && ($t > 31)) {
51 1031
                if ($yearFound) {
52 1
                    return Functions::VALUE();
53
                }
54 1031
                if ($t < 100) {
55 3
                    $t += 1900;
56
                }
57 1031
                $yearFound = true;
58
            }
59
        }
60 1085
        if (count($t1) === 1) {
61
            //    We've been fed a time value without any date
62 46
            return ((strpos((string) $t, ':') === false)) ? Functions::Value() : 0.0;
63
        }
64 1052
        unset($t);
65
66 1052
        $dateValue = self::t1ToString($t1, $dti, $yearFound);
67
68 1052
        $PHPDateArray = self::setUpArray($dateValue, $dti);
69
70 1052
        return self::finalResults($PHPDateArray, $dti, $baseYear);
71
    }
72
73 1052
    private static function t1ToString(array $t1, DateTimeImmutable $dti, bool $yearFound): string
74
    {
75 1052
        if (count($t1) == 2) {
76
            //    We only have two parts of the date: either day/month or month/year
77 44
            if ($yearFound) {
78 9
                array_unshift($t1, 1);
79
            } else {
80 36
                if (is_numeric($t1[1]) && $t1[1] > 29) {
81 1
                    $t1[1] += 1900;
82 1
                    array_unshift($t1, 1);
83
                } else {
84 35
                    $t1[] = $dti->format('Y');
85
                }
86
            }
87
        }
88 1052
        $dateValue = implode(' ', $t1);
89
90 1052
        return $dateValue;
91
    }
92
93
    /**
94
     * Parse date.
95
     *
96
     * @return array|bool
97
     */
98 1052
    private static function setUpArray(string $dateValue, DateTimeImmutable $dti)
99
    {
100 1052
        $PHPDateArray = date_parse($dateValue);
101 1052
        if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
102
            // If original count was 1, we've already returned.
103
            // If it was 2, we added another.
104
            // Therefore, neither of the first 2 stroks below can fail.
105 677
            $testVal1 = strtok($dateValue, '- ');
106 677
            $testVal2 = strtok('- ');
107 677
            $testVal3 = strtok('- ') ?: $dti->format('Y');
108 677
            Helpers::adjustYear((string) $testVal1, (string) $testVal2, $testVal3);
109 677
            $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3);
110 677
            if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
111 48
                $PHPDateArray = date_parse($testVal2 . '-' . $testVal1 . '-' . $testVal3);
112
            }
113
        }
114
115 1052
        return $PHPDateArray;
116
    }
117
118
    /**
119
     * Final results.
120
     *
121
     * @param array|bool $PHPDateArray
122
     *
123
     * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
124
     *                        depending on the value of the ReturnDateType flag
125
     */
126 1052
    private static function finalResults($PHPDateArray, DateTimeImmutable $dti, int $baseYear)
127
    {
128 1052
        $retValue = Functions::Value();
129 1052
        if (is_array($PHPDateArray) && $PHPDateArray['error_count'] == 0) {
130
            // Execute function
131 1023
            Helpers::replaceIfEmpty($PHPDateArray['year'], $dti->format('Y'));
132 1023
            if ($PHPDateArray['year'] < $baseYear) {
133 19
                return Functions::VALUE();
134
            }
135 1005
            Helpers::replaceIfEmpty($PHPDateArray['month'], $dti->format('m'));
136 1005
            Helpers::replaceIfEmpty($PHPDateArray['day'], $dti->format('d'));
137 1005
            $PHPDateArray['hour'] = 0;
138 1005
            $PHPDateArray['minute'] = 0;
139 1005
            $PHPDateArray['second'] = 0;
140 1005
            $month = (int) $PHPDateArray['month'];
141 1005
            $day = (int) $PHPDateArray['day'];
142 1005
            $year = (int) $PHPDateArray['year'];
143 1005
            if (!checkdate($month, $day, $year)) {
144 5
                return ($year === 1900 && $month === 2 && $day === 29) ? Helpers::returnIn3FormatsFloat(60.0) : Functions::VALUE();
145
            }
146 1002
            $retValue = Helpers::returnIn3FormatsArray($PHPDateArray, true);
147
        }
148
149 1031
        return $retValue;
150
    }
151
}
152