sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function set($key, $value)
{
$keys = explode('.', $key);
$data = $this->getAll();
$resource = &$data;
foreach ($keys as $key) {
if (!isset($resource[$key]) || !is_array($resource[$key])) {
$resource[$key] = [];
}
$resource ... | Set specific value by key if resource set. It's possible to set using . to separate keys by depth.
$getSet->set("one.two.three", "value") is equal to $resource["one"]["two"]["three"] = $value;
@param string $key
@param mixed $value
@return $this | entailment |
public function setMany(array $values)
{
if ($this->getResource()) {
foreach ($values as $key => $value) {
$this->set($key, $value);
}
}
return $this;
} | Set all key/value pairs in $values if resource is set and $values is an array
@param array $values
@return $this | entailment |
public function setAll(array $values)
{
if ($this->getResource()) {
if ($this->useLocalResource) {
$this->localResource = $values;
} else {
$GLOBALS[$this->getResource()] = $values;
}
}
return $this;
} | Set entire array onto the resource
@param array $values
@return $this | entailment |
public function remove($key)
{
$keys = explode('.', $key);
$data = $this->getAll();
$resource = &$data;
foreach ($keys as $index => $key) {
if (!isset($resource[$key])) {
// We bail, the requested key could not be found
return $this;
... | Remove an item by key. It's possible to use the dot-notation (->remove("one.two")).
@param string $key
@return $this | entailment |
public static function create($time, $msg = null, $newPriority = null)
{
$re = new RescheduleException($msg);
$re->setRescheduleDate(new \DateTime('@' . strtotime('+' . $time)));
$re->setRescheduleMessage($msg);
$re->setReshedulePriority($newPriority);
return $re;
} | Factory method.
@param string $time Time difference after which the job should be rescheduled.
Can be anything that strtotime accepts, without the `+` sign, eg: '10 seconds'
@param string $msg
@param integer $newPriority A new priority to apply the the job. If omitted the current priority will be used.
@return Resch... | entailment |
public function checkCodestyle($sniffersPath = null)
{
if (is_null($sniffersPath))
{
$sniffersPath = __DIR__ . '/.tmp/coding-standards';
}
$this->taskCodeChecks()
->setBaseRepositoryPath(__DIR__)
->setCodeStyleStandardsFolder($sniffersPath)
->setCodeStyleCheckFolders(
array(
'src'
)
... | Check the code style of the project against a passed sniffers using PHP_CodeSniffer_CLI
@param string $sniffersPath Path to the sniffers. If not provided Joomla Coding Standards will be used.
@return void | entailment |
protected function isPwdChangeAllowed(array $data, UserInterface $user, $errorExtension): bool
{
$form = $this->changePasswordForm;
$form->setData($data);
if (!$form->isValid()) {
$this->flashMessenger->setNamespace(AccountController::ERROR_NAME_SPACE . $errorExtension)
... | @TODO better error handling
@param array $data
@param UserInterface $user
@param string $errorExtension
@return bool | entailment |
public function closeTag()
{
$result = '</label>';
if ($this->element->hasAttribute('required') && $this->element->getAttribute('required')) {
$result = sprintf('<span class="required-mark">*</span> %s', $result);
}
return $result;
} | Return a closing label tag
@return string | entailment |
public function doItBaby()
{
if (
EnvironmentLabel::$plugin->getSettings()->showLabel
&& Craft::$app->getRequest()->isCpRequest
&& Craft::$app->getUser()->getIdentity()
) {
$view = Craft::$app->getView();
$view->registerCss($this->getCss());
$view->registerCss("{$this->getTargetSe... | If we're in an authenticated CP request, the label is added to the CP,
and some JS variables are injected for convenience debugging things in the console. | entailment |
public function find($template, $type)
{
foreach ($this->folders as $folder) {
foreach ($this->extensions as $extension) {
$path = $extension ? $folder.$template.'.'.$extension : $folder.$template;
if (file_exists($path)) {
return $path;
... | {@inheritdoc} | entailment |
public function getDownload4Id($id)
{
$query = $this->createQueryBuilder('p')
->select('p')
->where('p.id = :id')
->setParameter('id', $id)
->setMaxResults(1)
->getQuery();
return $query->getOneOrNullResult();
} | @param $id
@return null|\PServerCore\Entity\DownloadList | entailment |
public function getIp2Decimal($ip = null)
{
$ip = $ip ?: $this->getIp();
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return false;
}
$ipEntryData = explode('.', $ip);
return ((int)$ipEntryData[3]) + ($ipEntryData[2] * 256) + ($ipEntryData[1] *... | @param string|null $ip
@return bool|int | entailment |
public function init(array $frontendData): void
{
$this->_frontendData = Hash::merge(
$this->_frontendData, $frontendData
);
$this->_includeAppController();
$this->_includeComponents();
} | Initialize the helper. Needs to be called before running it.
@param array $frontendData Data to be passed to the frontend
@return void | entailment |
public static function getAssetCompressFiles(): array
{
$helper = new FrontendBridgeHelper(new View());
$dependencies = $helper->compileDependencies();
$plugins = array_map('\Cake\Utility\Inflector::underscore', Plugin::loaded());
foreach ($dependencies as $n => $dependency) {
... | Compiles an AssetCompress-compatible list of assets to be used in asset_compress.ini
files as a callback method
@return array | entailment |
public function subControllerElement(array $url, array $data = [], array $options = []): string
{
$options = Hash::merge([
'htmlElement' => 'div'
], $options);
$name = '../' . $url['controller'] . '/' . Inflector::underscore($url['action']);
$markup = '<' . $options['htm... | Renders a subcontroller element which gets an js controller instance assigned
@param array $url url array
@param array $data data array
@param array $options options array
@return string | entailment |
public function getMainContentClasses(array $additionalClasses = null): string
{
$classes = ['controller'];
if (!empty($additionalClasses)) {
$classes = Hash::merge($classes, $additionalClasses);
}
$classes[] = Inflector::underscore($this->_View->request->controller) . '-... | Constructs the classes for the element that represents the frontend controller's DOM
reference.
@param array $additionalClasses optional classes to add
@return string | entailment |
public function compileDependencies(array $defaultControllers = []): array
{
$this->_assetCompressMode = true;
$this->_includeAppController();
$this->_includeComponents();
$this->addController($defaultControllers);
$this->addAllControllers();
$this->_dependencies[] = ... | Returns a full list of the dependencies (used in console build task)
@param array $defaultControllers which JS controllers to include before all others
@return array | entailment |
public function run(): string
{
$out = '';
$this->_dependencies = array_unique($this->_dependencies);
$out .= $this->getNamespaceDefinitions();
$this->addCurrentController();
foreach ($this->_dependencies as $dependency) {
if (strpos($dependency, DS) !== false) ... | Includes the configured JS dependencies and appData - should
be called from the layout
@return string HTML | entailment |
public function getNamespaceDefinitions(): string
{
$script = 'var Frontend = {};';
$script .= 'var App = { Controllers: {}, Components: {}, Lib: {} };';
$tpl = 'App.Controllers.%s = {};';
foreach ($this->_pluginJsNamespaces as $pluginName) {
$script .= sprintf($tpl, $plu... | Returns a script block containing namespace definitions for plugin controllers.
@return string | entailment |
public function addCurrentController(): void
{
$controllerName = Inflector::camelize($this->_frontendData['request']['controller']);
$this->addController(
$controllerName . '.' . Inflector::camelize($this->_frontendData['request']['action'])
);
$this->addController($contr... | Adds the currently visited controller/action, if existant.
@return void | entailment |
public function addAllControllers(): void
{
$controllers = [];
// app/controllers/posts/*_controller.js
$folder = new Folder(WWW_ROOT . 'js/app/controllers');
foreach ($folder->findRecursive('.*\.js') as $file) {
$jsFile = '/' . str_replace(WWW_ROOT, '', $file);
... | Adds all controllers in app/controllers to the dependencies.
Please use only in development mode!
@return void | entailment |
public function addController($controllerName): bool
{
if (is_array($controllerName)) {
foreach ($controllerName as $cn) {
$this->addController($cn);
}
return true;
}
$split = explode('.', $controllerName);
$controller = $split[0]... | Include one or more JS controllers. Supports the 2 different file/folder structures.
- app/controllers/posts_edit_permissions_controller.js
- app/controllers/posts/edit_permissions_controller.js
- app/controllers/posts_controller.js
- app/controllers/posts/controller.js
@param string|array $controllerName Dot-separat... | entailment |
public function addComponent($componentName): bool
{
if (is_array($componentName)) {
foreach ($componentName as $cn) {
$this->addComponent($cn);
}
return true;
}
$componentFile = 'app/components/' . Inflector::underscore($componentName) . ... | Include one or more JS components
@param string|array $componentName CamelCased component name (e.g. SelectorAddressList)
@return bool | entailment |
public function setFrontendData($key, $value = null): void
{
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->setFrontendData($k, $v);
}
return;
}
$this->_frontendData['jsonData'][$key] = $value;
} | Allows manipulating frontend data
@param string|array $key Either the key or an array
@param mixed $value Value
@return void | entailment |
public function dialogBackButton(string $title = null): string
{
$button = '<button class="modal-back btn btn-default btn-xs">';
$button .= '<i class="fa fa-fw fa-arrow-left"></i>';
$button .= $title ?? __('back');
$button .= '</button>';
return $button;
} | Get the back button for modal dialogs if dialog_header is not used
@param string $title optional title of the button, default is translation of "back"
@return string HTML | entailment |
protected function _addDependency(string $file): void
{
$file = str_replace('\\', '/', $file);
if (!in_array($file, $this->_dependencies)) {
$this->_dependencies[] = $file;
}
} | Add a file to the frontend dependencies
@param string $file path to be added
@return void | entailment |
protected function _includeAppController(): void
{
$controller = null;
if (file_exists(WWW_ROOT . 'js/app/app_controller.js')) {
$controller = 'app/app_controller.js';
} else {
$controller = '/frontend_bridge/js/lib/app_controller.js';
}
$this->_depend... | Check if we have an AppController, if not, include a stub
@return void | entailment |
protected function _includeComponents(): void
{
// for now, we just include all components
$appComponentFolder = WWW_ROOT . 'js/app/components/';
$folder = new Folder($appComponentFolder);
$files = $folder->find('.*\.js');
if (!empty($files)) {
foreach ($files as ... | Includes the needed components
@return void | entailment |
public function isValid($value)
{
$valid = true;
$this->setValue($value);
$result = $this->query($value);
if (!$result) {
if ($result === false) {
$valid = false;
$this->error(self::ERROR_NOT_ACTIVE);
} elseif ($this->getOption... | @param mixed $value
@return bool
@throws Exception | entailment |
protected function query($value)
{
/** @var EntityManagerInterface $objectManager */
$objectManager = $this->getOption('object_manager');
/** @var string $targetClass */
$targetClass = $this->getOption('target_class');
/** @var \PServerCore\Entity\Repository\User $repo */
... | @param string $value
@return bool | entailment |
public function setDataFromArray(array $data)
{
foreach ($data as $property => $value) {
$method = 'set' . ucfirst($property);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
throw new \Parable\Routing\Exception(
... | Set data from array. Can only set values that have a corresponding setProperty method.
@param array $data
@return $this
@throws \Parable\Routing\Exception | entailment |
public function setUrl($url)
{
if (strpos($url, '/') !== 0) {
$url = '/' . $url;
}
$this->url = $url;
return $this;
} | Set the url this route is matched on.
@param string $url
@return $this | entailment |
public function checkValidProperties()
{
if (!$this->controller && !$this->action && !$this->callable) {
throw new \Parable\Routing\Exception('Either a controller/action combination or callable is required.');
}
if (empty($this->methods)) {
throw new \Parable\Routing\... | Check whether a valid set of properties is set.
@return $this
@throws \Parable\Routing\Exception | entailment |
public function parseUrlParameters()
{
$urlParts = explode('/', $this->url);
$this->parameters = [];
foreach ($urlParts as $index => $part) {
if (mb_substr($part, 0, 1) === '{' && mb_substr($part, -1) === '}') {
$this->parameters[$index] = mb_substr($part, 1, -1);... | Parse the parameters in $this->url and store them as index => name, so we can look for values later.
on.
@return $this | entailment |
protected function extractParameterValues($url)
{
$urlParts = explode('/', $url);
$this->values = [];
foreach ($this->parameters as $index => $name) {
$value = $urlParts[$index];
if ($value !== '') {
$this->setValue($name, $value);
}
... | Take $url and get all the values and store them in $this->values.
@param string $url
@return array | entailment |
protected function injectParameters($url)
{
$urlParts = explode('/', $url);
foreach ($this->values as $key => $value) {
$foundKey = array_search($value, $urlParts);
if ($foundKey !== false) {
$urlParts[$foundKey] = '{' . ltrim($key, '{}') . '}';
}... | Take $url and replace the 'values' with the parameters they represent. This gives us a 'corrected' url,
which can be directly matched with the route's url.
@param string $url
@return string | entailment |
public function matchDirectly($url)
{
if (!$this->isAcceptedRequestMethod()) {
return false;
}
if (rtrim($this->url, "/") === rtrim($url, "/")) {
return true;
}
return false;
} | Attempt to match $url to this route's url directly.
@param string $url
@return bool | entailment |
public function matchWithParameters($url)
{
if (!$this->isAcceptedRequestMethod()
|| !$this->isPartCountSame($url)
|| !$this->hasParameters()
) {
return false;
}
$this->extractParameterValues($url);
$correctedUrl = $this->injectParameters(... | Attempt to match $url to this route's url but also extract parameters & values.
@param string $url
@return bool | entailment |
public function isPartCountSame($url)
{
return count(explode('/', rtrim($url, '/'))) === count(explode('/', rtrim($this->url, '/')));
} | Verify whether this route's url has the same 'part' count.
@param string $url
@return bool | entailment |
public function getValue($key)
{
if (!isset($this->values[$key])) {
return null;
}
return $this->values[$key];
} | Return a value, if it exists.
@param string $key
@return mixed | entailment |
public function buildUrlWithParameters(array $parameters = [])
{
$url = $this->url;
if (!$this->hasParameters() && !$parameters) {
return $url;
}
foreach ($parameters as $key => $value) {
$url = str_replace('{' . $key . '}', $value, $url);
}
... | Build a url based on the route, replacing all parameters with the values passed (as [key => value]).
@param array $parameters
@return string | entailment |
public function isValid($value)
{
$valid = true;
$this->setValue($value);
$result = $this->query($value);
if ($result) {
$valid = false;
$this->error(self::ERROR_RECORD_FOUND);
}
return $valid;
} | @param mixed $value
@return bool
@throws Exception | entailment |
protected function query($value)
{
$class = $this->entityOptions->getUser();
/** @var \PServerCore\Entity\UserInterface $user */
$user = new $class();
$user->setUsername($value);
return $this->gameBackendService->isUserNameExists($user);
} | @param string $value
@return bool | entailment |
protected function extractAndSetData($data)
{
// Attempt to load as Json first, as it's easier to recognise a failure on
$data_parsed = json_decode($data, true);
// If there's an error, maybe it's array data? We do this second because parse_str is super-uncaring.
if (json_last_error... | Attempt to get the data from a string, which can be either json or array data.
@param string $data | entailment |
protected function build($withParentheses)
{
$builtConditions = [];
foreach ($this->conditions as $condition) {
if ($condition instanceof \Parable\ORM\Query\ConditionSet) {
$builtConditions[] = $condition->buildWithParentheses();
} else {
$buil... | Build the conditions into a string. Can be done either with parentheses or without.
@param bool $withParentheses
@return string | entailment |
public function setExpire($expire)
{
if (!$expire instanceof DateTime) {
if (is_integer($expire)) {
$expire = (new DateTime())->setTimestamp($expire);
} else {
$expire = new DateTime($expire);
}
}
$this->expire = $expire;
... | Set expire
@param $expire
@return self | entailment |
public function main()
{
if (count($this->args) < 2) {
return $this->error('Please pass the controller and action name.');
}
$controllerName = Inflector::camelize($this->args[0]);
$actionName = Inflector::camelize($this->args[1]);
$this->plugin = isset($this->para... | Main Action
@return void | entailment |
public function bake($controllerName, $actionName, $content = '')
{
if ($content === true) {
$content = $this->getContent($action);
}
if (empty($content)) {
return false;
}
$this->out("\n" . sprintf('Baking `%s%s/%s` JS controller file...', ($this->plu... | Bakes the JS file
@param string $controllerName Controller Name
@param string $actionName Action Name
@param string $content File Content
@return string | entailment |
public function getOptionParser()
{
$parser = parent::getOptionParser();
$parser->description(
'Bake a JS Controller for use in FrontendBridge '
)->addArgument('controller', [
'help' => 'Controller Name, e.g. Posts',
'required' => true
])->addArgu... | Gets the option parser instance and configures it.
@return \Cake\Console\ConsoleOptionParser | entailment |
public function register(UserInterface $user, string $code)
{
$params = [
'user' => $user,
'code' => $code
];
$this->send(self::SUBJECT_KEY_REGISTER, $user, $params);
} | RegisterMail
@param UserInterface $user
@param string $code | entailment |
public function getSubject4Key(string $key)
{
$subjectList = $this->collectionOptions->getMailOptions()->getSubject();
// added fallback if the key not exists, in the config
return $subjectList[$key] ?? $key;
} | @param string $key
@return string | entailment |
public function getQuestion4Id($id)
{
$query = $this->createQueryBuilder('p')
->select('p')
->where('p.id = :id')
->setParameter('id', $id)
->getQuery();
return $query->getOneOrNullResult();
} | @param $id
@return \PServerCore\Entity\SecretQuestion[]|null | entailment |
private function buildLoader($loader)
{
if ($loader instanceof TemplateLoaderInterface || is_callable($loader)) {
return $loader;
}
if (is_string($loader) && is_subclass_of($loader, TemplateLoaderInterface::class, true)) {
return function () use ($loader) {
... | @param \Brain\Hierarchy\Loader\TemplateLoaderInterface|callable|string $loader
@return \Closure|\Brain\Hierarchy\Loader\TemplateLoaderInterface | entailment |
public function write($message)
{
if (!$this->logFile) {
throw new \Parable\Log\Exception("No log file set. \Log\Writer\File requires a valid target file.");
}
$this->writeToFile($message);
return $this;
} | Write a message to the log file configured.
@param string $message
@return $this
@throws \Parable\Log\Exception | entailment |
public function setLogFile($logFile)
{
if (!$this->createfile($logFile)) {
throw new \Parable\Log\Exception("Log file is not writable.");
}
$this->logFile = $logFile;
return $this;
} | Set the log file to write to.
@param string $logFile
@return $this
@throws \Parable\Log\Exception | entailment |
protected function writeToFile($message)
{
$message = $message . PHP_EOL;
return @file_put_contents($this->logFile, $message, FILE_APPEND);
} | Write the message to the log file.
@param string $message
@return bool|int
@codeCoverageIgnore | entailment |
public function setErrorMode($errorMode)
{
if (in_array($errorMode, [\PDO::ERRMODE_SILENT, \PDO::ERRMODE_WARNING, \PDO::ERRMODE_EXCEPTION])) {
$this->errorMode = $errorMode;
}
return $this;
} | Set the error mode.
@param int $errorMode
@return $this | entailment |
public function getInstance()
{
if (!$this->instance && $this->getType() && $this->getLocation()) {
switch ($this->getType()) {
case static::TYPE_SQLITE:
$instance = $this->createPDOSQLite(
$this->getLocation(),
... | Return the instance, and start one if needed.
@return null|\PDO
@throws \Parable\ORM\Exception | entailment |
protected function createPDOSQLite($location, $errorMode)
{
$dsn = 'sqlite:' . $location;
$db = new \Parable\ORM\Database\PDOSQLite($dsn);
$db->setAttribute(\PDO::ATTR_ERRMODE, $errorMode);
return $db;
} | Create and return a sqlite PDO instance.
@param string $location
@param int $errorMode
@return \Parable\ORM\Database\PDOSQLite | entailment |
protected function createPDOMySQL($location, $database, $username, $password, $errorMode, $charset)
{
$dsn = 'mysql:host=' . $location . ';dbname=' . $database;
if ($charset !== null) {
$dsn .= ';charset=' . $charset;
}
$db = new \Parable\ORM\Database\PDOMySQL($dsn, $us... | Create and return a MySQL PDO instance.
@param string $location
@param string $database
@param string $username
@param string $password
@param int $errorMode
@param string $charset
@return \Parable\ORM\Database\PDOMySQL
@codeCoverageIgnore | entailment |
public function quote($string)
{
if (!$this->getInstance()) {
if (!$this->softQuoting) {
throw new \Parable\ORM\Exception("Can't quote without a database instance.");
}
$string = str_replace("'", "", $string);
return "'{$string}'";
}
... | If an instance is available, quote/escape the message through PDOs quote function.
If not and soft quoting is enabled, fudge it.
@param string $string
@return null|string
@throws \Parable\ORM\Exception | entailment |
public function query($query)
{
if (!$this->getInstance()) {
throw new \Parable\ORM\Exception("Can't run query without a database instance.");
}
return $this->getInstance()->query($query, \PDO::FETCH_ASSOC);
} | Passes $query on to the PDO instance if it's successfully initialized. If not, returns false. If so, returns
PDO result object.
@param string $query
@return \PDOStatement
@throws \Parable\ORM\Exception | entailment |
public function setConfig(array $config)
{
foreach ($config as $type => $value) {
$property = ucwords(str_replace('-', ' ', $type));
$property = lcfirst(str_replace(' ', '', $property));
$method = 'set' . ucfirst($property);
if (method_exists($this, $method)... | Use an array to pass multiple config values at the same time. The values must correspond to setters
defined on this class. If not, an exception is thrown.
@param array $config
@return $this
@throws \Parable\ORM\Exception | entailment |
public function success(Request $request)
{
$user = $this->getUser4Id($request->getUserId());
if (!$user) {
throw new InValidUserException('User not found');
}
// we already added add the reward, so skip this =)
if ($this->isStatusSuccess($request) && $this->isDo... | Method the add the reward
@param Request $request
@return boolean
@throws Throwable | entailment |
public function error(Request $request, Throwable $e)
{
$user = $this->getUser4Id($request->getUserId());
$this->saveDonateLog($request, $user, $e->getMessage());
return true;
} | Method to log the error
@param Request $request
@param Throwable $e
@return bool | entailment |
protected function mapPaymentProvider2DonateType(Request $request)
{
$result = '';
switch ($request->getProvider()) {
case Request::PROVIDER_PAYMENT_WALL:
$result = DonateLog::TYPE_PAYMENT_WALL;
break;
case Request::PROVIDER_SUPER_REWARD:
... | Helper to map the PaymentProvider 2 DonateType
@param Request $request
@return string | entailment |
protected function isDonateAlreadyAdded(Request $request)
{
/** @var \PServerCore\Entity\Repository\DonateLog $donateEntity */
$donateEntity = $this->entityManager->getRepository($this->collectionOptions->getEntityOptions()->getDonateLog());
return $donateEntity->isDonateAlreadyAdded($reque... | check is donate already added, if the provider ask, more than 1 time, this only works with a transactionId
@param Request $request
@return bool | entailment |
protected function getUser4Id($userId)
{
/** @var \PServerCore\Entity\Repository\User $userRepository */
$userRepository = $this->entityManager->getRepository($this->collectionOptions->getEntityOptions()->getUser());
return $userRepository->getUser4Id($userId);
} | @param int $userId
@return null|\PServerCore\Entity\UserInterface|\SmallUser\Entity\UserInterface | entailment |
public function generate(string $subject, string $status, string $color, string $format)
{
$badge = new Badge($subject, $status, $color, $format);
return $this->getRendererForFormat($badge->getFormat())->render($badge);
} | Generates a badge.
@param string $subject
@param string $status
@param string $color
@param string $format
@return \AltThree\Badger\BadgeImage | entailment |
public function generateFromString(string $string)
{
$badge = Badge::fromString($string);
return $this->getRendererForFormat($badge->getFormat())->render($badge);
} | Generates a badge from a string.
Example: license-MIT-blue.svg
@param string $string
@return \AltThree\Badger\BadgeImage | entailment |
protected function addRenderFormat(RenderInterface $renderer)
{
foreach ($renderer->getSupportedFormats() as $format) {
$this->renderers[$format] = $renderer;
}
} | Adds each renderer to its supported format.
@param \AltThree\Badger\Render\RenderInterface $renderer
@return void | entailment |
protected function getRendererForFormat(string $format)
{
if (!isset($this->renderers[$format])) {
throw new InvalidRendererException('No renders found for the given format: '.$format);
}
return $this->renderers[$format];
} | Returns the renderer for the given format.
@param string $format
@throws \AltThree\Badger\Exceptions\InvalidRendererException
@return \AltThree\Badger\Render\RenderInterface | entailment |
public function isValid($value)
{
$user = $this->getOption('user');
if (!$user instanceof UserInterface) {
throw new \RuntimeException('$user option is not a type of UserInterface');
}
$result = true;
$this->setValue($value);
if (!$this->secretQuestionSe... | Returns true if and only if $value meets the validation requirements
If $value fails validation, then this method returns false, and
getMessages() will return an array of messages that explain why the
validation failed.
@param mixed $value
@return bool
@throws Exception\RuntimeException If validation of $value is i... | entailment |
public function leaves(\WP_Query $query)
{
/** @var \WP_Post $post */
$post = $query->get_queried_object();
$post instanceof \WP_Post or $post = new \WP_Post((object) ['ID' => 0]);
$leaves = [];
empty($post->post_mime_type) or $mimetype = explode('/', $post->post_mime_type, ... | {@inheritdoc} | entailment |
public function load($class)
{
$path = str_replace('\\', DS, $class);
$path = '##replace##/' . trim($path, DS) . '.php';
$path = str_replace('/', DS, $path);
foreach ($this->getLocations() as $subPath) {
$actualPath = str_replace('##replace##', $subPath, $path);
... | Attempts to load the class if it exists.
@param string $class
@return bool | entailment |
public function setHttpCode($httpCode)
{
if (!array_key_exists($httpCode, $this->httpCodes)) {
throw new \Parable\Http\Exception("Invalid HTTP code set: '{$httpCode}'");
}
$this->httpCode = $httpCode;
return $this;
} | Set the HTTP code to set when the response is sent.
@param int $httpCode
@return $this
@throws \Parable\Http\Exception | entailment |
public function setOutput(\Parable\Http\Output\OutputInterface $output)
{
$this->output = $output;
$this->output->init($this);
return $this;
} | Set the output class to use and initialize it with the current response state.
@param \Parable\Http\Output\OutputInterface $output
@return $this | entailment |
public function prependContent($content)
{
if (!empty($content)) {
if (is_array($this->content)) {
array_unshift($this->content, $content);
} else {
$this->content = $content . $this->content;
}
}
return $this;
} | Prepend content to the currently set content, whether it's currently array or string data.
@param string $content
@return $this | entailment |
public function appendContent($content)
{
if (!empty($content)) {
if (is_array($this->content)) {
$this->content[] = $content;
} else {
$this->content .= $content;
}
}
return $this;
} | Append content to the currently set content, whether it's currently array or string data.
@param string $content
@return $this | entailment |
public function returnAllOutputBuffers()
{
$content = '';
if ($this->isOutputBufferingEnabled()) {
while ($this->isOutputBufferingEnabled()) {
$content .= $this->returnOutputBuffer();
}
}
return $content;
} | Return all open output buffering levels currently open.
@return string | entailment |
public function removeHeader($key)
{
if (isset($this->headers[$key])) {
unset($this->headers[$key]);
}
return $this;
} | Remove a header by key.
@param string $key
@return $this | entailment |
public function send()
{
$buffered_content = $this->returnAllOutputBuffers();
if (!empty($buffered_content) && is_string($this->content)) {
$this->content = $buffered_content . $this->content;
}
$this->content = $this->output->prepare($this);
if (!is_string($thi... | Build and send the response. | entailment |
public function getDir($directory)
{
$directory = str_replace('/', DS, $directory);
if (strpos($directory, $this->getBaseDir()) === false || !file_exists($directory)) {
$directory = $this->getBaseDir() . DS . ltrim($directory, DS);
}
return $directory;
} | Return dir based on the base dir.
@param string $directory
@return string | entailment |
public function addRight($name)
{
$rights = $this->getRights();
if (count($rights) === 0) {
$value = 1;
} else {
$value = 2 * end($rights);
}
$this->rights[$name] = $value;
return $this;
} | Add a right to the list. The correct value is calculated automatically.
@param string $name
@return $this | entailment |
public function getRight($name)
{
if (!isset($this->rights[$name])) {
return false;
}
return $this->rights[$name];
} | Return a specific right by name.
@param string $name
@return int|false | entailment |
public function check($provided, $name)
{
$provided = bindec($provided);
return (bool)($provided & $this->getRight($name));
} | Check if binary number $provided has the right bit for right $name.
@param string $provided
@param string $name
@return bool | entailment |
public function combine(array $rights)
{
$right_combined = str_repeat(0, count($this->rights));
foreach ($rights as $right) {
$right_combined |= $right;
}
return $right_combined;
} | Combine all right values in $rights into a keep-high combined result.
Takes an array of binary string values ([00011], [10011], ...])
@param array $rights
@return string | entailment |
public function getRightsFromNames(array $names)
{
$rights_string = '';
foreach ($this->getRights() as $right => $value) {
$rights_string .= in_array($right, $names) ? '1' : '0';
}
return strrev($rights_string);
} | Turn an array of right names (["read", "create"]) into a binary string of rights ("0011").
@param string[] $names
@return string | entailment |
public function getNamesFromRights($rights)
{
$names = [];
foreach ($this->rights as $name => $value) {
if ($this->check($rights, $name)) {
$names[] = $name;
}
}
return $names;
} | Turn a binary string of rights ("0011") into an array of right names (["read", "create"]).
@param string $rights
@return string[] | entailment |
public function run()
{
if (!$this->initialized) {
$this->initialize();
}
// Get the current url
$currentUrl = $this->toolkit->getCurrentUrl();
$currentFullUrl = $this->toolkit->getCurrentUrlFull();
// And try to match the route
$this->hook->... | Do all the setup and then attempt to match and dispatch the current url.
@return $this | entailment |
public function initialize()
{
if ($this->initialized) {
throw new \Parable\Framework\Exception("App has already been initialized.");
}
// And now possible packages get their turn.
$this->packageManager->registerPackages();
$this->loadConfig();
// Enabl... | Initialize the App to prepare it for being run.
@return $this
@throws \Parable\Framework\Exception
@throws \Parable\DI\Exception | entailment |
public function setErrorReportingEnabled($enabled)
{
ini_set('log_errors', 1);
if ($enabled) {
ini_set('display_errors', 1);
error_reporting(E_ALL);
} else {
ini_set('display_errors', 0);
error_reporting(E_ALL | ~E_DEPRECATED);
}
... | Enable error reporting, setting display_errors to on and reporting to E_ALL
@param bool $enabled
@return $this | entailment |
protected function startSession()
{
$this->hook->trigger(self::HOOK_SESSION_START_BEFORE);
$session = \Parable\DI\Container::get(\Parable\GetSet\Session::class);
$session->start();
$this->hook->trigger(self::HOOK_SESSION_START_AFTER, $session);
return $this;
} | Start the session.
@return $this | entailment |
protected function loadRoutes()
{
$this->hook->trigger(self::HOOK_LOAD_ROUTES_BEFORE);
if ($this->config->get('parable.routes')) {
foreach ($this->config->get('parable.routes') as $routesClass) {
$routes = \Parable\DI\Container::create($routesClass);
if (... | Load all the routes, if possible.
@return $this
@throws \Parable\Framework\Exception | entailment |
protected function loadConfig()
{
$this->hook->trigger(self::HOOK_LOAD_CONFIG_BEFORE);
$this->config->load();
$this->hook->trigger(self::HOOK_LOAD_CONFIG_AFTER);
} | Load the config and trigger hooks. | entailment |
protected function loadInits()
{
$this->hook->trigger(self::HOOK_LOAD_INITS_BEFORE);
if ($this->config->get('parable.inits')) {
$initLoader = \Parable\DI\Container::create(\Parable\Framework\Loader\InitLoader::class);
$initLoader->load($this->config->get('parable.inits'));
... | Create instances of given init classes.
@return $this | entailment |
protected function loadDatabase()
{
$this->hook->trigger(self::HOOK_INIT_DATABASE_BEFORE);
$database = \Parable\DI\Container::get(\Parable\ORM\Database::class);
$database->setConfig($this->config->get('parable.database'));
$this->hook->trigger(self::HOOK_INIT_DATABASE_AFTER);
... | Initialize the database instance with data from the config.
@return $this | entailment |
protected function loadLayout()
{
$this->hook->trigger(self::HOOK_LOAD_LAYOUT_BEFORE);
if ($this->config->get('parable.layout.header')) {
$this->response->setHeaderContent(
$this->view->partial($this->config->get('parable.layout.header'))
);
}
... | Load the layout header/footer if configured.
@return $this | entailment |
protected function dispatchRoute(\Parable\Routing\Route $route)
{
$this->response->setHttpCode(200);
$this->hook->trigger(self::HOOK_HTTP_200, $route);
$dispatcher = \Parable\DI\Container::get(\Parable\Framework\Dispatcher::class);
$dispatcher->dispatch($route);
return $thi... | Dispatch the provided route.
@param \Parable\Routing\Route $route
@return $this | entailment |
public function multiple(array $methods, $url, $callable, $name = null, $templatePath = null)
{
$routeData = [
'methods' => $methods,
'url' => $url,
'templatePath' => $templatePath,
];
if (is_array($callable)
&& count($callable) ... | Add a route which will respond to all methods passed in $methods.
The name is just a uniqid since quick routes aren't intended to be used the same as full routes.
A valid callable is anything that is considered 'invokable' (function, a class with __invoke, an anonymous
function), but this also includes an array of a ... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.