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

StringFormatValidator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 4
nc 4
nop 2
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