Example #1
0
	/**
	 * @return IPresenterResponse
	 */
	public function run(NPresenterRequest $request)
	{
		$this->request = $request;

		$httpRequest = $this->context->getByType('IHttpRequest');
		if (!$httpRequest->isAjax() && ($request->isMethod('get') || $request->isMethod('head'))) {
			$refUrl = clone $httpRequest->getUrl();
			$url = $this->context->getService('router')->constructUrl($request, $refUrl->setPath($refUrl->getScriptPath()));
			if ($url !== NULL && !$httpRequest->getUrl()->isEqual($url)) {
				return new NRedirectResponse($url, IHttpResponse::S301_MOVED_PERMANENTLY);
			}
		}

		$params = $request->getParameters();
		if (!isset($params['callback'])) {
			throw new NBadRequestException("Parameter callback is missing.");
		}
		$params['presenter'] = $this;
		$callback = new NCallback($params['callback']);
		$response = $callback->invokeArgs(NPresenterComponentReflection::combineArgs($callback->toReflection(), $params));

		if (is_string($response)) {
			$response = array($response, array());
		}
		if (is_array($response)) {
			if ($response[0] instanceof SplFileInfo) {
				$response = $this->createTemplate('NFileTemplate')
					->setParameters($response[1])->setFile($response[0]);
			} else {
				$response = $this->createTemplate('NTemplate')
					->setParameters($response[1])->setSource($response[0]);
			}
		}
		if ($response instanceof ITemplate) {
			return new NTextResponse($response);
		} else {
			return $response;
		}
	}
Example #2
0
	/**
	 * Logs message or exception to file and sends email notification.
	 * @param  string|array
	 * @param  int     one of constant INFO, WARNING, ERROR (sends email), CRITICAL (sends email)
	 * @return bool    was successful?
	 */
	public function log($message, $priority = self::INFO)
	{
		if (!is_dir($this->directory)) {
			throw new DirectoryNotFoundException("Directory '$this->directory' is not found or is not directory.");
		}

		if (is_array($message)) {
			$message = implode(' ', $message);
		}
		$res = error_log(trim($message) . PHP_EOL, 3, $this->directory . '/' . strtolower($priority) . '.log');

		if (($priority === self::ERROR || $priority === self::CRITICAL) && $this->email && $this->mailer
			&& @filemtime($this->directory . '/email-sent') + self::$emailSnooze < time() // @ - file may not exist
			&& @file_put_contents($this->directory . '/email-sent', 'sent') // @ - file may not be writable
		) {
			NCallback::create($this->mailer)->invoke($message, $this->email);
		}
		return $res;
	}
Example #3
0
	/**
	 * @return array
	 */
	protected static function exportRules($rules)
	{
		$payload = array();
		foreach ($rules as $rule) {
			if (!is_string($op = $rule->operation)) {
				$op = new NCallback($op);
				if (!$op->isStatic()) {
					continue;
				}
			}
			if ($rule->type === NRule::VALIDATOR) {
				$item = array('op' => ($rule->isNegative ? '~' : '') . $op, 'msg' => $rules->formatMessage($rule, FALSE));

			} elseif ($rule->type === NRule::CONDITION) {
				$item = array(
					'op' => ($rule->isNegative ? '~' : '') . $op,
					'rules' => self::exportRules($rule->subRules),
					'control' => $rule->control->getHtmlName()
				);
				if ($rule->subRules->getToggles()) {
					$item['toggle'] = $rule->subRules->getToggles();
				}
			}

			if (is_array($rule->arg)) {
				foreach ($rule->arg as $key => $value) {
					$item['arg'][$key] = $value instanceof IFormControl ? (object) array('control' => $value->getHtmlName()) : $value;
				}
			} elseif ($rule->arg !== NULL) {
				$item['arg'] = $rule->arg instanceof IFormControl ? (object) array('control' => $rule->arg->getHtmlName()) : $rule->arg;
			}

			$payload[] = $item;
		}
		return $payload;
	}
Example #4
0
	/**
	 * {use class MacroSet}
	 */
	public function macroUse(NMacroNode $node, NPhpWriter $writer)
	{
		NCallback::create($node->tokenizer->fetchWord(), 'install')
			->invoke($this->getCompiler())
			->initialize();
	}
Example #5
0
	/**
	 * __get() implementation.
	 * @param  object
	 * @param  string  property name
	 * @return mixed   property value
	 * @throws MemberAccessException if the property is not defined.
	 */
	public static function & get($_this, $name)
	{
		$class = get_class($_this);
		$uname = ucfirst($name);

		if (!isset(self::$methods[$class])) {
			self::$methods[$class] = array_flip(get_class_methods($class)); // public (static and non-static) methods
		}

		if ($name === '') {
			throw new MemberAccessException("Cannot read a class '$class' property without name.");

		} elseif (isset(self::$methods[$class][$m = 'get' . $uname]) || isset(self::$methods[$class][$m = 'is' . $uname])) { // property getter
			$val = $_this->$m();
			return $val;

		} elseif (isset(self::$methods[$class][$name])) { // public method as closure getter
			$val = NCallback::create($_this, $name);
			return $val;

		} else { // strict class
			$type = isset(self::$methods[$class]['set' . $uname]) ? 'a write-only' : 'an undeclared';
			throw new MemberAccessException("Cannot read $type property $class::\$$name.");
		}
	}
Example #6
0
	/**
	 * Generates code.
	 * @return string
	 */
	private function compile(NMacroNode $node, $def)
	{
		$node->tokenizer->reset();
		$writer = NPhpWriter::using($node, $this->compiler);
		if (is_string($def)&& substr($def, 0, 1) !== "\0") {
			return $writer->write($def);
		} else {
			return NCallback::create($def)->invoke($node, $writer);
		}
	}
Example #7
0
	protected function createComponent($name)
	{
		return $this->factory->invoke($name, $this);
	}
Example #8
0
	/**
	 * Formats PHP code for class instantiating, function calling or property setting in PHP.
	 * @return string
	 * @internal
	 */
	public function formatStatement(NDIStatement $statement, $self = NULL)
	{
		$entity = $this->normalizeEntity($statement->entity);
		$arguments = $statement->arguments;

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

		} elseif ($service = $this->getServiceName($entity)) { // factory calling or service retrieving
			if ($this->definitions[$service]->shared) {
				if ($arguments) {
					throw new NServiceCreationException("Unable to call service '$entity'.");
				}
				return $this->formatPhp('$this->getService(?)', array($service));
			}
			$params = array();
			foreach ($this->definitions[$service]->parameters as $k => $v) {
				$params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . NPhpHelpers::dump($v));
			}
			$rm = new NFunctionReflection(create_function(implode(', ', $params), ''));
			$arguments = NDIHelpers::autowireArguments($rm, $arguments, $this);
			return $this->formatPhp('$this->?(?*)', array(NDIContainer::getMethodName($service, FALSE), $arguments), $self);

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

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

		} elseif (!NValidators::isList($entity) || count($entity) !== 2) {
			throw new InvalidStateException("Expected class, method or property, " . NPhpHelpers::dump($entity) . " given.");

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

		} elseif (NStrings::contains($entity[1], '$')) { // property setter
			NValidators::assert($arguments, 'list:1', "setup arguments for '" . NCallback::create($entity) . "'");
			if ($this->getServiceName($entity[0], $self)) {
				return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0]), $self);
			} else {
				return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0]), $self);
			}

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

		} else { // static method
			$arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
			return $this->formatPhp("$entity[0]::$entity[1](?*)", array($arguments), $self);
		}
	}
Example #9
0
	/**
	 * Writes item into the cache.
	 * Dependencies are:
	 * - NCache::PRIORITY => (int) priority
	 * - NCache::EXPIRATION => (timestamp) expiration
	 * - NCache::SLIDING => (bool) use sliding expiration?
	 * - NCache::TAGS => (array) tags
	 * - NCache::FILES => (array|string) file names
	 * - NCache::ITEMS => (array|string) cache items
	 * - NCache::CONSTS => (array|string) cache items
	 *
	 * @param  mixed  key
	 * @param  mixed  value
	 * @param  array  dependencies
	 * @return mixed  value itself
	 * @throws InvalidArgumentException
	 */
	public function save($key, $data, array $dependencies = NULL)
	{
		$this->release();
		$key = $this->generateKey($key);

		if ($data instanceof NCallback || $data instanceof Closure) {
			$this->storage->lock($key);
			$data = NCallback::create($data)->invokeArgs(array(& $dependencies));
		}

		if ($data === NULL) {
			$this->storage->remove($key);
		} else {
			$this->storage->write($key, $data, $this->completeDependencies($dependencies, $data));
			return $data;
		}
	}
Example #10
0
	/**
	 * Calls method using autowiring.
	 * @param  mixed   class, object, function, callable
	 * @param  array   arguments
	 * @return mixed
	 */
	public function callMethod($function, array $args = array())
	{
		$callback = new NCallback($function);
		return $callback->invokeArgs(NDIHelpers::autowireArguments($callback->toReflection(), $args, $this));
	}