1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace Wei\Validator;
10:
11: 12: 13: 14: 15:
16: class EndsWith extends BaseValidator
17: {
18: protected $notFoundMessage = '%name% must end with "%findMe%"';
19:
20: protected $negativeMessage = '%name% must not end with "%findMe%"';
21:
22: protected $findMe;
23:
24: protected $case = false;
25:
26: 27: 28:
29: public function __invoke($input, $findMe = null, $case = null)
30: {
31: $findMe && $this->storeOption('findMe', $findMe);
32: is_bool($case) && $this->storeOption('case', $case);
33:
34: return $this->isValid($input);
35: }
36:
37: 38: 39:
40: protected function doValidate($input)
41: {
42: if (!$this->isString($input)) {
43: $this->addError('notString');
44: return false;
45: }
46:
47: if (is_scalar($this->findMe)) {
48: $pos = strlen($input) - strlen($this->findMe);
49: $fn = $this->case ? 'strrpos' : 'strripos';
50: if ($pos !== $fn($input, (string)$this->findMe)) {
51: $this->addError('notFound');
52: return false;
53: }
54: } elseif (is_array($this->findMe)) {
55: $pattern = array();
56: foreach ($this->findMe as $value) {
57: $pattern[] = preg_quote($value, '/');
58: }
59: $pattern = '/' . implode('|', $pattern) . '$/';
60: $this->case || $pattern .= 'i';
61:
62: if (!preg_match($pattern, $input)) {
63: $this->addError('notFound');
64: return false;
65: }
66: }
67:
68: return true;
69: }
70: }
71: