sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function loadSonata(ContainerBuilder $container, Loader\XmlFileLoader $loader) { $bundles = $container->getParameter('kernel.bundles'); if (!isset($bundles['SonataDoctrineORMAdminBundle'])) { return; // Sonata not installed } $refl = new \ReflectionMethod('Sonata\\DoctrineORMAdminBundle\\Filter\\StringFilter', 'filter'); if (method_exists($refl, 'getReturnType')) { if ($returnType = $refl->getReturnType()) { return; // Not compatible with this Sonata version } } $loader->load('sonata.xml'); }
Load the Sonata configuration, if the versions is supported @param ContainerBuilder $container @param Loader\XmlFileLoader $loader
entailment
protected function notify($message, array $params = [], $domain = null, $status = Notification::STATE_DONE) { $this->notificationPool->addNotification( new TranslatableNotificationMessage([ 'message' => $message, 'translationParams' => $params, 'domain' => $domain, ]), $status ); }
Registers a translatable notification. @param string $message @param array $params Translation parameters to be injected into $message. @param string $domain Translation domain. @param string $status On of Notification::STATE_DONE, Notification::STATE_ERROR, Notification::STATE_STARTED
entailment
protected function notifyError($message, array $params = [], $domain = null) { /** @Ignore */ $this->notify($message, $params, $domain, Notification::STATE_ERROR); }
Registers a translatable error notification. @param string $message @param array $params Translation parameters. @param string $domain Translation domain
entailment
protected function notifyPlural( $message, $number, array $params = [], $domain = null, $status = Notification::STATE_DONE ) { $this->notificationPool->addNotification( new TranslatableNotificationMessage([ 'message' => $message, 'number' => $number, 'translationParams' => $params, 'domain' => $domain, ]), $status ); }
Same as `notify()`, with pluralization. @param string $message @param int $number @param array $params @param string $domain @param string $status
entailment
protected function notifyErrorPlural($message, $number, array $params = [], $domain = null) { $this->notifyPlural($message, $number, $params, $domain, Notification::STATE_ERROR); }
Same as `notifyError()`, with pluralization. @param string $message @param int $number @param array $params @param string $domain
entailment
private function foundErrors() { $page = $this->getSession()->getPage(); $element = $page->find('css', '.is-error'); return $element != null; }
Helper function, returns true if errors are found in the page, false otherwise.
entailment
public function post($message, MessageCallback $callback = null) : void { self::getLogger()->warn("Calling '{}' will do nothing.", [__METHOD__]); }
Post a message on this bus. It is dispatched to all subscribed handlers. MessageCallback will be notified with each message handler calls. MessageCallback is not necessarily supported by all implementations! @param object $message @param MessageCallback $callback @return void @throws \InvalidArgumentException If $message is not an object
entailment
public function load(AggregateId $aggregateId) : AggregateRoot { $key = $this->createKey($aggregateId); Preconditions::checkArgument( array_key_exists($key, $this->aggregates), 'Aggregate with ID [%s] does not exist', $aggregateId ); self::getLogger()->debug('Aggregate identified by [{}] has been loaded', [$aggregateId]); return $this->aggregates[$key]; }
Load the aggregate identified by $aggregateId from the persistent storage. @param AggregateId $aggregateId @return AggregateRoot @throws \InvalidArgumentException If the $aggregateId is invalid
entailment
public function save(AggregateRoot $aggregateRoot) : void { $this->aggregates[$this->createKey($aggregateRoot->getId())] = $aggregateRoot; self::getLogger()->debug('Aggregate identified by [{}] has been persisted', [$aggregateRoot->getId()]); }
Persisting the given $aggregateRoot. @param AggregateRoot $aggregateRoot
entailment
public function registerObjectMessageFactory(ObjectMessageFactory $factory, string $messageClass) : void { $this->objectMessageFactories[$messageClass] = $factory; }
Only full matching class names are used, you should not register a factory for an abstract message class/interface! If there is no registered factory for a particular message class, DefaultObjectMessageFactory will be used. @param ObjectMessageFactory $factory @param $messageClass
entailment
public function onMessage(Mf4phpMessage $message) : void { Preconditions::checkArgument($message instanceof ObjectMessage, "Message must be an instance of ObjectMessage"); $object = $message->getObject(); if ($object instanceof MessageWrapper) { $object = $object->getMessage(); } parent::dispatch($object, self::emptyCallback()); }
Forward incoming message to handlers. @param Mf4phpMessage $message @throws InvalidArgumentException
entailment
protected function findObjectMessageFactory($message) : ObjectMessageFactory { $messageClass = get_class($message); foreach ($this->objectMessageFactories as $class => $factory) { if ($class === $messageClass) { return $factory; } } return $this->defaultObjectMessageFactory; }
Finds the appropriate message factory for the given message. @param $message @return ObjectMessageFactory
entailment
protected function dispatch($message, MessageCallback $callback) : void { $sendable = $message; if (!($message instanceof Serializable)) { $sendable = new MessageWrapper($message); } $mf4phpMessage = $this->findObjectMessageFactory($message)->createMessage($sendable); $this->dispatcher->send($this->queue, $mf4phpMessage); }
Send the message to the message queue. @param $message @param MessageCallback $callback
entailment
protected function getApiRoot() { $request = $this->requestStack->getMasterRequest(); $pathinfo = $request->getPathInfo(); $semanticPathinfo = $request->attributes->get('semanticPathinfo', $pathinfo); return $request->getBaseUrl() . substr($pathinfo, 0, strpos($pathinfo, $semanticPathinfo)) . '/'; }
Returns the apiRoot for the current application environment, ie the prefix to use for all api/AJAX calls. @return string
entailment
private function getAssetUrl($path) { $url = $this->assetsPackages->getUrl($path); if (!$url) { return $path; } /** * If `framework.assets.version: some_version` set, then $version = '?some_version'. * If `framework.assets: json_manifest_path` is used, then $version = '/'. */ $version = $this->assetsPackages->getVersion($path); if (false === strpos($version, '?')) { return $url; } return preg_replace('/\?' . $version . '/', '', $url); }
Returns asset URL without version (if any). @param string $path @return string
entailment
public function listCommand() { if ($this->clonePresets) { foreach ($this->clonePresets as $presetName => $presetConfiguration) { $this->renderHeadLine($presetName); $presetConfigurationAsYaml = Yaml::dump($presetConfiguration); $lines = explode(PHP_EOL, $presetConfigurationAsYaml); foreach ($lines as $line) { $this->renderLine($line); } } } }
Show the list of predefined clone configurations
entailment
public function defaultCommand(bool $yes = false, bool $keepDb = false) : void { if ($this->defaultPreset === null || $this->defaultPreset === '') { $this->renderLine('There is no default preset configured!'); $this->quit(1); } $this->presetCommand($this->defaultPreset, $yes, $keepDb); }
Clones the default preset @param boolean $yes confirm execution without further input @param boolean $keepDb skip dropping of database during sync
entailment
public function presetCommand($presetName, $yes = false, $keepDb = false) { if (count($this->clonePresets) > 0) { if ($this->clonePresets && array_key_exists($presetName, $this->clonePresets)) { $this->configurationService->setCurrentPreset($presetName); $configuration = $this->configurationService->getCurrentConfiguration(); $this->renderLine('Clone by preset ' . $presetName); $this->cloneRemoteHost( $configuration['host'], $configuration['user'], $configuration['port'], $configuration['path'], $configuration['context'], (isset($configuration['postClone']) ? $configuration['postClone'] : null ), $yes, $keepDb, (isset($configuration['flowCommand']) ? $configuration['flowCommand'] : null ), (isset($configuration['sshOptions']) ? $configuration['sshOptions'] : '' ) ); } else { $this->renderLine('The preset ' . $presetName . ' was not found!'); $this->quit(1); } } else { $this->renderLine('No presets found!'); $this->quit(1); } }
Clone a flow setup as specified in Settings.yaml (Sitegeist.MagicWand.clonePresets ...) @param string $presetName name of the preset from the settings @param boolean $yes confirm execution without further input @param boolean $keepDb skip dropping of database during sync
entailment
protected function cloneRemoteHost( $host, $user, $port, $path, $context = 'Production', $postClone = null, $yes = false, $keepDb = false, $remoteFlowCommand = null, $sshOptions = '' ) { // fallback if ($remoteFlowCommand === null) { $remoteFlowCommand = $this->flowCommand; } // read local configuration $this->renderHeadLine('Read local configuration'); $localDataPersistentPath = FLOW_PATH_ROOT . 'Data/Persistent'; // read remote configuration $this->renderHeadLine('Fetch remote configuration'); $remotePersistenceConfigurationYaml = $this->executeLocalShellCommand( 'ssh -p %s %s %s@%s "cd %s; FLOW_CONTEXT=%s ' . $remoteFlowCommand . ' configuration:show --type Settings --path Neos.Flow.persistence.backendOptions;"', [ $port, $sshOptions, $user, $host, $path, $context ], [ self::HIDE_RESULT ] ); if ($remotePersistenceConfigurationYaml) { $remotePersistenceConfiguration = \Symfony\Component\Yaml\Yaml::parse($remotePersistenceConfigurationYaml); } $remoteDataPersistentPath = $path . '/Data/Persistent'; ################# # Are you sure? # ################# if (!$yes) { $this->renderLine("Are you sure you want to do this? Type 'yes' to continue: "); $handle = fopen("php://stdin", "r"); $line = fgets($handle); if (trim($line) != 'yes') { $this->renderLine('exit'); $this->quit(1); } else { $this->renderLine(); $this->renderLine(); } } ###################### # Measure Start Time # ###################### $startTimestamp = time(); ################## # Define Secrets # ################## $this->addSecret($this->databaseConfiguration['user']); $this->addSecret($this->databaseConfiguration['password']); $this->addSecret($remotePersistenceConfiguration['user']); $this->addSecret($remotePersistenceConfiguration['password']); ####################### # Check Configuration # ####################### $this->checkConfiguration($remotePersistenceConfiguration); ################################################ # Fallback to default MySQL port if not given. # ################################################ if (!isset($remotePersistenceConfiguration['port'])) { $remotePersistenceConfiguration['port'] = $this->dbal->getDefaultPort($remotePersistenceConfiguration['driver']); } if (!isset($this->databaseConfiguration['port'])) { $this->databaseConfiguration['port'] = $this->dbal->getDefaultPort($this->databaseConfiguration['driver']); } ######################## # Drop and Recreate DB # ######################## if ($keepDb == false) { $this->renderHeadLine('Drop and Recreate DB'); $emptyLocalDbSql = $this->dbal->flushDbSql($this->databaseConfiguration['driver'], $this->databaseConfiguration['dbname']); $this->executeLocalShellCommand( 'echo %s | %s', [ escapeshellarg($emptyLocalDbSql), $this->dbal->buildCmd( $this->databaseConfiguration['driver'], $this->databaseConfiguration['host'], (int)$this->databaseConfiguration['port'], $this->databaseConfiguration['user'], $this->databaseConfiguration['password'], $this->databaseConfiguration['dbname'] ) ] ); } else { $this->renderHeadLine('Skipped (Drop and Recreate DB)'); } ###################### # Transfer Database # ###################### $this->renderHeadLine('Transfer Database'); $this->executeLocalShellCommand( 'ssh -p %s %s %s@%s -- %s | %s', [ $port, $sshOptions, $user, $host, $this->dbal->buildDumpCmd( $remotePersistenceConfiguration['driver'], $remotePersistenceConfiguration['host'], (int)$remotePersistenceConfiguration['port'], $remotePersistenceConfiguration['user'], $remotePersistenceConfiguration['password'], $remotePersistenceConfiguration['dbname'] ), $this->dbal->buildCmd( $this->databaseConfiguration['driver'], $this->databaseConfiguration['host'], (int)$this->databaseConfiguration['port'], $this->databaseConfiguration['user'], $this->databaseConfiguration['password'], $this->databaseConfiguration['dbname'] ) ] ); ################## # Transfer Files # ################## $resourceProxyConfiguration = $this->configurationService->getCurrentConfigurationByPath('resourceProxy'); if (!$resourceProxyConfiguration) { $this->renderHeadLine('Transfer Files'); $this->executeLocalShellCommand( 'rsync -e "ssh -p %s %s" -kLr %s@%s:%s/* %s', [ $port, addslashes($sshOptions), $user, $host, $remoteDataPersistentPath, $localDataPersistentPath ] ); } else { $this->renderHeadLine('Transfer Files - without Resources because a resourceProxyConfiguration is found'); $this->executeLocalShellCommand( 'rsync -e "ssh -p %s %s" --exclude "Resources/*" -kLr %s@%s:%s/* %s', [ $port, addslashes($sshOptions), $user, $host, $remoteDataPersistentPath, $localDataPersistentPath ] ); } ######################### # Transfer Translations # ######################### $this->renderHeadLine('Transfer Translations'); $remoteDataTranslationsPath = $path . '/Data/Translations'; $localDataTranslationsPath = FLOW_PATH_ROOT . 'Data/Translations'; // If the translation directory is available print true - because we didn't get the return value here $translationsAvailable = trim( $this->executeLocalShellCommand( 'ssh -p %s %s %s@%s "[ -d %s ] && echo true"', [ $port, $sshOptions, $user, $host, $remoteDataTranslationsPath] ) ); if ($translationsAvailable === 'true') { $this->executeLocalShellCommand( 'rsync -e "ssh -p %s %s" -kLr %s@%s:%s/* %s', [ $port, addslashes($sshOptions), $user, $host, $remoteDataTranslationsPath, $localDataTranslationsPath ] ); } ################ # Clear Caches # ################ $this->renderHeadLine('Clear Caches'); $this->executeLocalFlowCommand('flow:cache:flush'); ################## # Set DB charset # ################## if ($this->databaseConfiguration['driver'] == 'pdo_mysql' && $remotePersistenceConfiguration['charset'] != 'utf8mb4' ) { $this->renderHeadLine('Set DB charset'); $this->executeLocalFlowCommand('database:setcharset'); } ############## # Migrate DB # ############## $this->renderHeadLine('Migrate cloned DB'); $this->executeLocalFlowCommand('doctrine:migrate'); ##################### # Publish Resources # ##################### $this->renderHeadLine('Publish Resources'); $this->executeLocalFlowCommand('resource:publish'); ############## # Post Clone # ############## if ($postClone) { $this->renderHeadLine('Execute post_clone commands'); if (is_array($postClone)) { foreach ($postClone as $postCloneCommand) { $this->executeLocalShellCommandWithFlowContext($postCloneCommand); } } else { $this->executeLocalShellCommandWithFlowContext($postClone); } } ################# # Final Message # ################# $endTimestamp = time(); $duration = $endTimestamp - $startTimestamp; $this->renderHeadLine('Done'); $this->renderLine('Successfully cloned in %s seconds', [$duration]); }
Clone a Flow Setup via detailed hostname @param string $host ssh host @param string $user ssh user @param string $port ssh port @param string $path path on the remote server @param string $context flow_context on the remote server @param mixded $postClone command or array of commands to be executed after cloning @param boolean $yes confirm execution without further input @param boolean $keepDb skip dropping of database during sync @param string $remoteFlowCommand the flow command to execute on the remote system @param string $sshOptions additional options for the ssh command
entailment
public function __doRequestByCurl($request, $location, $action, $version, $one_way = FALSE) { // Call via Curl and use the timeout a $curl = curl_init($location); if ($curl === false) { throw new ClientException('Curl initialisation failed'); } /** @var $headers array of headers to be sent with request */ $headers = array( 'User-Agent: PHP-SOAP', 'Content-Type: text/xml; charset=utf-8', 'SOAPAction: "' . $action . '"', 'Content-Length: ' . strlen($request), ); $options = array( CURLOPT_VERBOSE => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $request, CURLOPT_HEADER => $headers, CURLOPT_HTTPHEADER => array(sprintf('Content-Type: %s', $version == 2 ? 'application/soap+xml' : 'text/xml'), sprintf('SOAPAction: %s', $action)), ); // Timeout in milliseconds $options = $this->__curlSetTimeoutOption($options, $this->timeout, 'CURLOPT_TIMEOUT'); // ConnectTimeout in milliseconds $options = $this->__curlSetTimeoutOption($options, $this->connectTimeout, 'CURLOPT_CONNECTTIMEOUT'); $this->__setCurlOptions($curl, $options); $response = curl_exec($curl); $this->lastResponse = $response; if (curl_errno($curl)) { $errorMessage = curl_error($curl); $errorNumber = curl_errno($curl); curl_close($curl); throw new ClientException($errorMessage, $errorNumber); } $header_len = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $header_len); $body = substr($response, $header_len); $this->lastResponseBody = $body; curl_close($curl); // Return? if ($one_way) { return null; } else { return $body; } }
@param string $request @param string $location @param string $action @param int $version @param bool $one_way @return string|null @throws ClientException
entailment
public function getEventsFor(AggregateId $aggregateId, string $stateHash = null) { $result = []; $add = false; $key = $this->createKey($aggregateId); $events = array_key_exists($key, $this->events) ? $this->events[$key] : []; /* @var $event DomainEvent */ foreach ($events as $event) { if ($add || $stateHash === null) { $result[] = $event; } elseif ($event->stateHash() === $stateHash) { $add = true; } } self::getLogger()->debug( 'Events for aggregate [{}] with state hash [{}] has been loaded', [$aggregateId, $stateHash] ); return new ArrayIterator($result); }
Must be return all events stored to aggregate identified by $aggregateId and $type. Events must be ordered by theirs persistent time. If the $stateHash parameter is set, the result will contain only the newer DomainEvents. @param AggregateId $aggregateId @param string $stateHash State hash @return Iterator|Countable
entailment
public function push($class, $args = [], $retry = true, $queue = self::QUEUE) { $jobId = $this->idGenerator->generate(); $this->atomicPush($jobId, $class, $args, $queue, $retry); return $jobId; }
Push a job @param string $class @param array $args @param bool $retry @param string $queue @return string
entailment
public function schedule($doAt, $class, $args = [], $retry = true, $queue = self::QUEUE) { $jobId = $this->idGenerator->generate(); $this->atomicPush($jobId, $class, $args, $queue, $retry, $doAt); return $jobId; }
Schedule a job at a certain time @param float $doAt @param string $class @param array $args @param bool $retry @param string $queue @return string
entailment
public function pushBulk($jobs = [], $queue = self::QUEUE) { $ids = []; foreach ($jobs as $job) { if (!isset($job['class'])) { throw new Exception('pushBulk: each job needs a job class'); } if (!isset($job['args']) || !is_array($job['args'])) { throw new Exception('pushBulk: each job needs args'); } $retry = isset($job['retry']) ? $job['retry'] : true; $doAt = isset($job['at']) ? $job['at'] : null; $jobId = $this->idGenerator->generate(); array_push($ids, $jobId); $this->atomicPush($jobId, $job['class'], $job['args'], $queue, $retry, $doAt); } return $ids; }
Push multiple jobs to queue Format: $jobs = [ [ 'class' => 'SomeClass', 'args' => array(), 'retry' => false, 'at' => microtime(true) ] ]; @param array $jobs @param string $queue @return string @throws exception Exception
entailment
private function atomicPush($jobId, $class, $args = [], $queue = self::QUEUE, $retry = true, $doAt = null) { if (array_values($args) !== $args) { throw new Exception('Associative arrays in job args are not allowed'); } if (!is_null($doAt) && !is_float($doAt) && is_string($doAt)) { throw new Exception('at argument needs to be in a unix epoch format. Use microtime(true).'); } $job = $this->serializer->serialize($jobId, $class, $args, $retry, $queue); if ($doAt === null) { $this->redis->sadd($this->name('queues'), $queue); $this->redis->lpush($this->name('queue', $queue), $job); } else { $this->redis->zadd($this->name('schedule'), $doAt, $job); } }
Push job to redis @param string $jobId @param string $class @param array $args @param string $queue @param bool $retry @param float|null $doAt @throws exception Exception
entailment
public function wrapTemplateAction($module) { if ($this->getModuleSetting($module, 'type') !== 'template') { throw new BadRequestHttpException($module . ' is not declared as a template'); } $path = $this->getModuleSetting($module, 'path'); $response = new Response(); return $this->render('eZPlatformUIBundle:Template:wraptemplate.js.twig', [ 'path' => $path, 'module' => $module, 'templateCode' => file_get_contents($path), ], $response); }
Wraps the template file content in a YUI module. The generated module also registers the template under the same name of the module. @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException if the module is not declared as a template @param string $module @return \Symfony\Component\HttpFoundation\Response
entailment
final public function loadFromHistory(Iterator $events) : void { $bus = self::createInnerEventBus($this); foreach ($events as $event) { $this->handleEventInAggregate($event, $bus); } }
Useful in case of Event Sourcing. @see EventSourcingRepository @param Iterator $events DomainEvent iterator
entailment
final protected function apply(DomainEvent $event) : void { $this->handleEventInAggregate($event); parent::raise($event); }
Fire a domain event from a handler method. @param DomainEvent $event
entailment
public function getSystemInfo() { $info = ezcSystemInfo::getInstance(); $accelerator = false; if ($info->phpAccelerator) { $accelerator = [ 'name' => $info->phpAccelerator->name, 'url' => $info->phpAccelerator->url, 'enabled' => $info->phpAccelerator->isEnabled, 'versionString' => $info->phpAccelerator->versionString, ]; } return [ 'cpuType' => $info->cpuType, 'cpuSpeed' => $info->cpuSpeed, 'cpuCount' => $info->cpuCount, 'memorySize' => $info->memorySize, 'phpVersion' => PHP_VERSION, 'phpAccelerator' => $accelerator, 'database' => [ 'type' => $this->connection->getDatabasePlatform()->getName(), 'name' => $this->connection->getDatabase(), 'host' => $this->connection->getHost(), 'username' => $this->connection->getUsername(), ], ]; }
Returns the system information: - cpu information - memory size - php version - php accelerator info - database related info. @return array
entailment
public function getEzPlatformInfo() { $info = [ 'version' => 'dev', 'symfony' => Kernel::VERSION, 'bundles' => $this->bundles, ]; ksort($info['bundles'], SORT_FLAG_CASE | SORT_STRING); return $info; }
Returns informations on the current eZ Platform install: - eZ Publish legacy version - eZ Publish legacy extensions - Symfony bundles. @return array
entailment
protected function defineCss(NodeBuilder $saNode) { $saNode ->arrayNode('css') ->children() ->arrayNode('files') ->prototype('scalar')->end() ->end() ->end() ->end(); }
Defines the expected configuration for the CSS. @param $saNode \Symfony\Component\Config\Definition\Builder\NodeBuilder
entailment
protected function defineJavaScript(NodeBuilder $saNode) { $saNode ->arrayNode('javascript') ->children() ->arrayNode('files') ->prototype('scalar')->end() ->end() ->end() ->end(); }
Defines the expected configuration for the JavaScript. @param $saNode \Symfony\Component\Config\Definition\Builder\NodeBuilder
entailment
protected function defineYui(NodeBuilder $saNode) { $saNode ->arrayNode('yui') ->children() ->enumNode('filter') ->values(['raw', 'min', 'debug']) ->info("Filter to apply to module urls. This filter will modify the default path for all modules.\nPossible values are 'raw', 'min' or 'debug''") ->end() ->booleanNode('combine') ->defaultTrue() ->info('If true, YUI combo loader will be used.') ->end() ->arrayNode('modules') ->useAttributeAsKey('yui_module_name') ->normalizeKeys(false) ->prototype('array') ->info('YUI module definitions') ->children() ->scalarNode('path') ->info("Path to the module's JS file, relative to web/ directory.") ->example('bundles/acmedemo/js/my_yui_module.js') ->end() ->arrayNode('requires') ->info("Module's dependencies. Use modules' name to reference them.") ->example(['ez-capi', 'parallel']) ->prototype('scalar')->end() ->end() ->arrayNode('dependencyOf') ->info("Reverse dependencies.\nWhen loading modules referenced here, current module will be considered as a dependency.") ->example(['ez-capi', 'parallel']) ->prototype('scalar')->end() ->end() ->enumNode('type') ->values(['js', 'template']) ->defaultValue('js') ->info("Type of module, either 'js' or 'template'") ->end() ->end() ->end() ->end() ->end() ->end(); }
Defines the expected configuration for the YUI modules. @param $saNode \Symfony\Component\Config\Definition\Builder\NodeBuilder
entailment
final public function post($message, MessageCallback $callback = null) : void { Preconditions::checkArgument(is_object($message), 'Incoming message is not an object'); if ($callback === null) { $callback = self::emptyCallback(); } $dispatchClosure = function () use ($message, $callback) { $this->dispatch($message, $callback); }; $this->createChain($message, $dispatchClosure)->proceed(); }
Post a message on this bus. It is dispatched to all subscribed handlers. MessageCallback will be notified with each message handler calls. MessageCallback is not necessarily supported by all implementations! @param object $message @param MessageCallback $callback @return void @throws InvalidArgumentException If $message is not an object @throws RuntimeException that may be thrown by an interceptor
entailment
public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data) { if (!$data || !is_array($data) || !array_key_exists('value', $data)) { return; } $data['value'] = trim($data['value']); if (strlen($data['value']) == 0) { return; } $data['type'] = !isset($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type']; $operator = $this->getOperator((int) $data['type']); if (!$operator) { $operator = 'LIKE'; } $entities = $queryBuilder->getRootEntities(); $classMetadata = $this->listener->getTranslatableMetadata(current($entities)); $transMetadata = $this->listener->getTranslatableMetadata($classMetadata->targetEntity); // Add inner join if (!$this->hasJoin($queryBuilder, $alias)) { $parameterName = $this->getNewParameterName($queryBuilder); $queryBuilder->innerJoin( sprintf('%s.%s', $alias, $classMetadata->translations->name), 'trans', Expr\Join::WITH, sprintf('trans.%s = :%s', $transMetadata->locale->name, $parameterName) ); $queryBuilder->setParameter($parameterName, $this->listener->getCurrentLocale()); } // c.name > '1' => c.name OPERATOR :FIELDNAME $parameterName = $this->getNewParameterName($queryBuilder); $or = $queryBuilder->expr()->orX(); $or->add(sprintf('%s.%s %s :%s', 'trans', $field, $operator, $parameterName)); if (ChoiceType::TYPE_NOT_CONTAINS == $data['type']) { $or->add($queryBuilder->expr()->isNull(sprintf('%s.%s', 'trans', $field))); } $this->applyWhere($queryBuilder, $or); if ($data['type'] == ChoiceType::TYPE_EQUAL) { $queryBuilder->setParameter($parameterName, $data['value']); } else { $queryBuilder->setParameter($parameterName, sprintf($this->getOption('format'), $data['value'])); } }
{@inheritdoc}
entailment
private function hasJoin(ProxyQueryInterface $queryBuilder, $alias) { $joins = $queryBuilder->getDQLPart('join'); if (!isset($joins[$alias])) { return false; } foreach ($joins[$alias] as $join) { if ('trans' === $join->getAlias()) { return true; } } return false; }
Does the query builder have a translation join @param ProxyQueryInterface $queryBuilder @return bool
entailment
public function withRepository(Repository $repository) : TransactionalBusesBuilder { $this->repository = $repository; $this->useDirectCommandBus(); return $this; }
This builder instance will create a {@link DirectCommandBus} with the given {@link Repository}. @param Repository $repository @return $this
entailment
function it_should_be_unique(){ $ids = []; $iterations = 100; for($i=0; $i < $iterations; $i++){ $ids[] = $this->getWrappedObject()->generate(); } return (count(array_values($ids)) === $iterations); }
Naive way of testing uniqueness, I know
entailment
public function process(ContainerBuilder $container) { $driver = $container->getDefinition('prezent_doctrine_translatable.driver_chain'); foreach ($container->getParameter('doctrine.entity_managers') as $name => $manager) { $adapter = new Definition( 'Metadata\\Driver\\DriverInterface', array( new Reference(sprintf('doctrine.orm.%s_metadata_driver', $name)), ) ); $class = 'Prezent\\Doctrine\\Translatable\\Mapping\\Driver\\DoctrineAdapter'; $method = 'fromMetadataDriver'; if (method_exists($adapter, 'setFactory')) { $adapter->setFactory([$class, $method]); } else { $adapter->setFactoryClass($class); $adapter->setFactoryMethod($method); } $driver->addMethodCall('addDriver', array($adapter)); } }
{@inheritDoc}
entailment
protected function dispatch($message, MessageCallback $callback) : void { $handled = false; foreach ($this->callableWrappersFor($message) as $callable) { $handled = true; if ($message instanceof PropagationStoppable && $message->isPropagationStopped()) { break; } try { $result = $callable->invoke($message); self::getLogger()->debug( "The following message has been dispatched to handler '{}' through message bus '{}': {}", [$callable, $this, $message] ); if ($result !== null) { $callback->onSuccess($result); } } catch (Exception $exp) { self::getLogger()->warn( "An error occurred in the following message handler through message bus '{}': {}, message is {}!", [$this, $callable, $message], $exp ); $context = new SubscriberExceptionContext($this, $message, $callable); try { $this->exceptionHandler->handleException($exp, $context); } catch (Exception $e) { self::getLogger()->error( "An error occurred in the exception handler with context '{}'", [$context], $e ); } try { $callback->onFailure($exp); } catch (Exception $e) { self::getLogger()->error("An error occurred in message callback on bus '{}'", [$this], $e); } } } if (!$handled && !($message instanceof DeadMessage)) { self::getLogger()->debug( "The following message as a DeadMessage is being posted to '{}' message bus: {}", [$this, $message] ); $this->dispatch(new DeadMessage($message), $callback); } }
Dispatches $message to all handlers. @param $message @param MessageCallback $callback @return void
entailment
private function initSoapClient() { if ($this->soapClient === NULL) { $this->soapClient = new SoapClient($this->service, $this->key, $this->cert, $this->trace, $this->passphrase); } }
Require to initialize a new SOAP client for a new request. @return void
entailment
public function load(AggregateId $aggregateId) : AggregateRoot { $aggregateRootClass = ObjectClass::forName($aggregateId->aggregateClass()); $aggregate = null; $stateHash = null; if ($this->eventStore instanceof SnapshotEventStore) { $aggregate = $this->eventStore->loadSnapshot($aggregateId); $stateHash = $aggregate === null ? null : $aggregate->stateHash(); } $events = $this->eventStore->getEventsFor($aggregateId, $stateHash); if ($aggregate === null) { Preconditions::checkArgument($events->valid(), 'Aggregate with ID [%s] does not exist', $aggregateId); $aggregate = $aggregateRootClass->newInstanceWithoutConstructor(); } $aggregateRootClass->cast($aggregate); $aggregate->loadFromHistory($events); return $aggregate; }
Initializes the stored aggregate with its events persisted in event store. @param AggregateId $aggregateId @return EventSourcedAggregateRoot @throws InvalidArgumentException If the $aggregateId is invalid
entailment
public function validateAttribute($model, $attribute) { $countries = []; if ($this->country !== null) { $countries = [$this->country]; } elseif ($this->countryAttribute !== null) { $countries = [$model->{$this->countryAttribute}]; } elseif (is_array($this->countries) && count($this->countries) > 0) { $countries = $this->countries; } if (count($countries) <= 0) { $countries = self::getPhoneUtil()->getSupportedRegions(); } foreach ($countries as $country) { try { $number = self::getPhoneUtil()->parse($model->$attribute, $country); if (self::getPhoneUtil()->isValidNumberForRegion($number, $country)) { if ($this->format) { $model->$attribute = self::getPhoneUtil()->format($number, PhoneNumberFormat::INTERNATIONAL); } $this->_successValidation = true; break; } } catch (NumberParseException $e) { $this->addError($model, $attribute, $this->numberParseExceptionMessage); } } if (!$this->_successValidation) { $this->addError($model, $attribute, $this->notValidPhoneNumberMessage); } return $this->_successValidation; }
Validate attribute @param \yii\base\Model $model @param string $attribute @return bool
entailment
public function visitFile(\SplFileInfo $file, MessageCatalogue $catalogue) { if ($file->getExtension() !== 'hbt') { return; } $fileContent = file_get_contents($file->getPathname()); $messages = $this->extractTemplate($fileContent, $catalogue); foreach ($messages as $message) { $message->addSource(new FileSource($file->getPathname())); $catalogue->add($message); } }
Called for non-specially handled files. This is not called if handled by a more specific method. @param \SplFileInfo $file @param MessageCatalogue $catalogue
entailment
protected function extractTemplate($fileContent, MessageCatalogue $catalogue) { $translateParameters = []; $translateFound = preg_match_all( '/\\{\\{\\s*translate\\s(.*)\\s*\\}\\}/', $fileContent, $translateParameters, PREG_SET_ORDER ); $messages = []; if ($translateFound) { foreach ($translateParameters as $translateParameter) { $message = $this->extractParameters($translateParameter[1], $catalogue); if ($message !== null) { $messages[] = $message; } } } return $messages; }
@param string $fileContent @param MessageCatalogue $catalogue @return Message[]
entailment
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new ApplicationConfigProviderPass()); $container->addCompilerPass(new TranslationDomainsExtensionsPass()); $container->addCompilerPass(new ValueObjectVisitorPass()); }
Builds the bundle. It is only ever called once when the cache is empty. This method can be overridden to register compilation passes, other extensions, ... @param ContainerBuilder $container A ContainerBuilder instance
entailment
public function disableValidation($once = false) { $this->skipValidation = ($once) ? Observer::SKIP_ONCE : Observer::SKIP_ALWAYS; return $this; }
Disable validation for this instance. @return $this
entailment
public function getValidator() { if (!$this->validator) { $this->validator = static::$validatorFactory->make( [], static::getCreateRules(), static::getValidationMessages(), static::getValidationAttributes() ); } return $this->validator; }
Get the validator instance. @return \Illuminate\Contracts\Validation\Validator
entailment
protected static function gatherRules() { // This rather gnarly looking logic is just for developer convenience // so he can define multiple rule groups on the model for clarity // and now we simply gather all rules and merge them together. $keys = static::getValidatedFields(); $result = array_fill_keys($keys, []); foreach ($keys as $key) { foreach (static::getRulesGroups() as $groupName) { $group = static::getRulesGroup($groupName); if (isset($group[$key])) { $rules = is_array($group[$key]) ? $group[$key] : explode('|', $group[$key]); foreach ($rules as &$rule) { if ($rule === 'unique') { $table = (new static)->getTable(); $rule .= ":{$table}"; } } unset($rule); $result[$key] = array_unique(array_merge($result[$key], $rules)); } } } return $result; }
Gather all the rules for the model and store it for easier use. @return array
entailment
public static function getValidatedFields() { $fields = []; foreach (static::getRulesGroups() as $groupName) { $fields = array_merge($fields, array_keys(static::getRulesGroup($groupName))); } return array_values(array_unique($fields)); }
Get array of attributes that have validation rules defined. @return array
entailment
protected static function getRulesGroups() { $groups = []; foreach (get_class_vars(get_called_class()) as $property => $val) { if (preg_match('/^.*rules$/i', $property)) { $groups[] = $property; } } return $groups; }
Get all the rules groups defined on this model. @return array
entailment
public function waitWhileLoading($selector = self::LOADING_SELECTOR, $onlyVisible = true) { $maxTime = time() + self::MAX_WAIT_TIMEOUT; do { $this->sleep(); $elem = $this->getSession()->getPage()->find('css', $selector); if ($elem && $onlyVisible) { try { $isVisible = $elem->isVisible(); } catch (\Exception $e) { // elem no longer present, assume not visible $elem = null; } } $done = $elem == null || ($onlyVisible && !$isVisible); } while (!$done && time() < $maxTime); if (!$done) { throw new \Exception("Timeout while waiting for loading element '$selector'."); } }
Wait while 'app loading' elements (such as spinner) exist for example, while opening and publishing contents, etc... @param $selector selector to match,
entailment
public function spin($lambda) { $e = null; $timeLimit = time() + self::SPIN_TIMEOUT; do { try { $return = $lambda($this); if ($return) { return $return; } } catch (\Exception $e) { } $this->sleep(); } while ($timeLimit > time()); throw new \Exception( 'Timeout while retreaving DOM element' . ($e !== null ? '. Last exception: ' . $e->getMessage() : '') ); }
Behat spin function Execute a provided function and return it's result if valid, if an exception is thrown or the result is false wait and retry until a max timeout is reached.
entailment
public function findAllWithWait($locator, $baseElement = null) { if (!$baseElement) { $baseElement = $this->getSession()->getPage(); } $elements = $this->spin( function () use ($locator, $baseElement) { $elements = $baseElement->findAll('css', $locator); foreach ($elements as $element) { // An exception may be thrown if the element is not valid/attached to DOM. $element->getValue(); } return $elements; } ); return $elements; }
Adpted Mink find function combined with a spin function to find all element with a given css selector that might still be loading. @param string $locator css selector for the element @param NodeElement $baseElement base Mink node element from where the find should be called @return NodeElement[]
entailment
public function findWithWait($selector, $baseElement = null, $checkVisibility = true) { if (!$baseElement) { $baseElement = $this->getSession()->getPage(); } $element = $this->spin( function () use ($selector, $baseElement, $checkVisibility) { $element = $baseElement->find('css', $selector); if (!$element) { throw new \Exception("Element with selector '$selector' was not found"); } // An exception may be thrown if the element is not valid/attached to DOM. $element->getValue(); if ($checkVisibility && !$element->isVisible()) { throw new \Exception("Element with selector '$selector' is not visible"); } return $element; } ); return $element; }
Adpted Mink find function combined with a spin function to find one element that might still be loading. @param string $selector css selector for the element @param \Behat\Mink\Element\NodeElement $baseElement base Mink node element from where the find should be called @return \Behat\Mink\Element\NodeElement
entailment
public function getElementByText($text, $selector, $textSelector = null, $baseElement = null) { if ($baseElement == null) { $baseElement = $this->getSession()->getPage(); } $elements = $this->findAllWithWait($selector, $baseElement); foreach ($elements as $element) { if ($textSelector != null) { try { $elementText = $this->findWithWait($textSelector, $element)->getText(); } catch (\Exception $e) { continue; } } else { $elementText = $element->getText(); } if ($elementText == $text) { return $element; } } return false; }
Finds an HTML element by class and the text value and returns it. @param string $text Text value of the element @param string $selector CSS selector of the element @param string $textSelector Extra CSS selector for text of the element @param string $baseElement Element in which the search is based @param int $iteration Iteration number, used to control number of executions @return array
entailment
public function clickElementByText($text, $selector, $textSelector = null, $baseElement = null) { $element = $this->getElementByText($text, $selector, $textSelector, $baseElement); if ($element && $element->isVisible()) { $element->click(); } elseif ($element) { throw new \Exception("Can't click '$text' element: not visible"); } else { throw new \Exception("Can't click '$text' element: not Found"); } }
Finds an HTML element by class and the text value and clicks it. @param string $text Text value of the element @param string $selector CSS selector of the element @param string $textSelector Extra CSS selector for text of the element @param string $baseElement Element in which the search is based
entailment
protected function openFinderExplorerNode($text, $parentNode) { $this->waitWhileLoading('.ez-ud-finder-explorerlevel-loading'); $parentNode = $this->findWithWait('.ez-view-universaldiscoveryfinderexplorerlevelview:last-child', $parentNode); $element = $this->getElementByText($text, '.ez-explorer-level-list-item', '.ez-explorer-level-item', $parentNode); if (!$element) { throw new \Exception("The browser node '$text' was not found"); } $element->click(); }
Clicks a content browser node based on the root of the browser or a given node. @param string $text The text of the node that is going to be clicked @param NodeElement $parentNode The base node to expand from, if null defaults to the content browser root @throws \Exception When not found
entailment
public function openFinderExplorerPath($path, $node) { $path = explode('/', $path); foreach ($path as $nodeName) { $this->openFinderExplorerNode($nodeName, $node); } }
Explores the content browser expanding it. @param string $path The content browser path such as 'Content1/Content2/ContentIWantToClick' @param NodeElement $node The base node to expand from
entailment
public function clickOnBrowsePath($path) { $this->clickDiscoveryBar('Content browse'); $this->waitWhileLoading('.is-universaldiscovery-hidden'); $node = $this->findWithWait('.ez-view-universaldiscoveryview'); $node = $this->findWithWait('.ez-view-universaldiscoveryfinderview .ez-ud-finder-explorerlevel', $node); $this->openFinderExplorerPath($path, $node); }
Explores the UDW, expanding it and click on the desired element. @param string $path The content browse path such as 'Content1/Content2/ContentIWantToClick'
entailment
public function dontSeeBrowsePath($path) { $found = true; try { $this->clickOnBrowsePath($path); } catch (\Exception $e) { $found = false; } if ($found) { throw new \Exception("Browse path '$path' was found"); } return true; }
Explores the UDW, to find the desired element. @param string $path The content browse path such as 'Content1/Content2/ContentIWantToClick'
entailment
protected function closeConfirmBox() { try { $elem = $this->getSession()->getPage()->find('css', '.ez-view-confirmboxview'); if ($elem && $elem->isVisible()) { $elem->find('css', '.ez-confirmbox-close-icon')->click(); $this->sleep(); } } catch (\Exception $e) { } }
Close the "Confirm" modal dialog, if it is visible.
entailment
protected function closeEditView() { try { $elem = $this->getSession()->getPage()->find('css', '.ez-main-content'); if ($elem && $elem->isVisible()) { $elem->find('css', '.ez-view-close')->click(); $this->waitWhileLoading(); } } catch (\Exception $e) { } }
Close the Edit view, if it is open.
entailment
protected function attachFile($fileName, $selector) { if ($this->getMinkParameter('files_path')) { $fullPath = rtrim( realpath( $this->getMinkParameter('files_path') ), DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR . $fileName; if (is_file($fullPath)) { $fileInput = 'input[type="file"]' . $selector; $field = $this->getSession()->getPage()->find('css', $fileInput); if (null === $field) { throw new Exception("File input $selector is not found"); } $field->attachFile($fullPath); } } else { throw new Exception("File $fileName is not found at the given location: $fullPath"); } }
Attaches a file to a input field on the HTML. @param string $file file name relative to mink definitions @param string $selector CSS file upload element selector
entailment
public static function create(array $properties, Direction $direction = null) : Sort { if ($direction === null) { $direction = Direction::$ASC; } $orders = []; foreach ($properties as $property) { $orders[] = new Order($direction, $property); } return new self($orders); }
Factory method to order by several properties with the same direction. @param array $properties @param Direction $direction @return Sort
entailment
public function andSort(Sort $sort = null) : Sort { if ($sort === null) { return $this; } $orders = $this->orders; foreach ($sort as $order) { $orders[] = $order; } return new Sort($orders); }
Does not modifies the object itself, will return a new instance instead. @param Sort $sort @return Sort
entailment
public function getOrderFor(string $property) : ?Order { /* @var $order Order */ foreach ($this as $order) { if ($order->getProperty() == $property) { return $order; } } return null; }
Returns the direction defined to the given property. @param string $property @return Order
entailment
private function loadFile($file, $ext) { $filename = $this->fixFilename($file, $ext); if (!is_readable($filename)) { throw new NotFoundException('file', $file); } return file_get_contents($filename); }
Reads file from disk. @param $file @param $ext @return string @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
entailment
private function sanitizeFilenames(array $files, $version) { $filesWithoutVersion = array_map(function ($file) use ($version) { if (preg_match('/\?' . preg_quote($version, '/') . '$/', $file)) { return substr($file, 0, -(strlen($version) + 1)); } return $file; }, $files); return $filesWithoutVersion; }
Removes version string (if any) from file paths. @param array $files @param string $version @return array
entailment
public function userInfo(string $username): Lastfm { $this->query = array_merge($this->query, [ 'method' => 'user.getInfo', 'user' => $username, ]); $this->pluck = 'user'; return $this; }
Get an array with user information. @param string $username @return Lastfm
entailment
public function userTopAlbums(string $username): Lastfm { $this->query = array_merge($this->query, [ 'method' => 'user.getTopAlbums', 'user' => $username, ]); $this->pluck = 'topalbums.album'; return $this; }
Get an array of top albums. @param string $username @return Lastfm
entailment
public function userTopArtists(string $username): Lastfm { $this->query = array_merge($this->query, [ 'method' => 'user.getTopArtists', 'user' => $username, ]); $this->pluck = 'topartists.artist'; return $this; }
Get an array of top artists. @param string $username @return Lastfm
entailment
public function userTopTracks(string $username): Lastfm { $this->query = array_merge($this->query, [ 'method' => 'user.getTopTracks', 'user' => $username, ]); $this->pluck = 'toptracks.track'; return $this; }
Get an array of top tracks. @param string $username @return Lastfm
entailment
public function userWeeklyTopArtists(string $username, \DateTime $startdate): Lastfm { $this->query = array_merge($this->query, [ 'method' => 'user.getWeeklyArtistChart', 'user' => $username, 'from' => $startdate->format('U'), 'to' => $startdate->modify('+7 day')->format('U'), ]); $this->pluck = 'weeklyartistchart.artist'; return $this; }
Get an array of weekly top artists. @param string $username @param \DateTime $startdate @return Lastfm
entailment
public function userWeeklyChartList(string $username): Lastfm { $this->query = array_merge($this->query, [ 'method' => 'user.getWeeklyChartList', 'user' => $username, ]); $this->pluck = 'weeklychartlist.chart'; return $this; }
Get an array of weekly chart list. @param string $username @return Lastfm
entailment
public function userRecentTracks(string $username): Lastfm { $this->query = array_merge($this->query, [ 'method' => 'user.getRecentTracks', 'user' => $username, ]); $this->pluck = 'recenttracks.track'; return $this; }
Get an array of most recent tracks. @param string $username @return Lastfm
entailment
public function nowListening(string $username) { $this->query = array_merge($this->query, [ 'method' => 'user.getRecentTracks', 'user' => $username, ]); $this->pluck = 'recenttracks.track.0'; $most_recent_track = $this->limit(1)->get(); if (!isset($most_recent_track['@attr']['nowplaying'])) { return false; } return $most_recent_track; }
Retrieve the track that is currently playing or "false" if not currently playing any track. @param string $username @return array|bool
entailment
public function period(string $period) { if (!in_array($period, Constants::PERIODS)) { throw new InvalidPeriodException('Request period is not valid. Valid values are defined in \Barryvanveen\Lastfm\Constants::PERIODS.'); } $this->query = array_merge($this->query ?? [], ['period' => $period]); return $this; }
Set or overwrite the period requested from the Last.fm API. @param string $period @throws InvalidPeriodException @return $this
entailment
public function limit(int $limit) { $this->query = array_merge($this->query ?? [], ['limit' => $limit]); return $this; }
Set or overwrite the number of items that is requested from the Last.fm API. @param int $limit @return $this
entailment
public function page(int $page) { $this->query = array_merge($this->query ?? [], ['page' => $page]); return $this; }
Set or overwrite the page of items that is requested from the Last.fm API. @param int $page @return $this
entailment
public function get(): array { $dataFetcher = new DataFetcher($this->httpClient); $this->data = $dataFetcher->get($this->query, $this->pluck); return $this->data; }
Retrieve results from the Last.fm API. @return array
entailment
public function get(array $query, $pluck = null) { $this->responseString = $this->client->get(self::LASTFM_API_BASEURL, [ 'http_errors' => false, 'query' => $query, ]); $this->data = json_decode((string) $this->responseString->getBody(), true); if (200 !== $this->responseString->getStatusCode() || null === $this->data) { $this->throwResponseException(); } if (isset($pluck)) { return $this->pluckData($this->data, $pluck); } return $this->data; }
Get, parse and validate a response from the given url. @param array $query @param null|string $pluck @return mixed
entailment
protected function throwResponseException() { if (null === $this->data) { throw new ResponseException('Undecodable response was returned.'); } if (isset($this->data['error'], $this->data['message'])) { throw new ResponseException($this->data['message'], $this->data['error']); } throw new ResponseException('Unknown error'); }
Throw an exception detailing what went wrong with this request. @throws ResponseException
entailment
protected function pluckData($data, $pluck) { if (isset($data[$pluck])) { return $data[$pluck]; } if (!$this->isNestedPluckString($pluck)) { throw new MalformedDataException('Malformed response data. Could not return requested array key.'); } $firstPluckPart = $this->getFirstPluckPart($pluck); if (!isset($data[$firstPluckPart])) { throw new MalformedDataException('Malformed response data. Could not return requested array key.'); } $remainingPluckPart = $this->getRemainingPluckPart($pluck); return $this->pluckData($data[$firstPluckPart], $remainingPluckPart); }
Pluck a specific index from the data array. $pluck may be a classic index or a dot-notated index, in which case the data array will be walked through recursively. Example 1: $data = ['foo' => 'bar', 'baz' => 'asd'], $pluck = 'foo', return = 'bar' Example 2: $data = ['foo' => ['bar' => 'baz']], $pluck = 'foo.bar', return = 'baz' Example 3: $data = ['foo' => [0 => 'bar', 1 => 'asd']], $pluck = 'foo.1', return = 'asd' Example 4: $data = ['foo' => 'bar', 'baz' => 'asd'], $pluck = '123', MalformedDataException @param array $data @param string $pluck @throws MalformedDataException @return mixed
entailment
private function getSiteaccessesByRepository() { $siteaccesses = []; foreach ($this->siteaccesses as $siteaccess) { $repository = $this->resolveRepositoryName( $this->configResolver->getParameter('repository', null, $siteaccess) ); if (!isset($siteaccesses[$repository])) { $siteaccesses[$repository] = []; } $siteaccesses[$repository][] = $siteaccess; } return $siteaccesses; }
Gets a list of siteaccesses grouped by repository. @return array
entailment
private function resolveRepositoryName($repository) { if ($repository === null) { $aliases = array_keys($this->repositories); $repository = array_shift($aliases); } return $repository; }
Resolves repository name. @param string|null $repository @return string
entailment
public function visitFile(\SplFileInfo $file, MessageCatalogue $catalogue) { if ($file->getExtension() !== 'js') { return; } $process = new Process('node ' . $this->translationDumperPath . ' ' . escapeshellarg($file)); $process->run(); $result = json_decode($process->getOutput()); if ($result && $result->translationsFound) { foreach ($result->translationsFound as $translation) { $message = new Message($translation->key, $translation->domain); $message->addSource(new FileSource($file->getPathname())); $catalogue->add($message); } } }
Called for non-specially handled files. This is not called if handled by a more specific method. @param \SplFileInfo $file @param MessageCatalogue $catalogue
entailment
public function serialize($jobId, $class, $args = [], $retry = true, $queue = null) { $class = is_object($class) ? get_class($class) : $class; $data = [ 'class' => $class, 'jid' => $jobId, 'created_at' => microtime(true), 'enqueued_at' => microtime(true), 'args' => $args, 'retry' => $retry, ]; if ($queue !== null) { $data['queue'] = $queue; } $jsonEncodedData = json_encode($data); if ($jsonEncodedData === false) { throw new JsonEncodeException($data, json_last_error(), json_last_error_msg()); } return $jsonEncodedData; }
Serialize and normalize job data @param string $jobId @param object|string $class @param array $args @param bool $retry @param string|null $queue @return string @throws JsonEncodeException
entailment
public function methodsFor($handler) : array { $handlerClass = get_class($handler); if (!array_key_exists($handlerClass, $this->configMap)) { $handlerClassObject = ObjectClass::forName($handlerClass); $handlerConfig = []; foreach ($this->configMap as $class => $currentConfigs) { if (ObjectClass::forName($class)->isAssignableFrom($handlerClassObject)) { $handlerConfig = array_merge($handlerConfig, $currentConfigs); } } $this->configMap[$handlerClass] = $handlerConfig; } return $this->configMap[$handlerClass]; }
Returns the registered {@link MethodConfiguration}s for the given handler. @param object $handler @return MethodConfiguration[]
entailment
public function yuiConfigLoaderFunction($configObject = '') { $modules = array_fill_keys($this->configResolver->getParameter('yui.modules', 'ez_platformui'), true); $yui = [ 'filter' => $this->configResolver->getParameter('yui.filter', 'ez_platformui'), 'modules' => [], ]; $combine = $this->configResolver->getParameter('yui.combine', 'ez_platformui'); if ($combine === true) { $yui['combine'] = true; } $yui['root'] = ''; $yui['comboBase'] = $this->router->generate('yui_combo_loader') . '?'; foreach (array_keys($modules) as $module) { if (!isset($yui['modules'][$module]['requires'])) { $yui['modules'][$module]['requires'] = []; } // Module dependencies if ($this->configResolver->hasParameter("yui.modules.$module.requires", 'ez_platformui')) { $yui['modules'][$module]['requires'] = array_merge( $yui['modules'][$module]['requires'], $this->configResolver->getParameter("yui.modules.$module.requires", 'ez_platformui') ); } // Reverse dependencies if ($this->configResolver->hasParameter("yui.modules.$module.dependencyOf", 'ez_platformui')) { foreach ($this->configResolver->getParameter("yui.modules.$module.dependencyOf", 'ez_platformui') as $dep) { // Add reverse dependency only if referred module is declared in the modules list. if (!isset($modules[$dep])) { if ($this->logger) { $this->logger->error("'$module' is declared to be a dependency of undeclared module '$dep'. Ignoring."); } continue; } $yui['modules'][$dep]['requires'][] = $module; } } if ($combine === true) { $yui['modules'][$module]['combine'] = true; } if ($this->configResolver->getParameter("yui.modules.$module.type", 'ez_platformui') === 'template') { $yui['modules'][$module]['requires'][] = 'template'; $yui['modules'][$module]['requires'][] = 'handlebars'; $yui['modules'][$module]['fullpath'] = $this->router->generate( 'template_yui_module', ['module' => $module] ); } else { $yui['modules'][$module]['fullpath'] = $this->asset( $this->configResolver->getParameter("yui.modules.$module.path", 'ez_platformui') ); } } // Now ensure that all requirements are unique foreach ($yui['modules'] as &$moduleConfig) { $moduleConfig['requires'] = array_unique($moduleConfig['requires']); } $res = ''; if ($configObject != '') { $res = $configObject . ' = '; } return $res . (defined('JSON_UNESCAPED_SLASHES') ? json_encode($yui, JSON_UNESCAPED_SLASHES) : json_encode($yui)) . ';'; }
Returns the YUI loader configuration. @param string $configObject @return string
entailment
public function load(AggregateId $aggregateId) : AggregateRoot { return $this->getProperRepository($aggregateId->aggregateClass())->load($aggregateId); }
Load the aggregate identified by $aggregateId from the persistent storage. @param AggregateId $aggregateId @return AggregateRoot @throws InvalidArgumentException If the $aggregateId is invalid
entailment
public function save(AggregateRoot $aggregateRoot) : void { $this->getProperRepository($aggregateRoot->className())->save($aggregateRoot); }
Persisting the given $aggregateRoot. @param AggregateRoot $aggregateRoot
entailment
public function shellAction(Request $request) { $this->translator->setLocale($request->getPreferredLanguage() ?: $request->getDefaultLocale()); return $this->render( 'eZPlatformUIBundle:PlatformUI:shell.html.twig', ['parameters' => $this->configAggregator->getConfig()] ); }
Renders the "shell" page to run the JavaScript application. @param \Symfony\Component\HttpFoundation\Request $request @return \Symfony\Component\HttpFoundation\Response
entailment
public function combineLoaderAction(Request $request) { $files = array_keys($request->query->all()); $version = $this->get('assets.packages')->getVersion('/'); try { $type = $this->loader->getCombinedFilesContentType($files, $version); $content = $this->loader->combineFilesContent($files, $version); } catch (NotFoundException $e) { throw new NotFoundHttpException($e->getMessage()); } catch (InvalidArgumentValue $e) { throw new BadRequestHttpException($e->getMessage()); } $headers = ['Content-Type' => $type]; if ($this->comboCacheTtl && $version != '') { $headers['Cache-Control'] = "public, s-maxage=$this->comboCacheTtl"; } return new Response( $content, Response::HTTP_OK, $headers ); }
Load JS or CSS assets. @param \Symfony\Component\HttpFoundation\Request $request @return \Symfony\Component\HttpFoundation\Response
entailment
public function setPjaxRequestLocale(GetResponseEvent $event) { $request = $event->getRequest(); if (!$event->isMasterRequest() || !$this->requestMatcher->matches($request)) { return; } $request->setLocale($request->getPreferredLanguage()); $request->attributes->set('_locale', $request->getPreferredLanguage()); }
On pjax requests, sets the request's locale from the browser's accept-language header. @param GetResponseEvent $event
entailment
protected function validateUpdate(Validable $model) { // When we are trying to update this model we need to set the update rules // on the validator first, next we can determine if the model is valid, // finally we restore original rules and notify in case of failure. $model->getValidator()->setRules($model->getUpdateRules()); $valid = $model->isValid(); $model->getValidator()->setRules($model->getCreateRules()); if (!$valid) { return false; } }
Halt updating if model doesn't pass validation. @param \Sofa\Eloquence\Contracts\Validable $model @return void|false
entailment
public function publishCollection(CollectionInterface $collection, callable $callback = null) { if (!$this->configurationService->getCurrentConfigurationByPath('resourceProxy')) { return parent::publishCollection($collection, $callback); } /** * @var ProxyAwareWritableFileSystemStorage $storage */ $storage = $collection->getStorage(); if (!$storage instanceof ProxyAwareWritableFileSystemStorage) { return parent::publishCollection($collection, $callback); } foreach ($collection->getObjects($callback) as $object) { /** @var StorageObject $object */ if ($storage->resourceIsPresentInStorage($object) === false) { // this storage ignores resources that are not yet in the filesystem as they // are optimistically created during read operations continue; } $sourceStream = $object->getStream(); $this->publishFile($sourceStream, $this->getRelativePublicationPathAndFilename($object)); fclose($sourceStream); } }
Publishes the whole collection to this target @param CollectionInterface $collection The collection to publish @param callable $callback Function called after each resource publishing @return void
entailment
final protected function raise(DomainEvent $event) : void { $this->setStateHash($this->calculateNextStateHash($event)); if ($event instanceof AbstractDomainEvent) { AbstractDomainEvent::initEvent($event, $this->getId(), $this->stateHash()); } EventPublisher::instance()->post($event); }
Updates the state hash and sends the DomainEvent to the EventPublisher. It also automatically fills the raised event if it extends AbstractDomainEvent. @param DomainEvent $event
entailment
public function seeRequiredFieldtOfType($label) { if ($this->platformStatus == self::WAITING_FOR_PUBLISHING) { $fieldManager = $this->getFieldTypeManager(); // $type = ... //$name = $fieldManager->getThisFieldTypeName(); $verification = new WebAssert($this->getSession()); //$verification->elementTextContains('css', $this->getEditLabelCss($type, $name), $label . '*');. $verification->elementTextContains('css', '.ez-fielddefinition-name', $label . '*'); } else { throw new \Exception('Cannot publish content, application in wrong state'); } }
@Then the :label field should be marked as required Checks to see if the field is marked as required when editing.
entailment
public function createSnapshot(AggregateId $aggregateId) : void { if (!$this->eventSourced($aggregateId)) { return; } /* @var $aggregateRoot EventSourcedAggregateRoot */ $aggregateRoot = $this->loadSnapshot($aggregateId); $stateHash = $aggregateRoot === null ? null : $aggregateRoot->stateHash(); $events = $this->getEventsFor($aggregateId, $stateHash); if ($events->count() == 0) { return; } if ($aggregateRoot === null) { $aggregateRoot = ObjectClass::forName($aggregateId->aggregateClass())->newInstanceWithoutConstructor(); } $aggregateRoot->loadFromHistory($events); $this->doCreateSnapshot($aggregateRoot); }
Events raised in the current transaction are not being stored in this snapshot. Only the already persisted events are being utilized. @param AggregateId $aggregateId
entailment