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

DateValidationUtility   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 9.09 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 4
loc 44
rs 10
c 0
b 0
f 0
wmc 6
lcom 0
cbo 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 5 2
A validateTimeDifference() 4 20 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
}