public function filter($phrase, $collumns) { $phrase = strtolower(Strings::toAscii($phrase)); $this->filter = array(Strings::split($phrase, '/\\s+/'), $collumns); $this->data = null; return $this; }
public function macroSet(MacroNode $node, PhpWriter $writer) { $parts = Strings::replace($node->args, '~(\\s*(=>|=)\\s*|\\s+)~', '~~~', 1); $parts = Strings::split($parts, '/~~~/'); $variable = $parts[0]; $rest = $parts[1]; return $writer->write($variable . ' = %modify(' . $rest . ')'); }
/** * @param string $string * @return array * @throws IntervalParseErrorException */ protected static function parseBoundaryDataFromString(string $string) : array { $letters = Strings::split($string, '//u', PREG_SPLIT_NO_EMPTY); if (count($letters) < 2) { throw new IntervalParseErrorException("Boundary part '{$string}' is too short. It must be at leas 2 character long. Example: '" . Boundary::STRING_OPENED_LEFT . "1' or '9" . Boundary::STRING_CLOSED_RIGHT . "'."); } return self::getElementAndStateData($letters); }
/** * @param string * @param Request */ public function __construct($response, Request $request) { $this->request = $request; $headers = Strings::split(substr($response, 0, $this->request->info['header_size']), "~[\n\r]+~", PREG_SPLIT_NO_EMPTY); $this->parseHeaders($headers); $this->body = substr($response, $this->request->info['header_size']); }
public function extractTags($input) { $matches = Strings::match($input, '/^\\s*(?<tag_list>\\[\\s*[\\pL\\d._-]+\\s*\\](?:\\s*(?&tag_list))?)/u'); if ($matches) { $tags = Strings::trim($matches['tag_list'], '[] '); $tags = Strings::split($tags, '/\\]\\s*\\[/'); $tags = array(array_map('Nette\\Utils\\Strings::webalize', $tags), $tags); } else { $tags = array(); } return $tags; }
/** * @return array */ public function getValue() { // temporarily disable filters $filters = $this->filters; $this->filters = array(); $res = Strings::split(parent::getValue(), "" . $this->delimiter . ""); $this->filters = $filters; foreach ($res as &$tag) { foreach ($this->filters as $filter) { $tag = $filter($tag); } if (!$tag) { unset($tag); } } return $res; }
/** * Parse search query. * * @param string * @return array associative array with keys 'query' and 'tags' */ public function parseQuery($input) { // normalize input $input = Strings::lower(Strings::trim($input)); $input = Strings::replace($input, '/\\s+/', ' '); // extract tags $matches = Strings::matchAll($input, '/(?<=^|\\s)tag:\\s*(?<tag_list>[\\pL\\d_-]+(?:\\s*,\\s*(?&tag_list))?)/u'); $tags = array(); $query = $input; foreach ($matches as $m) { $tmp = Strings::split($m['tag_list'], '/\\s*,\\s*/'); $tmp = array_map('Nette\\Utils\\Strings::webalize', $tmp); $tmp = array_unique($tmp); $tags = array_merge($tags, $tmp); $query = str_replace($m[0], '', $query); } $query = Strings::trim($query) ?: null; return array('query' => $query, 'tags' => $tags); }
/** * @param string $string * @param string $reference * @return string */ public static function underscoreToCamelWithoutPrefix($string, $reference) { // Find longest common prefix between $referencingColumn and (this) $tableName $referenceWords = Strings::split($reference, '#_#'); $stringWords = Strings::split($string, '#_#'); $remainingWords = $stringWords; for ($i = 0; $i < count($stringWords) && $i < count($referenceWords) && count($remainingWords) > 1; $i++) { if ($referenceWords[$i] == $stringWords[$i]) { array_shift($remainingWords); } else { break; } } if (count($remainingWords) > 0) { $result = ''; foreach ($remainingWords as $word) { Strings::firstUpper($word); $result .= Strings::firstUpper($word); } return $result; } return self::underscoreToCamel($string); }
public function renderDefault($search) { //FIXME tagy ::: 'publish_date <=' => new \DateTime() $string = Strings::lower(Strings::normalize($search)); $string = Strings::replace($string, '/[^\\d\\w]/u', ' '); $words = Strings::split(Strings::trim($string), '/\\s+/u'); $words = array_unique(array_filter($words, function ($word) { return Strings::length($word) > 1; })); $words = array_map(function ($word) { return Strings::toAscii($word); }, $words); $string = implode(' ', $words); $this->template->tag = $this->tags->findOneBy(['name' => $string]); $result = $this->posts->fulltextSearch($string); if (count($result) == 0) { $this->template->search = $search; $this->template->error = 'Nic nebylo nalezeno'; } else { $this->template->search = $search; $this->template->result = $result; } }
/** * Tokenize string. * @param string * @return array */ public function tokenize($input) { if ($this->types) { $tokens = Strings::matchAll($input, $this->re); $len = 0; $count = count($this->types); foreach ($tokens as &$match) { $type = NULL; for ($i = 1; $i <= $count; $i++) { if (!isset($match[$i])) { break; } elseif ($match[$i] != NULL) { $type = $this->types[$i - 1]; break; } } $match = array(self::VALUE => $match[0], self::OFFSET => $len, self::TYPE => $type); $len += strlen($match[self::VALUE]); } if ($len !== strlen($input)) { $errorOffset = $len; } } else { $tokens = Strings::split($input, $this->re, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE); $last = end($tokens); if ($tokens && !Strings::match($last[0], $this->re)) { $errorOffset = $last[1]; } } if (isset($errorOffset)) { list($line, $col) = $this->getCoordinates($input, $errorOffset); $token = str_replace("\n", '\\n', substr($input, $errorOffset, 10)); throw new TokenizerException("Unexpected '{$token}' on line {$line}, column {$col}."); } return $tokens; }
/** * Converts 'optionName' to 'option-name', i.e. from property convention to CLI convention * * @param string $propertyName * @return string */ public static function getCliOptionName($propertyName) { $words = Strings::split($propertyName, '/(?=[A-Z])/'); return strtolower(join("-", $words)); }
/** * Parse mask and array of default values; initializes object. * @param string * @param array * @return void */ private function setMask($mask, array $metadata) { $this->mask = $mask; // detect '//host/path' vs. '/abs. path' vs. 'relative path' if (preg_match('#(?:(https?):)?(//.*)#A', $mask, $m)) { $this->type = self::HOST; list(, $this->scheme, $mask) = $m; } elseif (substr($mask, 0, 1) === '/') { $this->type = self::PATH; } else { $this->type = self::RELATIVE; } foreach ($metadata as $name => $meta) { if (!is_array($meta)) { $metadata[$name] = $meta = [self::VALUE => $meta]; } if (array_key_exists(self::VALUE, $meta)) { if (is_scalar($meta[self::VALUE])) { $metadata[$name][self::VALUE] = (string) $meta[self::VALUE]; } $metadata[$name]['fixity'] = self::CONSTANT; } } if (strpbrk($mask, '?<>[]') === FALSE) { $this->re = '#' . preg_quote($mask, '#') . '/?\\z#A'; $this->sequence = [$mask]; $this->metadata = $metadata; return; } // PARSE MASK // <parameter-name[=default] [pattern]> or [ or ] or ?... $parts = Strings::split($mask, '/<([^<>= ]+)(=[^<> ]*)? *([^<>]*)>|(\\[!?|\\]|\\s*\\?.*)/'); $this->xlat = []; $i = count($parts) - 1; // PARSE QUERY PART OF MASK if (isset($parts[$i - 1]) && substr(ltrim($parts[$i - 1]), 0, 1) === '?') { // name=<parameter-name [pattern]> $matches = Strings::matchAll($parts[$i - 1], '/(?:([a-zA-Z0-9_.-]+)=)?<([^> ]+) *([^>]*)>/'); foreach ($matches as list(, $param, $name, $pattern)) { // $pattern is not used if (isset(static::$styles['?' . $name])) { $meta = static::$styles['?' . $name]; } else { $meta = static::$styles['?#']; } if (isset($metadata[$name])) { $meta = $metadata[$name] + $meta; } if (array_key_exists(self::VALUE, $meta)) { $meta['fixity'] = self::OPTIONAL; } unset($meta['pattern']); $meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]); $metadata[$name] = $meta; if ($param !== '') { $this->xlat[$name] = $param; } } $i -= 5; } // PARSE PATH PART OF MASK $brackets = 0; // optional level $re = ''; $sequence = []; $autoOptional = TRUE; $aliases = []; do { $part = $parts[$i]; // part of path if (strpbrk($part, '<>') !== FALSE) { throw new Nette\InvalidArgumentException("Unexpected '{$part}' in mask '{$mask}'."); } array_unshift($sequence, $part); $re = preg_quote($part, '#') . $re; if ($i === 0) { break; } $i--; $part = $parts[$i]; // [ or ] if ($part === '[' || $part === ']' || $part === '[!') { $brackets += $part[0] === '[' ? -1 : 1; if ($brackets < 0) { throw new Nette\InvalidArgumentException("Unexpected '{$part}' in mask '{$mask}'."); } array_unshift($sequence, $part); $re = ($part[0] === '[' ? '(?:' : ')?') . $re; $i -= 4; continue; } $pattern = trim($parts[$i]); $i--; // validation condition (as regexp) $default = $parts[$i]; $i--; // default value $name = $parts[$i]; $i--; // parameter name array_unshift($sequence, $name); if ($name[0] === '?') { // "foo" parameter $name = substr($name, 1); $re = $pattern ? '(?:' . preg_quote($name, '#') . "|{$pattern}){$re}" : preg_quote($name, '#') . $re; $sequence[1] = $name . $sequence[1]; continue; } // pattern, condition & metadata if (isset(static::$styles[$name])) { $meta = static::$styles[$name]; } else { $meta = static::$styles['#']; } if (isset($metadata[$name])) { $meta = $metadata[$name] + $meta; } if ($pattern == '' && isset($meta[self::PATTERN])) { $pattern = $meta[self::PATTERN]; } if ($default !== '') { $meta[self::VALUE] = (string) substr($default, 1); $meta['fixity'] = self::PATH_OPTIONAL; } $meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]); if (array_key_exists(self::VALUE, $meta)) { if (isset($meta['filterTable2'][$meta[self::VALUE]])) { $meta['defOut'] = $meta['filterTable2'][$meta[self::VALUE]]; } elseif (isset($meta[self::FILTER_OUT])) { $meta['defOut'] = call_user_func($meta[self::FILTER_OUT], $meta[self::VALUE]); } else { $meta['defOut'] = $meta[self::VALUE]; } } $meta[self::PATTERN] = "#(?:{$pattern})\\z#A"; // include in expression $aliases['p' . $i] = $name; $re = '(?P<p' . $i . '>(?U)' . $pattern . ')' . $re; if ($brackets) { // is in brackets? if (!isset($meta[self::VALUE])) { $meta[self::VALUE] = $meta['defOut'] = NULL; } $meta['fixity'] = self::PATH_OPTIONAL; } elseif (!$autoOptional) { unset($meta['fixity']); } elseif (isset($meta['fixity'])) { // auto-optional $re = '(?:' . $re . ')?'; $meta['fixity'] = self::PATH_OPTIONAL; } else { $autoOptional = FALSE; } $metadata[$name] = $meta; } while (TRUE); if ($brackets) { throw new Nette\InvalidArgumentException("Missing '[' in mask '{$mask}'."); } $this->aliases = $aliases; $this->re = '#' . $re . '/?\\z#A'; $this->metadata = $metadata; $this->sequence = $sequence; }
protected function setMask($mask) { $this->mask = $mask; $metadata = array(); // PARSE MASK // <parameter-name[=default] [pattern] [#class]> or [ or ] or ?... $parts = Strings::split($mask, '/<([^># ]+)() *([^>#]*)(#?[^>\\[\\]]*)>|(\\[!?|\\]|\\s*\\?.*)/'); $i = count($parts) - 1; // PARSE PATH PART OF MASK $brackets = 0; // optional level $re = ''; $sequence = array(); $autoOptional = TRUE; do { array_unshift($sequence, $parts[$i]); $re = preg_quote($parts[$i], '#') . $re; if ($i === 0) { break; } $i--; $part = $parts[$i]; // [ or ] if ($part === '[' || $part === ']' || $part === '[!') { $brackets += $part[0] === '[' ? -1 : 1; if ($brackets < 0) { throw new Nette\InvalidArgumentException("Unexpected '{$part}' in mask '{$mask}'."); } array_unshift($sequence, $part); $re = ($part[0] === '[' ? '(?:' : ')?') . $re; $i -= 5; continue; } $class = $parts[$i]; $i--; // validation class $pattern = trim($parts[$i]); $i--; // validation condition (as regexp) $default = $parts[$i]; $i--; // default value $name = $parts[$i]; $i--; // parameter name array_unshift($sequence, $name); if ($name[0] === '?') { // "foo" parameter $name = substr($name, 1); $re = $pattern ? '(?:' . preg_quote($name, '#') . "|{$pattern}){$re}" : preg_quote($name, '#') . $re; $sequence[1] = $name . $sequence[1]; continue; } // check name (limitation by regexp) if (preg_match('#[^a-z0-9_-]#i', $name)) { throw new Nette\InvalidArgumentException("Parameter name must be alphanumeric string due to limitations of PCRE, '{$name}' given."); } // pattern, condition & metadata if ($class !== '') { if (!isset(static::$styles[$class])) { throw new Nette\InvalidStateException("Parameter '{$name}' has '{$class}' flag, but Route::\$styles['{$class}'] is not set."); } $meta = static::$styles[$class]; } elseif (isset(static::$styles[$name])) { $meta = static::$styles[$name]; } else { $meta = static::$styles['#']; } if (isset($metadata[$name])) { $meta = $metadata[$name] + $meta; } if ($pattern == '' && isset($meta[self::PATTERN])) { $pattern = $meta[self::PATTERN]; } $meta[self::PATTERN] = "#(?:{$pattern})\\z#A" . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu'); // include in expression $re = '(?P<' . str_replace('-', '___', $name) . '>(?U)' . $pattern . ')' . $re; // str_replace is dirty trick to enable '-' in parameter name if ($brackets) { // is in brackets? if (!isset($meta[self::VALUE])) { $meta[self::VALUE] = $meta['defOut'] = NULL; } $meta['fixity'] = self::PATH_OPTIONAL; } elseif (!$autoOptional) { unset($meta['fixity']); } elseif (isset($meta['fixity'])) { // auto-optional $re = '(?:' . $re . ')?'; $meta['fixity'] = self::PATH_OPTIONAL; } else { $autoOptional = FALSE; } $metadata[$name] = $meta; } while (TRUE); if ($brackets) { throw new Nette\InvalidArgumentException("Missing closing ']' in mask '{$mask}'."); } $this->re = '#' . $re . '/?\\z#A' . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu'); $this->metadata = $metadata; $this->sequence = $sequence; }
/** * Fix downloaded file * @throws \Curl\CurlException * @throws \InvalidStateException * @return \Curl\Response */ private function parseFile() { if ($this->request->method === Request::DOWNLOAD) { $path_p = $this->request->downloadPath; @fclose($this->request->getOption('file')); // internationaly @ if (($fp = @fopen($this->request->fileProtocol . '://' . $path_p, "rb")) === FALSE) { // internationaly @ throw new \InvalidStateException("Fopen error for file '{$path_p}'"); } $headers = Strings::split(@fread($fp, $this->request->info['header_size']), "~[\n\r]+~", PREG_SPLIT_NO_EMPTY); // internationaly @ $this->Headers = array_merge($this->Headers, static::parseHeaders($headers)); @fseek($fp, $this->request->info['header_size']); // internationaly @ $path_t = $this->request->downloadPath . '.tmp'; if (($ft = @fopen($this->request->fileProtocol . '://' . $path_t, "wb")) === FALSE) { // internationaly @ throw new \InvalidStateException("Write error for file '{$path_t}' "); } while (!feof($fp)) { $row = fgets($fp, 4096); fwrite($ft, $row); } @fclose($fp); // internationaly @ @fclose($ft); // internationaly @ if (!@unlink($this->request->fileProtocol . '://' . $path_p)) { // internationaly @ throw new \InvalidStateException("Error while deleting file {$path_p} "); } if (!@rename($path_t, $path_p)) { // internationaly @ throw new \InvalidStateException("Error while renaming file '{$path_t}' to '" . basename($path_p) . "'. "); } chmod($path_p, 0755); if (!$this->Headers) { throw new CurlException("Headers parsing failed", NULL, $this); } } return $this; }
/** * Returns position of token in input string. * @param int token number * @return array [offset, line, column] */ public function getOffset($i) { $tokens = Strings::split($this->input, $this->re, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE); $offset = isset($tokens[$i]) ? $tokens[$i][1] : strlen($this->input); return array($offset, $offset ? substr_count($this->input, "\n", 0, $offset) + 1 : 1, $offset - strrpos(substr($this->input, 0, $offset), "\n")); }
/** * Parses headers from given list * @param array $input * * @return array */ public static function parseHeaders($input) { if (!is_array($input)) { $input = Strings::split($input, "~[\n\r]+~", PREG_SPLIT_NO_EMPTY); } # Extract the version and status from the first header $headers = array(); while ($m = Strings::match(reset($input), static::VERSION_AND_STATUS)) { $headers['Http-Version'] = $m['version']; $headers['Status-Code'] = $m['code']; $headers['Status'] = isset($m['status']) ? $m['code'] . ' ' . $m['status'] : ''; array_shift($input); } # Convert headers into an associative array foreach ($input as $header) { if ($m = Strings::match($header, static::HEADER_REGEXP)) { if (in_array($m['header'], array('Http-Version', 'Status-Code', 'Status'), TRUE)) { continue; } if (empty($headers[$m['header']])) { $headers[$m['header']] = $m['value']; } elseif (!is_array($headers[$m['header']])) { $headers[$m['header']] = array($headers[$m['header']], $m['value']); } else { $headers[$m['header']][] = $m['value']; } } } if (isset($headers['Set-Cookie'])) { $headers['Set-Cookie'] = new HttpCookies(is_array($headers['Set-Cookie']) ? $headers['Set-Cookie'] : array($headers['Set-Cookie'])); } return $headers; }
private static function parseHeaders($raw) { $headers = []; // Split the string on every "double" new line. foreach (explode("\r\n\r\n", $raw) as $index => $block) { // Loop of response headers. The "count() -1" is to //avoid an empty row for the extra line break before the body of the response. foreach (Utils\Strings::split(trim($block), '~[\\r\\n]+~') as $i => $line) { if (preg_match('~^([a-z-]+\\:)(.*)$~is', $line)) { list($key, $val) = explode(': ', $line, 2); $headers[$index][$key] = $val; } else { if (!empty($line)) { $headers[$index][] = $line; } } } } return $headers; }
/** * @param CurlWrapper $curl * * @return Response|NULL */ protected function buildRedirectResponse(CurlWrapper $curl) { if ($curl->info['redirect_count'] === 0) { return NULL; } $previous = $last = NULL; /** @var Response $last */ $parts = Strings::split($curl->responseHeaders, '~(HTTP/\\d\\.\\d\\s\\d+\\s.*)~m', PREG_SPLIT_NO_EMPTY); while ($rawHeaders = array_shift($parts)) { if ($http = Strings::match($rawHeaders, CurlWrapper::VERSION_AND_STATUS)) { if ($http['code'] < 200) { continue; } $rawHeaders .= array_shift($parts); } if (!$parts) { $curl->responseHeaders = $rawHeaders; return $last; } if ($headers = CurlWrapper::parseHeaders($rawHeaders)) { $previous = new Response($curl, $headers); if ($last !== NULL) { $previous->setPrevious($last); } } $last = $previous; } return $last; }
private function split($selectize) { $return = \Nette\Utils\Strings::split($selectize, '~' . $this->options['delimiter'] . '\\s*~'); return $return[0] === "" ? [] : $return; }
use Nette\Utils\ArrayHash; use Nette\Utils\Strings; $View = new ArrayHash(); $View->parameters = ArrayHash::from($App->parameters); define('THEME_DIR', dirname(__FILE__)); define('THEME_UTILS_DIR', THEME_DIR . '/utils'); define('ADMIN_UTILS_DIR', THEME_DIR . '/admin'); define('API_DIR', THEME_DIR . '/api'); define('FORMS_DIR', THEME_DIR . '/forms'); define('THEME_VIEWS_DIR', THEME_DIR . '/views'); define('NEON_WP_DIR', __DIR__ . '/define'); foreach (glob(THEME_UTILS_DIR . '/*.php') as $filename) { require_once $filename; } $Forms = new ArrayHash(); foreach (glob(FORMS_DIR . '/*.php') as $filename) { $Forms[basename($filename, '.php')] = (require_once $filename); } $View->Forms = $Forms; if (is_admin()) { foreach (glob(ADMIN_UTILS_DIR . '/*.php') as $filename) { require_once $filename; } } // CSRF protection $App->session->start(); if (Strings::startsWith($Url->pathInfo, 'api/')) { $ApiRequest = Strings::split(Strings::trim($Url->pathInfo, '~/+~'), '~/~'); array_shift($ApiRequest); require API_DIR . '/index.php'; }
Nette\InvalidStateException("Ambiguous class '$class' resolution; defined in $file and in ".$this->list[$lClass][0].".");{throw$e;}}$this->list[$lClass]=array($file,$time,$class);$this->files[$file]=$time;}private function scanDirectory($dir){if(is_dir($dir)){$ignoreDirs=is_array($this->ignoreDirs)?$this->ignoreDirs:Strings::split($this->ignoreDirs,'#[,\s]+#');$disallow=array();foreach($ignoreDirs as$item){if($item=realpath($item)){$disallow[$item]=TRUE;}}$iterator=Nette\Utils\Finder::findFiles(is_array($this->acceptFiles)?$this->acceptFiles:Strings::split($this->acceptFiles,'#[,\s]+#'))->filter(function($file)use(&$disallow){return!isset($disallow[$file->getPathname()]);})->from($dir)->exclude($ignoreDirs)->filter($filter=function($dir)use(&$disallow){$path=$dir->getPathname();if(is_file("$path/netterobots.txt")){foreach(file("$path/netterobots.txt")as$s){if($matches=Strings::match($s,'#^(?:disallow\\s*:)?\\s*(\\S+)#i')){$disallow[$path.str_replace('/',DIRECTORY_SEPARATOR,rtrim('/'.ltrim($matches[1],'/'),'/'))]=TRUE;}}}return!isset($disallow[$path]);});$filter(new\SplFileInfo($dir));}else{$iterator=new\ArrayIterator(array(new\SplFileInfo($dir)));}foreach($iterator as$entry){$path=$entry->getPathname();if(!isset($this->files[$path])||$this->files[$path]!==$entry->getMTime()){$this->scanScript($path);}}}private
public function process(\Nette\Application\UI\Form $form, $values) { $file = $values->file; if (!$file instanceof \Nette\Http\FileUpload) { throw new \Nette\FileNotFoundException('Nahraný soubor není typu Nette\\Http\\FileUpload. Pravděpodobně se nenahrál v pořádku.'); } if (!$file->isOk()) { throw new \Nette\FileNotFoundException('Soubor byl poškozen:' . $file->error); } if ($this->isImage && $file->isImage() !== $this->isImage) { throw new \Nette\InvalidArgumentException('Soubor musí být obrázek'); } if (is_array($this->allowType) && in_array($file->getContentType(), $this->allowType, TRUE)) { throw new \Nette\InvalidArgumentException('Soubor není povoleného typu'); } $this->handleCheckDirectory(); $targetPath = $this->wwwDir . DIRECTORY_SEPARATOR . $this->path; if ($this->randomFileName) { $SplitedName = \Nette\Utils\Strings::split($file->getSanitizedName(), '~\\.\\s*~'); $suffix = array_pop($SplitedName); $random = new \Nette\Utils\Random(); $randomName = $random->generate(48, '0-9a-zA-Z'); while (is_file($targetPath . DIRECTORY_SEPARATOR . $randomName . '.' . $suffix)) { $randomName = $random->generate(48, '0-9a-zA-Z'); } $name = $randomName . '.' . $suffix; } else { if ($this->rewriteExistingFiles) { $name = $file->getSanitizedName(); } else { $SplitedName = \Nette\Utils\Strings::split($file->getSanitizedName(), '~\\.\\s*~'); $suffix = array_pop($SplitedName); $counter = NULL; while (is_file($targetPath . DIRECTORY_SEPARATOR . implode('.', $SplitedName) . $counter . '.' . $suffix)) { $counter++; } $name = implode('.', $SplitedName) . $counter . '.' . $suffix; } } if ($file->isImage()) { $image = $file->toImage(); $width = $this->photo['width']; $height = $this->photo['height']; $flags = $this->photo['width']; if (!is_null($width) || !is_null($height)) { $image->resize($width, $height, $flags); } $image->save($targetPath . DIRECTORY_SEPARATOR . $name, $this->photo['quality'], $this->photo['type']); } else { $this->moveUploadedFile($file, $targetPath, $name); } if (!$this->randomFileName) { $fileName = implode('.', $SplitedName) . $counter; } else { $fileName = $randomName; } $this->onSuccess($this, $this->path, $fileName, $suffix); }
/** * @param Container $container * @param ConstraintViolationInterface $violation * @return Nette\Forms\IControl|Nette\Forms\Controls\BaseControl|UI\Form */ private function findControl(Container $container, ConstraintViolationInterface $violation) { if (!($m = Nette\Utils\Strings::split('.' . $violation->getPropertyPath(), '~([\\.\\[])~'))) { return $container->getForm(); // apply the error to form } $control = $container; while (($type = array_shift($m)) !== NULL && $control) { if (empty($type)) { continue; } $step = array_shift($m); if ($type === '[') { $step = substr($step, 0, -1); } $control = $control->getComponent($step, FALSE); } return $control instanceof Nette\Forms\IControl ? $control : $container->getForm(); }
public function getWordVariations($word) { $sNoBrackets = Strings::replace($word, "/[\\[\\](){}]/", ""); $keywords = array_merge(array($word, $sNoBrackets), explode("-", $sNoBrackets), explode("_", $sNoBrackets), explode(" ", $sNoBrackets), Strings::split($sNoBrackets, "[ _-]")); foreach ($keywords as $index => $kw) { $keywords[$index] = Strings::trim($kw); $keywords[$index] = Strings::replace($keywords[$index], '/^\\+/', ''); // remove + operator if (Strings::length($keywords[$index]) < 3) { unset($keywords[$index]); } else { $keywords[] = Strings::toAscii($keywords[$index]); } } $keywords = array_unique($keywords); $keywords = array_values($keywords); return $keywords; }
/** * @param \Reflector|\Nette\Reflection\ClassType|\Nette\Reflection\Method $refl * @param int $symbolPos * * @return int */ protected static function calculateAffectedLine(\Reflector $refl, $symbolPos) { $doc = $refl->getDocComment(); $cleanedDoc = self::cleanedPhpDoc($refl, $atPos); $beforeCleanLines = count(Strings::split(substr($doc, 0, $atPos), '~[\\n\\r]+~')); $parsedDoc = substr($cleanedDoc, 0, $symbolPos + 1); $parsedLines = count(Strings::split($parsedDoc, '~[\\n\\r]+~')); return $parsedLines + max($beforeCleanLines - 1, 0); }
/** * @param array * @param array|string * @param bool * * @return array */ public static function groupBy(array $array, $columns, $append = FALSE) { $columns = is_array($columns) ? $columns : Nette\Utils\Strings::split($columns, '~\\s*,\\s*~'); $grouped = array(); foreach ($array as $item) { $keys = array_map(function ($key) use($item) { return is_object($item) ? $item->{$key} : $item[$key]; }, $columns); $ref =& Nette\Utils\Arrays::getRef($grouped, $keys); if ($append) { if (!is_array($ref)) { $ref = array(); } $ref[] = $item; } else { $ref = $item; } unset($ref); } return $grouped; }
/** * Scan a directory for PHP files, subdirectories and 'netterobots.txt' file. * @param string * @return void */ private function scanDirectory($dir) { if (is_dir($dir)) { $disallow = array(); $iterator = Nette\Utils\Finder::findFiles(Strings::split($this->acceptFiles, '#[,\\s]+#'))->filter(function ($file) use(&$disallow) { return !isset($disallow[$file->getPathname()]); })->from($dir)->exclude(Strings::split($this->ignoreDirs, '#[,\\s]+#'))->filter($filter = function ($dir) use(&$disallow) { $path = $dir->getPathname(); if (is_file("{$path}/netterobots.txt")) { foreach (file("{$path}/netterobots.txt") as $s) { if ($matches = Strings::match($s, '#^disallow\\s*:\\s*(\\S+)#i')) { $disallow[$path . str_replace('/', DIRECTORY_SEPARATOR, rtrim('/' . ltrim($matches[1], '/'), '/'))] = TRUE; } } } return !isset($disallow[$path]); }); $filter(new \SplFileInfo($dir)); } else { $iterator = new \ArrayIterator(array(new \SplFileInfo($dir))); } foreach ($iterator as $entry) { $path = $entry->getPathname(); if (!isset($this->files[$path]) || $this->files[$path] !== $entry->getMTime()) { $this->scanScript($path); } } }
/** * Parses one time annotation. If it is invalid throws exception. * * @param string $time * @return string[][] * @throws \stekycz\Cronner\InvalidParameterException */ private static function parseOneTime($time) { $time = static::translateToTimes($time); $parts = Strings::split($time, '/\\s*-\\s*/'); if (!static::isValidTime($parts[0]) || isset($parts[1]) && !static::isValidTime($parts[1])) { throw new InvalidParameterException("Times annotation is not in valid format. It must looks like 'hh:mm[ - hh:mm]' but '" . $time . "' was given."); } $times = array(); if (static::isTimeOverMidnight($parts[0], isset($parts[1]) ? $parts[1] : NULL)) { $times[] = static::timePartsToArray('00:00', $parts[1]); $times[] = static::timePartsToArray($parts[0], '23:59'); } else { $times[] = static::timePartsToArray($parts[0], isset($parts[1]) ? $parts[1] : NULL); } return $times; }
/** * Parse mask and array of default values; initializes object. * @param string * @param array * @return void */ private function setMask($mask, array $metadata) { $this->mask = $mask; // detect '//host/path' vs. '/abs. path' vs. 'relative path' if (substr($mask, 0, 2) === '//') { $this->type = self::HOST; } elseif (substr($mask, 0, 1) === '/') { $this->type = self::PATH; } else { $this->type = self::RELATIVE; } foreach ($metadata as $name => $meta) { if (!is_array($meta)) { $metadata[$name] = array(self::VALUE => $meta, 'fixity' => self::CONSTANT); } elseif (array_key_exists(self::VALUE, $meta)) { $metadata[$name]['fixity'] = self::CONSTANT; } } // PARSE MASK // <parameter-name[=default] [pattern] [#class]> or [ or ] or ?... $parts = Strings::split($mask, '/<([^>#= ]+)(=[^># ]*)? *([^>#]*)(#?[^>\\[\\]]*)>|(\\[!?|\\]|\\s*\\?.*)/'); $this->xlat = array(); $i = count($parts) - 1; // PARSE QUERY PART OF MASK if (isset($parts[$i - 1]) && substr(ltrim($parts[$i - 1]), 0, 1) === '?') { // name=<parameter-name [pattern][#class]> $matches = Strings::matchAll($parts[$i - 1], '/(?:([a-zA-Z0-9_.-]+)=)?<([^># ]+) *([^>#]*)(#?[^>]*)>/'); foreach ($matches as $match) { list(, $param, $name, $pattern, $class) = $match; // $pattern is not used if ($class !== '') { if (!isset(static::$styles[$class])) { throw new Nette\InvalidStateException("Parameter '{$name}' has '{$class}' flag, but Route::\$styles['{$class}'] is not set."); } $meta = static::$styles[$class]; } elseif (isset(static::$styles['?' . $name])) { $meta = static::$styles['?' . $name]; } else { $meta = static::$styles['?#']; } if (isset($metadata[$name])) { $meta = $metadata[$name] + $meta; } if (array_key_exists(self::VALUE, $meta)) { $meta['fixity'] = self::OPTIONAL; } unset($meta['pattern']); $meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]); $metadata[$name] = $meta; if ($param !== '') { $this->xlat[$name] = $param; } } $i -= 6; } // PARSE PATH PART OF MASK $brackets = 0; // optional level $re = ''; $sequence = array(); $autoOptional = TRUE; do { array_unshift($sequence, $parts[$i]); $re = preg_quote($parts[$i], '#') . $re; if ($i === 0) { break; } $i--; $part = $parts[$i]; // [ or ] if ($part === '[' || $part === ']' || $part === '[!') { $brackets += $part[0] === '[' ? -1 : 1; if ($brackets < 0) { throw new Nette\InvalidArgumentException("Unexpected '{$part}' in mask '{$mask}'."); } array_unshift($sequence, $part); $re = ($part[0] === '[' ? '(?:' : ')?') . $re; $i -= 5; continue; } $class = $parts[$i]; $i--; // validation class $pattern = trim($parts[$i]); $i--; // validation condition (as regexp) $default = $parts[$i]; $i--; // default value $name = $parts[$i]; $i--; // parameter name array_unshift($sequence, $name); if ($name[0] === '?') { // "foo" parameter $name = substr($name, 1); $re = $pattern ? '(?:' . preg_quote($name, '#') . "|{$pattern}){$re}" : preg_quote($name, '#') . $re; $sequence[1] = $name . $sequence[1]; continue; } // check name (limitation by regexp) if (preg_match('#[^a-z0-9_-]#i', $name)) { throw new Nette\InvalidArgumentException("Parameter name must be alphanumeric string due to limitations of PCRE, '{$name}' given."); } // pattern, condition & metadata if ($class !== '') { if (!isset(static::$styles[$class])) { throw new Nette\InvalidStateException("Parameter '{$name}' has '{$class}' flag, but Route::\$styles['{$class}'] is not set."); } $meta = static::$styles[$class]; } elseif (isset(static::$styles[$name])) { $meta = static::$styles[$name]; } else { $meta = static::$styles['#']; } if (isset($metadata[$name])) { $meta = $metadata[$name] + $meta; } if ($pattern == '' && isset($meta[self::PATTERN])) { $pattern = $meta[self::PATTERN]; } if ($default !== '') { $meta[self::VALUE] = (string) substr($default, 1); $meta['fixity'] = self::PATH_OPTIONAL; } $meta['filterTable2'] = empty($meta[self::FILTER_TABLE]) ? NULL : array_flip($meta[self::FILTER_TABLE]); if (array_key_exists(self::VALUE, $meta)) { if (isset($meta['filterTable2'][$meta[self::VALUE]])) { $meta['defOut'] = $meta['filterTable2'][$meta[self::VALUE]]; } elseif (isset($meta[self::FILTER_OUT])) { $meta['defOut'] = call_user_func($meta[self::FILTER_OUT], $meta[self::VALUE]); } else { $meta['defOut'] = $meta[self::VALUE]; } } $meta[self::PATTERN] = "#(?:{$pattern})\\z#A" . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu'); // include in expression $re = '(?P<' . str_replace('-', '___', $name) . '>(?U)' . $pattern . ')' . $re; // str_replace is dirty trick to enable '-' in parameter name if ($brackets) { // is in brackets? if (!isset($meta[self::VALUE])) { $meta[self::VALUE] = $meta['defOut'] = NULL; } $meta['fixity'] = self::PATH_OPTIONAL; } elseif (!$autoOptional) { unset($meta['fixity']); } elseif (isset($meta['fixity'])) { // auto-optional $re = '(?:' . $re . ')?'; $meta['fixity'] = self::PATH_OPTIONAL; } else { $autoOptional = FALSE; } $metadata[$name] = $meta; } while (TRUE); if ($brackets) { throw new Nette\InvalidArgumentException("Missing closing ']' in mask '{$mask}'."); } $this->re = '#' . $re . '/?\\z#A' . ($this->flags & self::CASE_SENSITIVE ? '' : 'iu'); $this->metadata = $metadata; $this->sequence = $sequence; }
public function actionGuessGender($name) { $names = Strings::split($name, '~\\s+~'); $firstName = array_shift($names); $lastName = array_pop($names); $gender = $this->orm->users->getGender($firstName, $lastName); $this->sendJson(['gender' => $gender]); }