1: <?php
2: /**
3: * Wei Framework
4: *
5: * @copyright Copyright (c) 2008-2013 Twin Huang
6: * @license http://opensource.org/licenses/mit-license.php MIT License
7: */
8:
9: namespace Wei\Validator;
10:
11: /**
12: * Check if the input is starts with specified string
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: class StartsWith extends BaseValidator
17: {
18: protected $notFoundMessage = '%name% must start with "%findMe%"';
19:
20: protected $negativeMessage = '%name% must not start with "%findMe%"';
21:
22: protected $findMe;
23:
24: protected $case = false;
25:
26: /**
27: * {@inheritdoc}
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: * {@inheritdoc}
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: $fn = $this->case ? 'strpos' : 'stripos';
49: if (0 !== $fn($input, (string)$this->findMe)) {
50: $this->addError('notFound');
51: return false;
52: }
53: } elseif (is_array($this->findMe)) {
54: $pattern = array();
55: foreach ($this->findMe as $value) {
56: $pattern[] = preg_quote($value, '/');
57: }
58: $pattern = '/^' . implode('|', $pattern) . '/';
59: $this->case || $pattern .= 'i';
60:
61: if (!preg_match($pattern, $input)) {
62: $this->addError('notFound');
63: return false;
64: }
65: }
66:
67: return true;
68: }
69: }
70: