sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function any($url, $callable, $name = null, $templatePath = null) { $this->multiple(\Parable\Http\Request::VALID_METHODS, $url, $callable, $name, $templatePath); return $this; }
@param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment
public function get($url, $callable, $name = null, $templatePath = null) { $this->multiple([\Parable\Http\Request::METHOD_GET], $url, $callable, $name, $templatePath); return $this; }
Add a GET route with a callable and optionally a templatePath. @param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment
public function post($url, $callable, $name = null, $templatePath = null) { $this->multiple([\Parable\Http\Request::METHOD_POST], $url, $callable, $name, $templatePath); return $this; }
Add a POST route with a callable and optionally a templatePath. @param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment
public function put($url, $callable, $name = null, $templatePath = null) { $this->multiple([\Parable\Http\Request::METHOD_PUT], $url, $callable, $name, $templatePath); return $this; }
Add a PUT route with a callable and optionally a templatePath. @param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment
public function patch($url, $callable, $name = null, $templatePath = null) { $this->multiple([\Parable\Http\Request::METHOD_PATCH], $url, $callable, $name, $templatePath); return $this; }
Add a PATCH route with a callable and optionally a templatePath. @param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment
public function delete($url, $callable, $name = null, $templatePath = null) { $this->multiple([\Parable\Http\Request::METHOD_DELETE], $url, $callable, $name, $templatePath); return $this; }
Add a DELETE route with a callable and optionally a templatePath. @param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment
public function options($url, $callable, $name = null, $templatePath = null) { $this->multiple([\Parable\Http\Request::METHOD_OPTIONS], $url, $callable, $name, $templatePath); return $this; }
Add an OPTIONS route with a callable and optionally a templatePath. @param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment
public function setMemo($memo) { $memo = is_array($memo) ? json_encode($memo) : $memo; $this->memo = $memo; return $this; }
Set memo @param string $memo @return Logs
entailment
public function prepare( \Parable\Console\App $app, \Parable\Console\Output $output, \Parable\Console\Input $input, \Parable\Console\Parameter $parameter ) { $this->app = $app; $this->output = $output; $this->input = $input; $this->parameter = $parameter; return $this; }
Prepare the command, setting all classes the command is dependant on. @param \Parable\Console\App $app @param \Parable\Console\Output $output @param \Parable\Console\Input $input @param \Parable\Console\Parameter $parameter @return $this
entailment
public function addOption( $name, $valueRequired = Parameter::OPTION_VALUE_OPTIONAL, $defaultValue = null, $flagOption = false ) { $this->options[$name] = new \Parable\Console\Parameter\Option( $name, $valueRequired, $defaultValue, $flagOption ); return $this; }
Add an option for this command. @param string $name @param int $valueRequired @param mixed|null $defaultValue @param bool $flagOption @return $this
entailment
public function addArgument( $name, $required = Parameter::PARAMETER_OPTIONAL, $defaultValue = null ) { $this->arguments[] = new \Parable\Console\Parameter\Argument($name, $required, $defaultValue); return $this; }
Add an argument for this command. @param string $name @param int $required @param mixed $defaultValue @return $this
entailment
public function getUsage() { $string = []; $string[] = $this->getName(); foreach ($this->getArguments() as $argument) { if ($argument->isRequired()) { $string[] = $argument->getName(); } else { $string[] = "[{$argument->getName()}]"; } } foreach ($this->getOptions() as $option) { $dashes = '-'; if (!$option->isFlagOption()) { $dashes .= '-'; } if ($option->isValueRequired()) { $optionString = "{$option->getName()}=value"; } else { $optionString = "{$option->getName()}[=value]"; } $string[] = "[{$dashes}{$optionString}]"; } return implode(' ', $string); }
Build a usage string out of the arguments and options set on the command. Is automatically called when an exception is caught by App. @return string
entailment
public function run() { $callable = $this->getCallable(); if (is_callable($callable)) { return $callable($this->app, $this->output, $this->input, $this->parameter); } return false; }
Run the callable if it's set. This can be overridden by implementing the run method on a Command class. @return mixed
entailment
protected function runCommand(\Parable\Console\Command $command, array $parameters = []) { $parameter = new \Parable\Console\Parameter(); $parameter->setParameters($parameters); $command->prepare($this->app, $this->output, $this->input, $parameter); return $command->run(); }
Run another command from the current command, passing parameters as an array. @param \Parable\Console\Command $command @param array $parameters @return mixed
entailment
public static function fromString(string $format) { if (preg_match('/^(([^-]|--)+)-(([^-]|--)+)-(([^-]|--)+)\.(svg|png|gif|jpg)$/', $format, $match) === false && (7 != count($match))) { throw new InvalidArgumentException('The given format string is invalid: '.$format); } $subject = $match[1]; $status = $match[3]; $color = $match[5]; $format = $match[7]; return new self($subject, $status, $color, $format); }
Generates a badge from a string format. Example: I_m-liuggio-yellow.svg @param string $format @return \AltThree\Badger\Badge
entailment
protected function getColorMapOrAsHex(string $color) { return isset($this->colorMap[$color]) ? $this->colorMap[$color] : $color; }
Check if the color is within the color map, or return it as normal. @param string $color @return string
entailment
public static function setKeywordFormattingOptions(array $keywords) { $keyword_map = array( self::KEYWORD_NEWLINE => &self::$reserved_newline, self::KEYWORD_TOPLEVEL => &self::$reserved_toplevel ); foreach ($keywords as $keyword => $type) { if (!array_key_exists($type, $keyword_map)) { throw new \InvalidArgumentException( "Unexpected type '{$type}' : type must be a KEYWORD_* class constant" ); } foreach ($keyword_map as $keyword_type => $registered_keywords) { if (in_array($keyword, $registered_keywords)) { if ($type === $keyword_type) { continue(2); // the keyword is already of the specified type } // remove the keyword from its current type collection $keyword_map[$keyword_type] = array_diff($keyword_map[$keyword_type], array($keyword)); } } // add the keyword to the specified type collection $keyword_map[$type][] = $keyword; } }
Sets the formatting options of the SQL keywords. Expects an associative array where each key is an SQL keyword or expression, and each value a KEYWORD_* class constant. Existing keywords are moved to the specified category (i.e. toplevel or newline), while new keywords or expressions are directly added to it.
entailment
public function setWriter(\Parable\Log\Writer\WriterInterface $writer) { $this->writer = $writer; return $this; }
Set a writer class to use. @param \Parable\Log\Writer\WriterInterface $writer @return $this
entailment
public function write($message) { if (!$this->writer) { throw new \Parable\Log\Exception("Can't write without a valid \Log\Writer instance set."); } $message = $this->stringifyMessage($message); $this->writer->write($message); return $this; }
Write a message to the log writer. @param mixed $message @return $this @throws \Parable\Log\Exception
entailment
public function writeLines(array $messages) { if (!$this->writer) { throw new \Parable\Log\Exception("Can't writeLines without a valid \Log\Writer instance set."); } foreach ($messages as $message) { $this->write($message); } return $this; }
Write an array of messages to the log writer. @param array $messages @return $this @throws \Parable\Log\Exception
entailment
protected function stringifyMessage($message) { if (is_array($message) || is_object($message) || is_bool($message)) { return (string)var_export($message, true); } return (string)$message; }
Stringify a message so it can be written. @param mixed $message @return string
entailment
public function getNumberOfFailLogin4Ip($ip, $timeInterVal) { $query = $this->createQueryBuilder('p') ->select('p') ->where('p.ip = :ipString') ->setParameter('ipString', $ip) ->andWhere('p.created >= :expireTime') ->setParameter('expireTime', (new DateTime())->sub(new DateInterval(sprintf('PT%sS', $timeInterVal)))) ->getQuery(); /** * TODO remove count */ return count($query->getArrayResult()); }
@param $ip @param $timeInterVal @return int
entailment
public function isDonateAlreadyAdded($transactionId, $type) { if (!$transactionId) { return false; } $query = $this->createQueryBuilder('p') ->select('p') ->where('p.transactionId = :transactionId') ->setParameter('transactionId', $transactionId) ->andWhere('p.type = :type') ->setParameter('type', $type) ->andWhere('p.success = :success') ->setParameter('success', Entity::STATUS_SUCCESS) ->setMaxResults(1) ->getQuery(); return (bool)$query->getOneOrNullResult($query::HYDRATE_SIMPLEOBJECT); }
@param $transactionId @param $type @return bool @throws \Doctrine\ORM\NonUniqueResultException
entailment
public function getDonateHistorySuccess(\DateTime $dateTime) { $query = $this->createQueryBuilder('p') ->select('SUM(p.coins) as coins, p.type, COUNT(p.coins) as amount, p.created') ->where('p.success = :success') ->setParameter('success', Entity::STATUS_SUCCESS) ->andWhere('p.created >= :created') ->setParameter('created', $dateTime) ->groupBy('p.type, p.created') ->orderBy('p.created', 'asc') ->getQuery(); return $query->getResult(); }
Group date does not realy work on different DBMS, so we must do that in PHP @param \DateTime $dateTime @return array
entailment
public function getDonationDataSuccess(\DateTime $dateTime) { $query = $this->createQueryBuilder('p') ->select('SUM(p.coins) as coins, COUNT(p.coins) as amount') ->where('p.success = :success') ->setParameter('success', Entity::STATUS_SUCCESS) ->andWhere('p.created >= :created') ->setParameter('created', $dateTime) ->andWhere('p.type in (:type)') ->setParameter( 'type', [ Entity::TYPE_PAYMENT_WALL, Entity::TYPE_SUPER_REWARD, Entity::TYPE_XSOLLA, Entity::TYPE_PAY_PAL, Entity::TYPE_PAYSSION, Entity::TYPE_SOFORT, ], Connection::PARAM_STR_ARRAY ) ->getQuery(); return $query->getOneOrNullResult(); }
@param \DateTime $dateTime @return array
entailment
public function parseParameters() { $this->reset(); // Extract the scriptName $this->scriptName = array_shift($this->parameters); foreach ($this->parameters as $parameter) { $optionString = ltrim($parameter, '-'); if (substr($parameter, 0, 2) === "--") { $this->parseOption($optionString); } elseif (substr($parameter, 0, 1) === "-") { $this->parseFlagOption($optionString); } else { $this->parseArgument($parameter); } } return $this; }
Split the parameters into script name, command name, options and arguments. Flag options can be passed in a single set preceded by a dash: -a -b -c or concatenated together, which looks like this: -abc When an option is encountered with a value set, everything after = is seen as that value: -a -b -c=def or: -abc=def @return $this
entailment
protected function parseOption($optionString) { $optionParts = explode('=', $optionString); if (count($optionParts) > 1) { list($key, $value) = $optionParts; } else { $key = $optionString; $value = true; } $this->options[$key] = $value; return $this; }
Parse a long option (--option) string. @param string $optionString @return $this
entailment
protected function parseFlagOption($optionString) { for ($i = 0; $i < strlen($optionString); $i++) { $optionChar = substr($optionString, $i, 1); $optionParts = explode('=', substr($optionString, $i + 1)); if (count($optionParts) > 1 && empty($optionParts[0])) { $value = $optionParts[1]; } elseif ($optionChar !== "=") { $value = true; } else { break; } $this->flagOptions[$optionChar] = $value; } return $this; }
Parse a flag option string (-a or -abc, this last version is parsed as a concatenated string of one char per option). @param string $optionString @return $this
entailment
protected function parseArgument($parameter) { if ($this->commandNameEnabled && !$this->commandName) { $this->commandName = $parameter; } else { $this->arguments[] = $parameter; } return $this; }
Parse argument. If no command name set and commands are enabled, interpret as command name. Otherwise, add to argument list. @param string $parameter @return $this
entailment
public function setCommandOptions(array $options) { foreach ($options as $name => $option) { if ((!$option instanceof Parameter\Option)) { throw new \Parable\Console\Exception( "Options must be instances of Parameter\\Option. {$name} is not." ); } $this->commandOptions[$option->getName()] = $option; } return $this; }
Set the options from a command. @param \Parable\Console\Parameter\Option[] $options @return $this @throws \Parable\Console\Exception
entailment
public function checkCommandOptions() { foreach ($this->commandOptions as $option) { if ($option->isFlagOption()) { $parameters = $this->flagOptions; } else { $parameters = $this->options; } $option->addParameters($parameters); if ($option->isValueRequired() && $option->hasBeenProvided() && !$option->getValue()) { if ($option->isFlagOption()) { $message = "Option '-{$option->getName()}' requires a value, which is not provided."; } else { $message = "Option '--{$option->getName()}' requires a value, which is not provided."; } throw new \Parable\Console\Exception($message); } } }
Checks the options set against the parameters set. Takes into account whether an option is required to be passed or not, or a value is required if it's passed, or sets the defaultValue if given and necessary. @throws \Parable\Console\Exception
entailment
public function getOption($name) { if (!array_key_exists($name, $this->commandOptions)) { return null; } $option = $this->commandOptions[$name]; if ($option->hasBeenProvided() && $option->getProvidedValue() === null && $option->getDefaultValue() === null) { return true; } return $option->getValue(); }
Returns null if the value doesn't exist. Otherwise, it's whatever was passed to it or set as a default value. @param string $name @return mixed|null
entailment
public function getOptions() { $returnArray = []; foreach ($this->commandOptions as $option) { $returnArray[$option->getName()] = $this->getOption($option->getName()); } return $returnArray; }
Return all option values. @return array
entailment
public function setCommandArguments(array $arguments) { $orderedArguments = []; foreach ($arguments as $index => $argument) { if (!($argument instanceof Parameter\Argument)) { throw new \Parable\Console\Exception( "Arguments must be instances of Parameter\\Argument. The item at index {$index} is not." ); } $argument->setOrder($index); $orderedArguments[$index] = $argument; } $this->commandArguments = $orderedArguments; return $this; }
Set the arguments from a command. @param \Parable\Console\Parameter\Argument[] $arguments @return $this @throws \Parable\Console\Exception
entailment
public function checkCommandArguments() { foreach ($this->commandArguments as $index => $argument) { $argument->addParameters($this->arguments); if ($argument->isRequired() && !$argument->hasBeenProvided()) { throw new \Parable\Console\Exception( "Required argument with index #{$index} '{$argument->getName()}' not provided." ); } } }
Checks the arguments set against the parameters set. Takes into account whether an argument is required to be passed or not. @throws \Parable\Console\Exception
entailment
public function getArgument($name) { foreach ($this->commandArguments as $argument) { if ($argument->getName() === $name) { return $argument->getValue(); } } return null; }
Returns null if the value doesn't exist. Returns default value if set from command, and the actual value if passed on the command line. @param string $name @return mixed|null
entailment
public function getArguments() { $returnArray = []; foreach ($this->commandArguments as $argument) { $returnArray[$argument->getName()] = $argument->getValue(); } return $returnArray; }
Return all arguments passed. @return array
entailment
protected function reset() { $this->scriptName = null; $this->commandName = null; $this->options = []; $this->arguments = []; return $this; }
Reset the class to a fresh state. @return $this
entailment
public function enableCommandName() { if (!$this->commandNameEnabled && $this->commandName && isset($this->arguments[0]) && $this->arguments[0] === $this->commandName ) { unset($this->arguments[0]); $this->arguments = array_values($this->arguments); } $this->commandNameEnabled = true; return $this; }
Remove the command name from the arguments, if a command name is actually set. @return $this;
entailment
public function disableCommandName() { if ($this->commandNameEnabled && $this->commandName) { array_unshift($this->arguments, $this->commandName); } $this->commandNameEnabled = false; return $this; }
Add the command name to the arguments, if a command name is set. @return $this;
entailment
public function setJson($key, $value = null): void { if (is_array($key)) { foreach ($key as $k => $v) { $this->setJson($k, $v); } return; } $this->_jsonData[$key] = $value; }
Pass data to the frontend controller @param string|array $key string key or array of key=>values @param mixed $value value @return void
entailment
public function addAppData(string $key, $value = null): void { $this->_additionalAppData[$key] = $value; }
Adds additional data to the appData @param string $key string key @param mixed $value value @return void
entailment
public function setBoth($key, $value = null): void { $this->_controller->set($key, $value); $this->setJson($key, $value); }
Set a variable to both the frontend controller and the backend view @param string|array $key string key or array of key=>value @param mixed $value var value @return void
entailment
public function beforeRender(Event $event): void { $this->setJson('isAjax', $this->_controller->request->is('ajax')); $this->setJson('isMobile', $this->_controller->request->is('mobile')); $this->setBoth('isDialog', $this->_controller->request->is('dialog')); $this->setBoth('isJson', $this->_controller->request->is('json')); $this->setJson('debug', Configure::read('debug')); $ssl = false; if (env('HTTPS') || $this->_controller->request->is('ssl') || $this->_controller->request->env('HTTP_X_FORWARDED_PROTO') == 'https') { $ssl = true; } $appData = array( 'jsonData' => $this->_jsonData, 'webroot' => 'http' . ($ssl ? 's' : '') . '://' . env('HTTP_HOST') . $this->_controller->request->webroot, 'url' => $this->_controller->request->url, // 'controller' => $this->_controller->name, // 'action' => $this->_controller->request->action, // 'plugin' => $this->_controller->request->plugin, 'request' => array( 'query' => $this->_controller->request->query, 'pass' => $this->_controller->request->params['pass'], 'plugin' => $this->_controller->request->plugin, 'controller' => Inflector::underscore($this->_controller->name), 'action' => $this->_controller->request->action ) ); // merge in the additional frontend data $appData = Hash::merge($appData, $this->_additionalAppData); $this->_controller->set('frontendData', $appData); $this->_controller->set('closeDialog', $this->_closeDialog); }
Should be called explicitely in Controller::beforeRender() @param Event $event beforeRender event @return void
entailment
public function setValueType($valueType) { if (!in_array( $valueType, [ \Parable\Console\Parameter::OPTION_VALUE_REQUIRED, \Parable\Console\Parameter::OPTION_VALUE_OPTIONAL, ] )) { throw new \Parable\Console\Exception('Value type must be one of the OPTION_* constants.'); } $this->valueType = $valueType; return $this; }
Set whether the option's value is required. @param int $valueType @return $this @throws \Parable\Console\Exception
entailment
public function setFlagOption($enabled) { if ($enabled && mb_strlen($this->getName()) > 1) { throw new \Parable\Console\Exception("Flag options can only have a single-letter name."); } $this->flagOption = (bool)$enabled; return $this; }
@param bool $enabled @return $this @throws \Parable\Console\Exception
entailment
public function redirectToRoute($routeName, array $parameters = []) { $url = $this->router->getRouteUrlByName($routeName, $parameters); if (!$url) { throw new \Parable\Framework\Exception("Can't redirect to route, '{$routeName}' does not exist."); } $this->response->redirect($this->url->getUrl($url)); }
Redirect directly by using a route name. @param string $routeName @param array $parameters @throws \Parable\Framework\Exception
entailment
public function getFullRouteUrlByName($name, array $parameters = []) { $routeUrl = $this->router->getRouteUrlByName($name, $parameters); if ($routeUrl === null) { return null; } return $this->url->getUrl($routeUrl); }
Return full url from a route by $name, passing $parameters on (as [key => value]). @param string $name @param array $parameters @return string
entailment
public function find($template, $type) { if (empty($this->folders)) { return $this->finder->find($template, $type); } $templates = array_map(function ($folder) use ($template) { return $folder.'/'.$template; }, $this->folders); $templates[] = $template; return $this->finder->findFirst($templates, $type); }
{@inheritdoc}
entailment
protected function jsonActionResponse(Response $response): ServiceResponse { // get the frontendData set by the Frontend plugin and remove unnecessary data $frontendData = $this->viewVars['frontendData']; unset($frontendData['Types']); $response = [ 'code' => 'success', 'data' => [ 'frontendData' => $frontendData, 'html' => $response->body(), 'closeDialog' => $this->viewVars['closeDialog'] ] ]; return new ServiceResponse($response); }
jsonActionResponse @param \Cake\Network\Response $response the response @return \FrontendBridge\Lib\ServiceResponse
entailment
public function renderJsonAction($view, $layout): ServiceResponse { $layout = $this->getLayout($layout); if ($this->RequestHandler) { // Make sure the view is rendered as HTML, even if it is an AJAX request // jsonActionResponse() will make sure the JSON response is rendered correctly $this->RequestHandler->renderAs($this, 'ajax'); $this->RequestHandler->ext = 'html'; } $response = parent::render($view, $layout); return $this->jsonActionResponse($response); }
renderJsonAction @param string $view the view to render @param string $layout the layout to render @return \FrontendBridge\Lib\ServiceResponse
entailment
protected function getLayout(string $layout = null): string { if ($layout === null) { $frontendBridgeComponentExists = isset($this->FrontendBridge); $layout = 'FrontendBridge.json_action'; if ($frontendBridgeComponentExists) { $layout = $this->FrontendBridge->config('templatePaths.jsonAction'); } if ($this->request->is('dialog')) { $layout = 'FrontendBridge.dialog_action'; if ($frontendBridgeComponentExists) { $layout = $this->FrontendBridge->config('templatePaths.dialogAction'); } } } return $layout; }
Returns a layout to render. @param string $layout the layout path @return string
entailment
protected function redirectJsonAction($url): ServiceResponse { if (is_array($url)) { $url = $this->prepareUrl($url); } $response = [ 'code' => 'success', 'data' => [ 'inDialog' => $this->request->is('dialog') && !$this->FrontendBridge->_closeDialog, 'redirect' => $url ] ]; return new ServiceResponse($response); }
Json action redirect @param array|string $url URL @return \FrontendBridge\Lib\ServiceResponse
entailment
private function prepareUrl(array $url): array { // collect the pass parameters of the url under "pass" key for router.js compatibility $pass = []; foreach ($url as $key => $value) { if (is_int($key)) { $pass[$key] = $value; unset($url[$key]); } } $url['pass'] = $pass; return $url; }
Prepare a url array for the JS router @param array $url a standard CakePHP url array @return array
entailment
protected function renderSvg(array $params, $format) { $template = file_get_contents($this->path.'/'.$this->getTemplate()); foreach ($params as $key => $param) { $template = str_replace(sprintf('{{ %s }}', $key), $param, $template); } return BadgeImage::createFromString($template, $format); }
Render the badge from the parameters and format given. @param array $params @param string $format @return \AltThree\Badger\BadgeImage
entailment
public function leaves(\WP_Query $query) { /** @var \stdClass $term */ $term = $query->get_queried_object(); if (!isset($term->slug) || !isset($term->taxonomy)) { return ['taxonomy']; } return [ "taxonomy-{$term->taxonomy}-{$term->slug}", "taxonomy-{$term->taxonomy}", 'taxonomy', ]; }
{@inheritdoc}
entailment
protected function registerClassesFromMagicProperties() { $reflection = new \ReflectionClass(self::class); $docComment = $reflection->getDocComment(); $magicProperties = $docComment ? explode(PHP_EOL, $docComment) : []; foreach ($magicProperties as $magicProperty) { if (strpos($magicProperty, '@property') === false) { continue; } $partsString = trim(str_replace('* @property', '', $magicProperty)); $parts = explode('$', $partsString); list($className, $property) = $parts; $this->registerClass(trim($property), trim($className)); } return $this; }
For all the magic properties defined at the start of this class, loop through them and add them to our list of magic properties. @return $this
entailment
public function registerClass($property, $className) { // Make sure the $className is prefixed with a backslash $className = '\\' . ltrim($className, '\\'); $this->classes[$property] = $className; return $this; }
Register a class with the View for property lazy-loading. @param string $property @param string $className @return $this
entailment
public function partial($templatePath) { $this->response->startOutputBuffer(); $this->loadTemplatePath($templatePath); return $this->response->returnOutputBuffer(); }
Load a template path, interpret it fully and then return the resulting output as a string. @param string $templatePath @return string
entailment
protected function loadTemplatePath($templatePath) { $templatePath = $this->path->getDir($templatePath); if (file_exists($templatePath)) { require $templatePath; } return $this; }
Attempt to load the templatePath. @param string $templatePath @return $this
entailment
public function buildBaseUrl() { $domain = $this->request->getScheme() . '://' . $this->request->getHttpHost(); $url = $this->request->getScriptName(); // We only want to remove the first occurrence of our base path, and only if base path is valid if ($this->getBasePath()) { $basePathPos = strpos($url, $this->getBasePath()); if ($basePathPos !== false) { $url = substr_replace($url, '', $basePathPos, strlen($this->getBasePath())); } } // And we want to remove the script name separately, since it's possible base path is empty $url = str_replace($this->getScriptName(), '', $url); $this->baseUrl = $domain . '/' . ltrim($url, '/'); return $this; }
Build the correct baseUrl, based on data from the request. @return $this
entailment
public function addMap($pattern, $controller) { // Sanitize and explode the pattern. $pattern = explode('/', trim(parse_url((string) $pattern, PHP_URL_PATH), ' /')); // Prepare the route variables $vars = array(); // Initialize regular expression $regex = array(); // Loop on each segment foreach ($pattern as $segment) { if ($segment == '*') { // Match a splat with no variable. $regex[] = '.*'; } elseif ($segment[0] == '*') { // Match a splat and capture the data to a named variable. $vars[] = substr($segment, 1); $regex[] = '(.*)'; } elseif ($segment[0] == '\\' && $segment[1] == '*') { // Match an escaped splat segment. $regex[] = '\*' . preg_quote(substr($segment, 2)); } elseif ($segment == ':') { // Match an unnamed variable without capture. $regex[] = '[^/]*'; } elseif ($segment[0] == ':') { // Match a named variable and capture the data. $vars[] = substr($segment, 1); $regex[] = '([^/]*)'; } elseif ($segment[0] == '\\' && $segment[1] == ':') { // Match a segment with an escaped variable character prefix. $regex[] = preg_quote(substr($segment, 1)); } else { // Match the standard segment. $regex[] = preg_quote($segment); } } $this->maps[] = array( 'regex' => \chr(1) . '^' . implode('/', $regex) . '$' . \chr(1), 'vars' => $vars, 'controller' => (string) $controller, ); return $this; }
Add a route map to the router. If the pattern already exists it will be overwritten. @param string $pattern The route pattern to use for matching. @param string $controller The controller name to map to the given pattern. @return Router Returns itself to support chaining. @since 1.0 @deprecated 2.0 Deprecated without replacement
entailment
public function addMaps($maps) { foreach ($maps as $pattern => $controller) { $this->addMap($pattern, $controller); } return $this; }
Add an array of route maps to the router. If the pattern already exists it will be overwritten. @param array $maps A list of route maps to add to the router as $pattern => $controller. @return Router Returns itself to support chaining. @since 1.0 @deprecated 2.0 Deprecated without replacement
entailment
protected function fetchController($name) { // Derive the controller class name. $class = $this->controllerPrefix . ucfirst($name); // If the controller class does not exist panic. if (!class_exists($class)) { throw new \RuntimeException(sprintf('Unable to locate controller `%s`.', $class), 404); } // If the controller does not follows the implementation. if (!is_subclass_of($class, 'Joomla\\Controller\\ControllerInterface')) { throw new \RuntimeException( sprintf( 'Invalid Controller. Controllers must implement Joomla\Controller\ControllerInterface. `%s`.', $class ), 500 ); } // Instantiate the controller. $controller = new $class($this->input); return $controller; }
Get a Controller object for a given name. @param string $name The controller name (excluding prefix) for which to fetch and instance. @return ControllerInterface @since 1.0 @throws \RuntimeException @deprecated 2.0 Deprecated without replacement
entailment
protected function parseRoute($route) { $controller = false; // Trim the query string off. $route = preg_replace('/([^?]*).*/u', '\1', $route); // Sanitize and explode the route. $route = trim(parse_url($route, PHP_URL_PATH), ' /'); // If the route is empty then simply return the default route. No parsing necessary. if ($route == '') { return $this->default; } // Iterate through all of the known route maps looking for a match. foreach ($this->maps as $rule) { if (preg_match($rule['regex'], $route, $matches)) { // If we have gotten this far then we have a positive match. $controller = $rule['controller']; // Time to set the input variables. // We are only going to set them if they don't already exist to avoid overwriting things. foreach ($rule['vars'] as $i => $var) { $this->input->def($var, $matches[$i + 1]); // Don't forget to do an explicit set on the GET superglobal. $this->input->get->def($var, $matches[$i + 1]); } $this->input->def('_rawRoute', $route); break; } } // We were unable to find a route match for the request. Panic. if (!$controller) { throw new \InvalidArgumentException(sprintf('Unable to handle request for route `%s`.', $route), 404); } return $controller; }
Parse the given route and return the name of a controller mapped to the given route. @param string $route The route string for which to find and execute a controller. @return string The controller name for the given route excluding prefix. @since 1.0 @throws \InvalidArgumentException
entailment
public function run() { if ($this->app->getName()) { $this->output->writeln($this->app->getName()); $this->output->newline(); } $commandName = $this->parameter->getArgument('command_name'); if ($this->parameter->getCommandName() === $this->name && $commandName) { $this->showCommandHelp($this->parameter->getArgument('command_name')); } else { $this->showGeneralHelp(); } return $this; }
Show the names and descriptions of all commands set on the application at this moment. @return $this
entailment
protected function showGeneralHelp() { $this->output->writeln("<yellow>Available commands:</yellow>"); $longestName = 0; foreach ($this->app->getCommands() as $command) { $strlen = strlen($command->getName()); if ($strlen > $longestName) { $longestName = $strlen; } } foreach ($this->app->getCommands() as $command) { $name = $command->getName(); $this->output->write(str_pad(" <green>{$name}</green>", $longestName + 22, ' ', STR_PAD_RIGHT)); $this->output->write("{$command->getDescription()}"); $this->output->newline(); } }
Show information about all commands.
entailment
protected function showCommandHelp($commandName) { $command = $this->app->getCommand($commandName); if (!$command) { $this->output->writeln("<red>Unknown command:</red> {$commandName}"); return; } if ($command->getDescription()) { $this->output->writeln("<yellow>Description:</yellow>"); $this->output->writeln(" {$command->getDescription()}"); $this->output->newline(); } $this->output->writeln("<yellow>Usage:</yellow>"); $this->output->writeln(" {$command->getUsage()}"); }
Show the usage and description for a specific command. @param string $commandName
entailment
public function blockUser(UserInterface $user, $expire, $reason, $creator = null) { $class = $this->entityOptions->getUserBlock(); /** @var UserBlockEntity $userBlock */ $userBlock = new $class; $userBlock->setUser($user); $userBlock->setCreator($creator); $userBlock->setReason($reason); $userBlock->setExpire($expire); $this->blockUserWithEntity($userBlock); }
We want to block a user @param UserInterface $user @param $expire @param $reason @param null|UserInterface $creator
entailment
public function calculateWidth(string $text, int $size = null) { $size = round(($size ?: static::TEXT_SIZE) * 0.75, 1); $box = imagettfbbox($size, 0, $this->path, $text); return round(abs($box[2] - $box[0]) + static::SHIELD_PADDING_EXTERNAL + static::SHIELD_PADDING_INTERNAL, 1); }
Calculate the width of the text box. @param string $text @param int|null $size @return float
entailment
public function getKeyPress() { $this->disableShowInput(); $this->disableRequireReturn(); $input = null; while (1) { $input = fread(STDIN, 10000); break; } $this->enableShowInput(); $this->enableRequireReturn(); $specialKey = $this->detectSpecialKey($input); return $specialKey ? $specialKey : (string)$input; }
Return a single key press without waiting for a return. Hide provided input. Will return string values defined in $specialKeys for key presses defined in that array. @return string|null
entailment
protected function detectSpecialKey($input) { $specialKey = false; if (in_array(ord($input), [27, 127, 10])) { $specialKey = array_search(urlencode($input), $this->specialKeys); } return $specialKey ? $specialKey : null; }
Detect whether the key defined in $input is considered a special key. @param string $input @return string|null
entailment
public function getHidden() { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { throw new \Parable\Console\Exception( "Hidden input is not supported on windows." ); } $this->disableShowInput(); $input = $this->get(); $this->enableShowInput(); return $input; }
Request input from the user, while hiding the actual input. Use this to request passwords, for example. @return string @throws \Parable\Console\Exception
entailment
public function getYesNo($default = true) { $value = strtolower($this->get()); // Y/N values are ALWAYS directly returned as true/false if ($value === 'y') { return true; } elseif ($value === 'n') { return false; } // If no value, we return the default value if (empty($value)) { return (bool)$default; } // Anything else should be considered false return false; }
Request a y/n input from the user, with a default value highlighted as uppercase ([Y/n], for example). @param bool $default @return bool
entailment
public function get($type = null) { if (!$type) { return $this->messages; } if (isset($this->messages[$type])) { return $this->messages[$type]; } return []; }
Return all messages or all messages of $type. @param null|string $type @return array
entailment
public function getClear($type = null) { $messages = $this->get($type); $this->clear($type); return $messages; }
Return all messages or all messages of $type and then clear those messages. @param null|string $type @return array
entailment
public function add($message = null, $type = 'notice') { if (!isset($this->messages[$type]) || !is_array($this->messages[$type])) { $this->messages[$type] = []; } if ($message) { $this->messages[$type][] = $message; } $this->writeToSession(); return $this; }
Add a message to type notice by default, or to $type instead. @param null|string $message @param string $type @return $this
entailment
public function clear($type = null) { if (!$type) { $this->messages = []; } elseif (isset($this->messages[$type])) { unset($this->messages[$type]); } $this->writeToSession(); return $this; }
Clear all messages or all messages of $type. @param null|string $type @return $this
entailment
public function count($type = null) { if ($type) { return count($this->get($type)); } $count = 0; foreach ($this->get() as $type => $messages) { $count += count($messages); } return $count; }
Count all messages or all messages of $type. @param null|string $type @return int
entailment
protected function readFromSession() { if (is_array($this->session->get(self::SESSION_KEY))) { $this->messages = $this->session->get(self::SESSION_KEY); } return $this; }
Read messages stored in the session and load them into SessionMessage. @return $this
entailment
public function isUserValid4UserName($username) { $result = false; $user = $this->getUser4UserName($username); if (!$user) { $result = null; } elseif ($user->getRoles()) { $result = true; } return $result; }
@param $username @return bool|null null for user not exists and bool for roles exists or not
entailment
public function generateMigrationQueries(Bundle $bundle, AbstractPlatform $platform) { $schemas = $this->getSchemas(); $fromSchema = $schemas['fromSchema']; $toSchema = $schemas['toSchema']; $bundleTables = $this->getBundleTables($bundle, $schemas['metadata']); $this->filterSchemas(array($fromSchema, $toSchema), $bundleTables); $upQueries = $fromSchema->getMigrateToSql($toSchema, $platform); $downQueries = $fromSchema->getMigrateFromSql($toSchema, $platform); return array( self::QUERIES_UP => $upQueries, self::QUERIES_DOWN => $downQueries ); }
Generates bundle migration queries (up and down) for a given SQL platform. @param \Symfony\Component\HttpKernel\Bundle\Bundle $bundle @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform @return array
entailment
public function setMainConfigClassName($className) { if (!class_exists($className)) { throw new \Parable\Framework\Exception("Main Config class '{$className}' does not exist."); } $this->mainConfigClass = $className; return $this; }
Set the main config name to use. @param string $className @return $this @throws \Parable\Framework\Exception
entailment
public function load() { try { $this->addConfig(\Parable\DI\Container::get($this->mainConfigClass)); } catch (\Exception $e) { return $this; } if ($this->get('parable.configs')) { foreach ($this->get('parable.configs') as $configClass) { $this->addConfig(\Parable\DI\Container::get($configClass)); } } return $this; }
Load the main config and load all its values. If there are any child configs defined under "parable.configs", load all of those too. @return $this
entailment
public function addConfig(\Parable\Framework\Interfaces\Config $config) { $this->setMany($config->get()); return $this; }
Add a config and load all of its values. @param \Parable\Framework\Interfaces\Config $config @return $this
entailment
public function write($string) { $string = $this->parseTags($string); $this->enableClearLine(); echo $string; return $this; }
Write a string to the console and make sure clear line is enabled. @param string $string @return $this
entailment
public function getTerminalWidth() { if ($this->isInteractiveShell() || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && getenv('shell')) ) { return (int)shell_exec('tput cols'); } return self::TERMINAL_DEFAULT_WIDTH; }
Return the terminal width. If not an interactive shell, return default. @return int @codeCoverageIgnore
entailment
public function getTerminalHeight() { if ($this->isInteractiveShell() || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && getenv('shell')) ) { return (int)shell_exec('tput lines'); } return self::TERMINAL_DEFAULT_HEIGHT; }
Return the terminal height. If not an interactive shell, return default. @return int @codeCoverageIgnore
entailment
public function writeln($lines) { if (!is_array($lines)) { $lines = [$lines]; } foreach ($lines as $line) { $this->write($line); $this->newline(); } return $this; }
Write a line or array of lines to the console. This will always end in a newline. @param string|string[] $lines @return $this
entailment
public function clearLine() { if (!$this->isClearLineEnabled()) { return $this; } $this->cursorReset(); $this->write(str_repeat(' ', $this->getTerminalWidth())); $this->cursorReset(); $this->disableClearLine(); return $this; }
Clear the line, based on the terminal width and disable clear line. @return $this
entailment
public function writeBlockWithTags($string, array $tags = []) { if (!is_array($string)) { $string = explode(PHP_EOL, $string); } $strlen = 0; foreach ($string as $line) { $strlen = max($strlen, mb_strlen($line)); } $tagsOpen = ''; $tagsClose = ''; if (count($tags) > 0) { foreach ($tags as $tag) { $tagsOpen .= "<{$tag}>"; $tagsClose .= "</{$tag}>"; } } $lines = [ "", " {$tagsOpen}β”Œ" . str_repeat("─", $strlen + 2) . "┐{$tagsClose}", ]; foreach ($string as $line) { $padding = str_repeat(" ", $strlen - mb_strlen($line)); $lines[] = " {$tagsOpen}β”‚ {$line}{$padding} β”‚{$tagsClose}"; } $lines[] = " {$tagsOpen}β””" . str_repeat("─", $strlen + 2) . "β”˜{$tagsClose}"; $lines[] = ""; $this->writeln($lines); return $this; }
Write a block of text to the console, applying all tags appropriately. @param string|string[] $string @param string[] $tags @return $this
entailment
public function parseTags($string) { foreach ($this->tags as $tag => $code) { if (strpos($string, "<{$tag}>") !== false || strpos($string, "</{$tag}>") !== false ) { $string = str_replace("<{$tag}>", $code, $string); $string = str_replace("</{$tag}>", $this->tags['default'], $string); } } return $string . $this->tags['default']; }
Parse tags in a string to turn them into bash escape codes. @param string $string @return mixed
entailment
public function write(File $file) { $success = file_put_contents( $this->getRouteCachePath($file->getRoute()), $file->toString() ); if ($success === false) { throw new CacheFileSystemException( "Unable to save Cache file to disk in file " . $this->getRouteCachePath($file->getRoute()) ); } }
Saves the File $file to disk in the caches base directory, using a sha has of the route name @param File $file @throws CacheFileSystemException
entailment
public function read($route) { $routePath = $this->getRouteCachePath($route); if (!file_exists($routePath)) { return false; } try { return File::fromString(file_get_contents($routePath)); } catch (\Exception $e) { //Delete the cache file unlink($routePath); return false; } }
See's if the route provided has a cached version, if it does it returns a file object representing the cache. If no file is present it returns false @param $route @return bool|File
entailment
public function delete($route) { if (file_exists($this->getRouteCachePath($route))) { unlink($this->getRouteCachePath($route)); } }
Removes the cache for a given route @param $route
entailment
public function deleteAll() { foreach (scandir($this->directory) as $file) { if (!in_array($file, ['.', '..', 'keep'])) { unlink($this->directory . '/' . $file); } } }
Removes all cache entries
entailment
public function find($template, $type) { $name = trim(str_replace('\\', '/', $template), '/'); $depth = substr_count($name, '/'); $finder = clone $this->finder; $finder = $finder->depth("== {$depth}"); if ($depth) { $dir = dirname($name); $finder = $finder->path($dir); $name = basename($name); } $quotedName = preg_quote($name, '~'); /** @var \Iterator $iterator */ $iterator = $finder->files()->name("~^{$quotedName}(\.[\w]{1,})?$~")->getIterator(); if (!iterator_count($iterator) > 0) { return ''; } $array = iterator_to_array($iterator); return reset($array)->getRealPath(); }
{@inheritdoc}
entailment
public function render(Badge $badge) { $subjectWidth = $this->stringWidth($badge->getSubject()); $statusWidth = $this->stringWidth($badge->getStatus()); $params = [ 'vendorWidth' => $subjectWidth, 'valueWidth' => $statusWidth, 'totalWidth' => ($subjectWidth + $statusWidth) + 7, 'vendorColor' => $this->color, 'valueColor' => $badge->getHexColor(), 'vendor' => $badge->getSubject(), 'value' => $badge->getStatus(), 'vendorStartPosition' => round($subjectWidth / 2, 1) + 1, 'valueStartPosition' => $subjectWidth + $statusWidth / 2 + 6, 'arrowStartPosition' => $subjectWidth + 6, 'arrowPathPosition' => $subjectWidth + 6.5, ]; return $this->renderSvg($params, $badge->getFormat()); }
Render a badge. @param \AltThree\Badger\Badge $badge @return \AltThree\Badger\BadgeImage
entailment
public function addRoute($name, \Parable\Routing\Route $route) { $route->checkValidProperties(); $this->routes[$name] = $route; return $this; }
Add a Route object to the routes list as $name. @param string $name @param \Parable\Routing\Route $route @return $this
entailment
public function addRoutes(array $routes) { foreach ($routes as $name => $route) { $this->addRoute($name, $route); } return $this; }
Add an array of routes to the routes list, where key is the route name. @param \Parable\Routing\Route[] $routes @return $this
entailment