Exemple #1
1
 /**
  * @ORM\PreFlush()
  */
 public function preUpload()
 {
     if ($this->file) {
         if ($this->file instanceof FileUpload) {
             $basename = $this->file->getSanitizedName();
             $basename = $this->suggestName($this->getFilePath(), $basename);
             $this->setName($basename);
         } else {
             $basename = trim(Strings::webalize($this->file->getBasename(), '.', FALSE), '.-');
             $basename = $this->suggestName(dirname($this->file->getPathname()), $basename);
             $this->setName($basename);
         }
         if ($this->_oldPath && $this->_oldPath !== $this->path) {
             @unlink($this->getFilePathBy($this->_oldProtected, $this->_oldPath));
         }
         if ($this->file instanceof FileUpload) {
             $this->file->move($this->getFilePath());
         } else {
             copy($this->file->getPathname(), $this->getFilePath());
         }
         return $this->file = NULL;
     }
     if (($this->_oldPath || $this->_oldProtected !== NULL) && ($this->_oldPath != $this->path || $this->_oldProtected != $this->protected)) {
         $oldFilePath = $this->getFilePathBy($this->_oldProtected !== NULL ? $this->_oldProtected : $this->protected, $this->_oldPath ?: $this->path);
         if (file_exists($oldFilePath)) {
             rename($oldFilePath, $this->getFilePath());
         }
     }
 }
Exemple #2
1
 /**
  * Sets selected items (by keys).
  * @param  array
  * @return self
  */
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = [];
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     if ($this->checkAllowedValues && ($diff = array_diff($values, array_keys($this->items)))) {
         $set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, array_keys($this->items))), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed set [{$set}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
Exemple #3
0
 public function constructUrl(Request $appRequest, Url $refUrl)
 {
     // Module prefix not match.
     if ($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) {
         return null;
     }
     $params = $appRequest->getParameters();
     $urlStack = [];
     // Module prefix
     $moduleFrags = explode(":", Strings::lower($appRequest->getPresenterName()));
     $resourceName = array_pop($moduleFrags);
     $urlStack += $moduleFrags;
     // Resource
     $urlStack[] = Strings::lower($resourceName);
     // Id
     if (isset($params['id']) && is_scalar($params['id'])) {
         $urlStack[] = $params['id'];
         unset($params['id']);
     }
     // Set custom action
     if (isset($params['action']) && $this->_isApiAction($params['action'])) {
         unset($params['action']);
     }
     $url = $refUrl->getBaseUrl() . implode('/', $urlStack);
     // Add query parameters
     if (!empty($params)) {
         $url .= "?" . http_build_query($params);
     }
     return $url;
 }
Exemple #4
0
 /**
  * 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;
 }
 /**
  * @param Task $task
  * @param \SimpleXMLElement|null $pmml
  * @param DatabaseFactory $databaseFactory
  * @param PreprocessingFactory $preprocessingFactory
  * @param string $appVersion =''
  */
 public function __construct(Task $task, \SimpleXMLElement $pmml = null, DatabaseFactory $databaseFactory, PreprocessingFactory $preprocessingFactory, $appVersion = '')
 {
     if ($task instanceof Task) {
         $this->task = $task;
         $this->miner = $task->miner;
     }
     $this->appVersion = $appVersion;
     if (!empty($pmml)) {
         if ($pmml instanceof \SimpleXMLElement) {
             $this->pmml = $pmml;
         } elseif (is_string($pmml)) {
             $this->pmml = simplexml_load_string($pmml);
         }
     }
     if (!$pmml instanceof \SimpleXMLElement) {
         $this->prepareBlankPmml();
     }
     $this->appendTaskInfo();
     $this->databaseFactory = $databaseFactory;
     $this->preprocessingFactory = $preprocessingFactory;
     $connectivesArr = Cedent::getConnectives();
     foreach ($connectivesArr as $connective) {
         $this->connectivesArr[$connective] = Strings::firstUpper($connective);
     }
 }
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = array();
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     $items = $this->items;
     $nestedKeys = array();
     array_walk_recursive($items, function ($value, $key) use(&$nestedKeys) {
         $nestedKeys[] = $key;
     });
     if ($diff = array_diff($values, $nestedKeys)) {
         $range = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, $nestedKeys)), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed range [{$range}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
 /**
  * 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", '  '));
 }
 /**
  * @return self
  */
 public static function from(\ReflectionParameter $from)
 {
     $param = new static();
     $param->name = $from->getName();
     $param->reference = $from->isPassedByReference();
     if ($from->isArray()) {
         $param->typeHint = 'array';
     } elseif (PHP_VERSION_ID >= 50400 && $from->isCallable()) {
         $param->typeHint = 'callable';
     } else {
         try {
             $param->typeHint = $from->getClass() ? '\\' . $from->getClass()->getName() : NULL;
         } catch (\ReflectionException $e) {
             if (preg_match('#Class (.+) does not exist#', $e->getMessage(), $m)) {
                 $param->typeHint = '\\' . $m[1];
             } else {
                 throw $e;
             }
         }
     }
     $param->optional = PHP_VERSION_ID < 50407 ? $from->isOptional() || $param->typeHint && $from->allowsNull() : $from->isDefaultValueAvailable();
     $param->defaultValue = PHP_VERSION_ID === 50316 ? $from->isOptional() : $from->isDefaultValueAvailable() ? $from->getDefaultValue() : NULL;
     $namespace = $from->getDeclaringClass() ? $from->getDeclaringClass()->getNamespaceName() : NULL;
     $namespace = $namespace ? "\\{$namespace}\\" : '\\';
     if (Nette\Utils\Strings::startsWith($param->typeHint, $namespace)) {
         $param->typeHint = substr($param->typeHint, strlen($namespace));
     }
     return $param;
 }
Exemple #9
0
 public function startup()
 {
     parent::startup();
     $this->dir = new DirEntity();
     $this->dir->setInvisible(TRUE);
     $this->dir->setName(Strings::webalize(get_class($this)) . Strings::random());
 }
 /**
  * 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;
 }
Exemple #11
0
 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);
         }
     }
 }
Exemple #12
0
 /**
  * @param string $name
  * @param Language $language
  */
 public function __construct($name, Language $language)
 {
     $this->name = $name;
     $this->language = $language;
     $this->slug = Strings::webalize($name);
     $this->scenarios = new ArrayCollection();
 }
 public function getChangeDescription()
 {
     if ($this->count === 1) {
         return $this->changeInfos[0]->getChangeDescription();
     }
     return sprintf("%s %d %s", Strings::capitalize(StringUtils::verbToPastTense($this->getAction())), $this->count, StringUtils::pluralize($this->getEntityName()));
 }
 public function getChangeDescription()
 {
     if ($this->action === 'activate') {
         return "Site language switched to '{$this->languageName}'";
     }
     return Strings::capitalize(StringUtils::verbToPastTense($this->action)) . " translation '{$this->languageName}'";
 }
Exemple #15
0
 public static function formatRecordString($record, $formatString)
 {
     return Strings::replace($formatString, '#%[^%]*%#u', function ($m) use($record) {
         $m = Strings::trim($m[0], '%');
         return $m != '' ? $record[$m] : "%";
     });
 }
Exemple #16
0
 /**
  * @param string $actual
  * @param string $condition
  * @param mixed $expected
  * @throws Exception
  * @return bool
  */
 public function compare($actual, $condition, $expected)
 {
     $expected = (array) $expected;
     $expected = current($expected);
     $cond = str_replace(' ?', '', $condition);
     if ($cond === 'LIKE') {
         $actual = Strings::toAscii($actual);
         $expected = Strings::toAscii($expected);
         $pattern = str_replace('%', '(.|\\s)*', preg_quote($expected, '/'));
         return (bool) preg_match("/^{$pattern}\$/i", $actual);
     } elseif ($cond === '=') {
         return $actual == $expected;
     } elseif ($cond === '<>') {
         return $actual != $expected;
     } elseif ($cond === 'IS NULL') {
         return $actual === NULL;
     } elseif ($cond === 'IS NOT NULL') {
         return $actual !== NULL;
     } elseif ($cond === '<') {
         return (int) $actual < $expected;
     } elseif ($cond === '<=') {
         return (int) $actual <= $expected;
     } elseif ($cond === '>') {
         return (int) $actual > $expected;
     } elseif ($cond === '>=') {
         return (int) $actual >= $expected;
     } else {
         throw new Exception("Condition '{$condition}' not implemented yet.");
     }
 }
Exemple #17
0
 /**
  * Sets a header.
  * @param  string
  * @param  string|array  value or pair email => name
  * @param  bool
  * @return self
  */
 public function setHeader($name, $value, $append = FALSE)
 {
     if (!$name || preg_match('#[^a-z0-9-]#i', $name)) {
         throw new Nette\InvalidArgumentException("Header name must be non-empty alphanumeric string, '{$name}' given.");
     }
     if ($value == NULL) {
         // intentionally ==
         if (!$append) {
             unset($this->headers[$name]);
         }
     } elseif (is_array($value)) {
         // email
         $tmp =& $this->headers[$name];
         if (!$append || !is_array($tmp)) {
             $tmp = [];
         }
         foreach ($value as $email => $recipient) {
             if ($recipient !== NULL && !Strings::checkEncoding($recipient)) {
                 Nette\Utils\Validators::assert($recipient, 'unicode', "header '{$name}'");
             }
             if (preg_match('#[\\r\\n]#', $recipient)) {
                 throw new Nette\InvalidArgumentException('Name must not contain line separator.');
             }
             Nette\Utils\Validators::assert($email, 'email', "header '{$name}'");
             $tmp[$email] = $recipient;
         }
     } else {
         $value = (string) $value;
         if (!Strings::checkEncoding($value)) {
             throw new Nette\InvalidArgumentException('Header is not valid UTF-8 string.');
         }
         $this->headers[$name] = preg_replace('#[\\r\\n]+#', ' ', $value);
     }
     return $this;
 }
 /**
  * @param array $resources
  * @param bool $minify
  * @param string $baseDir
  * @throws AssetsException
  * @return array
  */
 public function getAssets(array $resources, $minify, $baseDir)
 {
     $config = [];
     $return = [];
     foreach ($resources as $resource) {
         $contents = file_get_contents($resource);
         $decompiled = Strings::endsWith($resource, '.json') ? json_decode($contents, TRUE) : Neon::decode($contents);
         $config = \Nette\DI\Config\Helpers::merge($config, $decompiled);
     }
     foreach ($config as $moduleArray) {
         foreach ($moduleArray as $type => $typeArray) {
             if (!isset(self::$supportTypes[$type])) {
                 throw new AssetsException("Found section '{$type}', but expected one of " . implode(', ', array_keys(self::$supportTypes)));
             }
             foreach ($typeArray as $minified => $assets) {
                 if ($minify) {
                     $return[$type][$minified] = TRUE;
                     continue;
                 }
                 foreach ((array) $assets as $row) {
                     if (strpos($row, '*') !== FALSE) {
                         /** @var \SplFileInfo $file */
                         foreach (Finder::findFiles(basename($row))->in($baseDir . '/' . dirname($row)) as $file) {
                             $return[$type][$minified][] = dirname($row) . '/' . $file->getBasename();
                         }
                     } else {
                         $return[$type][$minified][] = $row;
                     }
                 }
             }
         }
     }
     return $return;
 }
Exemple #19
0
 protected function drawGroups(OutputInterface $output, Group $group)
 {
     $output->writeln(Nette\Utils\Strings::padLeft('', $group->getDepth(), ' ') . '\\_ ' . $group->getName() . ":" . $group->getType());
     foreach ($group->getChild() as $v) {
         $this->drawGroups($output, $v);
     }
 }
 public function getChangeDescription()
 {
     if ($this->action === 'switch') {
         return "Theme switched to '{$this->themeName}'";
     }
     return Strings::capitalize(StringUtils::verbToPastTense($this->action)) . " theme '{$this->themeName}'";
 }
 public function loadConfiguration()
 {
     $config = $this->getSettings();
     $builder = $this->getContainerBuilder();
     /**
      * Same starting point is basic point, where app lives.
      */
     $config['baseDir'] = Strings::findPrefix([$config['wwwDir'], $config['appDir']]);
     /*$this->compiler->parseServices($builder, $this->loadFromFile(__DIR__ . DIRECTORY_SEPARATOR . 'services.neon'), $this->name);*/
     $builder->addDefinition($this->prefix('uploadFormFactory'))->setFactory('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Forms\\UploadFormFactory')->setClass('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Forms\\UploadFormFactory')->setArguments([$config['formClass'], $config['uploadFieldLabel']]);
     $builder->addDefinition($this->prefix('multiuploadFormFactory'))->setFactory('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Forms\\MultiuploadFormFactory')->setClass('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Forms\\MultiuploadFormFactory')->setArguments([$config['formClass'], $config['uploadFieldLabel']]);
     $builder->addDefinition($this->prefix('filterFormFactory'))->setFactory('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Forms\\FilterFormFactory')->setClass('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Forms\\FilterFormFactory')->setArguments([$config['formClass'], 'Query:']);
     $builder->addDefinition($this->prefix('cardMediaViewControl'))->setClass('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Controls\\CardView\\CardViewControl');
     $builder->addDefinition($this->prefix('gridMediaViewControlFactory'))->setFactory('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Controls\\GridMediaView\\GridMediaViewControlFactory');
     $builder->addDefinition($this->prefix('uploadControlFactory'))->setFactory('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Controls\\Upload\\UploadControlFactory')->setArguments(['disableMultiupload' => $config['disableMultiupload']]);
     $builder->addDefinition($this->prefix('ajaxUploadControlFactory'))->setFactory('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Controls\\AjaxUpload\\AjaxUploadControlFactory')->setArguments(['disableMultiupload' => $config['disableMultiupload']]);
     $builder->addDefinition($this->prefix('manager'))->setClass('vojtabiberle\\MediaStorage\\Manager')->setArguments(['config' => $config]);
     $builder->addDefinition($this->prefix('storage'))->setClass('vojtabiberle\\MediaStorage\\Storage')->setArguments(['mediaStoragePath' => $config['baseDir'] . DIRECTORY_SEPARATOR . $config['mediaStoragePath'], 'fileClass' => $config['fileClass'], 'imageClass' => $config['imageClass']]);
     if (0 === count($builder->findByType('vojtabiberle\\MediaStorage\\Bridges\\IFilesystemStorage'))) {
         $builder->addDefinition($this->prefix('filesystemStorage'))->setClass('vojtabiberle\\MediaStorage\\Bridges\\FilesystemStorage');
     }
     if (0 === count($builder->findByType('vojtabiberle\\MediaStorage\\Bridges\\IDatabaseStorage'))) {
         $builder->addDefinition($this->prefix('databaseStorage'))->setClass('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Model\\MediaStorage');
     }
     if ($config['router']['disable'] === false) {
         $builder->addDefinition($this->prefix('routerFactory'))->setFactory('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Router\\Factory::createRouter')->setClass('Nette\\Application\\IRouter')->setArguments([$config['router']])->setAutowired(false);
         $builder->addDefinition($this->prefix('mediaPresenter'))->setClass('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Presenters\\MediaPresenter');
     }
     $builder->addDefinition($this->prefix('mediaPopupPresenter'))->setClass('vojtabiberle\\MediaStorage\\Bridges\\Nette\\Presenters\\MediaPopupPresenter');
 }
Exemple #22
0
 /**
  * Vytvoreni nove galerie
  * @param type $values - name,editor_id,public[bool],start_public,stop_public
  * 
  * @return type 
  */
 public function addGallery($files, $galleryName, $conf = NULL)
 {
     if (!is_array($conf)) {
         $params = $this->context->getParameters();
         $driveConfigPath = $params['projectDir'] . '/config/drive.neon';
         if (!is_file($driveConfigPath)) {
             $driveConfigPath = __DIR__ . '/examples/gal.neon';
         }
         $conf = \Nette\Utils\Neon::decode(file_get_contents($driveConfigPath));
         $conf = $conf['gallery'];
     }
     $this->setStorage('gallery');
     $userId = 0;
     if ($this->presenter) {
         $userId = $this->presenter->user->isLoggedIn() ? $this->presenter->user->getId() : 0;
     }
     $galPath = isset($conf['path']) && !empty($conf['path']) ? Strings::webalize($conf['path']) : '';
     $id = $this->createGallery($galleryName, $userId, $galPath, serialize($conf));
     $galleryFolder = $this->relativePath;
     $this->mkDir($this->getFullPath(TRUE) . '/thumbs', FALSE, TRUE);
     $this->mkDir($this->getFullPath(TRUE) . '/originals', FALSE, TRUE);
     $this->_addFilesToGallery($galleryFolder, $files, $userId, $id, $conf);
     if (isset($conf['preserveOriginals']) && !$conf['preserveOriginals']) {
         $this->setPath($galleryFolder);
         $this->rmDir($this->getFullPath(TRUE) . '/originals/');
     }
     return $id;
 }
Exemple #23
0
 /**
  * Formats cell's content.
  * @param  mixed
  * @param  \DibiRow|array
  * @return string
  */
 public function formatContent($value, $data = NULL)
 {
     $value = htmlSpecialChars($value);
     if (is_array($this->replacement) && !empty($this->replacement)) {
         if (in_array($value, array_keys($this->replacement))) {
             $value = $this->replacement[$value];
         }
     }
     foreach ($this->formatCallback as $callback) {
         if (is_callable($callback)) {
             $value = call_user_func($callback, $value, $data);
         }
     }
     // translate & truncate
     if ($value instanceof Nette\Utils\Html) {
         $text = $this->dataGrid->translate($value->getText());
         if ($this->maxLength != 0) {
             $text = Nette\Utils\Strings::truncate($text, $this->maxLength);
         }
         $value->setText($text);
         $value->title = $this->dataGrid->translate($value->title);
     } else {
         if ($this->maxLength != 0) {
             $value = Nette\Utils\Strings::truncate($value, $this->maxLength);
         }
     }
     return $value;
 }
Exemple #24
0
 private function filterData()
 {
     foreach ($this->data as $id => $item) {
         $value = array();
         $match = true;
         foreach ($this->filter[1] as $collumn) {
             $value[$collumn] = strtolower(Strings::toAscii($item[$collumn]));
         }
         foreach ($this->filter[0] as $word) {
             $found = false;
             foreach ($value as $val) {
                 if (strstr($val, $word) !== false) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 $match = false;
                 break;
             }
         }
         if (!$match) {
             unset($this->data[$id]);
         }
     }
 }
Exemple #25
0
 /**
  * @param  string
  * @param  string
  * @return bool
  */
 public function isModuleCurrent($module, $presenter = NULL)
 {
     if (Strings::startsWith($name = $this->getName(), trim($module, ':') . ':')) {
         return $presenter === NULL ? TRUE : Strings::endsWith($name, ':' . $presenter);
     }
     return FALSE;
 }
 public function getChangeDescription()
 {
     if ($this->count === 1) {
         return $this->changeInfos[0]->getChangeDescription();
     }
     return Strings::firstUpper(StringUtils::verbToPastTense($this->getAction())) . " {$this->count} term-meta";
 }
 /**
  * Computes salted password hash.
  * @param string $password
  * @param string $salt
  * @return string
  */
 public static function calculateHash($password, $salt = null)
 {
     if ($salt === null) {
         $salt = '$2a$07$' . Nette\Utils\Strings::random(32) . '$';
     }
     return crypt($password, $salt);
 }
 /**
  * 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];
 }
 /**
  * Vrátí cestu k šabloně
  * @param string $templateName
  * @return string
  */
 protected function getTemplatePath($templateName)
 {
     if (Strings::endsWith($templateName, self::LATTE_EXTENSION) == FALSE) {
         $templateName = $templateName . self::LATTE_EXTENSION;
     }
     return $this->templatePath . $templateName;
 }
 private function findRepositories($config)
 {
     $classes = [];
     if ($config['scanDirs']) {
         $robot = new RobotLoader();
         $robot->setCacheStorage(new Nette\Caching\Storages\DevNullStorage());
         $robot->addDirectory($config['scanDirs']);
         $robot->acceptFiles = '*.php';
         $robot->rebuild();
         $classes = array_keys($robot->getIndexedClasses());
     }
     $repositories = [];
     foreach (array_unique($classes) as $class) {
         if (class_exists($class) && ($rc = new \ReflectionClass($class)) && $rc->isSubclassOf('Joseki\\LeanMapper\\Repository') && !$rc->isAbstract()) {
             $repositoryClass = $rc->getName();
             $entityClass = Strings::endsWith($repositoryClass, 'Repository') ? substr($repositoryClass, 0, strlen($repositoryClass) - 10) : $repositoryClass;
             $table = Utils::camelToUnderscore(Utils::trimNamespace($entityClass));
             if (array_key_exists($table, $repositories)) {
                 throw new \Exception(sprintf('Multiple repositories for table %s found.', $table));
             }
             $repositories[$table] = $repositoryClass;
         }
     }
     return $repositories;
 }