protected function createComponent($name) { $class = $this->containerClass; $this[$name] = $container = new $class(); $this->containerFactory->invoke($container, $this->parent); return $container; }
/** * 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); }
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))); } } }
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); }
/** * 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; }
/** * @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); }
/** * @return mixed * @throws MemberAccessException */ public function __call($name, $args) { $class = get_class($this); $isProp = ObjectMixin::hasProperty($class, $name); if ($name === '') { throw new MemberAccessException("Call to class '{$class}' method without name."); } elseif ($isProp === 'event') { // calling event handlers if (is_array($this->{$name}) || $this->{$name} instanceof \Traversable) { foreach ($this->{$name} as $handler) { Callback::invokeArgs($handler, $args); } } elseif ($this->{$name} !== NULL) { throw new UnexpectedValueException("Property {$class}::\${$name} must be array or NULL, " . gettype($this->{$name}) . ' given.'); } } elseif ($isProp && $this->{$name} instanceof \Closure) { // closure in property trigger_error("Invoking closure in property via \$obj->{$name}() is deprecated" . ObjectMixin::getSource(), E_USER_DEPRECATED); return call_user_func_array($this->{$name}, $args); } elseif (($methods =& ObjectMixin::getMethods($class)) && isset($methods[$name]) && is_array($methods[$name])) { // magic @methods trigger_error("Magic methods such as {$class}::{$name}() are deprecated" . ObjectMixin::getSource(), E_USER_DEPRECATED); list($op, $rp, $type) = $methods[$name]; if (count($args) !== ($op === 'get' ? 0 : 1)) { throw new InvalidArgumentException("{$class}::{$name}() expects " . ($op === 'get' ? 'no' : '1') . ' argument, ' . count($args) . ' given.'); } elseif ($type && $args && !ObjectMixin::checkType($args[0], $type)) { throw new InvalidArgumentException("Argument passed to {$class}::{$name}() must be {$type}, " . gettype($args[0]) . ' given.'); } if ($op === 'get') { return $rp->getValue($this); } elseif ($op === 'set') { $rp->setValue($this, $args[0]); } elseif ($op === 'add') { $val = $rp->getValue($this); $val[] = $args[0]; $rp->setValue($this, $val); } return $this; } elseif ($cb = ObjectMixin::getExtensionMethod($class, $name)) { // extension methods trigger_error("Extension methods such as {$class}::{$name}() are deprecated" . ObjectMixin::getSource(), E_USER_DEPRECATED); return Callback::invoke($cb, $this, ...$args); } else { ObjectMixin::strictCall($class, $name); } }
/** @return void */ private function loadData() { if ($this->data === NULL) { if ($this->entity instanceof \Closure) { $factory = $this->entity; } else { $class = $this->entity; $factory = function ($record) use($class) { return new $class($record); }; } $this->data = []; foreach ($this->selection as $row) { $record = $this->refTable === NULL ? $row : $row->ref($this->refTable, $this->refColumn); $this->data[] = NCallback::invoke($factory, $record); } } }
public function fireEvents() { /** @var ObjectForm|UI\Form $this */ if (!($submittedBy = $this->isSubmitted())) { return; } foreach ($this->onReceiveData ?: array() as $handler) { $params = Nette\Utils\Callback::toReflection($handler)->getParameters(); Nette\Utils\Callback::invoke($handler, $this); } $this->validate(); if ($this->object !== NULL) { $this->getObjectMapper()->save($this->object, $this); } if ($submittedBy instanceof Nette\Forms\ISubmitterControl) { if ($this->isValid()) { $submittedBy->onClick($submittedBy); } else { $submittedBy->onInvalidClick($submittedBy); } } if ($this->object !== NULL) { $validateControls = $submittedBy instanceof Nette\Forms\ISubmitterControl ? $submittedBy->getValidationScope() : NULL; if ($validateControls === NULL || count($validateControls) > 0) { $this->getViolationsMapper()->validateContainer($this->object, $this, $validateControls); } } if ($this->onSuccess) { foreach ($this->onSuccess as $handler) { if (!$this->isValid()) { $this->onError($this); break; } $params = Nette\Utils\Callback::toReflection($handler)->getParameters(); $values = isset($params[1]) ? $this->getValues($params[1]->isArray()) : NULL; Nette\Utils\Callback::invoke($handler, $this, $values); } } elseif (!$this->isValid()) { $this->onError($this); } $this->onSubmit($this); }
protected function startup() { $name = $this->getAction(TRUE); if ($this->db->table(self::CRON_TABLE)->where('name = ? AND stop IS NULL', $name)->count() > 0) { $this->terminate(); } $startTime = new DateTime(); $startTime->setTimestamp($_SERVER['REQUEST_TIME']); $row = $this->db->table(self::CRON_TABLE)->insert(array('server' => php_uname('n'), 'name' => $name, 'start' => $startTime)); $table = $this->db->table(self::CRON_TABLE); $callback = function ($result) use($table, $row) { /** @var \Nette\Database\Table\ActiveRow $row */ $row->update(array('stop' => new DateTime(), 'result' => $result, 'time' => round((microtime(TRUE) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000), 'memory' => memory_get_peak_usage(TRUE) / 1024)); }; $this->onShutdown[] = function () use($callback) { Callback::invoke($callback, 'done'); }; $this->application->onError[] = function () use($callback) { Callback::invoke($callback, 'error'); }; parent::startup(); }
public function fireEvents() { $originalOnSuccess = $this->onSuccess; $this->onSuccess = []; $this->onSuccess[] = function () use($originalOnSuccess) { $events = []; $events[] = $this->onBeforeSuccess; $events[] = [function ($form) { if ($this->mapper) { $this->mapper->save($form); } }]; $events[] = $originalOnSuccess; $events[] = $this->onAfterSuccess; try { foreach ($events as $event) { if (!is_array($event) && !$event instanceof \Traversable) { continue; } foreach ($event as $handler) { if (!$this->isValid()) { $this->onError($this); $this->abort(); } \Nette\Utils\Callback::invoke($handler, $this); } } } catch (StopExecutionException $e) { } }; if ($this->mapper && $this->mapper instanceof IValidationMapper) { $this->onValidate[] = [$this->mapper, 'validate']; } parent::fireEvents(); $this->onSuccess = $originalOnSuccess; }
/** * Send markers to template as JSON * @internal */ public function handleMarkers() { foreach ($this->onMarkers as $handler) { $params = Nette\Utils\Callback::toReflection($handler)->getParameters(); Nette\Utils\Callback::invoke($handler, $this, $params); } $this->getPresenter()->sendResponse(new JsonResponse((array) $this->markers)); }
/** * {use class MacroSet} */ public function macroUse(MacroNode $node, PhpWriter $writer) { Nette\Utils\Callback::invoke(array($node->tokenizer->fetchWord(), 'install'), $this->getCompiler())->initialize(); }
/** * __call() implementation. * @param object * @param string * @param array * @return mixed * @throws MemberAccessException */ public static function call($_this, $name, $args) { $class = get_class($_this); $isProp = self::hasProperty($class, $name); if ($name === '') { throw new MemberAccessException("Call to class '{$class}' method without name."); } elseif ($isProp === 'event') { // calling event handlers if (is_array($_this->{$name}) || $_this->{$name} instanceof \Traversable) { foreach ($_this->{$name} as $handler) { Callback::invokeArgs($handler, $args); } } elseif ($_this->{$name} !== NULL) { throw new Nette\UnexpectedValueException("Property {$class}::\${$name} must be array or NULL, " . gettype($_this->{$name}) . ' given.'); } } elseif ($isProp && $_this->{$name} instanceof \Closure) { // closure in property return call_user_func_array($_this->{$name}, $args); } elseif (($methods =& self::getMethods($class)) && isset($methods[$name]) && is_array($methods[$name])) { // magic @methods list($op, $rp, $type) = $methods[$name]; if (count($args) !== ($op === 'get' ? 0 : 1)) { throw new Nette\InvalidArgumentException("{$class}::{$name}() expects " . ($op === 'get' ? 'no' : '1') . ' argument, ' . count($args) . ' given.'); } elseif ($type && $args && !self::checkType($args[0], $type)) { throw new Nette\InvalidArgumentException("Argument passed to {$class}::{$name}() must be {$type}, " . gettype($args[0]) . ' given.'); } if ($op === 'get') { return $rp->getValue($_this); } elseif ($op === 'set') { $rp->setValue($_this, $args[0]); } elseif ($op === 'add') { $val = $rp->getValue($_this); $val[] = $args[0]; $rp->setValue($_this, $val); } return $_this; } elseif ($cb = self::getExtensionMethod($class, $name)) { // extension methods return Callback::invoke($cb, $_this, ...$args); } else { self::strictCall($class, $name, array_keys(self::getExtensionMethods($class))); } }
/** * Sends response to output. * @return void */ public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse) { $httpResponse->setContentType($this->contentType); $httpResponse->setHeader('Content-Disposition', ($this->forceDownload ? 'attachment' : 'inline') . '; filename="' . $this->name . '"'); $output = NULL; if ($this->precalculateFileSize) { ob_start(); Nette\Utils\Callback::invokeArgs($this->outputGenerator); $output = ob_get_clean(); $filesize = $length = strlen($output); } if ($this->resuming && $this->precalculateFileSize) { $httpResponse->setHeader('Accept-Ranges', 'bytes'); if (preg_match('#^bytes=(\\d*)-(\\d*)\\z#', $httpRequest->getHeader('Range'), $matches)) { list(, $start, $end) = $matches; if ($start === '') { $start = max(0, $filesize - $end); $end = $filesize - 1; } elseif ($end === '' || $end > $filesize - 1) { $end = $filesize - 1; } if ($end < $start) { $httpResponse->setCode(416); // requested range not satisfiable return; } $httpResponse->setCode(206); $httpResponse->setHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $filesize); $length = $end - $start + 1; } else { $httpResponse->setHeader('Content-Range', 'bytes 0-' . ($filesize - 1) . '/' . $filesize); } } if ($this->precalculateFileSize) { $httpResponse->setHeader('Content-Length', $length); } if (isset($start)) { echo substr($output, $start, $length); } elseif (isset($output)) { echo $output; } else { Nette\Utils\Callback::invoke($this->outputGenerator); } }
/** * @return void */ public function confirm() { foreach ($this->callbacks as $callback) { Callback::invoke($callback); } }
/** * Mark the start of a transaction block * * @param callable $callback * @throws \Exception|RedisClientException * @throws \Exception * @return mixed */ public function multi($callback = NULL) { $ok = $this->send('multi'); if ($callback === NULL) { return $ok; } try { Callback::invoke($callback, $this); return $this->exec(); } catch (RedisClientException $e) { throw $e; } catch (\Exception $e) { $this->send('discard'); throw $e; } catch (\Throwable $e) { $this->send('discard'); throw $e; } }
/** * @param $data * @param callable $compareCallback */ public function saveIfChanged($data, $compareCallback) { // The file exists if ($this->exists()) { $fromFile = $this->load(); $same = Callback::invoke($compareCallback, $fromFile); // And the create statement is the same if ($same) { echo "No change: {$this->name}<br>\n"; // then do not rewrite this file } else { echo "Updating: <strong>{$this->name}</strong><br>\n"; $this->save($data); } } else { echo "New: <strong>{$this->name}</strong><br>\n"; $this->save($data); } }
/** * Fires submit/click events. * @return void */ public function fireEvents() { if (!$this->isSubmitted()) { return; } elseif (!$this->getErrors()) { $this->validate(); } if ($this->submittedBy instanceof ISubmitterControl) { if ($this->isValid()) { $this->submittedBy->onClick($this->submittedBy); } else { $this->submittedBy->onInvalidClick($this->submittedBy); } } if (!$this->isValid()) { $this->onError($this); } elseif ($this->onSuccess !== NULL) { if (!is_array($this->onSuccess) && !$this->onSuccess instanceof \Traversable) { throw new Nette\UnexpectedValueException('Property Form::$onSuccess must be array or Traversable, ' . gettype($this->onSuccess) . ' given.'); } foreach ($this->onSuccess as $handler) { $params = Nette\Utils\Callback::toReflection($handler)->getParameters(); $values = isset($params[1]) ? $this->getValues($params[1]->isArray()) : NULL; Nette\Utils\Callback::invoke($handler, $this, $values); if (!$this->isValid()) { $this->onError($this); break; } } } $this->onSubmit($this); }
/** * Fires submit/click events. * @return void */ public function fireEvents() { if (!$this->isSubmitted()) { return; } elseif (!$this->getErrors()) { $this->validate(); } if ($this->submittedBy instanceof ISubmitterControl) { if ($this->isValid()) { $this->submittedBy->onClick($this->submittedBy); } else { $this->submittedBy->onInvalidClick($this->submittedBy); } } if ($this->onSuccess) { foreach ($this->onSuccess as $handler) { if (!$this->isValid()) { $this->onError($this); break; } Nette\Utils\Callback::invoke($handler, $this); } } elseif (!$this->isValid()) { $this->onError($this); } $this->onSubmit($this); }
public function __call($name, $args) { if ($callback = Nette\Utils\ObjectMixin::getExtensionMethod(get_class($this), $name)) { return Nette\Utils\Callback::invoke($callback, $this, ...$args); } return parent::__call($name, $args); }
/** * @param int|null $parent * @return mixed */ public function getPages($parent = null) { return Callback::invoke($this->loadCallback, $parent); }
/** * Performs the server side validation. * @param IControl[] * @return void */ public function validate(array $controls = NULL) { foreach ($controls === NULL ? $this->getComponents() : $controls as $control) { $control->validate(); } foreach ($this->onValidate ?: [] as $handler) { $params = Nette\Utils\Callback::toReflection($handler)->getParameters(); $values = isset($params[1]) ? $this->getValues($params[1]->isArray()) : NULL; Nette\Utils\Callback::invoke($handler, $this, $values); } $this->validated = TRUE; }
/** * @param string $parent * @param string $name * @param mixed $container * @param \Closure|NULL $factory * @return bool does container already exist? */ protected function lazyCreateContainer($parent, $name, &$container = NULL, \Closure $factory = NULL) { !isset($this[$parent]) && $this->addContainer($parent); if (!isset($this[$parent][$name])) { if ($factory !== NULL) { $subc = NCallback::invoke($factory); if (!$subc instanceof Nette\Forms\Container) { $type = gettype($subc); throw new Nette\InvalidArgumentException("Filter factory is expected to return Nette\\Forms\\Container, '" . ($type === 'object' ? get_class($subc) : $type) . "' given."); } $this[$parent][$name] = $subc; } else { $this[$parent]->addContainer($name); } $created = TRUE; } $container = $this[$parent][$name]; return !isset($created); }
/** * Call a template run-time helper. Do not call directly. * @param string helper name * @param array arguments * @return mixed */ public function __call($name, $args) { $lname = strtolower($name); if (!isset($this->helpers[$lname])) { foreach ($this->helperLoaders as $loader) { $helper = Callback::invoke($loader, $lname); if ($helper) { $this->registerHelper($lname, $helper); return Callback::invokeArgs($this->helpers[$lname], $args); } } return parent::__call($name, $args); } return Callback::invokeArgs($this->helpers[$lname], $args); }
public function createComponentForm() { $form = new UI\Form(); if ($this->filterFormFactory) { $form['filter'] = Callback::invoke($this->filterFormFactory); if (!isset($form['filter']['filter'])) { $form['filter']->addSubmit('filter', $this->translate('Filter')); } if (!isset($form['filter']['cancel'])) { $form['filter']->addSubmit('cancel', $this->translate('Cancel')); } $this->filterDefaults = array(); foreach ($form['filter']->controls as $name => $control) { $this->filterDefaults[$name] = $control->getValue(); } $this->filterDefaults = $this->filterFormFilter($this->filterDefaults); if (!$this->filterDataSource) { $this->filterDataSource = $this->filterDefaults; } } if ($this->editFormFactory && ($this->editRowKey !== NULL || !empty($_POST['edit']))) { $data = $this->editRowKey !== NULL && empty($_POST) ? $this->getData($this->editRowKey) : NULL; $form['edit'] = Callback::invokeArgs($this->editFormFactory, array($data)); if (!isset($form['edit']['save'])) { $form['edit']->addSubmit('save', 'Save'); } if (!isset($form['edit']['cancel'])) { $form['edit']->addSubmit('cancel', 'Cancel'); } if (!isset($form['edit'][$this->rowPrimaryKey])) { $form['edit']->addHidden($this->rowPrimaryKey); } $form['edit'][$this->rowPrimaryKey]->setDefaultValue($this->editRowKey)->setOption('rendered', TRUE); } if ($this->translator) { $form->setTranslator($this->translator); } // Actions if (count($this->actions) > 0) { $items = array(); foreach ($this->actions as $action) { $items[$action->getName()] = $action->getCaption(); } $form->addSelect('_action', 'Action', $items)->setPrompt($this->actionPrompt); $form->addSubmit('_do_action', 'Do'); } $form->onSuccess[] = function () { }; // fix for Nette Framework 2.0.x $form->onSubmit[] = $this->processForm; return $form; }
/** * @param mixed $record * @return void */ public function invoke($record) { return NCallback::invoke($this->callback, $record); }
/** * Creates repository importer from url. * * @param string|\Nette\Http\Url * @return IAddonImporter * @throws \NetteAddons\NotSupportedException */ public function createFromUrl($url) { $url = (string) $url; if (($name = static::getIdByUrl($url)) != NULL) { return Callback::invoke($this->factories[$name], $url); } else { throw new \NetteAddons\NotSupportedException('We support only ' . $this->getNames() . '.'); } }
/** * Performs the server side validation. * @param IControl[] * @return void */ public function validate(array $controls = NULL) { foreach ($controls === NULL ? $this->getComponents() : $controls as $control) { $control->validate(); } if ($this->onValidate !== NULL) { if (!is_array($this->onValidate) && !$this->onValidate instanceof \Traversable) { throw new Nette\UnexpectedValueException('Property Form::$onValidate must be array or Traversable, ' . gettype($this->onValidate) . ' given.'); } foreach ($this->onValidate as $handler) { $params = Nette\Utils\Callback::toReflection($handler)->getParameters(); $values = isset($params[1]) ? $this->getValues($params[1]->isArray()) : NULL; Nette\Utils\Callback::invoke($handler, $this, $values); } } $this->validated = TRUE; }
/** * Returns the rule type associated with the specified Resource, Role, and privilege. * @param string|Permission::ALL * @param string|Permission::ALL * @param string|Permission::ALL * @return mixed NULL if a rule does not exist or assertion fails, otherwise returns ALLOW or DENY */ private function getRuleType($resource, $role, $privilege) { if (!($rules = $this->getRules($resource, $role))) { return NULL; } if ($privilege === self::ALL) { if (isset($rules['allPrivileges'])) { $rule = $rules['allPrivileges']; } else { return NULL; } } elseif (!isset($rules['byPrivilege'][$privilege])) { return NULL; } else { $rule = $rules['byPrivilege'][$privilege]; } if ($rule['assert'] === NULL || Nette\Utils\Callback::invoke($rule['assert'], $this, $role, $resource, $privilege)) { return $rule['type']; } elseif ($resource !== self::ALL || $role !== self::ALL || $privilege !== self::ALL) { return NULL; } elseif (self::ALLOW === $rule['type']) { return self::DENY; } else { return self::ALLOW; } }