Ejemplo n.º 1
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.º 2
0
 /**
  * Returns the NEON representation of a value.
  * @param  mixed
  * @param  int
  * @return string
  */
 public static function encode($var, $options = NULL)
 {
     if ($var instanceof \DateTime) {
         return $var->format('Y-m-d H:i:s O');
     } elseif ($var instanceof NeonEntity) {
         return self::encode($var->value) . '(' . substr(self::encode($var->attributes), 1, -1) . ')';
     }
     if (is_object($var)) {
         $obj = $var;
         $var = array();
         foreach ($obj as $k => $v) {
             $var[$k] = $v;
         }
     }
     if (is_array($var)) {
         $isList = Arrays::isList($var);
         $s = '';
         if ($options & self::BLOCK) {
             if (count($var) === 0) {
                 return "[]";
             }
             foreach ($var as $k => $v) {
                 $v = self::encode($v, self::BLOCK);
                 $s .= ($isList ? '-' : self::encode($k) . ':') . (Strings::contains($v, "\n") ? "\n\t" . str_replace("\n", "\n\t", $v) : ' ' . $v) . "\n";
                 continue;
             }
             return $s;
         } else {
             foreach ($var as $k => $v) {
                 $s .= ($isList ? '' : self::encode($k) . ': ') . self::encode($v) . ', ';
             }
             return ($isList ? '[' : '{') . substr($s, 0, -2) . ($isList ? ']' : '}');
         }
     } elseif (is_string($var) && !is_numeric($var) && !preg_match('~[\\x00-\\x1F]|^\\d{4}|^(true|false|yes|no|on|off|null)\\z~i', $var) && preg_match('~^' . self::$patterns[1] . '\\z~x', $var)) {
         return $var;
     } elseif (is_float($var)) {
         $var = json_encode($var);
         return Strings::contains($var, '.') ? $var : $var . '.0';
     } else {
         return json_encode($var);
     }
 }
 public function loadConfiguration()
 {
     $builder = $this->getContainerBuilder();
     $config = $this->getConfig($this->defaults);
     Validators::assertField($config, 'class', 'string');
     Validators::assertField($config, 'directories', 'array');
     Validators::assertField($config, 'cache', 'bool');
     Validators::assertField($config, 'cacheExistingFilesOnly', 'bool');
     $directories = $config['directories'];
     if (Arrays::isList($directories)) {
         $directories = array_fill_keys($directories, PHP_INT_MAX);
     }
     foreach ($this->compiler->getExtensions() as $extension) {
         if ($extension instanceof ITemplateLocatorDirectoryProvider) {
             $directories = array_merge($directories, $extension->getTemplateLocatorDirectories());
         }
     }
     $processed = array();
     foreach ($directories as $directory => $priority) {
         if (FALSE !== ($directory = realpath($builder->expand($directory)))) {
             $processed[$directory] = $priority;
         }
     }
     $directories = $processed;
     $class = $config['class'];
     $locator = $builder->addDefinition($this->prefix('locator'));
     if ('detect' === $class && count($directories) || 'priority' === $class) {
         arsort($directories, SORT_NUMERIC);
         $locator->setClass('Rixxi\\Templating\\TemplateLocators\\PriorityTemplateLocator', array(array_keys($directories)));
     } elseif ('detect' === $class || 'conventional' === $class) {
         $locator->setClass('Rixxi\\Templating\\TemplateLocators\\ConventionalTemplateLocator');
     } else {
         $locator->setClass($class);
     }
     if ($config['cache']) {
         $locator->setAutowired(FALSE);
         $builder->addDefinition($this->prefix('cachedLocator'))->setClass('Rixxi\\Templating\\TemplateLocators\\CachedTemplateLocator', array(new Statement($this->prefix('@locator')), 2 => md5(serialize($config)), $config['cacheExistingFilesOnly']));
     }
     $builder->addDefinition($this->prefix('controlTemplateFactory'))->setClass('Rixxi\\Application\\UI\\Control\\TemplateFactory')->setAutowired(FALSE);
 }
Ejemplo n.º 4
0
 /**
  * Adds condition for primary key.
  * @param  mixed
  * @return self
  */
 public function wherePrimary($key)
 {
     if (is_array($this->primary) && Nette\Utils\Arrays::isList($key)) {
         if (isset($key[0]) && is_array($key[0])) {
             $this->where($this->primary, $key);
         } else {
             foreach ($this->primary as $i => $primary) {
                 $this->where($this->name . '.' . $primary, $key[$i]);
             }
         }
     } elseif (is_array($key) && !Nette\Utils\Arrays::isList($key)) {
         // key contains column names
         $this->where($key);
     } else {
         $this->where($this->name . '.' . $this->getPrimary(), $key);
     }
     return $this;
 }
Ejemplo n.º 5
0
	/**
	 * Finds whether a variable is a zero-based integer indexed array.
	 * @param  array
	 * @return bool
	 */
	public static function isList($value)
	{
		return Arrays::isList($value);
	}
Ejemplo n.º 6
0
 /**
  * Formats PHP code for class instantiating, function calling or property setting in PHP.
  * @return string
  * @internal
  */
 public function formatStatement(Statement $statement)
 {
     $entity = $this->normalizeEntity($statement->getEntity());
     $arguments = $statement->arguments;
     if (is_string($entity) && Strings::contains($entity, '?')) {
         // PHP literal
         return $this->formatPhp($entity, $arguments);
     } elseif ($service = $this->getServiceName($entity)) {
         // factory calling
         $params = [];
         foreach ($this->definitions[$service]->parameters as $k => $v) {
             $params[] = preg_replace('#\\w+\\z#', '\\$$0', is_int($k) ? $v : $k) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
         }
         $rm = new \ReflectionFunction(create_function(implode(', ', $params), ''));
         $arguments = Helpers::autowireArguments($rm, $arguments, $this);
         return $this->formatPhp('$this->?(?*)', [Container::getMethodName($service), $arguments]);
     } elseif ($entity === 'not') {
         // operator
         return $this->formatPhp('!?', [$arguments[0]]);
     } elseif (is_string($entity)) {
         // class name
         if ($constructor = (new ReflectionClass($entity))->getConstructor()) {
             $this->addDependency((string) $constructor->getFileName());
             $arguments = Helpers::autowireArguments($constructor, $arguments, $this);
         } elseif ($arguments) {
             throw new ServiceCreationException("Unable to pass arguments, class {$entity} has no constructor.");
         }
         return $this->formatPhp("new {$entity}" . ($arguments ? '(?*)' : ''), [$arguments]);
     } elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) {
         throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity)));
     } elseif (!preg_match('#^\\$?' . PhpHelpers::PHP_IDENT . '\\z#', $entity[1])) {
         throw new ServiceCreationException("Expected function, method or property name, '{$entity['1']}' given.");
     } elseif ($entity[0] === '') {
         // globalFunc
         return $this->formatPhp("{$entity['1']}(?*)", [$arguments]);
     } elseif ($entity[0] instanceof Statement) {
         $inner = $this->formatPhp('?', [$entity[0]]);
         if (substr($inner, 0, 4) === 'new ') {
             $inner = "({$inner})";
         }
         return $this->formatPhp("{$inner}->?(?*)", [$entity[1], $arguments]);
     } elseif (Strings::contains($entity[1], '$')) {
         // property setter
         Validators::assert($arguments, 'list:1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'");
         if ($this->getServiceName($entity[0])) {
             return $this->formatPhp('?->? = ?', [$entity[0], substr($entity[1], 1), $arguments[0]]);
         } else {
             return $this->formatPhp($entity[0] . '::$? = ?', [substr($entity[1], 1), $arguments[0]]);
         }
     } elseif ($service = $this->getServiceName($entity[0])) {
         // service method
         $class = $this->definitions[$service]->getImplement();
         if (!$class || !method_exists($class, $entity[1])) {
             $class = $this->definitions[$service]->getClass();
         }
         if ($class) {
             $arguments = $this->autowireArguments($class, $entity[1], $arguments);
         }
         return $this->formatPhp('?->?(?*)', [$entity[0], $entity[1], $arguments]);
     } else {
         // static method
         $arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
         return $this->formatPhp("{$entity['0']}::{$entity['1']}(?*)", [$arguments]);
     }
 }
Ejemplo n.º 7
0
 public function insert($data)
 {
     if ($data instanceof \Traversable && !$data instanceof Selection) {
         $data = iterator_to_array($data);
     }
     if (Nette\Utils\Arrays::isList($data)) {
         foreach (array_keys($data) as $key) {
             $data[$key][$this->column] = $this->active;
         }
     } else {
         $data[$this->column] = $this->active;
     }
     return parent::insert($data);
 }
Ejemplo n.º 8
0
 /**
  * @param array|mixed $data
  * @param \DOMNode $xml
  * @param string|NULL $previousKey
  */
 private function toXml($data, \DOMNode $xml, $previousKey = NULL)
 {
     if (is_array($data) || $data instanceof Traversable) {
         foreach ($data as $key => $value) {
             $node = $xml;
             if (is_int($key)) {
                 $node = $this->xml->createElement($previousKey);
                 $xml->appendChild($node);
             } else {
                 if (!Arrays::isList($value)) {
                     $node = $this->xml->createElement($key);
                     $xml->appendChild($node);
                 }
             }
             $this->toXml($value, $node, is_string($key) ? $key : $previousKey);
         }
     } else {
         $xml->appendChild($this->xml->createTextNode($data));
     }
 }
Ejemplo n.º 9
0
 /**
  * Adds condition for primary key.
  * @param  mixed
  * @return self
  */
 public function wherePrimary($key)
 {
     if (is_array($this->primary) && Arrays::isList($key)) {
         if (isset($key[0]) && is_array($key[0])) {
             $this->where($this->primary, $key);
         } else {
             foreach ($this->primary as $i => $primary) {
                 $this->where($this->name . '.' . $primary, $key[$i]);
             }
         }
     } elseif (is_array($key) && !Arrays::isList($key)) {
         // key contains column names
         $this->where($key);
     } else {
         $this->where($this->name . '.' . $this->getPrimary(), $key);
     }
     //$this->callSqlBuilder('wherePrimary', func_get_args());
     return $this;
 }
Ejemplo n.º 10
0
 /**
  * Parses single service definition from configuration.
  * @return void
  */
 public static function loadDefinition(ServiceDefinition $definition, $config)
 {
     if ($config === NULL) {
         return;
     } elseif (is_string($config) && interface_exists($config)) {
         $config = ['class' => NULL, 'implement' => $config];
     } elseif ($config instanceof Statement && is_string($config->getEntity()) && interface_exists($config->getEntity())) {
         $config = ['class' => NULL, 'implement' => $config->getEntity(), 'factory' => array_shift($config->arguments)];
     } elseif (!is_array($config) || isset($config[0], $config[1])) {
         $config = ['class' => NULL, 'factory' => $config];
     }
     if (array_key_exists('create', $config)) {
         trigger_error("Key 'create' is deprecated, use 'factory' or 'class' in configuration.", E_USER_DEPRECATED);
         $config['factory'] = $config['create'];
         unset($config['create']);
     }
     $known = ['class', 'factory', 'arguments', 'setup', 'autowired', 'dynamic', 'inject', 'parameters', 'implement', 'run', 'tags'];
     if ($error = array_diff(array_keys($config), $known)) {
         $hints = array_filter(array_map(function ($error) use($known) {
             return Nette\Utils\ObjectMixin::getSuggestion($known, $error);
         }, $error));
         $hint = $hints ? ", did you mean '" . implode("', '", $hints) . "'?" : '.';
         throw new Nette\InvalidStateException(sprintf("Unknown key '%s' in definition of service{$hint}", implode("', '", $error)));
     }
     $config = Helpers::filterArguments($config);
     if (array_key_exists('class', $config) || array_key_exists('factory', $config)) {
         $definition->setClass(NULL);
         $definition->setFactory(NULL);
     }
     if (array_key_exists('class', $config)) {
         Validators::assertField($config, 'class', 'string|Nette\\DI\\Statement|null');
         if (!$config['class'] instanceof Statement) {
             $definition->setClass($config['class']);
         }
         $definition->setFactory($config['class']);
     }
     if (array_key_exists('factory', $config)) {
         Validators::assertField($config, 'factory', 'callable|Nette\\DI\\Statement|null');
         $definition->setFactory($config['factory']);
     }
     if (array_key_exists('arguments', $config)) {
         Validators::assertField($config, 'arguments', 'array');
         $arguments = $config['arguments'];
         if (!Config\Helpers::takeParent($arguments) && !Nette\Utils\Arrays::isList($arguments) && $definition->getFactory()) {
             $arguments += $definition->getFactory()->arguments;
         }
         $definition->setArguments($arguments);
     }
     if (isset($config['setup'])) {
         if (Config\Helpers::takeParent($config['setup'])) {
             $definition->setSetup([]);
         }
         Validators::assertField($config, 'setup', 'list');
         foreach ($config['setup'] as $id => $setup) {
             Validators::assert($setup, 'callable|Nette\\DI\\Statement|array:1', "setup item #{$id}");
             if (is_array($setup)) {
                 $setup = new Statement(key($setup), array_values($setup));
             }
             $definition->addSetup($setup);
         }
     }
     if (isset($config['parameters'])) {
         Validators::assertField($config, 'parameters', 'array');
         $definition->setParameters($config['parameters']);
     }
     if (isset($config['implement'])) {
         Validators::assertField($config, 'implement', 'string');
         $definition->setImplement($config['implement']);
         $definition->setAutowired(TRUE);
     }
     if (isset($config['autowired'])) {
         Validators::assertField($config, 'autowired', 'bool|string|array');
         $definition->setAutowired($config['autowired']);
     }
     if (isset($config['dynamic'])) {
         Validators::assertField($config, 'dynamic', 'bool');
         $definition->setDynamic($config['dynamic']);
     }
     if (isset($config['inject'])) {
         Validators::assertField($config, 'inject', 'bool');
         $definition->addTag(Extensions\InjectExtension::TAG_INJECT, $config['inject']);
     }
     if (isset($config['run'])) {
         trigger_error("Option 'run' is deprecated, use 'run' as tag.", E_USER_DEPRECATED);
         $config['tags']['run'] = (bool) $config['run'];
     }
     if (isset($config['tags'])) {
         Validators::assertField($config, 'tags', 'array');
         if (Config\Helpers::takeParent($config['tags'])) {
             $definition->setTags([]);
         }
         foreach ($config['tags'] as $tag => $attrs) {
             if (is_int($tag) && is_string($attrs)) {
                 $definition->addTag($attrs);
             } else {
                 $definition->addTag($tag, $attrs);
             }
         }
     }
 }
Ejemplo n.º 11
0
	/**
	 * Formats PHP code for class instantiating, function calling or property setting in PHP.
	 * @return string
	 * @internal
	 */
	public function formatStatement(Statement $statement)
	{
		$entity = $this->normalizeEntity($statement->entity);
		$arguments = $statement->arguments;

		if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal
			return $this->formatPhp($entity, $arguments);

		} elseif ($service = $this->getServiceName($entity)) { // factory calling
			$params = array();
			foreach ($this->definitions[$service]->parameters as $k => $v) {
				$params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
			}
			$rm = new Reflection\GlobalFunction(create_function(implode(', ', $params), ''));
			$arguments = Helpers::autowireArguments($rm, $arguments, $this);
			return $this->formatPhp('$this->?(?*)', array(Container::getMethodName($service), $arguments));

		} elseif ($entity === 'not') { // operator
			return $this->formatPhp('!?', array($arguments[0]));

		} elseif (is_string($entity)) { // class name
			if ($constructor = Reflection\ClassType::from($entity)->getConstructor()) {
				$this->addDependency($constructor->getFileName());
				$arguments = Helpers::autowireArguments($constructor, $arguments, $this);
			} elseif ($arguments) {
				throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");
			}
			return $this->formatPhp("new $entity" . ($arguments ? '(?*)' : ''), array($arguments));

		} elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) {
			throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity)));

		} elseif ($entity[0] === '') { // globalFunc
			return $this->formatPhp("$entity[1](?*)", array($arguments));

		} elseif (Strings::contains($entity[1], '$')) { // property setter
			Validators::assert($arguments, 'list:1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'");
			if ($this->getServiceName($entity[0])) {
				return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0]));
			} else {
				return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0]));
			}

		} elseif ($service = $this->getServiceName($entity[0])) { // service method
			$class = $this->definitions[$service]->implement;
			if (!$class || !method_exists($class, $entity[1])) {
				$class = $this->definitions[$service]->class;
			}
			if ($class) {
				$arguments = $this->autowireArguments($class, $entity[1], $arguments);
			}
			return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments));

		} else { // static method
			$arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
			return $this->formatPhp("$entity[0]::$entity[1](?*)", array($arguments));
		}
	}
Ejemplo n.º 12
0
 /**
  * Creates a list of arguments using autowiring.
  * @return array
  * @internal
  */
 public function autowireArguments($class, $method, array $arguments)
 {
     $rc = new ReflectionClass($class);
     if (!$rc->hasMethod($method)) {
         if (!Nette\Utils\Arrays::isList($arguments)) {
             throw new ServiceCreationException("Unable to pass specified arguments to {$class}::{$method}().");
         }
         return $arguments;
     }
     $rm = $rc->getMethod($method);
     if (!$rm->isPublic()) {
         throw new ServiceCreationException("{$class}::{$method}() is not callable.");
     }
     $this->addDependency($rm);
     return Helpers::autowireArguments($rm, $arguments, $this);
 }