Ejemplo n.º 1
0
 /**
  * @param array $args
  * @return int
  */
 public function run(array $args = [])
 {
     /** @var ICollection|Addon[] $addons */
     $addons = $this->addonRepository->findBowers();
     // DO YOUR JOB ===============================================
     $counter = 0;
     foreach ($addons as $addon) {
         // Skip addon with bad data
         if ($extra = $addon->github->extra) {
             if ($bower = $extra->get('bower', FALSE)) {
                 // Create bower entity if not exist
                 if (!$addon->bower) {
                     $addon->bower = new Bower();
                 }
                 // Downloads
                 if ($stats = $this->bower->repo($bower['name'])) {
                     $addon->bower->downloads = Arrays::get($stats, ['hits'], 0);
                 }
                 // Keywords
                 $keywords = Arrays::get($bower, 'keywords', []);
                 $addon->bower->keywords = $keywords ? implode(',', $keywords) : NULL;
                 // Persist
                 $this->addonRepository->persistAndFlush($addon);
                 // Increase counting
                 $counter++;
             } else {
                 $this->log('Skip (bower) [no bower data]: ' . $addon->fullname);
             }
         } else {
             $this->log('Skip (bower) [no extra data]: ' . $addon->fullname);
         }
     }
     return $counter;
 }
Ejemplo n.º 2
0
 /**
  * Loads HTTP data.
  *
  * @return void
  */
 public function loadHttpData()
 {
     $path = $this->getHtmlName();
     // img_x or img['x']
     $path = explode('[', strtr(str_replace(']', '', strpos($path, '[') === false ? $path . '.x' : substr($path, 0, -2)), '.', '_'));
     $this->setValue(Nette\Utils\Arrays::get($this->getForm()->getHttpData(), $path, null));
 }
Ejemplo n.º 3
0
 public function loadConfiguration()
 {
     $container = $this->getContainerBuilder();
     $config = $this->getConfig($this->defaults);
     $entities = $collections = array();
     foreach ($config['entity'] as $domain => $entity) {
         $service = $container->addDefinition($entities[$domain] = $this->prefix($domain . '.entity'));
         Compiler::parseService($service, $entity);
         $service->setClass('NiceORM\\Entity')->setParameters(array('data' => NULL))->setShared(FALSE);
         $container->addDefinition($collections[$domain] = $this->prefix($domain . '.collection'))->setClass('NiceORM\\ICollection')->setFactory('NiceORM\\TableCollection', array($domain, '%data%'))->setParameters(array('data'))->setShared(FALSE);
     }
     $fields = $refs = $related = array();
     foreach ($config['tables'] as $domain => $table) {
         $fields[$domain] = $refs[$domain] = $related[$domain] = array();
         foreach (Arrays::get($config['fields'], $domain, array()) as $name => $column) {
             $fields[$domain][is_int($name) ? $column : $name] = $column;
         }
         foreach (Arrays::get($config['relations'], $domain, array()) as $name => $column) {
             if (is_int($name)) {
                 $refs[$domain][$column] = array($column, NULL, $column);
             } else {
                 $column = array_values((array) $column);
                 switch (count($column)) {
                     case 0:
                         $refs[$domain][$name] = array($name, NULL, $name);
                         break;
                     case 1:
                         $refs[$domain][$name] = array($name, $column[0], $name);
                         break;
                     case 2:
                         $refs[$domain][$name] = array($column[0], $column[1], $name);
                         break;
                     default:
                         $refs[$domain][$name] = array($column[0], $column[1], $column[2]);
                 }
             }
         }
     }
     foreach ($refs as $domain => $tableRefs) {
         foreach ($tableRefs as $name => $ref) {
             list($table, $column, $type) = $ref;
             if ($type === $name || empty($related[$type][$domain . 's'])) {
                 $related[$type][$domain . 's'] = array($config['tables'][$domain], $column, $domain);
             } elseif (!isset($refs[$domain][$type])) {
                 unset($related[$type][$domain . 's']);
             }
             $related[$type][$domain . 's:' . $name] = array($config['tables'][$domain], $column, $domain);
         }
     }
     $mappers = $accessors = array();
     foreach ($config['tables'] as $domain => $table) {
         $mapper = $container->addDefinition($mappers[$domain] = $this->prefix($domain . '.mapper'))->setClass('NiceORM\\ActiveRowMapper', array($domain, $table, $fields[$domain], $refs[$domain], $related[$domain]));
         $container->addDefinition($accessors[$domain] = $this->prefix($domain . '.accessor'))->setClass('NiceORM\\ActiveRowAccessor', array('%data%', $mapper))->setParameters(array('data'))->setShared(FALSE);
     }
     $entityFactory = $container->addDefinition($this->prefix('entityFactory'))->setClass('NiceORM\\DIEntityFactory', array($entities));
     $collectionFactory = $container->addDefinition($this->prefix('collectionFactory'))->setClass('NiceORM\\DICollectionFactory', array($collections));
     $accessorFactory = $container->addDefinition($this->prefix('accessorFactory'))->setClass('NiceORM\\DIAccessorFactory', array($accessors));
     $mapperAccessor = $container->addDefinition($this->prefix('mapperAccessor'))->setClass('NiceORM\\DIMapperAccessor', array($mappers));
     $container->addDefinition($this->prefix('manager'))->setClass('NiceORM\\Manager')->setFactory('NiceORM\\Manager', array($entityFactory, $collectionFactory, $accessorFactory, $mapperAccessor));
 }
Ejemplo n.º 4
0
 /**
  * @param Configurator $configurator
  */
 protected function loadConfigFiles(Configurator $configurator)
 {
     if ($this->autoloadConfig === TRUE || is_array($this->autoloadConfig)) {
         $scanDirs = $this->autoloadConfig === TRUE ? [$this->appDir] : $this->autoloadConfig;
         $cache = $this->createCache();
         $files = $cache->load(self::CACHE_NAMESPACE);
         if ($files === NULL) {
             $files = [0 => []];
             foreach (Finder::findFiles('*.neon')->from($scanDirs) as $path => $file) {
                 $content = Neon::decode(file_get_contents($path));
                 if (!is_array($content) || !array_key_exists('autoload', $content)) {
                     continue;
                 }
                 $autoload = Arrays::get($content, ['autoload', 0], FALSE);
                 if ($autoload === FALSE) {
                     continue;
                 }
                 $autoload = is_int($autoload) ? $autoload : 0;
                 if (!isset($files[$autoload])) {
                     $files[$autoload] = [];
                 }
                 $files[$autoload][] = $path;
             }
             $cache->save(self::CACHE_NAMESPACE, $files);
         }
         foreach ($files as $priorityFiles) {
             foreach ($priorityFiles as $config) {
                 $configurator->addConfig($config);
             }
         }
     }
     foreach ($this->configs as $config) {
         $configurator->addConfig($config);
     }
 }
Ejemplo n.º 5
0
 /**
  * Reads configuration from NEON file.
  * @param  string  file name
  * @return array
  * @throws Nette\InvalidStateException
  */
 public static function load($file)
 {
     if (!is_file($file) || !is_readable($file)) {
         throw new Nette\FileNotFoundException("File '{$file}' is missing or is not readable.");
     }
     $neon = Neon::decode(file_get_contents($file));
     $separator = trim(self::$sectionSeparator);
     $data = array();
     foreach ($neon as $secName => $secData) {
         if ($secData === NULL) {
             // empty section
             $secData = array();
         }
         if (is_array($secData)) {
             // process extends sections like [staging < production]
             $parts = $separator ? explode($separator, $secName) : array($secName);
             if (count($parts) > 1) {
                 $parent = trim($parts[1]);
                 if (!isset($data[$parent]) || !is_array($data[$parent])) {
                     throw new Nette\InvalidStateException("Missing parent section '{$parent}' in file '{$file}'.");
                 }
                 $secData = array_reverse(Nette\Utils\Arrays::mergeTree(array_reverse($secData, TRUE), array_reverse($data[$parent], TRUE)), TRUE);
                 $secName = trim($parts[0]);
                 if ($secName === '') {
                     throw new Nette\InvalidStateException("Invalid empty section name in file '{$file}'.");
                 }
             }
         }
         $data[$secName] = $secData;
     }
     return $data;
 }
Ejemplo n.º 6
0
 /**
  *
  * @param array $files
  * @param array $names Array of indexes of $files array representing current nesting level. E.g. if we are iterating over $files[k1][k2] then $names=[k1,k2]
  */
 private function processFiles(array $files, array $names = [])
 {
     foreach ($files as $name => $controlValue) {
         $names[] = $name;
         // MFU sends data in this format:
         //
         // array(
         //	"token" => "blablabla",
         //	"files" => array(
         //		0 => FileUpload(...),
         //		...
         //	)
         // )
         // expanded POST array with $names indexes
         $postFromHttpRequest = $this->httpRequest->getPost();
         $postArr = Arrays::getRef($postFromHttpRequest, $names);
         $isFormMFU = (is_array($controlValue) and isset($controlValue["files"]) and isset($postArr['token']));
         if ($isFormMFU) {
             $token = $postArr["token"];
             foreach ($controlValue["files"] as $file) {
                 self::processFile($token, $file);
             }
             // support for nested Nette\Forms\Container
         } elseif (is_array($controlValue)) {
             $this->processFiles($controlValue, $names);
         }
         // skip files not processed by MFU
         // they will be processed by Nette Forms
     }
 }
Ejemplo n.º 7
0
 public function addTags($type, array $tags)
 {
     $tags = Nette\Utils\Arrays::normalize($tags, TRUE);
     foreach ($this->findByType($type) as $def) {
         $def->setTags($def->getTags() + $tags);
     }
 }
Ejemplo n.º 8
0
 /**
  * @return mixed|NULL
  */
 private function getHttpData()
 {
     if ($this->http_post === NULL) {
         $path = explode(self::NAME_SEPARATOR, $this->lookupPath('Nette\\Forms\\Form'));
         $this->http_post = Nette\Utils\Arrays::get($this->getForm()->getHttpData(), $path, NULL);
     }
     return $this->http_post;
 }
Ejemplo n.º 9
0
 /**
  * @param string $message
  * @param int $count
  * @return string
  */
 function translate($message, $count = 0)
 {
     if (substr($message, 0, 5) != "book.") {
         return "";
     }
     $this->loadTexts();
     return Arrays::get($this->texts, substr($message, 5), "");
 }
Ejemplo n.º 10
0
 /**
  * @param array $values
  * @param array $entityProperties
  */
 protected function changeEmptyStringsToNull(array &$values, array $entityProperties = [])
 {
     foreach ($entityProperties as $property) {
         if ($property->getType() == 'string' and $property->isNullable()) {
             Arrays::renameKey($values, $property->getName(), $property->getName() . '%sN');
         }
     }
 }
Ejemplo n.º 11
0
 /**
  * @param string $name
  * @param mixed $default
  * @return mixed
  */
 public function get($name, $default = NULL)
 {
     if (func_num_args() > 1) {
         return Arrays::get($this->parameters, $name, $default);
     } else {
         return Arrays::get($this->parameters, $name);
     }
 }
Ejemplo n.º 12
0
 /**
  * Loads HTTP data.
  * @return void
  */
 public function loadHttpData()
 {
     $path = \explode('[', \strtr(\str_replace(array('[]', ']'), '', $this->getHtmlName()), '.', '_'));
     $origValue = Arrays::get($this->getForm()->getHttpData(), $path);
     $from = isset($origValue['from']) ? $origValue['from'] : '';
     $to = isset($origValue['to']) ? $origValue['to'] : '';
     $value = array('from' => $from, 'to' => $to);
     $this->setValue($value);
 }
Ejemplo n.º 13
0
 public function beforeCompile()
 {
     $builder = $this->getContainerBuilder();
     $connection = $builder->getDefinition('movi.connection');
     foreach (array_keys($builder->findByTag(self::FILTER_TAG)) as $filter) {
         $def = $builder->getDefinition($filter);
         $tags = Arrays::mergeTree($def->tags, $this->defaults);
         $connection->addSetup('registerFilter', [$tags['name'], ['@' . $filter, $tags['callback']], !empty($tags['wire']) ? $tags['wire'] : NULL]);
     }
 }
 /**
  * Returns unique token for method and params
  * @param  string $control
  * @param  string $method
  * @param  array $params
  * @return string
  */
 public function getCsrfToken($control, $method, $params)
 {
     $session = $this->getSession('Nextras.Application.UI.SecuredLinksPresenterTrait');
     if (!isset($session->token)) {
         $session->token = Nette\Utils\Random::generate();
     }
     $params = Nette\Utils\Arrays::flatten($params);
     $params = implode('|', array_keys($params)) . '|' . implode('|', array_values($params));
     return substr(md5($control . $method . $params . $session->token . $this->getSession()->getId()), 0, 8);
 }
Ejemplo n.º 15
0
 /**
  * @param \SplFileInfo $package
  * @return array
  * @throws \movi\FileNotFoundException
  */
 private function getData(\SplFileInfo $package)
 {
     $file = $package->getPathname() . '/' . self::PACKAGE_FILE;
     if (!file_exists($file) || !is_readable($file)) {
         throw new FileNotFoundException("JSON file for package '" . $package->getFilename() . "' was not found or is not readable.");
     }
     $data = Json::decode(file_get_contents($file), Json::FORCE_ARRAY);
     $data['dir'] = $package->getPathname();
     return Arrays::mergeTree($data, $this->defaults);
 }
Ejemplo n.º 16
0
	/**
	 * Expands %placeholders%.
	 * @param  mixed
	 * @param  array
	 * @param  bool
	 * @return mixed
	 * @throws Nette\InvalidArgumentException
	 */
	public static function expand($var, array $params, $recursive = FALSE)
	{
		if (is_array($var)) {
			$res = array();
			foreach ($var as $key => $val) {
				$res[$key] = self::expand($val, $params, $recursive);
			}
			return $res;

		} elseif ($var instanceof \stdClass || $var instanceof Statement) {
			$res = clone $var;
			foreach ($var as $key => $val) {
				$res->$key = self::expand($val, $params, $recursive);
			}
			return $res;

		} elseif (!is_string($var)) {
			return $var;
		}

		$parts = preg_split('#%([\w.-]*)%#i', $var, -1, PREG_SPLIT_DELIM_CAPTURE);
		$res = '';
		foreach ($parts as $n => $part) {
			if ($n % 2 === 0) {
				$res .= $part;

			} elseif ($part === '') {
				$res .= '%';

			} elseif (isset($recursive[$part])) {
				throw new Nette\InvalidArgumentException(sprintf('Circular reference detected for variables: %s.', implode(', ', array_keys($recursive))));

			} else {
				try {
					$val = Nette\Utils\Arrays::get($params, explode('.', $part));
				} catch (Nette\InvalidArgumentException $e) {
					throw new Nette\InvalidArgumentException("Missing parameter '$part'.", 0, $e);
				}
				if ($recursive) {
					$val = self::expand($val, $params, (is_array($recursive) ? $recursive : array()) + array($part => 1));
				}
				if (strlen($part) + 2 === strlen($var)) {
					return $val;
				}
				if (!is_scalar($val)) {
					throw new Nette\InvalidArgumentException("Unable to concatenate non-scalar parameter '$part' into '$var'.");
				}
				$res .= $val;
			}
		}
		return $res;
	}
Ejemplo n.º 17
0
 /**
  * Ověří mimetype předaného souboru.
  * @param \Nette\Http\FileUpload $file Nahraný soubor k ověření.
  * @return bool Má soubor správný mimetype?
  */
 public function checkType(\Nette\Http\FileUpload $file)
 {
     if (\Nette\Utils\Arrays::searchKey($this->getMimeTypes(), $file->getContentType()) !== FALSE) {
         return TRUE;
     } else {
         // Pokud se nepodaří ověřit mimetype, ověříme alespoň koncovku.
         if (array_search($this->getExtension($file->getName()), array_unique($this->getMimeTypes())) !== FALSE) {
             return TRUE;
         } else {
             return FALSE;
         }
     }
 }
 /**
  * @param User $sender
  * @param array $usersByRestrictions
  * @return array
  */
 private function prepareRecipients(User $sender, array $usersByRestrictions)
 {
     if (empty($usersByRestrictions)) {
         return [];
     }
     unset($usersByRestrictions['suspendedUsers'][$sender->getId()], $usersByRestrictions['activeUsers'][$sender->getId()]);
     if (!$this->authorizator->isAllowed($sender, 'message', 'send_to_restricted_recipients')) {
         $recipients = array_diff_key($usersByRestrictions['activeUsers'], $usersByRestrictions['suspendedUsers'], $usersByRestrictions['usersBlockedByMe'], $usersByRestrictions['usersBlockingMe']);
     } else {
         $recipients = $usersByRestrictions['activeUsers'] + $usersByRestrictions['usersBlockedByMe'] + $usersByRestrictions['usersBlockingMe'];
     }
     return Arrays::associate($recipients, 'id=username');
 }
 public function formatTemplateFiles(Presenter $presenter)
 {
     $name = $presenter->getName();
     $view = $presenter->view;
     $_presenter = substr($name, strrpos(':' . $name, ':'));
     $directories = $this->getAdjustedDirectories($presenter);
     $list = array();
     foreach ($directories as $dir) {
         $list[] = $this->getTemplateFiles("{$dir}/presenters", $_presenter, $view);
         $list[] = $this->getTemplateFiles($dir, $_presenter, $view);
     }
     return Arrays::flatten($list);
 }
Ejemplo n.º 20
0
 /**
  * @return array
  */
 public function send(IMessage $message)
 {
     try {
         $response = $this->client->send(sprintf('%s/%s.%s', $this->config->getEndpointUrl(), $message->getEndpointName(), $this->config->getFormat()), $this->config->getApiKey(), $message->getParams());
     } catch (\Exception $e) {
         throw new ClientException('There was an error while contacting the Mandrill API.', NULL, $e);
     }
     $answer = $this->getAdapter($this->config->getFormat())->process($response);
     if ($response->getStatusCode() !== 200 || !Arrays::isList($answer)) {
         throw new MandrillException(sprintf('%s: %s', isset($answer['name']) ? $answer['name'] : self::UNKNOWN_ERROR_NAME, isset($answer['message']) ? $answer['message'] : self::UNKNOWN_ERROR_MESSAGE), isset($answer['code']) ? $answer['code'] : self::UNKNOWN_ERROR_CODE);
     }
     return $answer;
 }
Ejemplo n.º 21
0
 /**
  * @return ArrayHash|null
  */
 public function loadOptions()
 {
     $options = $this->cache->load(Option::getCacheKey(), function () use(&$dependencies) {
         $options = $this->em->createQuery('SELECT o FROM ' . Option::class . ' o')->getArrayResult();
         if (empty($options)) {
             return null;
         }
         $options = ArrayHash::from(Arrays::associate($options, 'name=value'));
         $dependencies = [Cache::TAGS => Option::getCacheKey()];
         return $options;
     });
     return $options;
 }
Ejemplo n.º 22
0
 public function loadLabelExtentsionProperties()
 {
     $params = $this->context->getParameters();
     $loader = new Nette\Config\Loader();
     $commonConfigFile = CONFIG_DIR . '/labels/labelExtensions.neon';
     $projectConfigFile = $params['projectDir'] . '/config/labels/labelExtensions.neon';
     $config = $loader->load($commonConfigFile);
     //        dump($config);
     if (is_file($projectConfigFile)) {
         $projectConfig = $loader->load($projectConfigFile);
         $config = \Nette\Utils\Arrays::mergeTree($projectConfig, $config);
     }
     //        dump($config);
     return $config;
 }
Ejemplo n.º 23
0
 public function saveConfig()
 {
     $values = $this->data;
     $this->loadConfig();
     $data =& $this->data;
     foreach ($this->root as $item) {
         $data =& $data[$item];
     }
     $data = $data ?: array();
     $data = Arrays::mergeTree($values, $data);
     file_put_contents($this->fileName, $this->adapter->dump($this->data));
     if (function_exists('opcache_reset')) {
         opcache_reset();
     }
 }
Ejemplo n.º 24
0
 function __set($name, $val)
 {
     if (Nette\Utils\Arrays::searchKey($this->og, $name) !== FALSE) {
         $this->og[$name] = Nette\Utils\Strings::normalize($val);
     } else {
         if (Nette\Utils\Arrays::searchKey($this->fb, $name) !== FALSE) {
             $this->fb[$name] = Nette\Utils\Strings::normalize($val);
         } else {
             list($ar, $section, $name) = Nette\Utils\Strings::match($name, '/([a-zA-Z]+)[_]([a-zA-Z]*)/');
             if (Nette\Utils\Arrays::searchKey($this->{$section}, $name) !== FALSE) {
                 $this->{$section} = array_replace($this->{$section}, array($name => $val));
             }
         }
     }
 }
Ejemplo n.º 25
0
	/**
	 * @param \Nette\DI\Container
	 * @param array
	 */
	public function __construct(DI\Container $context, array $configuration = array())
	{
		$this->context = $context;
		$this->configuration = \Nette\Utils\Arrays::mergeTree(array(
			'productionMode' => $context->params['productionMode'],
			'proxyDir' => $context->expand("%appDir%/proxies"),
			'proxyNamespace' => 'App\Models\Proxies',
			'entityDirs' => array($context->params['appDir'], NELLA_FRAMEWORK_DIR),
			'migrations' => array(
				'name' => \Nella\Framework::NAME . " DB Migrations",
				'table' => "db_version",
				'directory' => $context->expand("%appDir%/migrations"),
				'namespace' => 'App\Models\Migrations',
			)
		), $configuration);
	}
Ejemplo n.º 26
0
 /**
  * @param array $args
  * @return int
  */
 public function run(array $args = [])
 {
     /** @var ICollection|Addon[] $addons */
     $addons = $this->addonRepository->findComposers();
     // DO YOUR JOB ===============================================
     $counter = 0;
     foreach ($addons as $addon) {
         try {
             // Skip addon with bad data
             if ($extra = $addon->github->extra) {
                 if ($composer = $extra->get('composer', FALSE)) {
                     if (!isset($composer['name'])) {
                         throw new InvalidStateException('No composer name at ' . $addon->fullname);
                     }
                     list($owner, $repo) = explode('/', $composer['name']);
                     // Create composer entity if not exist
                     if (!$addon->composer) {
                         $addon->composer = new Composer();
                     }
                     // Basic info
                     $addon->composer->name = Arrays::get($composer, 'name', NULL);
                     $addon->composer->description = Arrays::get($composer, 'description', NULL);
                     $addon->composer->type = Arrays::get($composer, 'type', NULL);
                     // Downloads
                     if ($stats = $this->composer->repo($owner, $repo)) {
                         $addon->composer->downloads = Arrays::get($stats, ['package', 'downloads', 'total'], 0);
                     }
                     // Keywords
                     $keywords = Arrays::get($composer, 'keywords', []);
                     $addon->composer->keywords = $keywords ? implode(',', $keywords) : NULL;
                     // Persist
                     $this->addonRepository->persistAndFlush($addon);
                     // Increase counting
                     $counter++;
                 } else {
                     $this->log('Skip (composer) [no composer data]: ' . $addon->fullname);
                 }
             } else {
                 $this->log('Skip (composer) [no extra data]: ' . $addon->fullname);
             }
         } catch (Exception $e) {
             Debugger::log($e, Debugger::EXCEPTION);
             $this->log('Skip (composer) [exception]: ' . $e->getMessage());
         }
     }
     return $counter;
 }
Ejemplo n.º 27
0
 public function getValue()
 {
     if (!$this->_valueLoaded) {
         $path = explode('[', strtr(str_replace(array('[]', ']'), '', $this->getHtmlName()), '.', '_'));
         unset($path[count($path) - 1]);
         $values = \Nette\Utils\Arrays::get((array) $this->getForm()->getHttpData(), $path, NULL);
         // remove photos
         if ($this->multi) {
             if (!$this->fileEntity) {
                 $this->fileEntity = new ArrayCollection();
             }
             foreach ($this->fileEntity as $file) {
                 $delete = isset($values[$this->name . '_delete_' . $file->id]) && $values[$this->name . '_delete_' . $file->id] == 'on';
                 if ($delete) {
                     $coll = $this->fileEntity;
                     $coll->removeElement($file);
                 }
             }
         } else {
             if ($this->fileEntity) {
                 $delete = isset($values[$this->name . '_delete_' . $this->fileEntity->id]) && $values[$this->name . '_delete_' . $this->fileEntity->id] == 'on';
                 if ($delete) {
                     return NULL;
                 }
             }
         }
         // get photos
         if ($values) {
             if ($this->multi) {
                 for ($i = 0; $i < 20; $i++) {
                     if ($values[$this->name . '-' . $i] && $values[$this->name . '-' . $i]->isOk()) {
                         $this->fileEntity[] = $entity = new FileEntity();
                         $entity->setFile($values[$this->name . '-' . $i]);
                     }
                 }
             } else {
                 if ($values[$this->name] && $values[$this->name]->isOk()) {
                     $this->fileEntity = $entity = new FileEntity();
                     $entity->setFile($values[$this->name]);
                 }
             }
         }
         $this->_valueLoaded = true;
     }
     return $this->fileEntity;
 }
Ejemplo n.º 28
0
 /**
  * Sets options and option groups from which to choose.
  * @return self
  */
 public function setItems(array $items, $useKeys = TRUE)
 {
     if (!$useKeys) {
         foreach ($items as $key => $value) {
             unset($items[$key]);
             if (is_array($value)) {
                 foreach ($value as $val) {
                     $items[$key][(string) $val] = $val;
                 }
             } else {
                 $items[(string) $value] = $value;
             }
         }
     }
     $this->options = $items;
     return parent::setItems(Nette\Utils\Arrays::flatten($items, TRUE));
 }
Ejemplo n.º 29
0
 /**
  * Extracts and sanitizes submitted form data for single control.
  * @param  array   submitted data
  * @param  string  control HTML name
  * @param  string  type Form::DATA_TEXT, DATA_LINE, DATA_FILE
  * @return string|string[]
  */
 public static function extractHttpData(array $data, $htmlName, $type)
 {
     $name = explode('[', str_replace(array('[]', ']', '.'), array('', '', '_'), $htmlName));
     $data = Nette\Utils\Arrays::get($data, $name, NULL);
     if (substr($htmlName, -2) === '[]') {
         $arr = array();
         foreach (is_array($data) ? $data : array() as $v) {
             $arr[] = $v = static::sanitize($type, $v);
             if ($v === NULL) {
                 return array();
             }
         }
         return $arr;
     } else {
         return static::sanitize($type, $data);
     }
 }
Ejemplo n.º 30
0
 /**
  * @param string $fileNamePrefix
  * @param bool $removeBackupFileAtTheEnd
  * @throws \Exception
  * @throws IOException
  * @return ResultObject[]
  */
 public function backup($fileNamePrefix = null, $removeBackupFileAtTheEnd = false)
 {
     $storagePath = $this->prepareStoragePath($this->backupTempPath);
     $file = new DatabaseBackupFile($storagePath);
     if (!empty($fileNamePrefix)) {
         $file->setNamePrefix($fileNamePrefix);
     }
     $this->mysqlDump->save($file->getFilePath());
     $resultObjects = [];
     /** @var IDatabaseBackupHandler $handler */
     foreach ($this->backupHandlers as $handler) {
         $results = $handler->process($file);
         $resultObjects = array_merge($resultObjects, $results);
     }
     if ($removeBackupFileAtTheEnd === true) {
         $this->removeBackupFile($file);
     }
     return Arrays::flatten($resultObjects);
 }