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['data']; } if ($before_insert_event->isStopped()) { return false; } $results = $this->collection->insert($data, $options); $after_insert_event = $this->dispatchEvent('Model.afterInsert', compact('results', 'data', 'options')); return $results; }
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 successfully committed to the database. @param array $data @param array $options @return mixed
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->result['criteria']; } if ($before_remove_event->isStopped()) { return false; } $result = $this->collection->remove($criteria, $options); $after_insert_event = $this->dispatchEvent('Model.afterRemove', compact('result', 'criteria')); return $result; }
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 successfully committed to the database. @param $criteria @param array $options @return mixed
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; } else { // Global installation, back up above the vendor/ directory $root = realpath($myself . '/../../../../../'); } } return $root; }
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_filter(explode(PHP_EOL, $process->getOutput())); $needle = 'Parse error: syntax error, '; if (! $process->isSuccessful()) { foreach (array_slice($output, 0, count($output) - 1) as $error) { $raw = ucfirst(substr($error, strlen($needle))); $message = str_replace(' in ' . $file->getFullPath(), '', $raw); $reporter->error($message, $this, $file); } } }
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 = ConnectionManager::get($conn); static::$_instances[$alias] = static::_create($alias, $mongo_connection, $config); return static::$_instances[$alias]; }
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 @param array $config @return mixed
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()) { return $namespaceUseAnalysis->getFullName(); } } return null; }
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(), $this->getMongoConfig(), $logger); $this->_connected = true; return $this->_mongo; }
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()->database($db); }
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 = stream_context_create($opts); return ['context' => $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]; if (!preg_match('@(?:^|\s+)type=@', $attributes)) { $attributes .= ' type="button"'; } return $beginning . $attributes . $end; }, $tokens->generateCode() ); $tokens->setCode($code); }
{@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(); } $cmd .= $file->getFullPath(); $process = $this->getProcess($cmd); $process->run(); if (! $process->isSuccessful()) { // Create the array of outputs and remove empty values. $output = json_decode($process->getOutput(), true); $filter = function ($acc, $file) { if ($file['errors'] > 0 || $file['warnings'] > 0) { return $acc + $file['messages']; } }; foreach (array_reduce($output['files'], $filter, []) as $error) { $message = $error['message'] . ' on line ' . $error['line']; $reporter->warning($message, $this, $file); } } }
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'])) { $message = 'File must begin with `<?php` or `#!/usr/bin/env php`'; $reporter->error($message, $this, $file); } }
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; default: return parent::cssClassProvider($name, $value); } }
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 $this; } throw new PopplerPhpException("File not found: ".$real_path); }
@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 '".get_class($this)."' Option (or Invalid Type): ".$key.'='.$value.' ('.gettype($value).')'); }
@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::getBinDirectory(); }
@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, 15))) { throw new AuthenticationErrorException($errorMessage, $errorCode); } else { throw new RuntimeException($errorMessage, $errorCode); } } else { if (array_key_exists('result', $this->data)) { $this->parseMultiRecordResult($object, $this->data); } elseif (array_key_exists($object, $this->data)) { $this->parseSingleRecordResult($object, $this->data); } elseif (array_key_exists('api_key', $this->data)) { $this->resultCount = 0; $this->result = $this->data['api_key']; } else { $asString = true; throw new RuntimeException('Unknown response format: '.$this->responseObj->getBoby($asString)); } } }
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 ($this->resultHasOnlyOneRecord($objectName, $data)) { $this->result = array($data['result'][$objectName]); } else { $this->result = $data['result'][$objectName]; } } else { $msg = sprintf('The response does not contain the expected object key \'%s\'', $objectName); throw new InvalidArgumentException($msg); } } }
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 = false; $objData = json_decode($json, false); if (JSON_ERROR_NONE !== json_last_error()) { throw new RuntimeException('Unable to decode json. Json error: ' . json_last_error()); } // At this point we have already estableshed that there exists a // property called 'result', which is a stdClass object with a // property that has the name of the object ($objectName). return is_object($objData->result->$objectName); }
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 made in order to obtain the entire result set. This kind of thing would typically happen when making a query and not asking for a single record by id or email. One would expect to get an array of records back for all requests of this kind of query. For example, if the total_results value is 250 we would have to make two requests to get all records. The first request would return 200 records and the second would return 50 records. This means that [result][objectname] is an array of records. Unfortunately this is not so in the following edge case: When total_results is 201, the first request again returns an array of 200 records, but the second request simply returns a single record (object), which puts the responsibility of discovering the result contents on the consumer. Since this library decodes a JSON response into associative arrays and not stdClass Objects this becomes a bit difficult. To provide a consisten experience this hack will do the work of ensuring that all responses that are part of a single query return the same type of data - an array of records (or in some cases an array with a single record). @param string $objectName @param array $data @access protected @return boolean
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'); } if ('ok' !== (string) $this->document->attributes()->stat) { $errorCode = (integer) $this->document->err->attributes()->code; $errorMessage = (string) $this->document->err; if (in_array($errorCode, array(1, 15))) { throw new AuthenticationErrorException($errorMessage, $errorCode); } else { throw new RuntimeException($errorMessage, $errorCode); } } if ('login' == $object) { $this->result = (string) $this->document->api_key; } else { if (!empty($this->document->result)) { $this->resultCount = (integer) $this->document->result->total_results; $this->result = $this->document->xpath('/rsp/result/'.$object); } elseif (!empty($this->document->$object)) { $this->resultCount = 1; $this->result = array($this->document->$object); } else { throw new RuntimeException('Unknown response format'); } } }
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 new SSHException(sprintf( "Unable to create ssh tunnel. Output: %s ErrorOutput: %s", $process->getOutput(), $process->getErrorOutput() )); } return $process; }
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) destination machine hostname. Required. - remotePort: (string) destination machine port. Required. - privateKey: (string) SSH private key. Required. - compression: (bool) whether to use compression. Optional, default false. @return Process @throws SSHException
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->format ); $this->apiKey = $this->doPost($object, $url, $parameters); return $this->apiKey; }
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' => $this->apiKey, 'user_key' => $this->userKey, 'format' => $this->format, 'output' => $this->output ), $parameters ); try { return $this->doPost($object, $url, $parameters); } catch (AuthenticationErrorException $e) { $this->authenticate(); $parameters['api_key'] = $this->apiKey; return $this->doPost($object, $url, $parameters); } }
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 and a call to authenticate is made to get a new key. @param string $object The name of the Pardot object of interest @param string $operation The operation to be performed on the object @param array $parameters The parameters to send @access public @return mixed In case of format=JSON it returns PHP arrays, if format=XML it will either return a single SimpleXMLElement or an array of SimpleXmlElements @throws HGG\Pardot\RequestException HGG\Pardot\RuntimeException
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('Content-Type', 'application/x-www-form-urlencoded') ->setBody(http_build_query($parameters)) ->send(); } catch (HttpException $e) { $msg = sprintf('%s. Http status code [%s]', $e->getMessage(), $e->getResponse()->getStatusCode()); throw new RequestException($msg, 0, $e, $url, $parameters); } catch (\Exception $e) { throw new RuntimeException($e->getMessage(), 0, $e, $url, $parameters); } if (204 == $httpResponse->getStatusCode()) { return array(); } try { $handler = $this->getHandler($httpResponse, $object); $result = $handler->parse()->getResult(); $this->totalResults = $handler->getResultCount(); return $result; } catch (ExceptionInterface $e) { $e->setUrl($url); $e->setParameters($parameters); throw $e; } catch (\Exception $e) { throw new RuntimeException($e->getMessage(), 0, $e, $url, $parameters); } }
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 @access protected @return mixed In case of format=JSON it returns PHP arrays, if format=XML it will either return a single SimpleXMLElement or an array of SimpleXmlElements @throws HGG\Pardot\RequestException HGG\Pardot\RuntimeException
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': $this->rawResponse = $response->xml(); $handler = new XmlResponseHandler($this->rawResponse, $object); break; } return $handler; }
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); } if (property_exists($result, 'error')) { switch ($result->error) { case 'API key is invalid.': throw new InvalidApiKeyException(); case 'An unknown server error occured.': throw ServerErrorException::fromRequest($request); } } return $result; }
@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::setBinDirectory(self::getBinDirectory()); } throw new PopplerPhpException("Poppler bin directory does not exist: ".$dir); }
@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::DFT) { return self::setOutputDirectory(self::getOutputDirectory()); } throw new PopplerPhpException("Output directory does not exist: ".$dir); }
@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-group"> <label for="field-$name">$display</label> <div class="input-group"> <div class="input-group-addon"> <i class="fa fa-laptop"></i> </div> <input id="field-$name" type="text" class="form-control" data-inputmask="'alias': 'ip'" data-mask="" name="$name" value="$value" $readOnly $required > </div> </div> HTML; if ($echo) echo $html; return $html; }
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(); $executor->execute($binDir . '/drush make-convert composer.lock', $make); $make = Yaml::parse($make); // Include any drupal-library packages in the make file. $libraries = $composer ->getRepositoryManager() ->getLocalRepository() ->getPackages(); $libraries = array_filter($libraries, function (PackageInterface $package) { return $package->getType() === 'drupal-library'; }); // Drop the vendor prefixes. foreach ($libraries as $library) { $oldKey = $library->getName(); $newKey = basename($oldKey); $make['libraries'][$newKey] = $make['libraries'][$oldKey]; unset($make['libraries'][$oldKey]); } // Check for any asset library overrides and apply if so. Also drop the // vendor name from the library. if (array_key_exists('libraries', $make)) { /** @var array[] $overrides */ $overrides = $composer->getPackage()->getExtra(); if (array_key_exists(static::ASSET_OVERRIDE_PROP, $overrides)) { /** @var array $override */ foreach ($overrides[static::ASSET_OVERRIDE_PROP] as $libraryName => $override) { // Skip unsupported packages. if (!array_key_exists($libraryName, $make['libraries'])) { continue; } // Remove excluded packages. if (array_key_exists('exclude', $override) && $override['exclude'] === TRUE) { unset($make['libraries'][$libraryName]); continue; } // If a key doesn't exist, generate one by stripping out the vendor // prefix. $key = basename($libraryName); if (array_key_exists('key', $override)) { $key = $override['key']; unset($override['key']); } $makeDef = $make['libraries'][$libraryName]; unset($make['libraries'][$libraryName]); $make['libraries'][$key] = $makeDef; // Apply all overrides. foreach ($override as $overrideKey => $overrideValue) { $make['libraries'][$key][$overrideKey] = $overrideValue; } } } } if (isset($make['projects']['drupal'])) { // Always use drupal.org's core repository, or patches will not apply. $make['projects']['drupal']['download']['url'] = 'https://git.drupal.org/project/drupal.git'; $core = [ 'api' => 2, 'core' => '8.x', 'projects' => [ 'drupal' => [ 'type' => 'core', 'version' => $make['projects']['drupal']['download']['tag'], ], ], ]; if (isset($make['projects']['drupal']['patch'])) { $core['projects']['drupal']['patch'] = $make['projects']['drupal']['patch']; } file_put_contents('drupal-org-core.make', $encoder->encode($core)); unset($make['projects']['drupal']); } foreach ($make['projects'] as &$project) { if ($project['download']['type'] === 'git') { if (!array_key_exists('tag', $project['download'])) { $tag = "{$project['download']['branch']}-dev"; } else { $tag = $project['download']['tag']; preg_match('/\d+\.x-\d+\.0/', $tag, $match); $tag = str_replace($match, str_replace('x-', NULL, $match), $tag); preg_match('/\d+\.\d+\.0/', $tag, $match); $tag = str_replace($match, substr($match[0], 0, -2), $tag); } $project['version'] = $tag; unset($project['download']); } } unset($project); file_put_contents('drupal-org.make', $encoder->encode($make)); }
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 context. $storeId = NULL; if (count($result) > 0) { $storeId = reset($result); } return $storeId; }
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 Marshaller\ActionListMarshaller()); $this->getConverter()->registerMarshaller(Operation\CounterList::class, new Marshaller\CounterListMarshaller()); $this->getConverter()->registerMarshaller(Operation\CounterTimestampedValue::class, new Marshaller\CounterTimestampedValueMarshaller()); $this->getConverter()->registerMarshaller(Operation\DirectoryEntries::class, new Marshaller\DirectoryEntriesMarshaller()); $this->getConverter()->registerMarshaller(Operation\DocRef::class, new Marshaller\DocRefMarshaller($this)); $this->getConverter()->registerMarshaller(Operation\LogEntries::class, new Marshaller\LogEntriesMarshaller()); $this->getConverter()->registerMarshaller(Operation\UserGroupList::class, new Marshaller\UserGroupListMarshaller()); $this->getConverter()->registerMarshaller(NuxeoException::class, new Marshaller\NuxeoExceptionMarshaller()); return $this; }
@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]); } $this->outputLine('...'); } $startTime = time(); $timeout = null; $numberOfJobExecutions = 0; do { $message = null; if ($exitAfter !== null) { $timeout = max(1, $exitAfter - (time() - $startTime)); } try { $message = $this->jobManager->waitAndExecute($queue, $timeout); } catch (JobQueueException $exception) { $numberOfJobExecutions ++; $this->outputLine('<error>%s</error>', [$exception->getMessage()]); if ($verbose && $exception->getPrevious() instanceof \Exception) { $this->outputLine(' Reason: %s', [$exception->getPrevious()->getMessage()]); } } catch (\Exception $exception) { $this->outputLine('<error>Unexpected exception during job execution: %s, aborting...</error>', [$exception->getMessage()]); $this->quit(1); } if ($message !== null) { $numberOfJobExecutions ++; if ($verbose) { $messagePayload = strlen($message->getPayload()) <= 50 ? $message->getPayload() : substr($message->getPayload(), 0, 50) . '...'; $this->outputLine('<success>Successfully executed job "%s" (%s)</success>', [$message->getIdentifier(), $messagePayload]); } } if ($exitAfter !== null && (time() - $startTime) >= $exitAfter) { if ($verbose) { $this->outputLine('Quitting after %d seconds due to <i>--exit-after</i> flag', [time() - $startTime]); } $this->quit(); } if ($limit !== null && $numberOfJobExecutions >= $limit) { if ($verbose) { $this->outputLine('Quitting after %d executed job%s due to <i>--limit</i> flag', [$numberOfJobExecutions, $numberOfJobExecutions > 1 ? 's' : '']); } $this->quit(); } } while (true); }
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 <i>exit-after</i> flag can be used in conjunction with cron-jobs in order to manually (re)start the worker after a given amount of time. With the <i>limit</i> flag the number of executed jobs can be limited before the script exits. This can be combined with <i>exit-after</i> to exit when either the time or job limit is reached The <i>verbose</i> flag can be used to gain some insight about which jobs are executed etc. @param string $queue Name of the queue to fetch messages from. Can also be a comma-separated list of queues. @param int $exitAfter If set, this command will exit after the given amount of seconds @param int $limit If set, only the given amount of jobs are processed (successful or not) before the script exits @param bool $verbose Output debugging information @return void @throws StopActionException
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 > count($jobs)) { $this->outputLine('(%d omitted) ...', [$totalCount - count($jobs)]); } $this->outputLine('(<b>%d total</b>)', [$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 Message $message */ $message = $this->messageCache->get($messageCacheIdentifier); $queue = $this->queueManager->getQueue($queue); $this->jobManager->executeJobForMessage($queue, $message); }
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_code} {$response->error_message}", $response->error_code); } return $response->result; }
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(); } $response = $this->send(json_encode($arr), $all_notify); // no response if batch is all notifications if ($all_notify) { return true; } // check for missing ids and return responses in order of requests $ordered_response = array(); foreach ($ids as $id) { if (array_key_exists($id, $response)) { $ordered_response[] = $response[$id]; unset($response[$id]); } else { throw new Clientside\Exception("Missing id in response"); } } // check for extra ids in response if (count($response) > 0) { throw new Clientside\Exception("Extra id(s) in response"); } return $ordered_response; }
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' => array( 'method' => 'POST', 'header' => $header, 'content' => $json)); $context = stream_context_create($opts); // try to physically send data to destination try { $response = file_get_contents($this->uri, false, $context); } catch (\Exception $e) { $message = "Unable to connect to {$this->uri}"; $message .= PHP_EOL . $e->getMessage(); throw new Clientside\Exception($message); } // handle communication errors if ($response === false) { throw new Clientside\Exception("Unable to connect to {$this->uri}"); } // notify has no response if ($notify) { return true; } // try to decode json $json_response = $this->decodeJSON($response); // handle response, create response object and return it return $this->handleResponse($json_response); }
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; } // return error response if (property_exists($response, 'error')) { return new Response(null, $response->id, $response->error->code, $response->error->message); } // return successful response return new Response($response->result, $response->id); }
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, $options); }
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); // timeout return null; } $this->emitMessageReserved($queue, $message); $queueSettings = $this->queueManager->getQueueSettings($queueName); try { if (isset($queueSettings['executeIsolated']) && $queueSettings['executeIsolated'] === true) { $messageCacheIdentifier = sha1(serialize($message)); $this->messageCache->set($messageCacheIdentifier, $message); Scripts::executeCommand('flowpack.jobqueue.common:job:execute', $this->flowSettings, false, ['queue' => $queue->getName(), 'messageCacheIdentifier' => $messageCacheIdentifier]); } else { $this->executeJobForMessage($queue, $message); } } catch (\Exception $exception) { $maximumNumberOfReleases = isset($queueSettings['maximumNumberOfReleases']) ? (integer)$queueSettings['maximumNumberOfReleases'] : 0; if ($message->getNumberOfReleases() < $maximumNumberOfReleases) { $releaseOptions = isset($queueSettings['releaseOptions']) ? $queueSettings['releaseOptions'] : []; $queue->release($message->getIdentifier(), $releaseOptions); $this->emitMessageReleased($queue, $message, $releaseOptions, $exception); throw new JobQueueException(sprintf('Job execution for job (message: "%s", queue: "%s") failed (%d/%d trials) - RELEASE', $message->getIdentifier(), $queue->getName(), $message->getNumberOfReleases() + 1, $maximumNumberOfReleases + 1), 1334056583, $exception); } else { $queue->abort($message->getIdentifier()); $this->emitMessageFailed($queue, $message, $exception); throw new JobQueueException(sprintf('Job execution for job (message: "%s", queue: "%s") failed (%d/%d trials) - ABORTING', $message->getIdentifier(), $queue->getName(), $message->getNumberOfReleases() + 1, $maximumNumberOfReleases + 1), 1334056584, $exception); } } finally { if ($messageCacheIdentifier !== null) { $this->messageCache->remove($messageCacheIdentifier); } } $queue->finish($message->getIdentifier()); $this->emitMessageFinished($queue, $message); return $message; }
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 $jobExecutionException The exception (if any) thrown by the job execution @return void @Flow\Signal @api
entailment
public function listCommand() { $rows = []; foreach ($this->queueConfigurations as $queueName => $queueConfiguration) { $queue = $this->queueManager->getQueue($queueName); try { $numberOfMessages = $queue->countReady(); } catch (\Exception $e) { $numberOfMessages = '-'; } $rows[] = [$queue->getName(), TypeHandling::getTypeForValue($queue), $numberOfMessages]; } $this->output->outputTable($rows, ['Queue', 'Type', '# messages']); }
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) ? json_encode($value, JSON_PRETTY_PRINT) : $value]; } $this->output->outputTable($rows, ['Option', '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()]); $this->outputLine('%s (#%s)', [$exception->getMessage(), $exception->getCode()]); $this->quit(1); } $this->outputLine('<success>Queue "%s" has been initialized successfully.</success>', [$queue->getName()]); }
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") @return void @throws Exception @throws StopActionException
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 messages from the queue!</error>'); $this->quit(1); } $queue->flush(); $this->outputLine('<success>Flushed queue "%s".</success>', [$queue->getName()]); }
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 @throws Exception @throws StopActionException
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->outputLine('<success>Submitted payload to queue "%s" with ID "%s".</success>', [$queue->getName(), $messageId]); }
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>JobInterface</i>. @param string $queue Name of the queue to submit a message to (e.g. "some-queue") @param string $payload Arbitrary payload, for example a serialized instance of a class implementing JobInterface @param string $options JSON encoded, for example '{"some-option": "some-value"}' @return void @throws Exception
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['titleColor']: $this->options['titleColor']; $withLabels = isset($params['withLabels']) ? $params['withLabels']: $this->options['withLabels']; $withLegend = isset($params['withLegend']) ? $params['withLegend']: $this->options['withLegend']; $transparent = isset($params['transparent']) ? $params['transparent']: $this->options['transparent']; $backgroundFillColor = isset($params['backgroundFillColor']) ? $params['backgroundFillColor']: null; $color = isset($params['color']) ? $params['color']: null; if (is_array($color)) { $color = implode('|', $color); } else { $color = $color? $color: null; } $labels = null; if ($withLabels) { $labels = implode('|', $data->getLabels()); } //still no legend but should have one? Take the default one... $legendString = $this->getLegendParamValue($data); $dataString = $this->getValueParamValue($data); //backgroundFill if (!is_null($backgroundFillColor)) { $chf = 'bg'; if ($transparent) { $chf = 'a'; } $chf = $chf . ',s,' . $backgroundFillColor; } $params = array( 'chd' => $dataString, 'cht' => static::CHART_TYPE, 'chs' => $width . 'x' . $height, 'chco' => $color, 'chtt' => $title, 'chts' => $titleColor . ',' . $titleSize, 'chl' => isset($labels)? $labels : null, 'chdl' => isset($legendString)? $legendString : null, 'chf' => isset($chf)? $chf : null, ); $params = array_merge($params, $rawParams); return self::BuildUrl($params); }
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(); $required = $this->getRequiredString(); $crud = $this->field->getCRUD(); $uploadURL = \LouisLam\Util::url("louislam-crud/upload"); $html = <<< HTML <label for="field-$name">$display </label> <textarea id="field-$name" class="editor" name="$name" $readOnly $required style="width:100%">$value</textarea> HTML; $fullFeatures = ($this->fullFeatures) ? "true" : "false"; $crud->addScript(<<< HTML <script> $(document).ready(function () { var element = $( 'textarea.editor[name=$name]' ); var fullFeatures = $fullFeatures; var ckConfig = { height: 600, width: "100%", extraPlugins: 'uploadimage', imageUploadUrl: '$uploadURL/json', filebrowserImageUploadUrl: '$uploadURL/js', allowedContent: true }; if (fullFeatures) { ckConfig.plugins = "dialogui,dialog,a11yhelp,about,basicstyles,bidi,blockquote,clipboard," + "button,panelbutton,panel,floatpanel,colorbutton,colordialog,menu," + "contextmenu,dialogadvtab,div,elementspath,enterkey,entities,popup," + "filebrowser,find,fakeobjects,flash,floatingspace,listblock,richcombo," + "font,format,forms,horizontalrule,htmlwriter,iframe,image,indent," + "indentblock,indentlist,justify,link,list,liststyle,magicline," + "maximize,newpage,pagebreak,pastefromword,pastetext,preview,print," + "removeformat,resize,save,menubutton,scayt,selectall,showblocks," + "showborders,smiley,sourcearea,specialchar,stylescombo,tab,table," + "tabletools,templates,toolbar,undo,wsc,wysiwygarea"; ckConfig.toolbar = 'Full'; ckConfig.toolbar_Full = [ { name: 'document', items : [ 'Source','-', 'NewPage','DocProps','Preview','Print','-','Templates' ] }, { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] }, { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] }, { name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] }, '/', { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] }, { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv', '-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] }, { name: 'links', items : [ 'Link','Unlink','Anchor' ] }, { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] }, '/', { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] }, { name: 'colors', items : [ 'TextColor','BGColor' ] }, { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] } ]; } element.ckeditor(ckConfig); element.ckeditor().resize("100%"); }); </script> HTML ); if ($echo) echo $html; return $html; }
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' => 'content', 'visibility' => [ 'request_path' => [ 'id' => 'request_path', 'pages' => '/products', 'negate' => FALSE, 'context_mapping' => [], ], ], ]); $block->save(); $block = Block::create([ 'id' => 'presto_theme_cart', 'status' => TRUE, 'plugin' => 'commerce_cart', 'weight' => 30, 'theme' => 'presto_theme', 'region' => 'navigation_collapsible', 'visibility' => [], 'settings' => [ 'id' => 'commerce_cart', 'label' => 'Cart', 'provider' => 'commerce_cart', 'label_display' => '0', 'dropdown' => 'false', ], ]); $block->save(); }
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 upper-case."); } $this->fieldList[$name] = new Field($this, $name, $dataType); }
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(); $fieldNames = func_get_args(); // For each parameters (field name) for ($i = 0; $i < $numargs; $i++) { $nameList[] = $fieldNames[$i]; } } foreach ($nameList as $name) { $field = $this->field($name); $field->show(); $newOrderList[$name] = $field; // Unset the field from the field list unset($this->fieldList[$name]); } // now $this->fieldList remains fields that user do not input. // Use user's order and append remaining fields to the back. $this->fieldList = array_merge($newOrderList, $this->fieldList); }
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 = 0; $i < $numargs; $i++) { $this->field($fieldNames[$i])->hide(); } } }
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 { return 100000; } } elseif ($this->searchResultCountClosure != null) { // For Custom Searching $c = $this->searchResultCountClosure; return $c($keyword); } else { $this->beforeGetListViewData(function ($tableName, $findClause, $limit, $bindingData) use (&$count) { // For RedBean Case $count = R::getCell("SELECT COUNT(*) FROM `$tableName` WHERE $findClause $limit", $bindingData); }, function ($sql, $limit, $bindingData) use (&$count) { // For SQL Case $count = R::getRow("SELECT COUNT(*) AS `count` FROM (" . $sql . $limit . ") AS user_defined_query", $bindingData)["count"]; }, null, null, $keyword); } return $count; }
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); } elseif ($keyword != null && trim($keyword) != "" && $this->searchClosure != null) { // For Custom Searching $c = $this->searchClosure; $list = $c($start, $rowPerPage, $keyword, $sortField, $sortOrder); } else { $this->beforeGetListViewData(function ($tableName, $findClause, $limit, $bindingData) use (&$list) { // For RedBean Case $list = R::find($tableName, $findClause . $limit, $bindingData); }, function ($sql, $limit, $bindingData) use (&$list) { // For SQL Case $list = R::getAll($sql . $limit, $bindingData); try { $list = R::convertToBeans($this->tableName, $list); } catch (\Exception $ex) { } }, $start, $rowPerPage, $keyword, $sortField, $sortOrder); } return $list; }
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"; } else { $limit = ""; } if ($this->sql != null) { // Custom SQL $list = []; $callbackSQL($this->sql, $limit, $this->bindingData); } else { $bindingData = $this->bindingData; // For Find All Clause if ($this->findAllClause != null) { $findClause = " 1 = 1 " . $this->findAllClause; } else if ($this->findClause != null) { $findClause = $this->findClause; } else { $findClause = " 1 = 1 "; } // Build a searching clause if ($keyword != null) { $searchClause = $this->buildSearchingClause(); $searchData = $this->buildSearchingData($keyword); $findClause = $searchClause . $findClause; // Merge Array $bindingData = array_merge($searchData, $bindingData); } // Sorting if ($sortField != null) { $fakeSelect = "SELECT * FROM louislamcrud_fake_table WHERE "; $parser = new PHPSQLParser($fakeSelect . $findClause); $sqlArray = $parser->parsed; $sqlArray["ORDER"][0]["expr_type"] = "colref"; $sqlArray["ORDER"][0]["base_expr"] = $sortField; $sqlArray["ORDER"][0]["sub_tree"] = null; $sqlArray["ORDER"][0]["direction"] = $sortOrder; $findClause = str_replace($fakeSelect, "", (new PHPSQLCreator($sqlArray))->created); } $callbackRedBean($this->tableName, $findClause, $limit, $bindingData); } } catch (\RedBeanPHP\RedException\SQL $ex) { throw $ex; } catch(\Exception $ex) { // TODO: This should be for not existing table only, not other exceptions. // If the table is not existing create one, create the table and run this function again. $this->createTable(); $this->beforeGetListViewData($callbackRedBean, $callbackSQL, $start, $rowPerPage, $keyword, $sortField, $sortOrder); } }
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 { $rowPerPage = 25; } if (isset($_POST["search"]["value"])) { $keyword = trim($_POST["search"]["value"]); } else { $keyword = null; } if (isset($_POST["order"][0]["column"])) { $fieldIndex = $_POST["order"][0]["column"] - 1; if ($fieldIndex >= 0) { $orderField = $this->getShowFields()[$fieldIndex]->getName(); $order = $_POST["order"][0]["dir"]; } else { $orderField = null; $order = null; } } else { $orderField = null; $order = null; } $list = $this->getListViewData($start, $rowPerPage, $keyword, $orderField, $order); $obj = new AjaxResult(); // Get the total number of record $obj->recordsTotal = $this->countTotalListViewData($keyword); $obj->recordsFiltered = $obj->recordsTotal; if (isset($_POST["draw"])) { $obj->draw = $_POST["draw"]; } foreach ($list as $bean) { $row = []; // Action $row[] = $this->getAction($bean); $fields = $this->getShowFields(); foreach ($fields as $field) { $row[] = $field->cellValue($bean); } $obj->data[] = $row; } $json = json_encode($obj); if ($echo) { echo $json; } return $json; }
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 { $rowPerPage = 15; } $list = $this->getListViewData($start, $rowPerPage); $obj = []; foreach ($list as $bean) { $row = []; // Action //$row[] = $this->getAction($bean); $fields = $this->getShowFields(); foreach ($fields as $field) { $row[$field->getName()] = $field->cellValue($bean); } $obj[] = $row; } $json = Util::prettyJSONPrint(json_encode($obj)); if ($echo) { echo $json; } return $json; }
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 = true; } else { $result->ok = false; $result->class = "callout-danger"; } if ($this->afterInsertBean != null) { $callable = $this->afterInsertBean; $callable($bean, $result); } return $result; }
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 = "callout-info"; } else { $result->class = "callout-danger"; } if ($this->afterUpdateBean != null) { $callable = $this->afterUpdateBean; $callable($this->currentBean, $result); } return $result; }
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->getShowFields(); foreach ($fields as $field) { $fieldType = $field->getFieldType(); // Check is unique if ($field->isUnique()) { // Try to find duplicate beans $fieldName = $field->getName(); $duplicateBeans = R::find($bean->getMeta('type'), " $fieldName = ? ", [$data[$field->getName()]]); if (count($duplicateBeans) > 0) { // TODO } } if($fieldType->getBeforeSaveBeanClosure() != null) { $beforeSaveBeanClosure = $fieldType->getBeforeSaveBeanClosure(); $beforeSaveBeanClosure($bean, $field->getStoreValue($data)); } else if ($field->getFieldRelation() == Field::MANY_TO_MANY) { // 1. Many to many // http://www.redbeanphp.com/many_to_many $keyName = "shared" . ucfirst($field->getName()) . "List"; // Clear the current list (tableB_tableA) try { $tableName = $this->getTableName() . "_" . $field->getName(); $idName = $this->getTableName() . "_id"; R::exec("DELETE FROM $tableName WHERE $idName = ?", [$bean->id]); } catch (\Exception $ex) { } // Clear the current list (tableA_tableB) try { $tableName = $field->getName() . "_" . $this->getTableName(); $idName = $this->getTableName() . "_id"; R::exec("DELETE FROM $tableName WHERE $idName = ?", [$bean->id]); } catch (\Exception $ex) { } // If User have checked a value in checkbox if (isset($data[$field->getName()])) { $valueList = $data[$field->getName()]; $slots = R::genSlots($valueList); $relatedBeans = R::find($field->getName(), " id IN ($slots)", $valueList); foreach ($relatedBeans as $relatedBean) { $bean->{$keyName}[] = $relatedBean; } } } else if ($field->getFieldRelation() == Field::ONE_TO_MANY) { // TODO One to many } else if (! $field->isStorable()) { // 2. If not storable, skip continue; } elseif ($field->getFieldRelation() == Field::NORMAL) { // 3.Normal data field $value = $field->getStoreValue($data); if ($value == LouisCRUD::NULL) { $value = null; } // Validate the value if ($field->isStorable()) $validateResult = $field->validate($value, $data); else { // TODO: check non-storable? $validateResult = true; } // If validate failed, return result object. if ($validateResult !== true) { $result = new Result(); $result->id = @$bean->id; $result->msg = $validateResult; $result->fieldName = $field->getName(); $result->class = "callout-danger"; return $result; } // Set the value to the current bean directly $bean->{$field->getName()} = $value; } } // Store // Return result object $result = new Result(); try { if ($bean->id > 0) { if ($this->beforeUpdateBean != null) { $callable = $this->beforeUpdateBean; $callable($this->currentBean); } } else { if ($this->beforeInsertBean != null) { $callable = $this->beforeInsertBean; $callable($bean); } } $id = R::store($bean); $needStore = false; foreach ($fields as $field) { $fieldType = $field->getFieldType(); if($fieldType->getAfterSaveBeanClosure() != null) { $afterSaveBeanClosure = $fieldType->getAfterSaveBeanClosure(); $needStore |= !!$afterSaveBeanClosure($bean, $field->getStoreValue($data)); } } if($needStore) { $id = R::store($bean); } $result->id = $id; $result->redirect_url = Stringy::create($this->getCreateSuccURL())->replace("{id}", $id)->__toString(); } catch (\Exception $ex) { $result->ok = false; $result->class = "callout-danger"; if ($bean->id > 0) { $callback = $this->onUpdateError; $result->msg = $callback($ex->getMessage()); } else { $callback = $this->onInsertError; $result->msg = $callback($ex->getMessage()); } } return $result; }
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 . "::layout"; } }
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; $this->error_message = "Invalid Request."; return false; } // reserved method prefix if (substr($this->method,0,4) == 'rpc.') { $this->error_code = self::ERROR_RESERVED_PREFIX; $this->error_message = "Illegal method name; Method cannot start with 'rpc.'"; return false; } // illegal method name if (!preg_match(self::VALID_FUNCTION_NAME, $this->method)) { $this->error_code = self::ERROR_INVALID_REQUEST; $this->error_message = "Invalid Request."; return false; } // mismatched json-rpc version if ($this->json_rpc != "2.0") { $this->error_code = self::ERROR_MISMATCHED_VERSION; $this->error_message = "Client/Server JSON-RPC version mismatch; Expected '2.0'"; return false; } // valid request return true; }
returns true if request is valid or returns false assigns error
entailment