Completed
Pull Request — master (#22)
by Matthew
06:23 queued 04:03
created

DateValidationUtility::validateTimeDifference()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 4
Ratio 20 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 6
nop 2
dl 4
loc 20
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Ps2alerts\Api\Utility;
4
5
use Ps2alerts\Api\Exception\InvalidArgumentException;
6
7
class DateValidationUtility
8
{
9
    /**
10
     * Validates a date to ensure it's to a certain format
11
     *
12
     * @param $date
13
     * @param string $format
14
     *
15
     * @return bool
16
     */
17
    public function validate($date, $format = 'Y-m-d H:i:s')
18
    {
19
        $d = \DateTime::createFromFormat($format, $date);
20
        return $d && $d->format($format) == $date;
21
    }
22
23
    /**
24
     * Validates a date range to ensure it's allowed within a certain limit.
25
     * @param $dates
26
     * @param int $maxDiff
27
     *
28
     * @throws InvalidArgumentException
29
     */
30
    public function validateTimeDifference($dates, int $maxDiff)
31
    {
32 View Code Duplication
        if (! is_array($dates)) {
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...
33
            $dates = str_replace('\'', '', $dates); // Remove escaping quotes
34
            $dates = explode(',', $dates);
35
        }
36
37
        if (! is_array) {
38
            throw new InvalidArgumentException('Somehow validateTimeDifference couldn\'t make a date array.');
39
        }
40
41
        $date1 = \DateTime::createFromFormat('Y-m-d', $dates[0]);
42
        $date2 = \DateTime::createFromFormat('Y-m-d', $dates[1]);
43
44
        $diff = $date2->diff($date1, true);
45
46
        if ($diff->days > $maxDiff) {
47
            throw new InvalidArgumentException("Number of days attempting to access is more than maximum allowed ($maxDiff)");
48
        }
49
    }
50
}