Created
April 22, 2015 11:24
-
-
Save kolyadin/b89d468927c89988e41e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
ini_set('display_errors', 1); | |
error_reporting(E_ALL); | |
/** | |
* Created by PhpStorm. | |
* User: Aleksey Kolyadin | |
* Date: 22.04.2015 | |
* Time: 13:32 | |
*/ | |
class DateValidator { | |
private $cyrillicDate = null; | |
private $isMonthPresented = false; | |
private $output = []; | |
const REGEX_YEAR = '(?<year>\d{1,2})\s*(год|года|лет)'; | |
const REGEX_YEAR_WITH_MONTH = "(?<year>\d{1,2})\s*(год|года|лет)\s*(?<month>0?[1-9]|1[012])\s*месяц(а|ев)?"; | |
/** | |
* @param string $cyrillicDate | |
*/ | |
public function __construct($cyrillicDate) { | |
$this->cyrillicDate = $cyrillicDate; | |
$this->checkMe(); | |
$this->parseMe(); | |
} | |
private function checkMe() { | |
$yearWithMonth = preg_split('@\s*(\d+)@', $this->cyrillicDate, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); | |
if (!count($yearWithMonth)) { | |
throw new \RuntimeException('Wrong birthday'); | |
} | |
array_filter($yearWithMonth, function ($var) { | |
if (trim($var) == '') { | |
throw new \RuntimeException('Wrong birthday'); | |
} | |
}); | |
$this->isMonthPresented = (count($yearWithMonth) == 4) ? true : false; | |
if ($this->isMonthPresented) { | |
if (!preg_match('@' . self::REGEX_YEAR_WITH_MONTH . '@is', $this->cyrillicDate)) { | |
throw new \RuntimeException('Wrong birthday'); | |
} | |
} | |
} | |
private function parseMe() { | |
if ($this->isMonthPresented) { | |
$regex = self::REGEX_YEAR_WITH_MONTH; | |
} else { | |
$regex = self::REGEX_YEAR; | |
} | |
preg_match("@$regex@is", $this->cyrillicDate, $matches); | |
if (!(isset($matches['month']))) { | |
$matches['month'] = 0; | |
} | |
$this->output = [ | |
'year' => $matches['year'], | |
'month' => $matches['month'] | |
]; | |
} | |
/** | |
* @return array | |
*/ | |
public function getYearAndMonth() { | |
return $this->output; | |
} | |
} | |
$validMe = new DateValidator('5 лет 13 месяцев'); | |
print '<pre>' . print_r($validMe->getYearAndMonth(), true) . '</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment