Last active
December 15, 2015 15:49
-
-
Save Voronchuk/5284687 to your computer and use it in GitHub Desktop.
WordCount string validator for Zend Framework 2 (based on Zend/Validator/File/WordCount).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* WordCount validator for strings. | |
* | |
* @link http://github.com/zendframework/zf2 for the canonical source repository | |
* @copyright Copyright (c) 2009-2013 Vyacheslav Voronchuk (http://www.wm-software.com) | |
* @license http://framework.zend.com/license/new-bsd New BSD License | |
*/ | |
namespace Application\Validator; | |
use Zend\Validator\File\WordCount as FileWordCount; | |
class WordCount extends FileWordCount | |
{ | |
/** | |
* @const string Error constants | |
*/ | |
const TOO_MUCH = 'stringWordCountTooMuch'; | |
const TOO_LESS = 'stringWordCountTooLess'; | |
const INVALID = 'stringLengthInvalid'; | |
/** | |
* @var array | |
*/ | |
protected $messageTemplates = array( | |
self::INVALID => "Invalid type given. String expected", | |
self::TOO_MUCH => "Too many words, maximum '%max%' are allowed but '%count%' were counted.", | |
self::TOO_LESS => "Too less words, minimum '%min%' are expected but '%count%' were counted", | |
); | |
/** | |
* Returns true if and only if the counted words are at least min and | |
* not bigger than max (when max is not null). | |
* | |
* @param string $value | |
* @return bool | |
*/ | |
public function isValid($value) | |
{ | |
if (!is_string($value)) { | |
$this->error(self::INVALID); | |
return false; | |
} | |
$this->setValue($value); | |
$this->count = str_word_count($value); | |
if (($this->getMax() !== null) && ($this->count > $this->getMax())) { | |
$this->error(self::TOO_MUCH); | |
return false; | |
} | |
if (($this->getMin() !== null) && ($this->count < $this->getMin())) { | |
$this->error(self::TOO_LESS); | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment