Passed
Pull Request — master (#56)
by
unknown
02:23
created

StringFormatValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 0
dl 0
loc 25
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 15 4
1
<?php
2
3
namespace ByJG\ApiTools\Base;
4
5
use DateTime;
6
7
/**
8
 * Adds ability to validate string format based on open api specification:
9
 *
10
 * @link https://swagger.io/docs/specification/data-models/data-types/
11
 */
12
class StringFormatValidator
13
{
14
    /**
15
     * Value must match the desired format (date, date-time), returns true if unknown format is provided.
16
     *
17
     * @param string $format
18
     * @param mixed $value
19
     * @return bool
20
     */
21
    public function validate($format, $value)
22
    {
23
        // full-date notation as defined by RFC 3339, section 5.6, for example, 2017-07-21
24
        if ($format === 'date' ) {
25
            $match = preg_match('/^[\d]{4}-[\d]{2}-[\d]{2}$/', $value);
26
            return $match !== false && $match !== 0;
27
        }
28
29
        // the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z
30
        if ($format === 'date-time') {
31
            return DateTime::createFromFormat(DateTime::ISO8601, $value) !== false;
32
        }
33
34
        return true;
35
    }
36
}
37