示例#1
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;
 }
示例#2
0
 public function parse($name)
 {
     $args = array_slice(func_get_args(), 1);
     if (Strings::endsWith($name, '.css')) {
         return $this->getCss($name);
     } else {
         if (Strings::endsWith($name, '.js')) {
             foreach ($args as $i => $option) {
                 if (!isset(self::$allowedOptions[$option])) {
                     throw new AssetsException("Option '{$option}' is not allowed.");
                 }
                 if ($option === 'ifMinified') {
                     if (!$this->minify) {
                         return;
                     }
                     unset($args[$i]);
                 } else {
                     if ($option === 'ifNotMinified') {
                         if ($this->minify) {
                             return;
                         }
                         unset($args[$i]);
                     }
                 }
             }
             return $this->getJs($name, $args);
         } else {
             throw new AssetsException("Assets must ends with .js or .css, '{$name}' given.");
         }
     }
 }
 /**
  * @param \Nette\Application\Application $application
  * @param \Nette\Application\Request $request
  */
 public function __invoke(Application $application, Request $request)
 {
     if (PHP_SAPI === 'cli') {
         newrelic_background_job(TRUE);
     }
     $params = $request->getParameters();
     $action = $request->getPresenterName();
     if (isset($params[$this->actionKey])) {
         $action = sprintf('%s:%s', $action, $params[$this->actionKey]);
     }
     if (!empty($this->map)) {
         foreach ($this->map as $pattern => $appName) {
             if ($pattern === '*') {
                 continue;
             }
             if (Strings::endsWith($pattern, '*')) {
                 $pattern = Strings::substring($pattern, 0, -1);
             }
             if (Strings::startsWith($pattern, ':')) {
                 $pattern = Strings::substring($pattern, 1);
             }
             if (Strings::startsWith($action, $pattern)) {
                 \VrtakCZ\NewRelic\Tracy\Bootstrap::setup($appName, $this->license);
                 break;
             }
         }
     }
     newrelic_name_transaction($action);
     newrelic_disable_autorum();
 }
示例#4
0
 /**
  * @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;
 }
示例#5
0
 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;
 }
 /**
  * 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;
 }
示例#7
0
 /**
  * @static
  * @param string $value
  * @param string $type
  * @return array
  */
 public static function prepareFilter($value, $type)
 {
     /* select nebo boolean muze byt pouze equal */
     if ($type == self::SELECT || $type == self::BOOLEAN) {
         return array("condition" => self::EQUAL, "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);
     }
 }
示例#8
0
 /**
  * @param LoadClassMetadataEventArgs $args
  */
 public function loadClassMetadata(LoadClassMetadataEventArgs $args)
 {
     $meta = $args->getClassMetadata();
     if ($this->_l) {
         if (Strings::endsWith($meta->associationMappings[$this->_lName]['targetEntity'], '::dynamic')) {
             $meta->associationMappings[$this->_lName]['targetEntity'] = $this->getTargetEntity($meta->name, $this->_l);
         }
         return;
     }
     foreach ($meta->getAssociationNames() as $name) {
         if (!Strings::endsWith($meta->associationMappings[$name]['targetEntity'], '::dynamic')) {
             continue;
         }
         $em = $args->getEntityManager();
         $target = $this->getTargetEntity($meta, $name);
         $this->_l = $meta->name;
         $this->_lName = $meta->associationMappings[$name]['inversedBy'];
         if (!$this->_lName) {
             $this->_lName = $meta->associationMappings[$name]['mappedBy'];
         }
         if ($this->_lName) {
             $targetMeta = $em->getClassMetadata($target);
         }
         $this->_l = FALSE;
         $meta->associationMappings[$name]['targetEntity'] = $target;
         if ($this->_lName) {
             $targetMeta->associationMappings[$this->_lName]['targetEntity'] = $meta->name;
         }
     }
 }
示例#9
0
 /**
  * @param  \Exception $e
  * @return void
  */
 protected function handleException(\Exception $e)
 {
     if ($e instanceof \Nette\Database\UniqueConstraintViolationException) {
         if (NStrings::endsWith($e->getMessage(), ' for key \'username\'')) {
             throw new DuplicateNameException();
         }
     }
 }
 /**
  * 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';
     }
 }
示例#11
0
 private function isTaxonomyChildren($id)
 {
     $childrenSuffix = '_children';
     if (!Strings::endsWith($id, $childrenSuffix)) {
         return false;
     }
     $maybeTaxonomyName = Strings::substring($id, 0, Strings::length($id) - Strings::length($childrenSuffix));
     return in_array($maybeTaxonomyName, $this->taxonomies);
 }
 /**
  * Funkce vracející URL pro přístup ke zvolenému mineru
  * @param string $minerType
  * @return string
  */
 public function getMinerUrl($minerType)
 {
     $url = @$this->params['driver_' . $minerType]['server'];
     if (!empty($url) && !empty($this->params['driver_' . $minerType]['minerUrl'])) {
         if (!Strings::endsWith($this->params['driver_' . $minerType]['server'], '/')) {
             $url .= ltrim($this->params['driver_' . $minerType]['minerUrl'], '/');
         }
     }
     return $url;
 }
示例#13
0
 public function joinTableName($sourceEntity, $targetEntity, $propertyName = null)
 {
     if (Strings::endsWith($targetEntity, '::dynamic')) {
         $targetEntity = $this->detectTargetEntity($sourceEntity, $propertyName);
     }
     if (Strings::endsWith($sourceEntity, '::dynamic')) {
         $sourceEntity = $this->detectTargetEntity($targetEntity, $propertyName);
     }
     return strtolower($this->classToNamespace($sourceEntity)) . '_' . parent::joinTableName($sourceEntity, $targetEntity, $propertyName);
 }
示例#14
0
 /**
  * Returns target service name<br>
  * As default it convert name of class 'MyExtraService' to 'myExtra'
  * @return string
  */
 public function getName()
 {
     $class = get_called_class();
     $slashPos = strrpos($class, "\\");
     $className = trim(substr($class, $slashPos), "\\");
     if (Strings::endsWith($className, self::NAME_SUFFIX)) {
         $className = substr($className, 0, strlen($className) - strlen(self::NAME_SUFFIX));
     }
     return lcfirst($className);
 }
示例#15
0
 function __construct($root)
 {
     if (!Strings::endsWith($root, '/')) {
         $root .= '/';
     }
     if (!is_dir($root)) {
         throw new FileNotFoundException("Root directory '{$root}' not found.");
     }
     $this->root = $root;
 }
示例#16
0
 /**
  * @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]);
 }
示例#17
0
 /**
  * @param array $sourceFiles
  * @param string $outputFile
  * @return array
  */
 protected function compile($sourceFiles, $outputFile)
 {
     $file = fopen($outputFile, 'w');
     foreach ($sourceFiles as $sourceFile) {
         $fileCode = rtrim(file_get_contents($sourceFile), " \t\n\r\v;");
         fwrite($file, (Strings::endsWith($sourceFile, '.min.js') ? $fileCode : JSMin::minify($fileCode)) . ";\n");
         fflush($file);
     }
     fclose($file);
     return $sourceFiles;
 }
示例#18
0
文件: Message.php 项目: jedenweb/mail
 /**
  * @param string
  *
  * @return JedenWeb\Mail\Message  Provides fluent interface.
  * @throws Nette\InvalidArgumentException
  */
 public function setTemplateFile($file)
 {
     if (!\Nette\Utils\Strings::endsWith($file, '.latte')) {
         $file .= '.latte';
     }
     if (strpos($file, DIRECTORY_SEPARATOR) === FALSE) {
         $file = $this->templateDir . DIRECTORY_SEPARATOR . $file;
     }
     $this->getTemplate()->setFile($file);
     return $this;
 }
示例#19
0
 /**
  * @param \Nette\Application\Request $appRequest
  * @param \Nette\Http\Url $refUrl
  * @return string|null
  */
 public function constructUrl(Request $appRequest, Url $refUrl)
 {
     $presenter = $appRequest->getPresenterName();
     if (!Strings::startsWith($presenter, self::SUBMODULE_NAME . ':')) {
         return null;
     }
     if (Strings::endsWith($presenter, ':' . self::DEFAULT_PRESENTER)) {
         $presenter = substr($presenter, 0, -strlen(':' . self::DEFAULT_PRESENTER));
     }
     $appRequest->setPresenterName(substr($presenter, strlen(self::SUBMODULE_NAME . ':')));
     return parent::constructUrl($appRequest, $refUrl);
 }
示例#20
0
 public static function guessCodeByClass(string $sniffClass) : string
 {
     self::ensureClassNameIsValid($sniffClass);
     $parts = explode('\\', $sniffClass);
     $standardName = $parts[count($parts) - 4];
     if (Strings::endsWith($standardName, 'CodingStandard')) {
         $standardName = substr($standardName, 0, -strlen('CodingStandard'));
     }
     $categoryName = $parts[count($parts) - 2];
     $sniffName = $parts[count($parts) - 1];
     $sniffName = substr($sniffName, 0, -strlen('Sniff'));
     return $standardName . '.' . $categoryName . '.' . $sniffName;
 }
示例#21
0
 /**
  * @param array $args
  * @return bool
  */
 public function run(array $args = [])
 {
     /** @var ICollection|Addon[] $addons */
     $addons = $this->addonRepository->findActive();
     // FILTER PACKAGES ===========================================
     if (isset($args['rest']) && $args['rest'] === TRUE) {
         $addons = $addons->findBy(['this->github->content' => NULL]);
     }
     // DO YOUR JOB ===============================================
     $counter = 0;
     foreach ($addons as $addon) {
         // Skip packages with bad data
         if ($extra = $addon->github->extra) {
             if ($url = $extra->get(['github', 'readme', 'download_url'], NULL)) {
                 $content = @file_get_contents($url);
                 if ($content) {
                     // Content
                     $addon->github->content = $content;
                     // Readme type
                     if ($addon->github->readme === NULL) {
                         $url = strtolower($url);
                         if (Strings::endsWith($url, 'md')) {
                             $addon->github->readme = Github::README_MARKDOWN;
                         } else {
                             if (Strings::endsWith($url, 'texy')) {
                                 $addon->github->readme = Github::README_TEXY;
                             } else {
                                 $addon->github->readme = Github::README_RAW;
                             }
                         }
                     }
                     // Replace relative links
                     if ($addon->github->readme === Github::README_MARKDOWN) {
                         $this->reformatMarkdownLinks($addon->github);
                     }
                     // Persist
                     $this->addonRepository->persistAndFlush($addon);
                     // Increase counting
                     $counter++;
                 } else {
                     $this->log('Skip (content) [failed download content]: ' . $addon->fullname);
                 }
             } else {
                 $this->log('Skip (content) [no github readme data]: ' . $addon->fullname);
             }
         } else {
             $this->log('Skip (content) [no extra data]: ' . $addon->fullname);
         }
     }
     return $counter;
 }
示例#22
0
 /**
  * Removes the content of a directory (not the directory itself). Works recursively.
  *
  * @param string $path Path to a directory.
  */
 public static function removeContent($path)
 {
     if (!is_dir($path)) {
         return;
     }
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
     foreach ($iterator as $item) {
         if ($item->isDir() && Strings::endsWith($iterator->key(), ".git")) {
             self::possiblyFixGitPermissions($iterator->key());
         }
     }
     $fs = new \Symfony\Component\Filesystem\Filesystem();
     $fs->remove($iterator);
 }
示例#23
0
 /**
  * Convert date to RFC822
  * @param string|date $date
  * @return string
  */
 public static function prepareDate($date)
 {
     if (is_string($date) && $date === (string) (int) $date) {
         $date = (int) $date;
     }
     if (is_string($date) && !\Nette\Utils\Strings::endsWith($date, "GMT")) {
         $date = strtotime($date);
     }
     if (is_int($date)) {
         $date = gmdate('D, d M Y H:i:s', $date) . " GMT";
     }
     if ($date instanceof DibiDateTime) {
         $date = $date->format(DateTime::RFC822);
     }
     return $date;
 }
示例#24
0
 private function updateConfigValue($config, $key, $value)
 {
     // We don't use NEON decoding and encoding again as that removes comments etc.
     require_once __DIR__ . '/../../vendor/nette/utils/src/Utils/Strings.php';
     // General matching: https://regex101.com/r/sE2iB1/1
     // Concrete example: https://regex101.com/r/sE2iB1/2
     $re = "/^({$key})(:\\s*)(\\S[^#\\r\\n]+)(\\h+#?.*)?\$/m";
     $subst = "\$1\$2{$value}\$4";
     if (preg_match_all($re, $config, $matches)) {
         $result = preg_replace($re, $subst, $config);
     } else {
         // value was not there, add it to the end
         $result = $config . (Strings::endsWith($config, "\n") ? "" : "\n");
         $result .= "{$key}: {$value}\n";
     }
     return $result;
 }
 /**
  * @inheritdoc
  */
 public function getTableByRepositoryClass($repositoryClass)
 {
     if (Strings::endsWith($repositoryClass, 'ClosureRepository')) {
         $class = substr($repositoryClass, 0, -strlen('ClosureRepository')) . 'Repository';
         if (in_array('Joseki\\LeanMapper\\ClosureTable\\ClosureRepositoryTrait', class_uses($class))) {
             $repositoryClass = $closure = $class;
         }
     }
     if (!array_key_exists($repositoryClass, $this->repositoryToTable)) {
         throw new InvalidArgumentException(sprintf('Class "%s" not registered in Mapper', $repositoryClass));
     }
     $table = $this->repositoryToTable[$repositoryClass];
     $schema = $this->tableToSchema[$table];
     if (isset($closure)) {
         $table .= '_closure';
     }
     return $schema ? implode('.', [$schema, $table]) : $table;
 }
示例#26
0
	/**
	 * 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);
			}
		}
	}
 /**
  * Funkce pro doplnění základních parametrů do API
  * @param string $jsonString
  * @return string
  */
 private function replaceJsonVariables($jsonString)
 {
     $link = $this->link('//Default:default');
     $url = new Url($link);
     if (empty($url->host)) {
         $url = $this->getHttpRequest()->getUrl()->hostUrl;
         if (Strings::endsWith($url, '/')) {
             rtrim($url, '/');
         }
         $url .= $link;
         $url = new Url($url);
     }
     $hostUrl = Strings::endsWith($url->getHost(), '/') ? rtrim($url->getHost(), '/') : $url->getHost();
     $basePath = rtrim($url->getBasePath(), '/');
     $paramsArr = ['%VERSION%' => $this->getInstallVersion(), '%BASE_PATH%' => $basePath, '%HOST%' => $hostUrl];
     $arrSearch = [];
     $arrReplace = [];
     foreach ($paramsArr as $key => $value) {
         $arrSearch[] = $key;
         $arrReplace[] = $value;
     }
     return str_replace($arrSearch, $arrReplace, $jsonString);
 }
 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;
 }
示例#29
0
 /**
  * Define rule for layout selection. If no rule defined, then layout is accepted every times
  * @param string $rule
  * @return $this
  *
  * @example addRule("Home");            //Only for Home presenter without module
  * @example addRule("!Home");            //Not for Home presenter without module
  * @example addRule("*me");            //Only for presenter ends with "me" without module
  * @example addRule("!*me");            //Not for presenter ends with "me" without module
  * @example addRule("*:Home");            //Only for Home presenter inside whatever first level module
  * @example addRule("!*:Home");            //Not for Home presenters inside whatever first level module
  * @example addRule("**:Home");            //Only for Home presenter inside whatever module
  * @example addRule("!**:Home");        //Not for Home presenters inside whatever module
  * @example addRule("***me");            //Only for presenter ends with "me" inside whatever module
  * @example addRule("!***me");        //Not for presenter ends with "me" inside whatever module
  * @example addRule("Admin:*");            //Only for presenters inside Admin module
  * @example addRule("!Admin:*");        //Not for presenters inside Admin module
  * @example addRule("Extra:Admin:*");    //Only for presenters inside Extra:Admin module
  * @example addRule("!Extra:Admin:*");    //Not for presenters inside Extra:Admin module
  * @example addRule("Extra:*:Home");    //Only for Home presenters inside Extra module wit whatever sub-module
  * @example addRule("!Extra:*:Home");    //Not for Home presenters inside Extra module wit whatever sub-module
  */
 public function addRule($rule)
 {
     $expected = true;
     if ($rule[0] == "!") {
         $rule = substr($rule, 1);
         $expected = false;
     }
     //Verification
     if (Strings::startsWith($rule, ":")) {
         throw new \OutOfRangeException("Rule '{$rule}' cannot start with char ':'");
     }
     if (Strings::endsWith($rule, ":")) {
         throw new \OutOfRangeException("Rule '{$rule}' cannot end with char ':'");
     }
     if (strpos($rule, '!') !== false) {
         throw new \OutOfRangeException("Rule cannot contain char '!' in the middle");
     }
     //Translations
     $translations = array("::" => ":[a-zA-Z0-9]+:", "**" => "[a-zA-Z0-9:]+", "*" => "[a-zA-Z0-9]+");
     $regularExpression = "~^" . strtr($rule, $translations) . "\$~";
     $this->rules[$regularExpression] = $expected;
     return $this;
 }
示例#30
0
 /**
  * Create new entity from array or string which is JSON
  * @param string|array $data
  * @param bool $inverse
  * @throws \Nette\Utils\JsonException
  */
 public function __construct($data = NULL, $inverse = false)
 {
     if ($data !== null) {
         if (is_string($data)) {
             $data = Json::decode($data);
         }
         $this->initMapping($inverse ? 'out' : 'in');
         foreach ($data as $key => $value) {
             if ($value instanceof \stdClass) {
                 $value = (array) $value;
             }
             $reflection = $this->getReflection();
             if ($this->attributeNames->offsetExists($key)) {
                 $propertyName = $this->attributeNames->offsetGet($key);
                 if ($reflection->hasProperty($propertyName)) {
                     $property = $reflection->getProperty($propertyName);
                     $type = $property->getAnnotation('var');
                     if (Strings::endsWith($type, 'Entity')) {
                         $classWithNamespace = sprintf("\\%s\\%s", $reflection->getNamespaceName(), (string) $type);
                         if (is_array($value) && $property->hasAnnotation('collection')) {
                             $arrayData = array();
                             foreach ($value as $valueData) {
                                 $arrayData[] = new $classWithNamespace($valueData, $inverse);
                             }
                             $this->{$propertyName} = $arrayData;
                         } else {
                             $this->{$propertyName} = new $classWithNamespace($value);
                         }
                     } else {
                         $this->{$propertyName} = $value;
                     }
                 }
             }
         }
     }
 }