/** * {@inheritdoc} */ protected function transfer() { while (!$this->stopped && !$this->source->isConsumed()) { if ($this->source->getContentLength() && $this->source->isSeekable()) { // If the stream is seekable and the Content-Length known, then stream from the data source $body = new ReadLimitEntityBody($this->source, $this->partSize, $this->source->ftell()); } else { // We need to read the data source into a temporary buffer before streaming $body = EntityBody::factory(); while ($body->getContentLength() < $this->partSize && $body->write($this->source->read(max(1, min(10 * Size::KB, $this->partSize - $body->getContentLength()))))) { } } // @codeCoverageIgnoreStart if ($body->getContentLength() == 0) { break; } // @codeCoverageIgnoreEnd $params = $this->state->getUploadId()->toParams(); $command = $this->client->getCommand('UploadPart', array_replace($params, array('PartNumber' => count($this->state) + 1, 'Body' => $body, 'ContentMD5' => (bool) $this->options['part_md5'], Ua::OPTION => Ua::MULTIPART_UPLOAD))); // Notify observers that the part is about to be uploaded $eventData = $this->getEventData(); $eventData['command'] = $command; $this->dispatch(self::BEFORE_PART_UPLOAD, $eventData); // Allow listeners to stop the transfer if needed if ($this->stopped) { break; } $response = $command->getResponse(); $this->state->addPart(UploadPart::fromArray(array('PartNumber' => count($this->state) + 1, 'ETag' => $response->getHeader('ETag', true), 'Size' => $body->getContentLength(), 'LastModified' => gmdate(DateFormat::RFC2822)))); // Notify observers that the part was uploaded $this->dispatch(self::AFTER_PART_UPLOAD, $eventData); } }
/** * Create new container * * @param array $values The parameters or objects. */ public function __construct(array $values = []) { // Initialize container for Slim and Pimple parent::__construct($values); $this['config'] = isset($values['config']) ? $values['config'] : []; if (!isset($container['provider/factory'])) { $this['provider/factory'] = function (Container $container) { return new Factory(['base_class' => ServiceProviderInterface::class, 'resolver_options' => ['suffix' => 'ServiceProvider']]); }; } $defaults = ['charcoal/app/service-provider/app' => [], 'charcoal/app/service-provider/cache' => [], 'charcoal/app/service-provider/database' => [], 'charcoal/app/service-provider/logger' => [], 'charcoal/app/service-provider/translator' => [], 'charcoal/app/service-provider/view' => []]; if (!empty($this['config']['service_providers'])) { $providers = array_replace($defaults, $this['config']['service_providers']); } else { $providers = $defaults; } foreach ($providers as $provider => $values) { if (false === $values) { continue; } if (!is_array($values)) { $values = []; } $provider = $this['provider/factory']->get($provider); $this->register($provider, $values); } }
/** * Executing curl request * @param array $additionalOptions * @return mixed */ protected function executeRequest(array $additionalOptions) { $cookiesPath = __DIR__ . DIRECTORY_SEPARATOR . self::COOKIES_FILE_NAME; $options = array_replace([CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEFILE => $cookiesPath, CURLOPT_COOKIEJAR => $cookiesPath], $additionalOptions); curl_setopt_array($this->ch, $options); return curl_exec($this->ch); }
public function setOptions($optionsGiven) { $options = array_replace($this->getDefaults(), $optionsGiven); $this->angle = $options["angle"]; $this->rotationPoint = $options["rotationPoint"]; $this->layer = $options["layer"]; }
public function preBind(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); $data = array_replace($this->unbind($form), $data ?: array()); $event->setData($data); }
public function match($pathinfo) { $allow = array(); $pathinfo = rawurldecode($pathinfo); $context = $this->context; $request = $this->request; if (0 === strpos($pathinfo, '/blog')) { // cl_blog_home if (preg_match('#^/blog(?:/(?P<page>\\d*))?$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'cl_blog_home')), array('_controller' => 'CL\\BlogBundle\\Controller\\AdvertController::indexAction', 'page' => 1)); } if (0 === strpos($pathinfo, '/blog/ad')) { // cl_blog_view if (0 === strpos($pathinfo, '/blog/advert') && preg_match('#^/blog/advert/(?P<id>\\d+)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'cl_blog_view')), array('_controller' => 'CL\\BlogBundle\\Controller\\AdvertController::viewAction')); } // cl_blog_add if ($pathinfo === '/blog/add') { return array('_controller' => 'CL\\BlogBundle\\Controller\\AdvertController::addAction', '_route' => 'cl_blog_add'); } } // cl_blog_edit if (0 === strpos($pathinfo, '/blog/edit') && preg_match('#^/blog/edit/(?P<id>\\d+)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'cl_blog_edit')), array('_controller' => 'CL\\BlogBundle\\Controller\\AdvertController::editAction')); } // cl_blog_delete if (0 === strpos($pathinfo, '/blog/delete') && preg_match('#^/blog/delete/(?P<id>\\d+)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'cl_blog_delete')), array('_controller' => 'CL\\BlogBundle\\Controller\\AdvertController::deleteAction')); } } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); }
private static function create($uri, $method = 'GET', $server = array()) { $server = array_replace(array('SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'HTTP_HOST' => 'localhost', 'HTTP_USER_AGENT' => 'PHP-routing request', 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5', 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'REMOTE_ADDR' => '127.0.0.1', 'SCRIPT_NAME' => '', 'SCRIPT_FILENAME' => '', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'REQUEST_TIME' => time()), $server); $server['REQUEST_URI'] = $uri; $server['PATH_INFO'] = ''; $server['REQUEST_METHOD'] = strtoupper($method); $components = parse_url($uri); if (isset($components['host'])) { $server['SERVER_NAME'] = $components['host']; $server['HTTP_HOST'] = $components['host']; } if (isset($components['scheme'])) { if ('https' === $components['scheme']) { $server['HTTPS'] = 'on'; $server['SERVER_PORT'] = 443; } else { unset($server['HTTPS']); $server['SERVER_PORT'] = 80; } } if (isset($components['port'])) { $server['SERVER_PORT'] = $components['port']; $server['HTTP_HOST'] = $server['HTTP_HOST'] . ':' . $components['port']; } if (isset($components['user'])) { $server['PHP_AUTH_USER'] = $components['user']; } if (isset($components['pass'])) { $server['PHP_AUTH_PW'] = $components['pass']; } return new \Routing\Request($server); }
/** * 格式化表单校验消息,并进行json数组化预处理 * * @param array $messages 未格式化之前数组 * @param array $json 原始json数组数据 * @return array */ function format_json_message($messages, $json) { $reason = format_message($messages); $info = '失败原因为:' . $reason; $json = array_replace($json, ['info' => $info]); return $json; }
/** * return token string * * @param string[] $token detected handlebars {{ }} token * @param string[]|null $merge list of token strings to be merged * * @return string Return whole token * * @expect 'c' when input array(0, 'a', 'b', 'c', 'd', 'e') * @expect 'cd' when input array(0, 'a', 'b', 'c', 'd', 'e', 'f') * @expect 'qd' when input array(0, 'a', 'b', 'c', 'd', 'e', 'f'), array(3 => 'q') */ public static function toString($token, $merge = null) { if (is_array($merge)) { $token = array_replace($token, $merge); } return implode('', array_slice($token, 3, -2)); }
public function register(Application $app) { $app['task-manager.logger'] = $app->share(function (Application $app) { $logger = new $app['monolog.logger.class']('task-manager logger'); $logger->pushHandler(new NullHandler()); return $logger; }); $app['task-manager'] = $app->share(function (Application $app) { $options = $app['task-manager.listener.options']; $manager = TaskManager::create($app['dispatcher'], $app['task-manager.logger'], $app['task-manager.task-list'], ['listener_protocol' => $options['protocol'], 'listener_host' => $options['host'], 'listener_port' => $options['port'], 'tick_period' => 1]); $manager->addSubscriber($app['ws.task-manager.broadcaster']); return $manager; }); $app['task-manager.logger.configuration'] = $app->share(function (Application $app) { $conf = array_replace(['enabled' => true, 'level' => 'INFO', 'max-files' => 10], $app['conf']->get(['main', 'task-manager', 'logger'], [])); $conf['level'] = defined('Monolog\\Logger::' . $conf['level']) ? constant('Monolog\\Logger::' . $conf['level']) : Logger::INFO; return $conf; }); $app['task-manager.task-list'] = $app->share(function (Application $app) { $conf = $app['conf']->get(['registry', 'executables', 'php-conf-path']); $finder = new PhpExecutableFinder(); $php = $finder->find(); return new TaskList($app['EM']->getRepository('Phraseanet:Task'), $app['root.path'], $php, $conf); }); }
/** * {@inheritdoc} */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, array('allow_add' => $options['allow_add'], 'allow_delete' => $options['allow_delete'])); if ($form->getConfig()->hasAttribute('prototype')) { $view->vars['prototype'] = $form->getConfig()->getAttribute('prototype')->createView($view); } }
public function buildView(TableView $view, TableInterface $table, array $options) { parent::buildView($view, $table, $options); $view->vars['responsive'] = $options['responsive']; $view->vars['attr'] = array('class' => $this->getElementClass($options)); $view->vars = array_replace($view->vars, array('value' => $table->getViewData(), 'data' => $table->getNormData())); }
/** * {@inheritDoc} */ public function createConfig(array $config = array()) { $config = ArrayObject::ensureArrayObject($config); $config->defaults($this->defaultConfig); $config->defaults(array('payum.template.layout' => '@PayumCore/layout.html.twig', 'payum.http_client' => HttpClientFactory::create(), 'guzzle.client' => HttpClientFactory::createGuzzle(), 'twig.env' => function (ArrayObject $config) { $loader = new \Twig_Loader_Filesystem(); foreach ($config['payum.paths'] as $namespace => $path) { $loader->addPath($path, $namespace); } return new \Twig_Environment($loader); }, 'payum.action.get_http_request' => new GetHttpRequestAction(), 'payum.action.capture_payment' => new CapturePaymentAction(), 'payum.action.execute_same_request_with_model_details' => new ExecuteSameRequestWithModelDetailsAction(), 'payum.action.render_template' => function (ArrayObject $config) { return new RenderTemplateAction($config['twig.env'], $config['payum.template.layout']); }, 'payum.extension.endless_cycle_detector' => new EndlessCycleDetectorExtension(), 'payum.action.get_currency' => function (ArrayObject $config) { return new GetCurrencyAction($config['payum.iso4217']); }, 'payum.prepend_actions' => array(), 'payum.prepend_extensions' => array(), 'payum.prepend_apis' => array(), 'payum.default_options' => array(), 'payum.required_options' => array(), 'payum.api.http_client' => function (ArrayObject $config) { return $config['payum.http_client']; }, 'payum.security.token_storage' => null)); if ($config['payum.security.token_storage']) { $config['payum.action.get_token'] = function (ArrayObject $config) { return new GetTokenAction($config['payum.security.token_storage']); }; } $config['payum.paths'] = array_replace(['PayumCore' => __DIR__ . '/Resources/views'], $config['payum.paths'] ?: []); return (array) $config; }
/** * {@inheritdoc} * * Override of CsvWriter flush method to use the file buffer */ public function flush() { if (!is_file($this->bufferFile)) { return; } $exportDirectory = dirname($this->getPath()); if (!is_dir($exportDirectory)) { $this->localFs->mkdir($exportDirectory); } $this->writtenFiles[$this->getPath()] = basename($this->getPath()); if (false === ($csvFile = fopen($this->getPath(), 'w'))) { throw new RuntimeErrorException('Failed to open file %path%', ['%path%' => $this->getPath()]); } $header = $this->isWithHeader() ? $this->headers : []; if (false === fputcsv($csvFile, $header, $this->delimiter)) { throw new RuntimeErrorException('Failed to write to file %path%', ['%path%' => $this->getPath()]); } $bufferHandle = fopen($this->bufferFile, 'r'); $hollowProduct = array_fill_keys($this->headers, ''); while (null !== ($bufferedProduct = $this->readProductFromBuffer($bufferHandle))) { $fullProduct = array_replace($hollowProduct, $bufferedProduct); if (false === fputcsv($csvFile, $fullProduct, $this->delimiter, $this->enclosure)) { throw new RuntimeErrorException('Failed to write to file %path%', ['%path%' => $this->getPath()]); } elseif (null !== $this->stepExecution) { $this->stepExecution->incrementSummaryInfo('write'); } } fclose($bufferHandle); unlink($this->bufferFile); fclose($csvFile); }
/** * {@inheritdoc} */ public function fix(\SplFileInfo $file, $content) { $tokens = Tokens::fromCode($content); $namespacesImports = $tokens->getNamespaceUseIndexes(true); $usesOrder = array(); if (!count($namespacesImports)) { return $content; } foreach ($namespacesImports as $uses) { $uses = array_reverse($uses); $usesOrder = array_replace($usesOrder, $this->getNewOrder($uses, $tokens)); } // First clean the old content // This must be done first as the indexes can be scattered foreach ($usesOrder as $use) { for ($i = $use[1]; $i <= $use[2]; ++$i) { $tokens[$i]->clear(); } } $usesOrder = array_reverse($usesOrder, true); // Now insert the new tokens, starting from the end foreach ($usesOrder as $index => $use) { $declarationTokens = Tokens::fromCode('<?php use ' . $use[0] . ';'); $declarationTokens[0]->clear(); // <?php $declarationTokens[1]->clear(); // use $declarationTokens[2]->clear(); // space $declarationTokens[count($declarationTokens) - 1]->clear(); // ; $tokens->insertAt($index, $declarationTokens); } return $tokens->generateCode(); }
/** * Create a transport. * * The $transport parameter can be one of the following values: * * * string: The short name of a transport. For instance "Http", "Memcache" or "Thrift" * * object: An already instantiated instance of a transport * * array: An array with a "type" key which must be set to one of the two options. All other * keys in the array will be set as parameters in the transport instance * * @param mixed $transport A transport definition * @param \Elastica\Connection $connection A connection instance * @param array $params Parameters for the transport class * * @throws \Elastica\Exception\InvalidException * * @return AbstractTransport */ public static function create($transport, Connection $connection, array $params = array()) { if (is_array($transport) && isset($transport['type'])) { $transportParams = $transport; unset($transportParams['type']); $params = array_replace($params, $transportParams); $transport = $transport['type']; } if (is_string($transport)) { $className = 'Elastica\\Transport\\' . $transport; if (!class_exists($className)) { throw new InvalidException('Invalid transport'); } $transport = new $className(); } if ($transport instanceof self) { $transport->setConnection($connection); foreach ($params as $key => $value) { $transport->setParam($key, $value); } } else { throw new InvalidException('Invalid transport'); } return $transport; }
public function setDefaultValues() { /* Eigentlich brauchen wir gar keine DefaultHeader Values, weil der Server schon echt viel für uns macht nicht ganz sicher hier */ $this->values = array_replace(array('Pragma' => 'no-cache', 'Cache-Control' => 'private, no-cache', 'Vary' => 'Accept'), $this->values); return $this; }
public function match($pathinfo) { $allow = array(); $pathinfo = rawurldecode($pathinfo); $context = $this->context; $request = $this->request; // homepage if (rtrim($pathinfo, '/') === '') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo . '/', 'homepage'); } return array('_controller' => 'AppBundle\\Controller\\DefaultController::indexAction', '_route' => 'homepage'); } if (0 === strpos($pathinfo, '/todos')) { // todo_list if ($pathinfo === '/todos') { return array('_controller' => 'AppBundle\\Controller\\TodoController::indexAction', '_route' => 'todo_list'); } // todo_create if ($pathinfo === '/todos/create') { return array('_controller' => 'AppBundle\\Controller\\TodoController::createAction', '_route' => 'todo_create'); } // todo_edit if (0 === strpos($pathinfo, '/todos/edit') && preg_match('#^/todos/edit/(?P<id>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'todo_edit')), array('_controller' => 'AppBundle\\Controller\\TodoController::editAction')); } // todo_details if (0 === strpos($pathinfo, '/todos/details') && preg_match('#^/todos/details/(?P<id>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'todo_details')), array('_controller' => 'AppBundle\\Controller\\TodoController::detailsAction')); } } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); }
/** * Loads the Twig configuration. * * @param array $config An array of configuration settings * @param ContainerBuilder $container A ContainerBuilder instance */ public function configLoad($config, ContainerBuilder $container) { if (!$container->hasDefinition('twig')) { $loader = new XmlFileLoader($container, __DIR__ . '/../Resources/config'); $loader->load('twig.xml'); } // form resources foreach (array('resources', 'resource') as $key) { if (isset($config['form'][$key])) { $resources = (array) $config['form'][$key]; $container->setParameter('twig.form.resources', array_merge($container->getParameter('twig.form.resources'), $resources)); unset($config['form'][$key]); } } // globals $def = $container->getDefinition('twig'); $globals = $this->fixConfig($config, 'global'); if (isset($globals[0])) { foreach ($globals as $global) { $def->addMethodCall('addGlobal', array($global['key'], new Reference($global['id']))); } } else { foreach ($globals as $key => $id) { $def->addMethodCall('addGlobal', array($key, new Reference($id))); } } unset($config['globals'], $config['global']); // convert - to _ foreach ($config as $key => $value) { $config[str_replace('-', '_', $key)] = $value; } $container->setParameter('twig.options', array_replace($container->getParameter('twig.options'), $config)); }
public function match($pathinfo) { $allow = array(); $pathinfo = rawurldecode($pathinfo); $context = $this->context; $request = $this->request; if (0 === strpos($pathinfo, '/noticias')) { // noticias if (rtrim($pathinfo, '/') === '/noticias') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo . '/', 'noticias'); } return array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\noticiasController::indexAction', '_route' => 'noticias'); } // noticias_show if (preg_match('#^/noticias/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'noticias_show')), array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\noticiasController::showAction')); } // noticias_new if ($pathinfo === '/noticias/new') { return array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\noticiasController::newAction', '_route' => 'noticias_new'); } // noticias_create if ($pathinfo === '/noticias/create') { if ($this->context->getMethod() != 'POST') { $allow[] = 'POST'; goto not_noticias_create; } return array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\noticiasController::createAction', '_route' => 'noticias_create'); } not_noticias_create: // noticias_edit if (preg_match('#^/noticias/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'noticias_edit')), array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\noticiasController::editAction')); } // noticias_update if (preg_match('#^/noticias/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) { if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) { $allow = array_merge($allow, array('POST', 'PUT')); goto not_noticias_update; } return $this->mergeDefaults(array_replace($matches, array('_route' => 'noticias_update')), array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\noticiasController::updateAction')); } not_noticias_update: // noticias_delete if (preg_match('#^/noticias/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) { $allow = array_merge($allow, array('POST', 'DELETE')); goto not_noticias_delete; } return $this->mergeDefaults(array_replace($matches, array('_route' => 'noticias_delete')), array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\noticiasController::deleteAction')); } not_noticias_delete: // uni_marca_homepage if ($pathinfo === '/noticias') { return array('_controller' => 'uni\\bundle\\marcaBundle\\Controller\\DefaultController::indexAction', '_route' => 'uni_marca_homepage'); } } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); }
/** * {@inheritDoc} */ public function createToken($gatewayName, $model, $targetPath, array $targetParameters = array(), $afterPath = null, array $afterParameters = array()) { /** @var TokenInterface $token */ $token = $this->tokenStorage->create(); $token->setHash($token->getHash() ?: Random::generateToken()); $token->setGatewayName($gatewayName); if ($model instanceof IdentityInterface) { $token->setDetails($model); } elseif (null !== $model) { $token->setDetails($this->storageRegistry->getStorage($model)->identify($model)); } if (0 === strpos($targetPath, 'http')) { $targetUrl = Url::createFromUrl($targetPath); $targetUrl->getQuery()->set(array_replace(array('payum_token' => $token->getHash()), $targetUrl->getQuery()->toArray(), $targetParameters)); $token->setTargetUrl((string) $targetUrl); } else { $token->setTargetUrl($this->generateUrl($targetPath, array_replace(array('payum_token' => $token->getHash()), $targetParameters))); } if ($afterPath && 0 === strpos($afterPath, 'http')) { $afterUrl = Url::createFromUrl($afterPath); $afterUrl->getQuery()->modify($afterParameters); $token->setAfterUrl((string) $afterUrl); } elseif ($afterPath) { $token->setAfterUrl($this->generateUrl($afterPath, $afterParameters)); } $this->tokenStorage->update($token); return $token; }
protected function createRequest($class, array $parameters) { $this->httpClient = $this->httpClient ?: $this->getDefaultHttpClient(); $this->httpRequest = $this->httpRequest ?: $this->getDefaultHttpRequest(); $obj = new $class($this->httpClient, $this->httpRequest); return $obj->initialize(array_replace($this->getParameters(), $parameters)); }
/** * {@inheritdoc} */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, array('multiple' => $options['multiple'], 'expanded' => $options['expanded'], 'preferred_choices' => $options['choice_list']->getPreferredViews(), 'choices' => $options['choice_list']->getRemainingViews(), 'separator' => '-------------------', 'empty_value' => null)); // The decision, whether a choice is selected, is potentially done // thousand of times during the rendering of a template. Provide a // closure here that is optimized for the value of the form, to // avoid making the type check inside the closure. if ($options['multiple']) { $view->vars['is_selected'] = function ($choice, array $values) { return false !== array_search($choice, $values, true); }; } else { $view->vars['is_selected'] = function ($choice, $value) { return $choice === $value; }; } // Check if the choices already contain the empty value // Only add the empty value option if this is not the case if (0 === count($options['choice_list']->getIndicesForValues(array('')))) { $view->vars['empty_value'] = $options['empty_value']; } if ($options['multiple'] && !$options['expanded']) { // Add "[]" to the name in case a select tag with multiple options is // displayed. Otherwise only one of the selected options is sent in the // POST request. $view->vars['full_name'] = $view->vars['full_name'] . '[]'; } }
/** * Set response cookie * * @param string $name Cookie name * @param string|array $value Cookie value, or cookie properties */ public function set($name, $value) { if (!is_array($value)) { $value = ['value' => (string) $value]; } $this->responseCookies[$name] = array_replace($this->defaults, $value); }
public function __construct(S3Client $service, $bucket, array $options = array(), $detectContentType = false) { $this->service = $service; $this->bucket = $bucket; $this->options = array_replace(array('create' => false, 'directory' => '', 'acl' => 'private'), $options); $this->detectContentType = $detectContentType; }
/** * Registers node routes */ public function onRequest() { $site = App::module('system/site'); $frontpage = $site->config('frontpage'); $nodes = Node::findAll(true); uasort($nodes, function ($a, $b) { return strcmp(substr_count($a->path, '/'), substr_count($b->path, '/')) * -1; }); foreach ($nodes as $node) { if ($node->status !== 1 || !($type = $site->getType($node->type))) { continue; } $type = array_replace(['alias' => '', 'redirect' => '', 'controller' => ''], $type); $type['defaults'] = array_merge(isset($type['defaults']) ? $type['defaults'] : [], $node->get('defaults', []), ['_node' => $node->id]); $type['path'] = $node->path; $route = null; if ($node->get('alias')) { App::routes()->alias($node->path, $node->link, $type['defaults']); } elseif ($node->get('redirect')) { App::routes()->redirect($node->path, $node->get('redirect'), $type['defaults']); } elseif ($type['controller']) { App::routes()->add($type); } if (!$frontpage && isset($type['frontpage']) && $type['frontpage']) { $frontpage = $node->id; } } if ($frontpage && isset($nodes[$frontpage])) { App::routes()->alias('/', $nodes[$frontpage]->link); } else { App::routes()->get('/', function () { return __('No Frontpage assigned.'); }); } }
/** * Loads assets from the supplied node. * * @param \Twig_Node $node * * @return array An array of asset formulae indexed by name */ private function loadNode(\Twig_Node $node) { $formulae = array(); if ($node instanceof AsseticNode) { $formulae[$node->getAttribute('name')] = array($node->getAttribute('inputs'), $node->getAttribute('filters'), array('output' => $node->getAttribute('asset')->getTargetPath(), 'name' => $node->getAttribute('name'), 'debug' => $node->getAttribute('debug'), 'combine' => $node->getAttribute('combine'), 'vars' => $node->getAttribute('vars'))); } elseif ($node instanceof \Twig_Node_Expression_Function) { $name = version_compare(\Twig_Environment::VERSION, '1.2.0-DEV', '<') ? $node->getNode('name')->getAttribute('name') : $node->getAttribute('name'); if ($this->twig->getFunction($name) instanceof AsseticFilterFunction) { $arguments = array(); foreach ($node->getNode('arguments') as $argument) { $arguments[] = eval('return ' . $this->twig->compile($argument) . ';'); } $invoker = $this->twig->getExtension('assetic')->getFilterInvoker($name); $inputs = isset($arguments[0]) ? (array) $arguments[0] : array(); $filters = $invoker->getFilters(); $options = array_replace($invoker->getOptions(), isset($arguments[1]) ? $arguments[1] : array()); if (!isset($options['name'])) { $options['name'] = $invoker->getFactory()->generateAssetName($inputs, $filters, $options); } $formulae[$options['name']] = array($inputs, $filters, $options); } } foreach ($node as $child) { if ($child instanceof \Twig_Node) { $formulae += $this->loadNode($child); } } if ($node->hasAttribute('embedded_templates')) { foreach ($node->getAttribute('embedded_templates') as $child) { $formulae += $this->loadNode($child); } } return $formulae; }
/** * @param array $content * @param array $defaultValues * * @return array */ protected function getFormValues(array &$content, array &$defaultValues) { if (!$this->hasFormValues($content)) { return $defaultValues; } return array_replace($defaultValues, $content['formValues']); }
/** * {@inheritdoc} */ public function normalize($object, $format = null, array $context = []) { if (!$this->serializer instanceof NormalizerInterface) { throw new \LogicException('Serializer must be a normalizer'); } $data = []; if (null !== $object->getFamily()) { $data[self::FAMILY_FIELD] = $this->serializer->normalize($object->getFamily(), $format, $context); } foreach ($object->getGroups() as $group) { $data[self::GROUPS_FIELD][] = $this->serializer->normalize($group, $format, $context); $inGroupField = sprintf('%s_%d', self::IN_GROUP_FIELD, $group->getId()); $data[$inGroupField] = true; } if ($object->getCreated()) { $data[self::CREATED_FIELD] = $this->serializer->normalize($object->getCreated(), $format, $context); } if ($object->getUpdated()) { $data[self::UPDATED_FIELD] = $this->serializer->normalize($object->getUpdated(), $format, $context); } foreach ($object->getValues() as $value) { $normalizedData = $this->serializer->normalize($value, $format, $context); if (null !== $normalizedData) { $data = array_replace($data, $normalizedData); } } $completenesses = []; foreach ($object->getCompletenesses() as $completeness) { $completenesses = array_merge($completenesses, $this->serializer->normalize($completeness, $format, $context)); } $data[self::COMPLETENESSES_FIELD] = $completenesses; $data[self::ENABLED_FIELD] = (bool) $object->isEnabled(); return $data; }
/** * {@inheritdoc} */ public function fix(\SplFileInfo $file, $content) { $tokens = Tokens::fromCode($content); $namespacesImports = $tokens->getImportUseIndexes(true); if (0 === count($namespacesImports)) { return $content; } $usesOrder = array(); foreach ($namespacesImports as $uses) { $usesOrder = array_replace($usesOrder, $this->getNewOrder(array_reverse($uses), $tokens)); } // First clean the old content // This must be done first as the indexes can be scattered foreach ($usesOrder as $use) { $tokens->clearRange($use['startIndex'], $use['endIndex']); } $usesOrder = array_reverse($usesOrder, true); // Now insert the new tokens, starting from the end foreach ($usesOrder as $index => $use) { $declarationTokens = Tokens::fromCode('<?php use ' . $use['namespace'] . ';'); $declarationTokens->clearRange(0, 2); // clear `<?php use ` $declarationTokens[count($declarationTokens) - 1]->clear(); // clear `;` $declarationTokens->clearEmptyTokens(); $tokens->insertAt($index, $declarationTokens); } return $tokens->generateCode(); }