Inheritance: use trait Nette\StaticClass
Example #1
0
 /**
  * @return array
  */
 public static function exportRules(Rules $rules, $json = TRUE)
 {
     $payload = array();
     foreach ($rules as $rule) {
         if (!is_string($op = $rule->validator)) {
             if (!Nette\Utils\Callback::isStatic($op)) {
                 continue;
             }
             $op = Nette\Utils\Callback::toString($op);
         }
         if ($rule->branch) {
             $item = array('op' => ($rule->isNegative ? '~' : '') . $op, 'rules' => static::exportRules($rule->branch, FALSE), 'control' => $rule->control->getHtmlName());
             if ($rule->branch->getToggles()) {
                 $item['toggle'] = $rule->branch->getToggles();
             }
         } else {
             $item = array('op' => ($rule->isNegative ? '~' : '') . $op, 'msg' => Validator::formatMessage($rule, FALSE));
         }
         if (is_array($rule->arg)) {
             foreach ($rule->arg as $key => $value) {
                 $item['arg'][$key] = $value instanceof IControl ? array('control' => $value->getHtmlName()) : $value;
             }
         } elseif ($rule->arg !== NULL) {
             $item['arg'] = $rule->arg instanceof IControl ? array('control' => $rule->arg->getHtmlName()) : $rule->arg;
         }
         $payload[] = $item;
     }
     return $json ? $payload ? Nette\Utils\Json::encode($payload) : NULL : $payload;
 }
 /**
  * @param AbstractRequest $request
  * @return AbstractResponse
  * @throws DispatcherException
  */
 public function dispatch(AbstractRequest $request)
 {
     switch ($request->getType()) {
         case AbstractRequest::TYPE_CONFIRM:
             if (!$this->confirmCallback) {
                 throw new DispatcherException("Dispatcher: Confirm callback is not defined.");
             }
             $res = Callback::invokeArgs($this->confirmCallback, [$request, $this->prepareConfirmResponse()]);
             if (!$res instanceof ConfirmResponse) {
                 throw new DispatcherException('Return value from callback is not ConfirmResponse type.');
             }
             return $res;
         case AbstractRequest::TYPE_SMS:
             if (!$this->smsCallback) {
                 throw new DispatcherException("Dispatcher: Info callback is not defined.");
             }
             $res = Callback::invokeArgs($this->smsCallback, [$request, $this->prepareResponse()]);
             if (!$res instanceof Response) {
                 throw new DispatcherException('Return value from callback is not Response type.');
             }
             return $res;
         default:
             throw new DispatcherException("Dispatcher: Uknown request type.");
     }
 }
 protected function createComponent($name)
 {
     $class = $this->containerClass;
     $this[$name] = $container = new $class();
     $this->containerFactory->invoke($container, $this->parent);
     return $container;
 }
Example #4
0
 /**
  * @param string   $name
  * @param string   $caption
  * @param callable $callback
  */
 public function __construct($name, $caption, $callback)
 {
     $this->name = $name;
     $this->caption = $caption;
     Callback::check($callback);
     $this->callback = $callback;
 }
Example #5
0
 /**
  * @param string $mask example images/<format>/<month>/<image>
  * @param IImageCallback $presenterCallback
  * @return Route
  */
 public static function createRouter($mask, IImageCallback $presenterCallback)
 {
     $filterIn = function ($params) {
         if ($params['presenter'] != 'Nette:Micro' || !isset($params['image']) || !isset($params['format'])) {
             return NULL;
         }
         return $params;
     };
     $filterOut = function ($params) use($mask) {
         if ($params['presenter'] != 'Nette:Micro' || !isset($params['image']) || !isset($params['format'])) {
             return NULL;
         }
         if ($params['image'] instanceof IFile) {
             $image = $params['image'];
             /* @var $file IFile */
             $params['image'] = $image->getName() . '.' . $image->getExt();
             if (preg_match('/<month>/', $mask)) {
                 $params['month'] = $image->getUploaded()->format('Ym');
             }
         }
         if ($params['format'] instanceof IImageFormat) {
             $params['format'] = $params['format']->getName();
         }
         return $params;
     };
     $callback = function ($image, $format) use($presenterCallback) {
         return \Nette\Utils\Callback::invokeArgs($presenterCallback, [$image, $format]);
     };
     $route = new Route($mask, [Route::PRESENTER_KEY => 'Nette:Micro', 'callback' => $callback, NULL => [Route::FILTER_IN => $filterIn, Route::FILTER_OUT => $filterOut]]);
     return $route;
 }
Example #6
0
 public function handleAutocomplete($q)
 {
     if (!$this->callback) {
         throw new Nette\InvalidStateException('Undefined Typehad callback.');
     }
     $this->getPresenter()->sendJson(Nette\Utils\Callback::invokeArgs($this->callback, [$q]));
 }
Example #7
0
 public function formatValue($row)
 {
     if ($this->callback) {
         return Callback::invokeArgs($this->callback, [$row, $this]);
     }
     return $this->getChainedValue($row);
 }
Example #8
0
 public function getBodyContent($data)
 {
     if (array_key_exists(self::CALLBACK, $this->option) === FALSE) {
         if (isset($data[$this->option[self::ID]]) === FALSE && is_null($data[$this->option[self::ID]]) === FALSE) {
             throw new Grid_Exception('Column ' . $this->option[self::ID] . ' does not exists in DataSource.');
         }
         $src = $data[$this->option[self::ID]];
     } else {
         $args = array($data);
         if (isset($this->option[self::CALLBACK_ARGS])) {
             if (!is_array($this->option[self::CALLBACK_ARGS])) {
                 throw new Grid_Exception(__CLASS__ . '::CALLBACK_ARGS must be an array. ' . gettype($this->option[self::CALLBACK_ARGS]) . ' given.');
             }
             $args = array_merge($args, $this->option[self::CALLBACK_ARGS]);
         }
         $src = Callback::invokeArgs($this->option[self::CALLBACK], $args);
     }
     $img = Html::el('img', array('src' => $src));
     if (isset($this->option[self::MAX_WIDTH]) === TRUE) {
         $img->style('max-width:' . $this->fixPixels($this->option[self::MAX_WIDTH]), TRUE);
     }
     if (isset($this->option[self::MAX_HEIGHT]) === TRUE) {
         $img->style('max-height:' . $this->fixPixels($this->option[self::MAX_HEIGHT]), TRUE);
     }
     return $img;
 }
Example #9
0
 /**
  * @param Container $container
  * @param array $callbacks [optional]
  */
 public function __construct(Container $container, $callbacks = [])
 {
     $this->container = $container;
     /** @var $httpRequest Request */
     $request = $container->getService("httpRequest");
     // Determine production/development mode
     $this->active = !Debugger::$productionMode;
     // # Clean cache
     $this->callbacks["cache"] = ['name' => "Clear cache", 'callback' => Callback::closure($this, "clearCache"), 'args' => [[Cache::ALL => TRUE]]];
     // # Clean session
     $this->callbacks["session"] = ['name' => "Clear session", 'callback' => Callback::closure($this, "clearSession"), 'args' => []];
     // # Clean logs
     $this->callbacks["logs"] = ['name' => "Clear logs", 'callback' => Callback::closure($this, "clearLogs"), 'args' => [[Cache::ALL => TRUE]]];
     // Merge custom callbacks
     $this->callbacks = array_merge($this->callbacks, $callbacks);
     // Check signal receiver
     if ($this->active && ($cb = $request->getQuery("callback-do", FALSE))) {
         if ($cb === "all") {
             $this->onCallbacksCall();
             $this->invokeCallbacks();
         } else {
             $this->onCallbackCall($cb);
             $this->invokeCallback($cb);
         }
     }
 }
Example #10
0
 /**
  * Filter data
  * @param array $filters
  * @return static
  */
 public function filter(array $filters)
 {
     foreach ($filters as $filter) {
         if ($filter->isValueSet()) {
             if ($filter->hasConditionCallback()) {
                 Callback::invokeArgs($filter->getConditionCallback(), [$this->data_source, $filter->getValue()]);
             } else {
                 if ($filter instanceof Filter\FilterText) {
                     $this->applyFilterText($filter);
                 } else {
                     if ($filter instanceof Filter\FilterMultiSelect) {
                         $this->applyFilterMultiSelect($filter);
                     } else {
                         if ($filter instanceof Filter\FilterSelect) {
                             $this->applyFilterSelect($filter);
                         } else {
                             if ($filter instanceof Filter\FilterDate) {
                                 $this->applyFilterDate($filter);
                             } else {
                                 if ($filter instanceof Filter\FilterDateRange) {
                                     $this->applyFilterDateRange($filter);
                                 } else {
                                     if ($filter instanceof Filter\FilterRange) {
                                         $this->applyFilterRange($filter);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $this;
 }
Example #11
0
 public function addCallbackItem($name, $description, $callback)
 {
     $this->check($name);
     Callback::check($callback);
     $item = new CallbackItem($this, $name, $description, $callback);
     $this->items[$name] = $item;
     return $item;
 }
Example #12
0
 /**
  * Allows calling $column->icon() instead of $column->setIcon (Same for title, class, ...)
  * @param  string $name
  * @param  array  $args
  * @return mixed
  */
 public function __call($name, $args)
 {
     $method_setter = 'set' . ucfirst($name);
     if (method_exists($this, $method_setter)) {
         return Nette\Utils\Callback::invokeArgs([$this, $method_setter], $args);
     }
     parent::__call($name, $args);
 }
Example #13
0
 public function __call($name, $args)
 {
     if (isset($this->methods[strtolower($name)])) {
         return Callback::invokeArgs($this->methods[strtolower($name)], $args);
     } else {
         return parent::__call($name, $args);
     }
 }
Example #14
0
 /**
  * Returns final link for button or null.
  *
  * @param $row
  *
  * @return string|null
  */
 public function getLink($row)
 {
     if (!empty($this->linkCallback)) {
         return Callback::invokeArgs($this->linkCallback, [$row]);
     } else {
         return null;
     }
 }
Example #15
0
 /**
  * Denies one or more Roles access to [certain $privileges upon] the specified Resource(s).
  * If $assertion is provided, then it must return TRUE in order for rule to apply.
  *
  * @param string|array|Permission::ALL $roles
  * @param string|array|Permission::ALL $resources
  * @param string|array|Permission::ALL $privileges
  * @param callable $assertion
  * @return self
  */
 public function deny($roles = self::ALL, $resources = self::ALL, $privileges = self::ALL, $assertion = null)
 {
     if ($assertion !== null) {
         $assertion = function () use($assertion) {
             return Callback::invoke($assertion, $this->identity, $this->getQueriedResource(), $this->getQueriedRole());
         };
     }
     return parent::deny($roles, $resources, $privileges, $assertion);
 }
Example #16
0
 public function validate(array $controls = NULL)
 {
     foreach ($this->beforeValidate ?: [] as $handler) {
         $params = Callback::toReflection($handler)->getParameters();
         $values = isset($params[1]) ? $this->getValues($params[1]->isArray()) : NULL;
         $this->values = Callback::invoke($handler, $this, $values);
     }
     parent::validate($controls);
 }
 private function loadRows()
 {
     if (is_callable($this->rows)) {
         $this->rows = Callback::invoke($this->rows);
         if (!is_array($this->rows)) {
             throw new \Nette\InvalidStateException(sprintf('Rows must be array of values or callable array source, %s given.', gettype($this->rows)));
         }
     }
 }
Example #18
0
 /**
  * @param $params
  * @throws \Nette\InvalidStateException
  */
 public function handleRemote($params)
 {
     if (!is_callable($this->remote)) {
         throw new Nette\InvalidStateException('Undefined Typehad callback.');
     }
     $q = array_key_exists('q', $params) ? $params['q'] : NULL;
     // call remote function with displayed key and query
     $this->presenter->sendJson(Nette\Utils\Callback::invokeArgs($this->remote, [$this->display, $q]));
 }
 public function setQueues(array $queues)
 {
     $this->queues = array();
     foreach ($queues as $name => $queue) {
         if (!isset($queue['callback'])) {
             throw new InvalidArgumentException("The queue '{$name}' is missing a callback.");
         }
         Callback::check($queue['callback']);
         $this->queues[$name] = $queue;
     }
 }
Example #20
0
 /**
  * Get throw getter
  *
  * @param string $propertyName
  * @param object $entity
  * @return null
  */
 protected function invokeGetter($propertyName, $entity)
 {
     $getterName = ['get' . ucfirst($propertyName), 'is' . ucfirst($propertyName)];
     $value = NULL;
     foreach ($getterName as $getter) {
         if (method_exists($entity, $getter) && $value === NULL) {
             $value = Callback::invoke([$entity, $getter]);
         }
     }
     return $value;
 }
Example #21
0
 public function getCount($filter, $order)
 {
     if (!isset($this->limit)) {
         throw new InvalidStateException('Property limit must be set.');
     }
     if (!isset($this->offset)) {
         throw new InvalidStateException('Property offset must be set.');
     }
     $selection = Callback::invokeArgs($this->callback, [$filter, $order]);
     return $selection->count();
 }
Example #22
0
 public function formatValue($row)
 {
     if ($this->callback) {
         return Callback::invokeArgs($this->callback, [$row, $this]);
     }
     $value = $this->getChainedValue($row);
     if (!is_numeric($value)) {
         $type = is_object($value) ? get_class($value) : gettype($value);
         throw new InvalidTypeException("Expected numeric value, but  '{$type}' given from '{$this->getName()}'");
     }
     return number_format($value, $this->precision, $this->decimalSeparator, $this->thousandSeparator);
 }
Example #23
0
 public function getBodyContent($data)
 {
     if (array_key_exists(self::CALLBACK, $this->option) === FALSE) {
         $this->checkColumnId($data);
         return $data[$this->option[self::ID]];
     } else {
         $args = array($data);
         if (isset($this->option[self::CALLBACK_ARGS]) && is_array($this->option[self::CALLBACK_ARGS])) {
             $args = array_merge($args, $this->option[self::CALLBACK_ARGS]);
         }
         return Callback::invokeArgs($this->option[self::CALLBACK], $args);
     }
 }
Example #24
0
 public function getBodyContent($data)
 {
     $template = $this->getTemplate();
     if (array_key_exists(self::CALLBACK, $this->option)) {
         Callback::check($this->option[self::CALLBACK]);
         $args = array($data, $template);
         if (isset($this->option[self::CALLBACK_ARGS]) && is_array($this->option[self::CALLBACK_ARGS])) {
             $args = array_merge($args, $this->option[self::CALLBACK_ARGS]);
         }
         Callback::invokeArgs($this->option[self::CALLBACK], $args);
     }
     return trim($template);
 }
Example #25
0
 /**
  * @return mixed
  */
 public function getEntity()
 {
     if ($this->entity == NULL) {
         if ($this->entityFactory == NULL) {
             throw new InvalidStateException('Undefined entity factory.');
         }
         $this->entity = Callback::invokeArgs($this->entityFactory, [$this]);
         if (!is_object($this->entity)) {
             throw new InvalidStateException('Entity factory has to return an object.');
         }
     }
     return $this->entity;
 }
Example #26
0
 /**
  * Renders HTML code for custom panel.
  * @return string
  */
 public function getPanel()
 {
     if (!$this->resources) {
         return null;
     }
     $esc = \Nette\Utils\Callback::closure('Latte\\Runtime\\Filters::escapeHtml');
     $click = function ($o, $c = false) {
         return \Tracy\Dumper::toHtml($o, ['collapse' => $c]);
     };
     ob_start();
     include __DIR__ . '/panel.phtml';
     return ob_get_clean();
 }
Example #27
0
	/**
	 * @return Nette\Application\IResponse
	 */
	public function run(Application\Request $request)
	{
		$this->request = $request;

		if ($this->httpRequest && $this->router && !$this->httpRequest->isAjax() && ($request->isMethod('get') || $request->isMethod('head'))) {
			$refUrl = clone $this->httpRequest->getUrl();
			$url = $this->router->constructUrl($request, $refUrl->setPath($refUrl->getScriptPath()));
			if ($url !== NULL && !$this->httpRequest->getUrl()->isEqual($url)) {
				return new Responses\RedirectResponse($url, Http\IResponse::S301_MOVED_PERMANENTLY);
			}
		}

		$params = $request->getParameters();
		if (!isset($params['callback'])) {
			throw new Application\BadRequestException('Parameter callback is missing.');
		}
		$params['presenter'] = $this;
		$callback = $params['callback'];
		$reflection = Nette\Utils\Callback::toReflection(Nette\Utils\Callback::check($callback));
		$params = Application\UI\PresenterComponentReflection::combineArgs($reflection, $params);

		if ($this->context) {
			foreach ($reflection->getParameters() as $param) {
				if ($param->getClassName()) {
					unset($params[$param->getPosition()]);
				}
			}

			$params = Nette\DI\Helpers::autowireArguments($reflection, $params, $this->context);
			$params['presenter'] = $this;
		}

		$response = call_user_func_array($callback, $params);

		if (is_string($response)) {
			$response = array($response, array());
		}
		if (is_array($response)) {
			list($templateSource, $templateParams) = $response;
			$response = $this->createTemplate()->setParameters($templateParams);
			if (!$templateSource instanceof \SplFileInfo) {
				$response->getLatte()->setLoader(new Latte\Loaders\StringLoader);
			}
			$response->setFile($templateSource);
		}
		if ($response instanceof Application\UI\ITemplate) {
			return new Responses\TextResponse($response);
		} else {
			return $response;
		}
	}
 /**
  * @param  mixed   class, object, callable
  * @param  string  method
  * @return \Closure
  */
 public static function closure($callable, $m = NULL)
 {
     if ($m !== NULL) {
         $callable = array($callable, $m);
     } elseif ($callable instanceof \Closure) {
         return $callable;
     }
     self::check($callable, TRUE);
     $_callable_ = $callable;
     return function () use($_callable_) {
         Callback::check($_callable_);
         return call_user_func_array($_callable_, func_get_args());
     };
 }
Example #29
0
 public function __construct(IContainer $parent, $name, $description = NULL, $component = NULL)
 {
     parent::__construct($parent, $name, $description);
     $i = 0;
     while ($i <= (is_null($this->page_limit) ? self::DEFAULT_COUNT : $this->page_limit)) {
         if (!$component instanceof IContainer) {
             Callback::invokeArgs($component, array($this->parent->getParent(), $name . $i));
         } else {
             $this->parent->getParent()->addComponent($component, $name . $i);
         }
         $this->keys[] = $i;
         $i++;
     }
 }
Example #30
0
 /**
  * @param \Nette\Application\UI\Form $form
  * @param callable $resetLinkCallback
  */
 protected function save(Form $form, $resetLinkCallback)
 {
     /** @var \Venne\Security\User $user */
     $user = $this->userRepository->findOneBy(array('email' => $form['email']->value));
     if (!$user) {
         $form->addError($form->getTranslator()->translate('User with email %email% does not exist.', null, array('email' => $form['email']->value)));
         return;
     }
     $key = $user->resetPassword();
     $url = Callback::invoke($resetLinkCallback, $key);
     $this->entityManager->persist($user);
     $this->entityManager->flush($user);
     $this->securityManager->sendRecoveryUrl($user, $url);
 }