Validator::isFormatValid()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace As3\Modlr\Util;
4
5
/**
6
 * Responsibile for validating common components of metadata and other formats.
7
 *
8
 * @author Jacob Bare <[email protected]>
9
 */
10
class Validator
11
{
12
    /**
13
     * Valid entity string formats.
14
     *
15
     * @var array
16
     */
17
    private $stringFormats = ['dash', 'camelcase', 'studlycaps', 'underscore'];
18
19
    /**
20
     * Valid regex patterns per name format.
21
     *
22
     * @var array
23
     */
24
    private $nameFormats = [
25
        'studlycaps'    => '/^[A-Z]{1}[a-zA-Z]{0,}$/',
26
        'camelcase'     => '/^[a-z]{1}[a-zA-Z]{0,}$/',
27
        'dash'          => '/^(?!.*--.*)[a-z]{1}[a-z-]{0,}(?<!-)$/',
28
        'underscore'    => '/^(?!.*__.*)[a-z]{1}[a-z_]{0,}(?<!_)$/',
29
    ];
30
31
    /**
32
     * Validates a name (such as entity types or entity field keys) to a selected format.
33
     *
34
     * @param   string  $format
35
     * @param   string  $name
36
     * @return  bool
37
     */
38
    public function isNameValid($format, $name)
39
    {
40
        if (false === $this->isFormatValid($format)) {
41
            return false;
42
        }
43
        $name = iconv(mb_detect_encoding($name), 'UTF-8', $name);
44
45
        $valid = $this->nameFormats[$format];
46
        return !preg_match($valid, $name) ? false : true;
47
    }
48
49
    /**
50
     * Validates an entity string format.
51
     *
52
     * @param   string  $format
53
     * @return  bool
54
     */
55
    public function isFormatValid($format)
56
    {
57
        return in_array($format, $this->stringFormats);
58
    }
59
}
60