ValidatorFunctionMap   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 134
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 26
Bugs 2 Features 3
Metric Value
wmc 12
lcom 1
cbo 2
dl 0
loc 134
rs 10
c 26
b 2
f 3

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getInstance() 0 10 2
B get() 0 41 6
A buildErrorMessage() 0 10 2
A funcNameToUnderscore() 0 13 1
1
<?php
2
/**
3
 * Author: Nil Portugués Calderó <[email protected]>
4
 * Date: 9/16/14
5
 * Time: 9:42 PM
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace NilPortugues\Validator;
12
13
use NilPortugues\Validator\Validation\FileUpload\FileUploadException;
14
15
/**
16
 * Class ValidatorFunctionMap
17
 * @package NilPortugues\Validator
18
 */
19
class ValidatorFunctionMap
20
{
21
    /**
22
     * @var array
23
     */
24
    private $functionMap = [];
25
26
    /**
27
     * @var AbstractValidator
28
     */
29
    private $validator;
30
31
    /**
32
     * @var self
33
     */
34
    private static $instance;
35
36
    /**
37
     * @param AbstractValidator $abstractValidator
38
     * @param array $functionMap
39
     */
40
    private function __construct(AbstractValidator $abstractValidator, array &$functionMap)
41
    {
42
        $this->validator   = $abstractValidator;
43
        $this->functionMap = $functionMap;
44
    }
45
    /**
46
     * @param AbstractValidator $abstractValidator
47
     * @param array $functionMap
48
     * @return ValidatorFunctionMap
49
     */
50
    public static function getInstance(AbstractValidator $abstractValidator, array &$functionMap)
51
    {
52
        if (!isset(self::$instance)) {
53
            self::$instance = new self($abstractValidator, $functionMap);
54
        }
55
        $i = self::$instance;
56
        $i->validator = $abstractValidator;
57
58
        return self::$instance;
59
    }
60
61
    /**
62
     * Gets the function from the function map and runs it against the values.
63
     *
64
     * @param string $propertyName
65
     * @param string $funcName
66
     * @param array  $arguments
67
     * @param array  $errorValues
68
     * @param array  $errors
69
     *
70
     * @throws \InvalidArgumentException
71
     * @return bool
72
     */
73
    public function get($propertyName, $funcName, array $arguments = [], array &$errorValues = [], array &$errors)
74
    {
75
        if (false === \array_key_exists($funcName, $this->functionMap)) {
76
            throw new \InvalidArgumentException(
77
                \sprintf('Validator key \'%s\' not found', $funcName)
78
            );
79
        }
80
81
        $function = $this->functionMap[$funcName];
82
        $class    = \explode("::", $function);
83
84
        try {
85
            $result = \call_user_func_array([$class[0], $class[1]], $arguments);
86
87
            if (false === $result) {
88
                $funcName = $this->funcNameToUnderscore($funcName);
89
                if (false === \array_key_exists($funcName, $errors)) {
90
                    throw new \InvalidArgumentException(
91
                        \sprintf('Validator key \'%s\' not found in error file', $funcName)
92
                    );
93
                }
94
95
                if (\strlen($errors[$funcName]) > 0) {
96
                    $this->validator->setError(
97
                        $this->buildErrorMessage($errorValues, $errors, $funcName, $propertyName),
98
                        $funcName
99
                    );
100
                }
101
            }
102
        } catch (FileUploadException $e) {
103
            $lowerCaseFuncName = $this->funcNameToUnderscore($e->getMessage());
104
            $this->validator->setError(
105
                $this->buildErrorMessage($errorValues, $errors, $e->getMessage(), $propertyName),
106
                $lowerCaseFuncName
107
            );
108
109
            $result = false;
110
        }
111
112
        return $result;
113
    }
114
115
    /**
116
     * @param array  $errorValues
117
     * @param array  $errors
118
     * @param string $funcName
119
     * @param string $propertyName
120
     *
121
     * @return string
122
     */
123
    private function buildErrorMessage(array $errorValues, array &$errors, $funcName, $propertyName)
124
    {
125
        $message = \str_replace(':attribute', "'".$propertyName."'", $errors[$funcName]);
126
127
        foreach ($errorValues as $key => $value) {
128
            $message = \str_replace(":{$key}", $value, $message);
129
        }
130
131
        return $message;
132
    }
133
134
    /**
135
     * @param string $funcName
136
     *
137
     * @return string
138
     */
139
    private function funcNameToUnderscore($funcName)
140
    {
141
        $camel = \preg_replace(
142
            '/(?!^)[[:upper:]][[:lower:]]/',
143
            '$0',
144
            \preg_replace(
145
                '/(?!^)[[:upper:]]+/', "_" . '$0',
146
                \str_replace(['::__construct', '::'], ['', '.'], $funcName)
147
            )
148
        );
149
150
        return \str_replace('_attribute', '', \strtolower($camel));
151
    }
152
}
153