sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function insert(array $data, $options = []) { $before_insert_event = $this->dispatchEvent('Model.beforeInsert', compact('data', 'options')); if (!empty($before_insert_event->result['data']) && $before_insert_event->result['data'] !== $data) { $data = $before_insert_event->result[...
Wraps Monga's native `insert()` method on their Collection object. If the beforeInsert() method is defined, calls that method with this methods arguments and allows direct modification of the $data argument before the insert query is called. If the afterInsert() method is defined, it is called after the insert is suc...
entailment
public function remove($criteria, $options = []) { $before_remove_event = $this->dispatchEvent('Model.beforeRemove', compact('criteria')); if (!empty($before_remove_event->result['criteria']) && $before_remove_event->result['criteria'] !== $criteria) { $criteria = $before_remove_event->...
Wraps Monga's native `remove()` method on their Collection object. If the beforeRemove() method is defined, calls that method with this methods arguments and allows direct modification of the $criteria argument before the remove query is called. If the afterRemove() method is defined, it is called after the remove is...
entailment
public function canReview(ReviewableInterface $subject) { if ($subject instanceof FileInterface) { return $this->canReviewFile($subject); } if ($subject instanceof CommitMessageInterface) { return $this->canReviewMessage($subject); } return false; ...
Determine if the subject can be reviewed. @param ReviewableInterface $subject @return boolean
entailment
private function getRootDirectory() { static $root; if (!$root) { $working = getcwd(); $myself = __DIR__; if (0 === strpos($myself, $working)) { // Local installation, the working directory is the root $root = $working; ...
Get the root directory for a process command. @return string
entailment
public function fix(SplFileInfo $file, Tokens $tokens): void { $code = $this->removeRedundantTrailingSpaces($tokens->generateCode()); $tokens->setCode($code); }
{@inheritdoc}
entailment
public function review(ReporterInterface $reporter, ReviewableInterface $file) { $cmd = sprintf('php --syntax-check %s', $file->getFullPath()); $process = $this->getProcess($cmd); $process->run(); // Create the array of outputs and remove empty values. $output = array_filte...
Checks PHP files using the builtin PHP linter, `php -l`.
entailment
public function fix(SplFileInfo $file, Tokens $tokens): void { $code = preg_replace_callback( '@{{\s*(d|dump)\s*\(\s*.+?\s*\)\s*}}@imsu', function ($matches) { return ''; }, $tokens->generateCode() ); $tokens->setCode($code); ...
{@inheritdoc}
entailment
public function select(callable $filter) { if (! $this->collection) { return new FileCollection(); } $filtered = array_filter($this->collection, $filter); return new FileCollection($filtered); }
Filters the collection with the given closure, returning a new collection. @return FileCollection
entailment
public static function get($alias, $config = []) { if (static::_isInstantiated($alias)) { return static::$_instances[$alias]; } // Sets connection based on whether $conn = isset($config['connection']) ? $config['connection'] : 'mongo_db'; $mongo_connection = Con...
Get an instance of a Collection class from the default namespace with the appropriate datasource injected into the Collection instance. You can change the datasource of the returned Collection object by passing a datasource string into the 'connection' paramater of the $config array for this function. @param $alias @...
entailment
private function getFirstClassNameInFile(File $file): ?string { $position = $file->findNext(T_CLASS, 0); if ($position === false) { return null; } $fileClassName = ClassHelper::getFullyQualifiedName($file, $position); return ltrim($fileClassName, '\\'); }
We can not use Symplify\TokenRunner\Analyzer\SnifferAnalyzer\Naming::getClassName() as it does not include namespace of declared class. @param \PHP_CodeSniffer\Files\File $file @return string|null
entailment
private function matchUseImports(Tokens $tokens, string $className): ?string { $namespaceUseAnalyses = $this->namespaceUsesAnalyzer->getDeclarationsFromTokens($tokens); foreach ($namespaceUseAnalyses as $namespaceUseAnalysis) { if ($className === $namespaceUseAnalysis->getShortName()) {...
Tries to match names against use imports, e.g. "SomeClass" returns "SomeNamespace\SomeClass" for: use SomeNamespace\AnotherClass; use SomeNamespace\SomeClass; @param \PhpCsFixer\Tokenizer\Tokens $tokens @param string $className @return string|null
entailment
public function connect() { if ($this->_mongo) { return $this->_mongo; } if ($this->logger() && $this->logQueries()) { $logger = $this->buildStreamContext(); } else { $logger = []; } $this->_mongo = Monga::connection($this->dns(),...
Connects to our MongoDB instance and returns the connection object. If we have connected previously, returns the old connection object that's already been established. @return Monga\Connection|null
entailment
public function config($config = null) { if ($this->_config) { return $this->_config; } $this->_config = $config; return $this->_config; }
Gets and Sets our configuration array for our connection class. @param null $config @return null
entailment
public function dns($dns = null) { if ($dns) { $this->_config['dns'] = $dns; return $dns; } if (isset($this->_config['dns'])) { return $this->_config['dns']; } return 'mongodb://localhost:27017'; }
Gets or Sets the DNS string for our connection in our configuration array. If no DNS string is provided, the default localhost DNS is returned. @param null $dns @return null|string
entailment
protected function arrayInclude($array, Array $includedKeys) { $config = []; foreach($includedKeys as $key){ if (isset($array[$key])) { $config[$key] = $array[$key]; } } return $config; }
Helper method for returning an associative array with only the keys provided in the second argument. Used for building our Monga/MongoClient configuration without passing in unneeded keys that will throw errors. @param $array @param array $includedKeys @return array
entailment
public function getDefaultDatabase() { if (!isset($this->_config['database'])) { throw new Exception(sprintf('You have not configured a default database for Datasource %s yet.', $this->_config['name'])); } $db = $this->_config['database']; return $this->connect()->databas...
Returns the default Database for a connection as defined by $config['name'] @return Monga\Database|\MongoDB
entailment
protected function buildStreamContext() { $opts = []; // If we have a logger defined, merge the context options from our logger with the context array if ($this->logQueries() && $logger = $this->logger()) { $opts['mongodb'] = $logger->getContext(); } $context = ...
Builds our context object for passing in query logging options as well as the SSL context for HTTPS @return array
entailment
public function fix(SplFileInfo $file, Tokens $tokens): void { $code = preg_replace_callback( '@(<button\b)(.*?)(\s*/?>)@imsu', function ($matches) { $beginning = $matches[1]; $attributes = $matches[2]; $end = $matches[3]; ...
{@inheritdoc}
entailment
public function getOptionsForConsole() { $builder = ''; foreach ($this->options as $option => $value) { $builder .= '--' . $option; if ($value) { $builder .= '=' . $value; } $builder .= ' '; } return $builder; }
Gets a string of the set options to pass to the command line. @return string
entailment
public function setOption($option, $value) { if ($option === 'report') { throw new \RuntimeException('"report" is not a valid option name.'); } $this->options[$option] = $value; return $this; }
Adds an option to be included when running PHP_CodeSniffer. Overwrites the values of options with the same name. @param string $option @param string $value @return PhpCodeSnifferReview
entailment
public function review(ReporterInterface $reporter, ReviewableInterface $file) { $bin = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, 'vendor/bin/phpcs'); $cmd = $bin . ' --report=json '; if ($this->getOptionsForConsole()) { $cmd .= $this->getOptionsForConsole(); } ...
Checks PHP files using PHP_CodeSniffer.
entailment
public function review(ReporterInterface $reporter, ReviewableInterface $file) { $cmd = sprintf('read -r LINE < %s && echo $LINE', $file->getFullPath()); $process = $this->getProcess($cmd); $process->run(); if (! in_array(trim($process->getOutput()), ['<?php', '#!/usr/bin/env php']...
Checks if the set file starts with the correct character sequence, which helps to stop any rouge whitespace making it in before the first php tag. @link http://stackoverflow.com/a/2440685
entailment
public static function cssClassProvider($name, $value) { switch ($name) { case 'table_condensed': return $value ? 'table-condensed' : ''; break; case 'collapsed_sidebar': return $value ? 'sidebar-collapse' : ''; break; ...
Provides css class by given attribute name and value. @param $name string attribute name @param $value boolean|string attribute value @return string css class
entailment
public function report($level, $message, ReviewInterface $review, ReviewableInterface $subject) { $issue = new Issue($level, $message, $review, $subject); $this->issues->append($issue); return $this; }
Reports an Issue raised by a Review. @param int $level @param string $message @param ReviewInterface $review @param ReviewableInterface $subject @return Reporter
entailment
public function info($message, ReviewInterface $review, ReviewableInterface $subject) { $this->report(Issue::LEVEL_INFO, $message, $review, $subject); return $this; }
Reports an Info Issue raised by a Review. @param string $message @param ReviewInterface $review @param ReviewableInterface $subject @return Reporter
entailment
public function warning($message, ReviewInterface $review, ReviewableInterface $subject) { $this->report(Issue::LEVEL_WARNING, $message, $review, $subject); return $this; }
Reports an Warning Issue raised by a Review. @param string $message @param ReviewInterface $review @param ReviewableInterface $subject @return Reporter
entailment
public function error($message, ReviewInterface $review, ReviewableInterface $subject) { $this->report(Issue::LEVEL_ERROR, $message, $review, $subject); return $this; }
Reports an Error Issue raised by a Review. @param string $message @param ReviewInterface $review @param ReviewableInterface $subject @return Reporter
entailment
public function open($pdfFile) { $real_path = H::parseFileRealPath($pdfFile); if (is_file($real_path)) { $this->source_pdf = $real_path; if (!Config::isKeySet(C::OUTPUT_DIR)) { Config::setOutputDirectory(dirname($pdfFile)); } return ...
@param $pdfFile @return $this @throws PopplerPhpException
entailment
public function setOutputSubDir($dir_name) { $dir_name = H::parseDirName($dir_name); if (!empty($dir_name)) { $this->output_sub_dir = $dir_name; return $this; } throw new PopplerPhpException("Directory name must be an alphanumeric string"); }
@param $dir_name @return $this @throws PopplerPhpException
entailment
public function setOption($key, $value) { $util_options = $this->utilOptions(); if (array_key_exists($key, $util_options) and $util_options[ $key ] == gettype($value)) { $this->options[ $key ] = $value; return $this; } throw new PopplerPhpException("Unknown ...
@param $key @param $value @return $this @throws PopplerPhpException
entailment
public function unsetOption($key) { if ($this->hasOption($key)) $this->options = array_except($this->options, $key); return $this; }
@param $key @return $this
entailment
public function setFlag($key) { $util_flags = $this->utilFlags(); if (in_array($key, $util_flags)) { $this->flags[ $key ] = $key; return $this; } throw new PopplerPhpException("Unknown '".get_class($this)."' Flag: ".$key); }
@param $key @return $this @throws PopplerPhpException
entailment
public function unsetFlag($key) { if ($this->hasFlag($key)) $this->flags = array_except($this->flags, $key); return $this; }
@param $key @return $this
entailment
public function binDir($dir = '') { if (!empty($dir)) { $this->binary_dir = Config::setBinDirectory($dir); return $this; } elseif ($dir == C::DFT) { $this->binary_dir = Config::setBinDirectory(Config::getBinDirectory()); } return Config::...
@param string $dir @return $this
entailment
public function setOutputFilenamePrefix($name) { $name = H::parseFileName($name); if (!empty($name)) { $this->output_file_name = $name; return $this; } throw new PopplerPhpException("Filename must be an alphanumeric string"); }
@param $name @return $this @throws PopplerPhpException
entailment
public function addException($exception) { if ($exception->getMessage()) { $this->message .= "\n".$exception->getMessage(); } $this->exceptions[] = $exception; }
addException @param mixed $exception @access public @return void
entailment
protected function doParse() { $object = $this->objectNameToKey($this->objectName); if ('ok' !== $this->data['@attributes']['stat']) { $errorCode = (int) $this->data['@attributes']['err_code']; $errorMessage = $this->data['err']; if (in_array($errorCode, array(1...
Parse the response document @access protected @throws AuthenticationErrorException, InvalidArgumentException, RuntimeException @return array
entailment
protected function parseMultiRecordResult($objectName, $data) { $this->resultCount = (int) $data['result']['total_results']; if (0 === $this->resultCount) { $this->result = array(); } else { if (array_key_exists($objectName, $data['result'])) { if ($t...
Parse response document containing multiple records @param string $objectName The name of the Pardot object being requested @param array $data The data as an associative array @access protected @throws InvalidArgumentException @return void
entailment
protected function resultHasOnlyOneRecord($objectName, $data) { $json = json_encode($data); if (JSON_ERROR_NONE !== json_last_error()) { throw new RuntimeException('Unable to encode previously decoded data back to JSON. Json error: ' . json_last_error()); } $asString = ...
Determine if the content inside of [result][objecname] consists of a single record or an array of records The results from the Pardot API are unfortunately not consisten and have to be normalized. When the result set has more than limit (which is max 200) records, it requires that multiple calls to the API must be ma...
entailment
protected function doParse() { // just make it work modified base class $this->document = $this->data; $object = $this->objectName; if (!$this->document instanceof SimpleXmlElement) { throw new RuntimeException('document is not instance of SimpleXmlElement'); } ...
Parse the response document @access protected @return void
entailment
public function openTunnel(array $config): Process { $process = new Process($this->createSshCommand($config)); $process->setTimeout(60); $process->start(); while ($process->isRunning()) { sleep(1); } if ($process->getExitCode() !== 0) { throw...
Open SSH tunnel defined by config @param array $config Configuration fields: - user: (string) SSH proxy username. Required. - sshHost: (string) SSH proxy hostname. Required. - sshPort: (string) SSH protocol port. Optional, default 22. - localPort: (string) local port. Optional, default 33006. - remoteHost: (string) ...
entailment
public function authenticate() { $object = 'login'; $url = sprintf('/api/%s/version/%s', $object, $this->version); $parameters = array( 'email' => $this->email, 'password' => $this->password, 'user_key' => $this->userKey, 'format' => $this...
Make a call to the login endpoint and obtain an API key This step is not absolutely necessary, because the post method will check for the presence of a key and will call this method if there is none. @access public @return void
entailment
public function post($object, $operation, $parameters) { if (null === $this->apiKey) { $this->authenticate(); } $url = sprintf('/api/%s/version/%s/do/%s', $object, $this->version, $operation); $parameters = array_merge( array( 'api_key' => $t...
Makes necessary preparations for a POST request to the Pardot API, handles authentication retries The method constructs a valid url based on the object and the operator. If the API key is null, it also makes a call to the authenticate method. If an API key is present but happens to be stale, this is detected as well a...
entailment
protected function getClient() { $retries = 5; $httpCodes = null; $curlCodes = null; $plugin = BackoffPlugin::getExponentialBackoff($retries, $httpCodes, $curlCodes); $client = new Client($this->baseUrl); $client->addSubscriber($plugin); return $client; ...
Construct the Guzzle Http Client with the exponential retry plugin @access protected @return \Guzzle|Http\Client
entailment
protected function doPost($object, $url, $parameters) { $httpResponse = null; $headers = null; $postBody = null; $options = $this->httpClientOptions; try { $httpResponse = $this->client->post($url, $headers, $postBody, $options) ->setHeader('Conte...
Makes the actual HTTP POST call to the API, parses the response and returns the data if there is any. Throws exceptions in case of error. @param string $object The name of the object to perform an operation on @param string $url The URL that will be accessed @param array $parameters The parameters to send ...
entailment
protected function getHandler($response, $object) { $handler = null; switch ($this->format) { case 'json': $this->rawResponse = $response->json(); $handler = new JsonResponseHandler($this->rawResponse, $object); break; case 'xml': $thi...
Instantiate the appropriate Response document handler based on the format @param Guzzle\Http|Message|Response $response The Guzzle Response object @param string $object The name of the pardot obj @access protected @return HGG\Pardot\AbstractResponseHanler
entailment
public function getAddresses($postcode = null, $number = null, $from = 0) { return $this->get('/addresses/', [ 'postcode' => $postcode, 'number' => $number, 'from' => $from ]); }
@param string|null $postcode @param string|null $number @param int $from @return \stdClass
entailment
public function getPostcodesByCoordinates($latitude, $longitude, $sort = self::POSTCODES_SORT_DISTANCE) { return $this->get('/postcodes/', [ 'coords' => [ 'latitude' => $latitude, 'longitude' => $longitude ], 'sort' => $sort ]); ...
@param string $latitude @param string $longitude @param string $sort @return \stdClass
entailment
private function get($path, array $params = []) { $request = $this->createHttpGetRequest($this->buildUrl($path), $params); $response = $this->httpClient->sendRequest($request); return $this->parseResponse($response, $request); }
@param string $path @param array $params @return \stdClass @throws RequestException
entailment
private function createHttpGetRequest($url, array $params = []) { $url .= (count($params) > 0 ? '?' . http_build_query($params, null, '&', PHP_QUERY_RFC3986) : ''); return new Request('GET', $url); }
@param string $method @param string $url @param array $queryParams @return Request
entailment
private function parseResponse(ResponseInterface $response, RequestInterface $request) { $result = json_decode((string) $response->getBody()->getContents()); if (json_last_error() !== JSON_ERROR_NONE) { throw new CouldNotParseResponseException('Could not parse response', $response); ...
@param ResponseInterface $response @return \stdClass @throws CouldNotParseResponseException
entailment
public static function setBinDirectory($dir) { $real_path = realpath($dir); if ($real_path) { $real_path = H::parseDirName($real_path); self::set(C::BIN_DIR, $real_path); return $real_path; } elseif ($dir == C::DFT) { return self::set...
@param $dir @return mixed|string @throws PopplerPhpException
entailment
public static function setOutputDirectory($dir, $new = false) { $real_path = $new ? $dir : realpath($dir); if ($real_path) { $real_path = H::parseDirName($real_path); self::set(C::OUTPUT_DIR, $real_path); return $real_path; } elseif ($dir == C::D...
@param $dir @param bool $new @return mixed|string @throws PopplerPhpException
entailment
public static function getOutputDirectory($default = null) { $check = is_dir($default); $default = $check ? $default : H::parseDirName(C::DEFAULT_OUTPUT_DIR); return self::get(C::OUTPUT_DIR, realpath($default)); }
@param mixed $default @return mixed
entailment
public static function decode($data) { $decoded = \base64_decode($data, true); if ($decoded === false) { throw new DecodingError(); } return $decoded; }
Decodes the supplied data from Base64 @param string $data @return mixed @throws DecodingError if the input has been invalid
entailment
public static function encodeUrlSafe($data) { $encoded = self::encode($data); return \strtr( $encoded, self::LAST_THREE_STANDARD, self::LAST_THREE_URL_SAFE ); }
Encodes the supplied data to a URL-safe variant of Base64 @param mixed $data @return string @throws EncodingError if the input has been invalid
entailment
public static function decodeUrlSafe($data) { $data = \strtr( $data, self::LAST_THREE_URL_SAFE, self::LAST_THREE_STANDARD ); return self::decode($data); }
Decodes the supplied data from a URL-safe variant of Base64 @param string $data @return mixed @throws DecodingError if the input has been invalid
entailment
public static function encodeUrlSafeWithoutPadding($data) { $encoded = self::encode($data); $encoded = \rtrim( $encoded, \substr(self::LAST_THREE_STANDARD, -1) ); return \strtr( $encoded, \substr(self::LAST_THREE_STANDARD, 0, -1), \substr(self::LAST_THREE_URL_SAFE, 0, -1) ); }
Encodes the supplied data to a URL-safe variant of Base64 without padding @param mixed $data @return string @throws EncodingError if the input has been invalid
entailment
public function render($echo = false) { $name = $this->field->getName(); $display = $this->field->getDisplayName(); $value = $this->getValue(); $readOnly = $this->getReadOnlyString(); $required = $this->getRequiredString(); $html = <<< HTML <div class="form...
Render Field for Create/Edit @param bool|true $echo @return string
entailment
public static function execute(Event $event) { $composer = $event->getComposer(); $encoder = new IniEncoder(); // Convert the lock file to a make file using Drush's make-convert command. $binDir = $composer->getConfig()->get('bin-dir'); $make = NULL; $executor = new ProcessExecutor(); $exec...
Main entry point for command. @param \Composer\Script\Event $event Composer event. @throws \RuntimeException
entailment
protected function loadStoreId() { $query = Drupal::entityQuery('commerce_store'); $result = $query->execute(); // There should only ever be one value returned so we naively use the first // item in the array. This should generally be safe as this should only run // within a Drupal site install con...
Loads the main store. @return int Loaded store ID or NULL if one couldn't be found.
entailment
public function toArray() { return array_filter( array( 'id' => $this->id, 'label' => $this->label, 'type' => $this->type, ), function ($val) { return !is_null($val);} ); }
returns an array representation of the instance @return array
entailment
protected function setupDefaultMarshallers() { $this->getConverter()->registerMarshaller(Blob::class, new Marshaller\BlobMarshaller()); $this->getConverter()->registerMarshaller(Blobs::class, new Marshaller\BlobsMarshaller()); $this->getConverter()->registerMarshaller(Operation\ActionList::class, new Marsha...
@return NuxeoClient @throws AnnotationException
entailment
public function workCommand($queue, $exitAfter = null, $limit = null, $verbose = false) { if ($verbose) { $this->output('Watching queue <b>"%s"</b>', [$queue]); if ($exitAfter !== null) { $this->output(' for <b>%d</b> seconds', [$exitAfter]); } ...
Work on a queue and execute jobs This command is used to execute jobs that are submitted to a queue. It is meant to run in a "server loop" and should be backed by some Process Control System (e.g. supervisord) that will restart the script if it died (due to exceptions or memory limits for example). Alternatively the ...
entailment
public function listCommand($queue, $limit = 1) { $jobs = $this->jobManager->peek($queue, $limit); $totalCount = $this->queueManager->getQueue($queue)->countReady(); foreach ($jobs as $job) { $this->outputLine('<b>%s</b>', [$job->getLabel()]); } if ($totalCount >...
List queued jobs Shows the label of the next <i>$limit</i> Jobs in a given queue. @param string $queue The name of the queue @param integer $limit Number of jobs to list (some queues only support a limit of 1) @return void @throws JobQueueException
entailment
public function executeCommand($queue, $messageCacheIdentifier) { if(!$this->messageCache->has($messageCacheIdentifier)) { throw new JobQueueException(sprintf('No message with identifier %s was found in the message cache.', $messageCacheIdentifier), 1517868903); } /** @var Messa...
Execute one job @param string $queue @param string $messageCacheIdentifier An identifier to receive the message from the cache @return void @internal This command is mainly used by the JobManager and FakeQueue in order to execute commands in sub requests @throws JobQueueException
entailment
public function sendRequest($req) { $response = $this->send($req->getJSON()); if ($response->id != $req->id) { throw new Clientside\Exception("Mismatched request id"); } if(isset($response->error_code)) { throw new Clientside\Exception("{$response->error_cod...
send a single request object
entailment
public function sendNotify($req) { if (property_exists($req, 'id') && $req->id != null) { throw new Clientside\Exception("Notify requests must not have ID set"); } $this->send($req->getJSON(), true); return true; }
send a single notify request object
entailment
public function sendBatch($reqs) { $arr = array(); $ids = array(); $all_notify = true; foreach ($reqs as $req) { if ($req->id) { $all_notify = false; $ids[] = $req->id; } $arr[] = $req->getArray(); } ...
send an array of request objects as a batch
entailment
public function send($json, $notify = false) { // use http authentication header if set $header = "Content-Type: application/json\r\n"; if ($this->authHeader) { $header .= $this->authHeader; } // prepare data to be sent $opts = array( 'http' =...
send raw json to the server
entailment
function decodeJSON($json) { $json_response = json_decode($json); if ($json_response === null) { throw new Clientside\Exception("Unable to decode JSON response from: {$json}"); } return $json_response; }
decode json throwing exception if unable
entailment
public function handleResponse($response) { // recursion for batch if (is_array($response)) { $response_arr = array(); foreach ($response as $res) { $response_arr[$res->id] = $this->handleResponse($res); } return $response_arr; ...
handle the response and return a result or an error
entailment
public function queue(string $queueName, JobInterface $job, array $options = []): void { $queue = $this->queueManager->getQueue($queueName); $payload = serialize($job); $messageId = $queue->submit($payload, $options); $this->emitMessageSubmitted($queue, $messageId, $payload, $option...
Put a job in the queue @param string $queueName @param JobInterface $job The job to submit to the queue @param array $options Simple key/value array with options that will be passed to the queue for this job (optional) @return void @api
entailment
public function waitAndExecute(string $queueName, $timeout = null): ?Message { $messageCacheIdentifier = null; $queue = $this->queueManager->getQueue($queueName); $message = $queue->waitAndReserve($timeout); if ($message === null) { $this->emitMessageTimeout($queue); ...
Wait for a job in the given queue and execute it A worker using this method should catch exceptions @param string $queueName @param integer $timeout @return Message The message that was processed or NULL if no job was executed and a timeout occurred @throws \Exception @api
entailment
protected function emitMessageReleased(QueueInterface $queue, Message $message, array $releaseOptions, \Exception $jobExecutionException = null): void { }
Signal that is triggered when a message has been re-released to the queue @param QueueInterface $queue The queue the released message belongs to @param Message $message The message that was released to the queue again @param array $releaseOptions The options that were passed to the release call @param \Exception $jobE...
entailment
public function listCommand() { $rows = []; foreach ($this->queueConfigurations as $queueName => $queueConfiguration) { $queue = $this->queueManager->getQueue($queueName); try { $numberOfMessages = $queue->countReady(); } catch (\Exception $e) { ...
List configured queues Displays all configured queues, their type and the number of messages that are ready to be processed. @return void @throws Exception
entailment
public function describeCommand($queue) { $queueSettings = $this->queueManager->getQueueSettings($queue); $this->outputLine('Configuration options for Queue <b>%s</b>:', [$queue]); $rows = []; foreach ($queueSettings as $name => $value) { $rows[] = [$name, is_array($value...
Describe a single queue Displays the configuration for a queue, merged with the preset settings if any. @param string $queue Name of the queue to describe (e.g. "some-queue") @return void @throws Exception
entailment
public function setupCommand($queue) { $queue = $this->queueManager->getQueue($queue); try { $queue->setUp(); } catch (\Exception $exception) { $this->outputLine('<error>An error occurred while trying to setup queue "%s":</error>', [$queue->getName()]); $t...
Initialize a queue Checks connection to the queue backend and sets up prerequisites (e.g. required database tables) Most queue implementations don't need to be initialized explicitly, but it doesn't harm and might help to find misconfigurations @param string $queue Name of the queue to initialize (e.g. "some-queue") ...
entailment
public function flushCommand($queue, $force = false) { $queue = $this->queueManager->getQueue($queue); if (!$force) { $this->outputLine('Use the --force flag if you really want to flush queue "%s"', [$queue->getName()]); $this->outputLine('<error>Warning: This will delete all...
Remove all messages from a queue! This command will delete <u>all</u> messages from the given queue. Thus it should only be used in tests or with great care! @param string $queue Name of the queue to flush (e.g. "some-queue") @param bool $force This flag is required in order to avoid accidental flushes @return void @...
entailment
public function submitCommand($queue, $payload, $options = null) { $queue = $this->queueManager->getQueue($queue); if ($options !== null) { $options = json_decode($options, true); } $messageId = $queue->submit($payload, $options !== null ? $options : []); $this->o...
Submit a message to a given queue This command can be used to "manually" add messages to a given queue. <b>Example:</b> <i>flow queue:submit some-queue "some payload" --options '{"delay": 14}'</i> To make this work with the <i>JobManager</i> the payload has to be a serialized instance of an object implementing <i>Jo...
entailment
public function getUrl(DataTable $data, $width, $height, $title = null, $params = array(), $rawParams = array()) { $title = isset($title) ? $title: null; $titleSize = isset($params['titleSize']) ? $params['titleSize']: null; $titleColor = isset($params['titleColor']) ? $params['t...
Returns a URL for the Google Image Chart @param DataTable $data (labels are keys... if associative array) @param integer $width @param integer $height @param array $color @param string $title @return string the Google Image Chart URL of the PieChart
entailment
public function render($echo = false) { $name = $this->field->getName(); $display = $this->field->getDisplayName(); $defaultValue = $this->field->getDefaultValue(); $bean = $this->field->getBean(); $value = $this->getValue(); $readOnly = $this->getReadOnlyString(); ...
Render Field for Create/Edit @param bool|true $echo @return string
entailment
public static function createBlocks() { $block = Block::create([ 'id' => 'presto_theme_views_block__presto_product_listing_listing_block', 'status' => TRUE, 'plugin' => 'views_block:presto_product_listing-listing_block', 'weight' => 10, 'theme' => 'presto_theme', 'region' => 'con...
Create block. We do a manual entity create as for some reason it won't import via config. @throws \Drupal\Core\Entity\EntityStorageException
entailment
public function field($name) { if (!isset($this->fieldList[$name])) { $this->addField($name); } return $this->fieldList[$name]; }
Get or Create a field with a name @param string $name The Field Name @return Field The field object @throws Exception
entailment
public function addField($name, $dataType = "varchar(255)") { if ($name == "") { throw new Exception("Field name cannot be empty."); } // Check if the name whether is satisfied if (ctype_upper($name[0])) { throw new Exception("Field name cannot start with upp...
Create a field with a name @param $name @param string $dataType it can be varchar/int/text @throws Exception
entailment
public function getShowFields() { $fields = []; foreach ($this->fieldList as $field) { if (! $field->isHidden()) { // Must be number index $fields[] = $field; } } return $fields; }
Get an array of Field(s) which is/are going to be shown. @return Field[]
entailment
public function showFields($fieldNameList) { $nameList = []; $newOrderList = []; if (is_array($fieldNameList)) { // Array Style $nameList = $fieldNameList; } else { // Grocery CRUD style $numargs = func_num_args(); $fieldN...
Show and order field(s) @param string[] $fieldNameList An array of field name(s).
entailment
public function hideFields($fieldNameList) { if (is_array($fieldNameList)) { foreach ($fieldNameList as $name) { $this->field($name)->hide(); } } else { $numargs = func_num_args(); $fieldNames = func_get_args(); for ($i = ...
Hide fields, useful if you want to keep the field in the database but not show on the curd page. @param string[] $fieldNameList An array of field name(s).
entailment
public function createTable() { $bean = R::xdispense($this->tableName); R::store($bean); R::trash($bean); }
Create Table Problem: The first ID is always start from 2. TODO: Create table with pure SQL, but be careful it may not support for all databases.
entailment
protected function countTotalListViewData($keyword = null) { $count = 0; if ($this->listViewDataClosure != null) { if ($this->countListViewDataClosure != null) { $c = $this->countListViewDataClosure; return $c($keyword); } else { ...
Count Total List view data @param string $keyword @return int
entailment
protected function getListViewData($start = null, $rowPerPage = null, $keyword = null, $sortField = null, $sortOrder = null) { $list = []; if ($this->listViewDataClosure != null) { $c = $this->listViewDataClosure; $list = $c($start, $rowPerPage, $keyword, $sortField, $sortOrder)...
Get List view data @param int $start @param int $rowPerPage @param string $keyword @param string $sortField @param string $sortOrder ASC/DESC @return array List of beans @throws \RedBeanPHP\RedException\SQL
entailment
protected function beforeGetListViewData($callbackRedBean, $callbackSQL, $start = null, $rowPerPage = null, $keyword = null, $sortField = null, $sortOrder = null) { try { // Paging if ($start != null && $rowPerPage != null) { $limit = " LIMIT $start,$rowPerPage"; ...
Prepare the SQL or parameter for RedBean TODO: Sort by multiple fields? @param int $start @param int $rowPerPage @param string $keyword @param string $sortField @param null $sortOrder ASC/DESC @param callable $callbackRedBean @param callable $callbackSQL @throws \RedBeanPHP\RedException\SQL
entailment
public function getListViewJSONString($echo = true) { $this->beforeRender(); if (isset($_POST["start"])) { $start = $_POST["start"]; } else { $start = 0; } if (isset($_POST["length"])) { $rowPerPage = $_POST["length"]; } else { ...
For Ajax ListView (DataTables) @param bool|true $echo @return string @throws NoFieldException @throws \RedBeanPHP\RedException\SQL
entailment
public function getJSONList($echo = true) { $this->beforeRender(); if (isset($_POST["start"])) { $start = $_POST["start"]; } else { $start = 0; } if (isset($_POST["length"])) { $rowPerPage = $_POST["length"]; } else { $row...
For API @param bool|true $echo @return mixed @throws NoFieldException @throws \RedBeanPHP\RedException\SQL
entailment
public function loadBean($id) { if ($this->currentBean != null) { throw new BeanNotNullException(); } $this->currentBean = R::load($this->tableName, $id); }
Load a bean. For Edit and Create only. Before rendering the edit or Create page, you have to load a bean first. @param $id @throws BeanNotNullException You can load one time only.
entailment
public function insertBean($data) { $bean = R::xdispense($this->tableName); $result = $this->saveBean($bean, $data); if (empty($result->msg)) { $result->msg = "The record has been created successfully."; $result->class = "callout-info"; $result->ok = ...
Store Data into Database @param $data @return int|string
entailment
public function updateBean($data) { if ($this->currentBean ==null) { throw new NoBeanException(); } $result = $this->saveBean($this->currentBean, $data); // Return result if (empty($result->msg)) { $result->msg = "Saved."; $result->class ...
Update a bean. @param $data @return Result @throws NoBeanException
entailment
protected function saveBean($bean, $data) { // Handle File Field that may not in the $data, because Filename always go into $_FILES. foreach ($_FILES as $fieldName => $file) { $data[$fieldName] = $file["name"]; } // Store Showing fields only $fields = $this->getS...
Insert or Update a bean @param OODBBean $bean @param $data array @return Result
entailment
private function getLayoutName() { if ($this->layout != null) { return $this->layout; } try { return $this->template->exists("backend_layout") ? "backend_layout" : $this->theme . "::layout"; } catch (\LogicException $ex) { return $this->theme . ":...
Get Current Layout Name in Plates Template Engine style If user have created a layout.php in the default folder, use their layout.php. Or else use the default layout. @return string Layout Name
entailment
public function checkValid() { // error code/message already set if ($this->error_code && $this->error_message) { return false; } // missing jsonrpc or method if (!$this->json_rpc || !$this->method) { $this->error_code = self::ERROR_INVALID_REQUEST; ...
returns true if request is valid or returns false assigns error
entailment