/** * Calls public method if exists. * @param string $method * @param array $params * @throws \Nette\Application\BadRequestException * @return bool does method exist? */ protected function tryCall($method, array $params) { $rc = $this->getReflection(); if ($rc->hasMethod($method)) { $rm = $rc->getMethod($method); if ($rm->isPublic() && !$rm->isAbstract() && !$rm->isStatic()) { $this->checkRequirements($rm); $args = $rc->combineArgs($rm, $params); if (\Nette\Utils\Strings::match($method, "~^(action|render|handle).+~")) { $methodParams = $rm->getParameters(); foreach ($methodParams as $i => $param) { /** @var \Nette\Reflection\Parameter $param */ if ($className = $param->getClassName()) { if ($paramValue = $args[$i]) { $entity = $this->findById($className, $paramValue); if ($entity) { $args[$i] = $entity; } else { throw new \Nette\Application\BadRequestException("Value '{$paramValue}' not found in collection '{$className}'."); } } else { if (!$param->allowsNull()) { throw new \Nette\Application\BadRequestException("Value '{$param}' cannot be NULL."); } } } } } $rm->invokeArgs($this, $args); return TRUE; } } return FALSE; }
/** * @param string $contentType * @return string */ public static function charsetFromContentType($contentType) { if ($m = Strings::match($contentType, static::CONTENT_TYPE)) { return $m['charset']; } return NULL; }
/** * Generates and checks presenter class name. * @param string presenter name * @return string class name * @throws InvalidPresenterException */ public function getPresenterClass(&$name) { if (isset($this->cache[$name])) { return $this->cache[$name]; } if (!is_string($name) || !Nette\Utils\Strings::match($name, '#^[a-zA-Z\\x7f-\\xff][a-zA-Z0-9\\x7f-\\xff:]*\\z#')) { throw new InvalidPresenterException("Presenter name must be alphanumeric string, '{$name}' is invalid."); } $class = $this->formatPresenterClass($name); if (!class_exists($class)) { throw new InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' was not found."); } $reflection = new \ReflectionClass($class); $class = $reflection->getName(); if (!$reflection->implementsInterface('Nette\\Application\\IPresenter')) { throw new InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' is not Nette\\Application\\IPresenter implementor."); } elseif ($reflection->isAbstract()) { throw new InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' is abstract."); } $this->cache[$name] = $class; if ($name !== ($realName = $this->unformatPresenterClass($class))) { trigger_error("Case mismatch on presenter name '{$name}', correct name is '{$realName}'.", E_USER_WARNING); $name = $realName; } return $class; }
/** * Returns Git info * * @return array */ public static function getGitInfo() { $gitBinary = VP_GIT_BINARY; $info = []; $process = new Process(ProcessUtils::escapeshellarg($gitBinary) . " --version"); $process->run(); $info['git-binary-as-configured'] = $gitBinary; $info['git-available'] = $process->getErrorOutput() === null || !strlen($process->getErrorOutput()); if ($info['git-available'] === false) { $info['output'] = ['stdout' => trim($process->getOutput()), 'stderr' => trim($process->getErrorOutput())]; $info['env-path'] = getenv('PATH'); return $info; } $output = trim($process->getOutput()); $match = Strings::match($output, "~git version (\\d[\\d\\.]+\\d).*~"); $version = $match[1]; $gitPath = "unknown"; if ($gitBinary == "git") { $osSpecificWhereCommand = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? "where" : "which"; $process = new Process("{$osSpecificWhereCommand} git"); $process->run(); if ($process->isSuccessful()) { $gitPath = $process->getOutput(); } } else { $gitPath = $gitBinary; } $info['git-version'] = $version; $info['git-binary-as-called-by-vp'] = $gitBinary; $info['git-full-path'] = $gitPath; $info['versionpress-min-required-version'] = RequirementsChecker::GIT_MINIMUM_REQUIRED_VERSION; $info['matches-min-required-version'] = RequirementsChecker::gitMatchesMinimumRequiredVersion($version); return $info; }
/** * Values to be saved to es index * * @return FALSE|array [field => data] */ public function getIndexData() { if ($this->hidden) { return FALSE; } $blockCount = 0; $schemaCount = 0; $positions = []; foreach ($this->blocks as $block) { $blockCount++; $schemaCount += $block->blockSchemaBridges->count(); $positions[] = $block->getPositionOf($this); } if ($blockCount) { $avgPosition = array_sum($positions) / count($positions); } else { // title heuristics $number = Strings::match($this->title, '~\\s(\\d\\d?)(?!\\.)\\D*$~'); $avgPosition = $number ? $number[1] : 0; if ($avgPosition > 20) { // most probably not number of part $avgPosition = 0; } } return ['title' => $this->title, 'suggest' => $this->title, 'bucket' => $this->type, 'description' => $this->description, 'block_count' => $blockCount, 'schema_count' => $schemaCount, 'position' => $avgPosition]; }
public final function getVersion() { if (($version = Strings::match(get_class($this), '#\\d{10}#')) === null) { throw new InvalidStateException('Invalid migration class name - it does not contains timestamp'); } return (int) $version[0]; }
/** * {control name[:method] [params]} */ public function macroControl(MacroNode $node, PhpWriter $writer) { $words = $node->tokenizer->fetchWords(); if (!$words) { throw new CompileException('Missing control name in {control}'); } $name = $writer->formatWord($words[0]); $method = isset($words[1]) ? ucfirst($words[1]) : ''; $method = Strings::match($method, '#^\\w*\\z#') ? "render{$method}" : "{\"render{$method}\"}"; $tokens = $node->tokenizer; $pos = $tokens->position; $param = $writer->formatArray(); $tokens->position = $pos; while ($tokens->nextToken()) { if ($tokens->isCurrent('=>') && !$tokens->depth) { $wrap = TRUE; break; } } if (empty($wrap)) { $param = substr($param, 1, -1); // removes array() or [] } return "/* line {$node->startLine} */ " . ($name[0] === '$' ? "if (is_object({$name})) \$_tmp = {$name}; else " : '') . '$_tmp = $this->global->uiControl->getComponent(' . $name . '); ' . 'if ($_tmp instanceof Nette\\Application\\UI\\IRenderable) $_tmp->redrawControl(NULL, FALSE); ' . ($node->modifiers === '' ? "\$_tmp->{$method}({$param});" : $writer->write("ob_start(function () {}); \$_tmp->{$method}({$param}); echo %modify(ob_get_clean());")); }
/** * {element name[:method] [key]} */ public function macroElement(MacroNode $node, PhpWriter $writer) { $rawName = $node->tokenizer->fetchWord(); if ($rawName === FALSE) { throw new CompileException("Missing element type in {element}"); } $rawName = explode(':', $rawName, 2); $name = $writer->formatWord($rawName[0]); $method = isset($rawName[1]) ? ucfirst($rawName[1]) : ''; $method = Strings::match($method, '#^\\w*$#') ? "render{$method}" : "{\"render{$method}\"}"; $idRaw = $node->tokenizer->fetchWord(); $param = $writer->formatArray(); if (!Strings::contains($node->args, '=>')) { $param = substr($param, 6, -1); // removes array() } if (!$idRaw) { throw new CompileException("Missing element title in {element}"); } if (substr($idRaw, 0, 1) !== '$') { $id = Helpers::encodeName($idRaw); } else { $id = $idRaw; } return '$_ctrl = $_presenter->getComponent(\\CmsModule\\Content\\ElementManager::ELEMENT_PREFIX . ' . '"' . $id . '"' . ' . \'_\' . ' . $name . '); ' . '$_ctrl->setName("' . trim($idRaw, '"\'') . '");' . 'if ($presenter->isPanelOpened() && (!isset($__element) || !$__element)) { echo "<span id=\\"' . \CmsModule\Content\ElementManager::ELEMENT_PREFIX . (substr($id, 0, 1) === '$' ? '{' . $id . '}' : $id) . '_' . $rawName[0] . '\\" style=\\"display: inline-block; min-width: 50px; min-height: 25px;\\" class=\\"venne-element-container\\" data-venne-element-id=\\"' . trim($id, '"\'') . '\\" data-venne-element-name=\\"' . $rawName[0] . '\\" data-venne-element-route=\\"" . $presenter->route->id . "\\" data-venne-element-language=\\"" . $presenter->language->id . "\\" data-venne-element-buttons=\\"" . (str_replace(\'"\', "\'", json_encode($_ctrl->getViews()))) . "\\">"; }' . 'if ($_ctrl instanceof Nette\\Application\\UI\\IRenderable) $_ctrl->validateControl(); ' . "\$_ctrl->{$method}({$param});" . 'if ($presenter->isPanelOpened()) { echo "</span>"; }'; }
/** * @param \Doctrine\DBAL\Exception\UniqueConstraintViolationException $e * @param \Kdyby\Doctrine\EntityDao $dao * @param \Carrooi\Doctrine\Entities\BaseEntity $entity * @return static */ public static function createFromDuplicateEntryException(UniqueConstraintViolationException $e, EntityDao $dao, BaseEntity $entity) { $match = Strings::match($e->getMessage(), '/DETAIL:\\s+Key\\s\\(([a-z_]+)\\)/'); $column = $dao->getClassMetadata()->getColumnName($match[1]); $value = $dao->getClassMetadata()->getFieldValue($entity, $match[1]); return new static($e, $entity, $column, $value); }
public function convertFrom(&$data) { if ($data instanceof \DateTime) { $this->entity->data->{$this->fieldName} = $data->format('Y-m-d H:i:s'); $this->setTimestamp($data->getTimestamp()); // @ - Bug #45543 - https://bugs.php.net/bug.php?id=45543 if ($data->getTimezone() !== false) { @$this->setTimezone($data->getTimezone()); } return; } elseif (is_int($data) || intval($data) == $data) { $this->setTimestamp(intval($data)); $this->entity->data->{$this->fieldName} = $this->format('Y-m-d H:i:s'); return; } elseif (is_string($data)) { if (($matches = Strings::match($data, '#^[0-4]{4}-[0-9]{2}-[0-9]{2}$#')) !== false) { $this->setTimestamp(strtotime($data)); $this->entity->data->{$this->fieldName} = $this->format('Y-m-d H:i:s'); } else { throw new Nette\InvalidArgumentException("Unsupported string format " . var_export($data, true) . " for " . get_called_class()); } return; } throw new Nette\InvalidArgumentException("'" . gettype($data) . "' is not supported by " . get_called_class()); }
/** * Generates and checks presenter class name. * * @param string presenter name * @return string class name * @throws Application\InvalidPresenterException */ public function getPresenterClass(&$name) { if (isset($this->cache[$name])) { return $this->cache[$name]; } if (!is_string($name) || !Nette\Utils\Strings::match($name, '#^[a-zA-Z\\x7f-\\xff][a-zA-Z0-9\\x7f-\\xff:]*\\z#')) { throw new Application\InvalidPresenterException("Presenter name must be alphanumeric string, '{$name}' is invalid."); } $classes = $this->formatPresenterClasses($name); if (!$classes) { throw new Application\InvalidPresenterException("Cannot load presenter '{$name}', no applicable mapping found."); } $class = $this->findValidClass($classes); if (!$class) { throw new Application\InvalidPresenterException("Cannot load presenter '{$name}', none of following classes were found: " . implode(', ', $classes)); } $reflection = new Nette\Reflection\ClassType($class); $class = $reflection->getName(); if (!$reflection->implementsInterface('Nette\\Application\\IPresenter')) { throw new Application\InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' is not Nette\\Application\\IPresenter implementor."); } if ($reflection->isAbstract()) { throw new Application\InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' is abstract."); } return $this->cache[$name] = $class; }
public function __construct(Nette\Loaders\RobotLoader $robotLoader) { $classes = $robotLoader->getIndexedClasses(); foreach ($classes as $class => $file) { if (class_exists($class)) { $reflection = new \Nette\Reflection\ClassType($class); if ($reflection->implementsInterface('Tatami\\Modules\\IModule')) { if (!($reflection->isAbstract() or $reflection->isInterface())) { $this->modules[] = $this->parseModuleName($reflection->getShortName()); } } if ($reflection->isSubclassOf('Tatami\\Presenters\\BackendPresenter')) { $moduleName = $this->parseModuleName($reflection->getNamespaceName()); $presenterName = $this->parsePresenterName($reflection->getShortName()); $this->presenters[$moduleName][] = $presenterName; $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if (Strings::match($method->name, '/action/') or Strings::match($method->name, '/render/')) { $this->actions[$presenterName][] = $this->parseActionName($method->name); } } } unset($reflection); } } }
public function matches($urlPath) { if (!($matches = Strings::match($urlPath, $this->re))) { // stop, not matched return NULL; } // deletes numeric keys, restore '-' chars $params = array(); foreach ($matches as $k => $v) { if (is_string($k) && $v !== '') { $params[str_replace('___', '-', $k)] = $v; // trick } } // 4) APPLY FILTERS & FIXITY foreach ($this->metadata as $name => $meta) { if (isset($params[$name])) { if (!is_scalar($params[$name])) { } elseif (isset($meta[self::FILTER_IN])) { // applies filterIn only to scalar parameters $params[$name] = call_user_func($meta[self::FILTER_IN], (string) $params[$name]); } } } if (isset($this->metadata[NULL][self::FILTER_IN])) { $params = call_user_func($this->metadata[NULL][self::FILTER_IN], $params); if ($params === NULL) { return NULL; } } return $params; }
/** * @param string $message * @param array $args */ public function addError($message, $args = array()) { // Hack for translator - and key string like "foo.bar" if ($this->translator && \Nette\Utils\Strings::match($message, '~^[a-z\\.]+$~i')) { $message = $this->translator->translate($message, NULL, $args); } parent::addError($message); }
/** * Convert client request data to array or traversable * @param string $data * @return Media * * @throws MappingException */ public function parse($data) { $matches = Strings::match($data, "@^data:([\\w/]+?);(\\w+?),(.*)\$@si"); if (!$matches) { throw new MappingException('Given data URL is invalid.'); } return new Media(base64_decode($matches[3]), $matches[1]); }
private static function toSemVer($v1) { $shortVersionMatcher = "/^(\\d\\.\\d)(-.*)?\$/"; $matches = Strings::match($v1, $shortVersionMatcher); if ($matches) { return $matches[1] . ".0" . (isset($matches[2]) ? $matches[2] : ""); } return $v1; }
/** * Finds addon by composer name. * * @param string * @return \Nette\Database\Table\ActiveRow|FALSE */ private function findAddon($composerFullName) { $composerVendor = $composerName = NULL; if (($data = Strings::match($composerFullName, Addon::COMPOSER_NAME_RE)) !== NULL) { $composerVendor = $data['vendor']; $composerName = $data['name']; } return $this->db->table('addons')->where(array('composerVendor' => $composerVendor, 'composerName' => $composerName))->limit(1)->fetch(); }
/** * Maps HTTP request to a Request object. * * @param Nette\Http\IRequest $httpRequest * @return NULL|Request */ public function match(Nette\Http\IRequest $httpRequest) { $path = ltrim($httpRequest->getUrl()->getPath(), '/'); if (Nette\Utils\Strings::match($path, '~^' . preg_quote($this->mask, '~') . '/*($|\\?)~')) { header("Location: {$this->target}", TRUE, 301); die; } return NULL; }
/** * @param string|\Nette\Http\Url * @return array|NULL (vendor, name) */ public static function getVendorAndName($url) { if (($matches = Strings::match((string) $url, self::URL_PATTERN_PUBLIC)) !== NULL) { return array($matches['vendor'], $matches['name']); } elseif (($matches = Strings::match((string) $url, self::URL_PATTERN_PRIVATE)) !== NULL) { return array($matches['vendor'], $matches['name']); } return NULL; }
/** * Correct value rowguid * * @param string $rowguid * * @return string|null */ protected function Rowguid($rowguid) { // is correct uuid ? if (Strings::match($rowguid, '/^\\{{0,1}[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\\}{0,1}$/i')) { return (string) $rowguid; } else { return null; } }
public static function decode($string) { $digits = ['I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000]; $string = Strings::upper($string); if (!Strings::match($string, '#[IVXLCDMN]+#')) { throw new \InvalidArgumentException('Malformed symbol detected. Allowed symbols are: IVXLCDMN'); } if (count(explode('V', $string)) > 2 || count(explode('L', $string)) > 2 || count(explode('D', $string)) > 2) { throw new \InvalidArgumentException('Multiple occurencies of V, L or D symbols'); } if ($string === 'N') { return 0; } $count = 1; $last = 'Z'; foreach (str_split($string) as $char) { if ($char === $last) { $count++; if ($count === 4) { throw new \InvalidArgumentException('Malformed Roman number'); } } else { $count = 1; $last = $char; } } $ptr = 0; $values = []; $maxDigit = 1000; while ($ptr < strlen($string)) { $numeral = $string[$ptr]; $digit = $digits[$numeral]; if ($digit > $maxDigit) { throw new \InvalidArgumentException('Rule 3'); } if ($ptr < strlen($string) - 1) { $nextNumeral = $string[$ptr + 1]; $nextDigit = $digits[$nextNumeral]; if ($nextDigit > $digit) { if (!in_array($numeral, ['I', 'X', 'C']) || $nextDigit > $digit * 10 || count(explode($numeral, $string)) > 2) { throw new \InvalidArgumentException('Rule 3'); } $maxDigit = $digit - 1; $digit = $nextDigit - $digit; $ptr++; } } $values[] = $digit; $ptr++; } for ($i = 0; $i < count($values) - 1; $i++) { if ($values[$i] < $values[$i + 1]) { throw new \InvalidArgumentException('Rule 5'); } } return array_sum($values); }
/** * Search for strings inside '<' and '>' * * @param $name * @return mixed */ protected static function findTokens($name) { $found = Nette\Utils\Strings::match($name, '~(\\<[a-z-]\\>)+~i'); if ($found) { return array_map(function ($str) { return substr($str, 1, -1); }, $found); } return FALSE; }
/** * @param string * @return string|null */ private function normalizeGithubUrl($url) { $match = Strings::match($url, '~(?P<url>github\\.com/[\\w\\.\\-]+/[\\w\\.\\-]+)~i'); if (is_array($match) && isset($match['url'])) { if (!Strings::match($match['url'], '~gist\\.github\\.com~')) { return 'https://' . $match['url']; } } return null; }
/** * * @param string $word * @param string $genus (rod) * @param string $number (číslo - jednotné nebo množné) * @param string $case (pád) * @return string */ public function inflect($word, $genus = 'n', $number = 's', $case = 'nom') { foreach ($this->dictionary as $key => $shapes) { if (Strings::match($word, $key) && isset($this->dictionary[$key][$genus][$number][$case])) { $inflectedWord = Strings::replace($word, $key, $shapes[$genus][$number][$case]); return $inflectedWord; } } return $inflectedWord; }
/** * @param string * @return string */ public static function normalizeGithubRepositoryUrl($url) { self::assertGithubRepositoryUrl($url); $url = str_replace('github.com:', 'github.com/', $url); if (Strings::endsWith($url, '.git')) { $url = Strings::substring($url, 0, -4); } $match = Strings::match($url, '~' . self::GITHUB_REGEXP . '~'); return 'https://' . Strings::lower($match[0]); }
/** * @param string name of current render method, typically __METHOD__ (containing "ClassName::render") * @return void */ protected function doRender($renderMethod) { $template = $this->getTemplate(); $classFile = $this->getReflection()->getFileName(); list(, $view) = Strings::match($renderMethod, '~::render(.*)\\z~'); $templateFile = Strings::replace($classFile, '~(?<=/)(.+)\\.php\\z~i', function ($m) use($view) { return $m[1] . ($view ? ".{$view}" : '') . '.latte'; }); $template->setFile($templateFile); $template->render(); }
/** * @param string $value * @return Condition * @throws \Exception * @internal */ public function __getCondition($value) { if ($this->where === NULL && is_string($this->condition)) { list(, $from, $to) = \Nette\Utils\Strings::match($value, $this->mask); $from = \DateTime::createFromFormat($this->dateFormatInput, trim($from)); $to = \DateTime::createFromFormat($this->dateFormatInput, trim($to)); $values = $from && $to ? array($from->format($this->dateFormatOutput), $to->format($this->dateFormatOutput)) : NULL; return $values ? Condition::setup($this->getColumn(), $this->condition, $values) : Condition::setupEmpty(); } return parent::__getCondition($value); }
/** * @param string * @return string */ public function normalizeUrl($url) { $name = $this->getIdByUrl($url); if ($name !== NULL) { $data = Callback::invoke(array($this->classes[$name], 'normalizeUrl'), $url); if ($data !== NULL) { return $data; } } return Strings::match($url, '~^[a-z+]+://~i') ? $url : 'http://' . $url; }
public function render() { list($acc) = func_get_args(); $dic = $this->presenter->context; if (!$dic->parameters['productionMode']) { return; } $this->template->acc = $acc; list(, $this->template->domain) = Strings::match($dic->httpRequest->url->host, '~([^.]+.[^.]+)$~'); $this->template->ssl = $dic->httpRequest->isSecured(); $this->template->render(); }
/** * @param string $html * @return \Lunchbot\Menu\LunchMenuItem[] */ public function parseHtml(string $html) : array { $crawler = new Crawler(); $crawler->addContent($html); $rows = $crawler->filter('div.entry-content table tr')->each(function (Crawler $node) { return $node; }); $todayDayOfWeek = (int) $this->today->format('N'); $currentDayBlock = false; /** @var Crawler $item */ $result = []; foreach ($rows as $item) { $headlineTag = $item->children(); $headline = $headlineTag->text(); $dayOfWeek = \Nette\Utils\Strings::match($headline, '~^(\\w+)\\s~u')[1] ?? null; if (isset(self::$DAYS[$dayOfWeek])) { if ($currentDayBlock) { break; // found tomorrow menu block } elseif (self::$DAYS[$dayOfWeek] === $todayDayOfWeek) { $currentDayBlock = true; } } elseif ($currentDayBlock) { if (\Nette\Utils\Strings::trim($headline) === 'Dezert') { break; } $result[] = new LunchMenuItem($headlineTag->siblings()->text()); } } return $result; }