/** * @param string $query * @return \Nette\Database\Table\Selection */ public function findFulltext($query) { if (strpos($query, ' ') !== FALSE) { $query = explode(' ', $query); } else { $query = array($query); } $result = $this->table()->where('document_state', 'public'); // maybe, there will be some tags in the query, let's see $tags = []; foreach ($query as $keyword) { if (strpos($keyword, '#') === 0 and Strings::length($keyword) > 2) { // yes, this is a tag $tags[] = str_replace('#', '', $keyword); } elseif (strpos($keyword, '#') === FALSE) { // this is definitely not a tag $result->where('title LIKE ? OR content LIKE ? OR :article_tag.tag.name LIKE ?', array("%" . $keyword . "%", "%" . $keyword . "%", "%" . $keyword . "%")); } } // if there are any tags, add them to the search conditions if (count($tags) > 0) { $result->where(':article_tag.tag.name IN ?', $tags); $result->group("article.id")->having("COUNT(DISTINCT :article_tag.tag.name) = ?", count($tags)); } return $result; }
/** * Sets name of current task. * * @param string|null $taskName */ public function setTaskName($taskName = NULL) { if ($taskName !== NULL && (!$taskName || !is_string($taskName) || Strings::length($taskName) <= 0)) { throw new InvalidTaskNameException('Given task name is not valid.'); } $this->taskName = $taskName; }
/** * Length validator: is control's value length in range? * * @param TextBase * @param array min and max length pair * * @return bool */ public static function validateLength(TextBase $control, $range) { if (!is_array($range)) { $range = array($range, $range); } return Validators::isInRange(Strings::length($control->getValue()), $range); }
protected function createGrid() { $grid = $this->createPreparedGrid(); $grid->setModel($this->getModel()); $grid->addColumnNumber('id', 'ID')->setSortable()->setFilterNumber(); $grid->addColumnText('username', 'Přihlašovací jméno')->setSortable()->setDefaultSort('asc')->setFilterText(); $grid->addColumnText('name', 'Jméno')->setSortable()->setFilterText(); $grid->addColumnText('surname', 'Příjmení')->setSortable()->setFilterText(); $grid->addColumnText('email', 'Email')->setCustomRender(function ($row) { if (Strings::length($row->email) <= 0) { return ''; } return Html::el('a')->setText($row->email)->href('mailto:' . $row->email); })->setSortable()->setFilterText()->setColumn('user.email'); $section = $grid->addColumnText('section', 'Sekce'); $this->helpers->setupAsMultirecord($section, function ($row) { $selection = $this->sectionFacade->all(); $this->userFilter->filterId($selection, $row->id, ':user_has_section'); $selection->select("section.id,section.name"); return $selection->fetchPairs('id', 'name'); }); $role = $grid->addColumnText('role', 'Role'); $this->helpers->setupAsMultirecord($role, function ($row) { $selection = $this->roleFacade->all(); $this->userFilter->filterId($selection, $row->id, ':user_has_role'); $selection->select("role.code,role.name"); return $selection->fetchPairs('code', 'name'); }); $this->helpers->addEditAction($grid); $this->helpers->addDeleteEvent($grid, $this->deleteRow, function ($row) { return $row->surname . ' ' . $row->name; }); return $grid; }
/** * Filter: removes unnecessary whitespace and shortens value to control's max length. * * @return string */ public function sanitize($value) { if ($this->control->maxlength && Nette\Utils\Strings::length($value) > $this->control->maxlength) { $value = Nette\Utils\Strings::substring($value, 0, $this->control->maxlength); } return Nette\Utils\Strings::trim(strtr($value, "\r\n", ' ')); }
private function maybeReplacePlaceholderWithPrefix($key) { if (Strings::startsWith($key, self::PREFIX_PLACEHOLDER)) { return $this->dbPrefix . Strings::substring($key, Strings::length(self::PREFIX_PLACEHOLDER)); } return $key; }
protected function prepareTemplate($id) { $this->template->id = $id; $this->template->current = $this->action; if (Strings::length($id)) { $this->template->roleName = $this->getRoleName($id); } }
/** * Model\Entity\SomeEntity -> some_entity * @param string $entityClass * @return string */ public function getTable($entityClass) { if (Strings::endsWith($entityClass, 'y')) { return $this->camelToUnderdash(Strings::substring($this->trimNamespace($entityClass), 0, Strings::length($entityClass))) . 'ies'; } else { return $this->camelToUnderdash($this->trimNamespace($entityClass)) . 's'; } }
/** * @return Template */ public function createTemplate(UI\Control $control = NULL) { $latte = $this->latteFactory->create(); $template = new Template($latte); $presenter = $control ? $control->getPresenter(FALSE) : NULL; if ($control instanceof UI\Presenter) { $latte->setLoader(new Loader($control)); } if ($latte->onCompile instanceof \Traversable) { $latte->onCompile = iterator_to_array($latte->onCompile); } array_unshift($latte->onCompile, function ($latte) use($control, $template) { $latte->getParser()->shortNoEscape = TRUE; $latte->getCompiler()->addMacro('cache', new Nette\Bridges\CacheLatte\CacheMacro($latte->getCompiler())); UIMacros::install($latte->getCompiler()); if (class_exists('Nette\\Bridges\\FormsLatte\\FormMacros')) { Nette\Bridges\FormsLatte\FormMacros::install($latte->getCompiler()); } if ($control) { $control->templatePrepareFilters($template); } }); $latte->addFilter('url', 'rawurlencode'); // back compatiblity foreach (array('normalize', 'toAscii', 'webalize', 'padLeft', 'padRight', 'reverse') as $name) { $latte->addFilter($name, 'Nette\\Utils\\Strings::' . $name); } $latte->addFilter('null', function () { }); $latte->addFilter('length', function ($var) { return is_string($var) ? Nette\Utils\Strings::length($var) : count($var); }); $latte->addFilter('modifyDate', function ($time, $delta, $unit = NULL) { return $time == NULL ? NULL : Nette\Utils\DateTime::from($time)->modify($delta . $unit); // intentionally == }); if (!array_key_exists('translate', $latte->getFilters())) { $latte->addFilter('translate', function () { throw new Nette\InvalidStateException('Translator has not been set. Set translator using $template->setTranslator().'); }); } // default parameters $template->control = $template->_control = $control; $template->presenter = $template->_presenter = $presenter; $template->user = $this->user; $template->netteHttpResponse = $this->httpResponse; $template->netteCacheStorage = $this->cacheStorage; $template->baseUri = $template->baseUrl = $this->httpRequest ? rtrim($this->httpRequest->getUrl()->getBaseUrl(), '/') : NULL; $template->basePath = preg_replace('#https?://[^/]+#A', '', $template->baseUrl); $template->flashes = array(); if ($presenter instanceof UI\Presenter && $presenter->hasFlashSession()) { $id = $control->getParameterId('flash'); $template->flashes = (array) $presenter->getFlashSession()->{$id}; } return $template; }
/** * Invoke filter * * @param string code * @param WebLoader loader * @param string file * @return string */ public function __invoke($code, \Lohini\WebLoader\WebLoader $loader, $file = NULL) { $regexp = '/@charset ["\']utf\\-8["\'];(\\n)?/i'; $removed = Strings::replace($code, $regexp); // At least one charset was in the code if (Strings::length($removed) < Strings::length($code)) { $code = self::CHARSET . "\n" . $removed; } return $code; }
/** * @param $queryString */ public function prepareFulltext($queryString) { if (!$this->queryPrepared) { if (Strings::length($queryString) > 2) { $this->template->searchResults = $this->articleManager->findFulltext($queryString); } elseif (Strings::length($queryString) > 0) { $this->template->searchStatus = 'too-short'; } $this->queryPrepared = TRUE; } }
/** * Funkce pro symetrické zakódování hesla * @param string $password * @return string */ public static function encodePassword($password) { $saltLength = Strings::length(self::PASSWORDS_SALT) - 1; $passwordsSalt = self::PASSWORDS_SALT . self::PASSWORDS_SALT . self::PASSWORDS_SALT; $randNumber = rand(1, $saltLength); $char = Strings::substring($passwordsSalt, $randNumber, 1); //získán náhodný znak ze soli $length = 12; $key = Strings::substring($passwordsSalt, $randNumber, $length); $encodedPassword = $char . $length . self::encrypt($password, $key); return $encodedPassword; }
public function renderDefault($page = 1) { $empty = FALSE; $this->page = $page; $paginator = new Paginator(); $paginator->setItemsPerPage(10); $paginator->setPage($this->page); if (!$this->user->isAllowed('Article', 'editAll')) { $count = $this->articleManager->getCount($this->user->id); } else { $count = $this->articleManager->getCount(); } $paginator->setItemCount($count); if (Strings::length($this->q) >= 3) { $this->fulltextQuery = $this->q; } if ($this->fulltextQuery) { if (!$this->user->isAllowed('Article', 'editAll')) { $fulltextArticles = $this->articleManager->findFulltext($this->fulltextQuery)->fetchAll(); } else { $fulltextArticles = $this->articleManager->findFulltext($this->fulltextQuery)->where('article.user_id', $this->user->id)->fetchAll(); } if (!empty($fulltextArticles)) { $paginator->setItemCount(count($fulltextArticles)); $fulltextPages = array_chunk($fulltextArticles, $paginator->itemsPerPage, true); $this->template->listOfArticles = $fulltextPages[$paginator->page - 1]; } else { $paginator->setItemCount(0); $this->template->listOfArticles = array(); } } else { if (!$this->user->isAllowed('Article', 'editAll')) { $this->template->listOfArticles = $this->articleManager->findAll()->where('article.user_id', $this->user->id)->limit($paginator->getLength(), $paginator->getOffset())->fetchAll(); } else { $this->template->listOfArticles = $this->articleManager->findAll()->limit($paginator->getLength(), $paginator->getOffset())->fetchAll(); } if (empty($this->template->listOfArticles)) { $empty = TRUE; } } $this->template->fulltextQuery = $this->q; $this->template->page = $this->page; $this->template->empty = $empty; if ($count > $paginator->itemsPerPage && !$paginator->last) { $this->template->showMoreButton = TRUE; } if ($this->ajax) { $this->redrawControl('datalistResult'); } }
/** * Returns instance of ImageInfo about fetched thumbnail * * @param string $name * @return \Imager\ImageInfo */ public function fetchThumbnail($name) { if (!isset($name) || Strings::length($name) === 0) { throw new InvalidArgumentException('Name of fetched file cannot be empty.'); } $thumbnail = $this->getThumbnailPath($name); if (!file_exists($thumbnail)) { $msg = sprintf('Thumbnail image "%s" not exists.', $thumbnail); throw new NotExistsException($msg); } $parts = Helpers::parseName($name); if (isset($parts['id'])) { $source = $this->fetch($parts['id']); } return new ImageInfo($thumbnail, $source); }
/** * @param \Nette\Application\UI\Control $control * @return \Nette\Bridges\ApplicationLatte\Template */ public function createTemplate(\Nette\Application\UI\Control $control) { $latte = $this->latteFactory->create(); $template = new Template($latte); $presenter = $control->getPresenter(false); if ($control instanceof \Nette\Application\UI\Presenter) { $latte->setLoader(new Loader($control)); } if ($latte->onCompile instanceof \Traversable) { $latte->onCompile = iterator_to_array($latte->onCompile); } array_unshift($latte->onCompile, function ($latte) use($control, $template) { $latte->getParser()->shortNoEscape = true; $latte->getCompiler()->addMacro('cache', new CacheMacro($latte->getCompiler())); UIMacros::install($latte->getCompiler()); FormMacros::install($latte->getCompiler()); $control->templatePrepareFilters($template); }); $latte->addFilter('url', 'rawurlencode'); // back compatiblity foreach (array('normalize', 'toAscii', 'webalize', 'padLeft', 'padRight', 'reverse') as $name) { $latte->addFilter($name, 'Nette\\Utils\\Strings::' . $name); } $latte->addFilter('null', function () { }); $latte->addFilter('length', function ($var) { return is_string($var) ? \Nette\Utils\Strings::length($var) : count($var); }); $latte->addFilter('modifyDate', function ($time, $delta, $unit = null) { return $time == null ? null : \Nette\Utils\DateTime::from($time)->modify($delta . $unit); // intentionally == }); // default parameters $template->control = $template->_control = $control; $template->presenter = $template->_presenter = $presenter; $template->netteHttpResponse = $this->httpResponse; $template->netteCacheStorage = $this->cacheStorage; $template->pathResolver = $this->pathResolver; $template->netteUser = $this->user; $template->basePath = preg_replace('#https?://[^/]+#A', '', $this->httpRequest ? rtrim($this->httpRequest->getUrl()->getBaseUrl(), '/') : null); $template->flashes = array(); if ($presenter instanceof \Nette\Application\UI\Presenter && $presenter->hasFlashSession()) { $id = $control->getParameterId('flash'); $template->flashes = (array) $presenter->getFlashSession()->{$id}; } return $template; }
/** * @param string */ public function renderSitemap($type = 'html') { $this->template->addons = $this->addons->findAll(); $this->template->vendors = $this->addons->findVendors(); $this->template->categories = $this->tags->findMainTags(); $pages = array(); foreach (Finder::findFiles('*.texy')->from($this->pagesDataPath) as $file) { /** @var \SplFileInfo $file */ $slug = Strings::substring($file->getRealPath(), Strings::length($this->pagesDataPath) + 1, -5); $data = $this->pageProcessor->process(file_get_contents($file->getRealPath())); $createdAt = new \DateTime(); $createdAt->setTimestamp($file->getMTime()); $pages[] = (object) array('slug' => $slug, 'name' => $data['title'], 'createdAt' => $createdAt); } $this->template->pages = $pages; if ($type == 'xml') { $this->setView('sitemap.xml'); } }
/** * Handles autoloading of classes or interfaces. * @param string * @return void */ public function tryLoad($type) { $mapper = function ($namespace) use ($type) { // find namespace in map return Strings::startsWith(strtolower($type), strtolower($namespace)) ? $namespace : NULL; }; $namespace = array_filter(array_keys($this->map), $mapper); sort($namespace); if (count($namespace)) { // is in map? $namespace = end($namespace); $type = substr($type, Strings::length($namespace) + (Strings::endsWith($namespace, '\\') ? 0 : 1)); // remove namespace $path = $this->map[$namespace] . "/"; // map dir $path .= str_replace('\\', DIRECTORY_SEPARATOR, $type); // class to file in map $path .= ".php"; if (file_exists($path)) { \Nette\Utils\LimitedScope::load($path); } } }
public static function createDbDatetimeFormatFromDateParts($year, $month, $day, $hour, $minute, $second) { if (Strings::length($month) == 1) { $month = "0" . $month; } if (Strings::length($day) == 1) { $day = "0" . $day; } if (Strings::length($hour) == 1) { $hour = "0" . $hour; } if (Strings::length($minute) == 1) { $minute = "0" . $minute; } if (Strings::length($second) == 1) { $second = "0" . $second; } return $year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":" . $second; }
private function createPresenterName($string) { $presenter = ''; $enlarge = false; for ($i = 0; $i < \Nette\Utils\Strings::length($string); $i++) { $char = \Nette\Utils\Strings::substring($string, $i, 1); if ($char == '-') { $enlarge = true; } if (ord($char) >= 65 && ord($char) <= 90 || ord($char) >= 97 && ord($char) <= 122) { if ($i == 0 || $enlarge) { $presenter .= \Nette\Utils\Strings::upper($char); if ($enlarge) { $enlarge = false; } } else { $presenter .= $char; } } } return $presenter; }
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; } }
public function formatTemplateFile(Control $control) { $templateFiles = []; if ($control instanceof Presenter) { $namespaceName = $control->getReflection()->getNamespaceName(); $trimmedName = $control->getReflection()->getShortName(); if (Strings::endsWith($trimmedName, 'Presenter')) { $trimmedName = Strings::substring($trimmedName, 0, Strings::length($trimmedName) - 9); } $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getCurrentTheme() . DIRECTORY_SEPARATOR . $namespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte'); $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getFallbackTheme() . DIRECTORY_SEPARATOR . $namespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte'); if (Strings::endsWith($namespaceName, '\\Presenters')) { $trimmedNamespaceName = Strings::substring($control->getReflection()->getNamespaceName(), 0, Strings::length($namespaceName) - 11); // trim /Presenters from namespace $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getCurrentTheme() . DIRECTORY_SEPARATOR . $trimmedNamespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte'); $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getFallbackTheme() . DIRECTORY_SEPARATOR . $trimmedNamespaceName . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $trimmedName . DIRECTORY_SEPARATOR . $control->getView() . '.latte'); } } else { $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getCurrentTheme() . DIRECTORY_SEPARATOR . $control->getReflection()->getNamespaceName() . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $control->getReflection()->getShortName() . '.latte'); $templateFiles[] = $this->unifyDirectorySeparators($this->getThemeManager()->getThemesDir() . DIRECTORY_SEPARATOR . $this->getThemeManager()->getFallbackTheme() . DIRECTORY_SEPARATOR . $control->getReflection()->getNamespaceName() . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $control->getReflection()->getShortName() . '.latte'); } return $templateFiles; }
/** * Count/length validator. Range is array, min and max length pair. * @return bool */ public static function validateLength(IControl $control, $range) { if (!is_array($range)) { $range = array($range, $range); } $value = $control->getValue(); return Validators::isInRange(is_array($value) ? count($value) : Strings::length($value), $range); }
/** * Returns syntax highlighted SQL command. * @param string * @return string */ public static function dumpSql($sql, array $params = NULL, Connection $connection = NULL) { static $keywords1 = 'SELECT|(?:ON\\s+DUPLICATE\\s+KEY)?UPDATE|INSERT(?:\\s+INTO)?|REPLACE(?:\\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\\s+BY|ORDER\\s+BY|LIMIT|OFFSET|SET|VALUES|LEFT\\s+JOIN|INNER\\s+JOIN|TRUNCATE'; static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|[RI]?LIKE|REGEXP|TRUE|FALSE'; // insert new lines $sql = " {$sql} "; $sql = preg_replace("#(?<=[\\s,(])({$keywords1})(?=[\\s,)])#i", "\n\$1", $sql); // reduce spaces $sql = preg_replace('#[ \\t]{2,}#', ' ', $sql); $sql = wordwrap($sql, 100); $sql = preg_replace('#([ \\t]*\\r?\\n){2,}#', "\n", $sql); // syntax highlight $sql = htmlSpecialChars($sql, ENT_IGNORE, 'UTF-8'); $sql = preg_replace_callback("#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])({$keywords1})(?=[\\s,)])|(?<=[\\s,(=])({$keywords2})(?=[\\s,)=])#is", function ($matches) { if (!empty($matches[1])) { // comment return '<em style="color:gray">' . $matches[1] . '</em>'; } elseif (!empty($matches[2])) { // error return '<strong style="color:red">' . $matches[2] . '</strong>'; } elseif (!empty($matches[3])) { // most important keywords return '<strong style="color:blue">' . $matches[3] . '</strong>'; } elseif (!empty($matches[4])) { // other keywords return '<strong style="color:green">' . $matches[4] . '</strong>'; } }, $sql); // parameters $sql = preg_replace_callback('#\\?#', function () use($params, $connection) { static $i = 0; if (!isset($params[$i])) { return '?'; } $param = $params[$i++]; if (is_string($param) && (preg_match('#[^\\x09\\x0A\\x0D\\x20-\\x7E\\xA0-\\x{10FFFF}]#u', $param) || preg_last_error())) { return '<i title="Length ' . strlen($param) . ' bytes"><binary></i>'; } elseif (is_string($param)) { $length = Nette\Utils\Strings::length($param); $truncated = Nette\Utils\Strings::truncate($param, Helpers::$maxLength); $text = htmlspecialchars($connection ? $connection->quote($truncated) : '\'' . $truncated . '\'', ENT_NOQUOTES, 'UTF-8'); return '<span title="Length ' . $length . ' characters">' . $text . '</span>'; } elseif (is_resource($param)) { $type = get_resource_type($param); if ($type === 'stream') { $info = stream_get_meta_data($param); } return '<i' . (isset($info['uri']) ? ' title="' . htmlspecialchars($info['uri'], ENT_NOQUOTES, 'UTF-8') . '"' : NULL) . '><' . htmlSpecialChars($type, ENT_NOQUOTES, 'UTF-8') . ' resource></i> '; } else { return htmlspecialchars($param, ENT_NOQUOTES, 'UTF-8'); } }, $sql); return '<pre class="dump">' . trim($sql) . "</pre>\n"; }
/** * Length validator: is control's value length in range? * @param TextBase * @param array min and max length pair * @return bool */ public static function validateLength(TextBase $control, $range) { if (!is_array($range)) { $range = array($range, $range); } $len = Strings::length($control->getValue()); return ($range[0] === NULL || $len >= $range[0]) && ($range[1] === NULL || $len <= $range[1]); }
/** * Metoda vracející určovací funkci pro určování finálních hodnot preprocessingu * @param Preprocessing $preprocessing * @param int &$attributeStrLen - délka názvů jednotlivých skupin * @return callable */ private function generateAttributeValuesBinsFunction(Preprocessing $preprocessing, &$attributeStrLen) { $valuesBins = $preprocessing->valuesBins; //připravení pole pro jednoduché přiřazování hodnot $finalValuesArr = array(); /** @var Interval[] $finalIntervalsArr */ $finalIntervalsArr = array(); foreach ($valuesBins as $valuesBin) { $name = $valuesBin->name; $attributeStrLen = max($attributeStrLen, Strings::length($name)); $values = $valuesBin->values; if (!empty($values)) { foreach ($values as $value) { $finalValuesArr[$value->value] = $valuesBin->name; } } $intervals = $valuesBin->intervals; if (!empty($intervals)) { foreach ($intervals as $interval) { $finalIntervalsArr[$valuesBin->name] = $interval; } } } if (!empty($finalValuesArr)) { $result = function ($value) use($finalValuesArr) { if (isset($finalValuesArr[$value])) { return $finalValuesArr[$value]; } else { return null; } }; return $result; } if (!empty($finalIntervalsArr)) { $result = function ($value) use($finalIntervalsArr) { foreach ($finalIntervalsArr as $key => $interval) { if ($interval->containsValue($value)) { return $key; } } return null; }; return $result; } return function () { return null; }; }
/** * Returns array of string length. * @param mixed * @return int */ public static function length($var) { return is_string($var) ? Strings::length($var) : count($var); }
/** * @param Form $form */ public function quickSearchFormSucceeded(Form $form, $values) { if (Strings::length($values->q) >= 3) { $this->fulltextQuery = $values->q; } else { $this->fulltextQuery = ''; } if (in_array('light', $values->filter)) { $this->filterLight = TRUE; } else { $this->filterLight = FALSE; } if (in_array('large', $values->filter)) { $this->filterLarge = TRUE; } else { $this->filterLarge = FALSE; } if ($this->isAjax()) { $this->redrawControl('datalist'); } }
/** * Converts name and surname to short form. E.g. "John Doe" => "John D." * * @param $name * @return string * @register */ public static function shortName($name) { $name = explode(' ', $name, 2); if (isset($name[1]) && Strings::length($name[1])) { return $name[0] . ' ' . Strings::upper(Strings::substring($name[1], 0, 1)) . '.'; } else { return $name[0]; } }
/** * @static * @param string $value * @param string $type * @return array */ public static function prepareFilter($value, $type) { /* select or boolean can be only equal */ if ($type == self::SELECT || $type == self::BOOLEAN) { return array("condition" => self::EQUAL, "value" => $value); } elseif ($type == self::MULTISELECT) { return array("condition" => self::IN, "value" => $value); } elseif ($type == self::TEXT) { foreach (self::getConditionsByType(self::TEXT) as $name => $condition) { if (Strings::endsWith($value, $condition) && !Strings::startsWith($value, $condition) && $name == self::STARTSWITH) { return array("condition" => $name, "value" => Strings::substring($value, 0, "-" . Strings::length($condition))); } elseif (Strings::startsWith($value, $condition) && !Strings::endsWith($value, $condition) && $name == self::ENDSWITH) { return array("condition" => $name, "value" => Strings::substring($value, Strings::length($condition))); } } return array("condition" => self::CONTAINS, "value" => $value); } elseif ($type == self::DATE) { foreach (self::getConditionsByType(self::DATE) as $name => $condition) { if (Strings::startsWith($value, $condition)) { return array("condition" => $name, "value" => Strings::substring($value, Strings::length($condition))); } } return array("condition" => self::DATE_EQUAL, "value" => $value); } elseif ($type == self::NUMERIC) { foreach (self::getConditionsByType(self::NUMERIC) as $name => $condition) { if (Strings::startsWith($value, $condition)) { return array("condition" => $name, "value" => (int) Strings::substring($value, Strings::length($condition))); } } return array("condition" => self::EQUAL, "value" => (int) $value); } }
/** * Render email as list * @param $array * @param $maxlen * @return string */ public function renderArray($array, $maxlen) { $text = implode($this->arrayDelimiter, (array) $array); if (is_null($maxlen) || Strings::length($text) < $maxlen) { return $text; } else { return Strings::truncate($text, $maxlen); } }