1<?php
2
3/*
4 * This file is part of Respect/Validation.
5 *
6 * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
7 *
8 * For the full copyright and license information, please view the "LICENSE.md"
9 * file that was distributed with this source code.
10 */
11
12namespace Respect\Validation\Rules;
13
14use Respect\Validation\Exceptions\ComponentException;
15use Respect\Validation\Exceptions\ValidationException;
16use Respect\Validation\Validator;
17
18class KeyValue extends AbstractRule
19{
20    public $comparedKey;
21    public $ruleName;
22    public $baseKey;
23
24    public function __construct($comparedKey, $ruleName, $baseKey)
25    {
26        $this->comparedKey = $comparedKey;
27        $this->ruleName = $ruleName;
28        $this->baseKey = $baseKey;
29    }
30
31    private function getRule($input)
32    {
33        if (!isset($input[$this->comparedKey])) {
34            throw $this->reportError($this->comparedKey);
35        }
36
37        if (!isset($input[$this->baseKey])) {
38            throw $this->reportError($this->baseKey);
39        }
40
41        try {
42            $rule = Validator::__callStatic($this->ruleName, [$input[$this->baseKey]]);
43            $rule->setName($this->comparedKey);
44        } catch (ComponentException $exception) {
45            throw $this->reportError($input, ['component' => true]);
46        }
47
48        return $rule;
49    }
50
51    private function overwriteExceptionParams(ValidationException $exception)
52    {
53        $params = [];
54        foreach ($exception->getParams() as $key => $value) {
55            if (in_array($key, ['template', 'translator'])) {
56                continue;
57            }
58
59            $params[$key] = $this->baseKey;
60        }
61
62        $exception->configure($this->comparedKey, $params);
63
64        return $exception;
65    }
66
67    public function assert($input)
68    {
69        $rule = $this->getRule($input);
70
71        try {
72            $rule->assert($input[$this->comparedKey]);
73        } catch (ValidationException $exception) {
74            throw $this->overwriteExceptionParams($exception);
75        }
76
77        return true;
78    }
79
80    public function check($input)
81    {
82        $rule = $this->getRule($input);
83
84        try {
85            $rule->check($input[$this->comparedKey]);
86        } catch (ValidationException $exception) {
87            throw $this->overwriteExceptionParams($exception);
88        }
89
90        return true;
91    }
92
93    public function validate($input)
94    {
95        try {
96            $rule = $this->getRule($input);
97        } catch (ValidationException $e) {
98            return false;
99        }
100
101        return $rule->validate($input[$this->comparedKey]);
102    }
103}
104