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 = &$resource[$key]; } $resource = $value; $this->setAll($data); return $this; }
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; } if ($index < (count($keys) - 1)) { $resource = &$resource[$key]; } } unset($resource[$key]); $this->setAll($data); 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 RescheduleException
entailment
public function checkCodestyle($sniffersPath = null) { if (is_null($sniffersPath)) { $sniffersPath = __DIR__ . '/.tmp/coding-standards'; } $this->taskCodeChecks() ->setBaseRepositoryPath(__DIR__) ->setCodeStyleStandardsFolder($sniffersPath) ->setCodeStyleCheckFolders( array( 'src' ) ) ->checkCodeStyle() ->run() ->stopOnFail(); }
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) ->addMessage('Form not valid.'); return false; } $data = $form->getData(); if (!$user->hashPassword($user, $data['currentPassword'])) { $this->flashMessenger->setNamespace(AccountController::ERROR_NAME_SPACE . $errorExtension) ->addMessage('Wrong Password.'); return false; } return true; }
@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->getTargetSelector()} { content: '{$this->getRenderedText()}'; }"); $view->registerJs($this->getJs()); } }
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; } } } return ''; }
{@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] * 256 * 256) + ($ipEntryData[0] * 256 * 256 * 256); }
@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) { $parts = explode('/', $dependency); if (empty($parts[0]) && in_array($parts[1], $plugins)) { $prefix = '/' . $parts[1] . '/'; $dependency = preg_replace( '/^' . str_replace('/', '\/', $prefix) . '/', 'plugin:' . Inflector::camelize($parts[1]) . ':', $dependency ); } if (substr($dependency, 0, 4) == '/js/') { $dependency = substr($dependency, 4); } $dependencies[$n] = $dependency; } return $dependencies; }
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['htmlElement'] . ' class="controller subcontroller '; $markup .= Inflector::underscore($url['controller']) . '-' . Inflector::underscore($url['action']); $markup .= '" data-controller="' . $url['controller'] . '" data-action="' . $url['action'] . '" '; $markup .= $this->getInstanceIdDataAttribute() . '>'; $markup .= $this->_View->element($name, $data, $options); $markup .= '</' . $options['htmlElement'] . '>'; return $markup; }
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) . '-' . Inflector::underscore($this->_View->request->action); return h(implode(' ', $classes)); }
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[] = '/frontend_bridge/js/bootstrap.js'; $this->_assetCompressMode = false; return array_unique($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) { $dependency = str_replace(DS, '/', $dependency); } $jsFile = $this->Html->script($dependency); $out .= $jsFile . "\n"; } $out .= $this->getAppDataJs($this->_frontendData); $out .= $this->Html->script('/frontend_bridge/js/bootstrap.js'); return $out; }
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, $pluginName); } return $this->Html->scriptBlock($script); }
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($controllerName); }
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); $controllers[] = $jsFile; } // Add All Plugin Controllers foreach (Plugin::loaded() as $pluginName) { $pluginPath = Plugin::path($pluginName); $pluginJsControllersFolder = $pluginPath . (substr($pluginPath, -1) === '/' ? '' : '/') . 'webroot/js/app/controllers/'; $pluginJsControllersFolder = str_replace('\\', '/', $pluginJsControllersFolder); if (is_dir($pluginJsControllersFolder)) { $this->_pluginJsNamespaces[] = $pluginName; $folder = new Folder($pluginJsControllersFolder); $files = $folder->findRecursive('.*\.js'); foreach ($files as $file) { $file = str_replace('\\', '/', $file); $file = str_replace($pluginJsControllersFolder, '', $file); if ($this->_assetCompressMode) { $controllers[] = 'plugin:' . $pluginName . ':js/app/controllers/' . $file; } else { $controllers[] = '/' . Inflector::underscore($pluginName) . '/js/app/controllers/' . $file; } } } } // Move all controllers with base_ prefix to the top, so other controllers // can inherit from them foreach ($controllers as $n => $file) { if (substr(basename($file), 0, 5) == 'base_') { unset($controllers[$n]); array_unshift($controllers, $file); } } foreach ($controllers as $file) { $this->_addDependency($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]; $action = null; if (isset($split[1])) { $action = $split[1]; } // In the case of a plugin, we need to check the subfolder. if (empty($this->plugin)) { $absolutePath = WWW_ROOT . 'js/'; $pluginPrefix = ''; } else { $absolutePath = Plugin::path($this->plugin) . 'webroot/js/'; $pluginPrefix = '/' . Inflector::underscore($this->plugin) . '/js/'; } $paths = array(); $path = 'app/controllers/'; if ($controller && $action == '*') { // add the base controller $this->addController($controller); // app/controllers/posts/*_controller.js $subdirPath = $path . Inflector::underscore($controller) . '/'; $folder = new Folder($absolutePath . $subdirPath); $files = $folder->find('.*\.js'); if (!empty($files)) { foreach ($files as $file) { $this->_addDependency($pluginPrefix . $subdirPath . $file); } } $folder = new Folder($absolutePath . $path); // app/controllers/posts_*.js $files = $folder->find(Inflector::underscore($controller) . '_.*_controller\.js'); if (!empty($files)) { foreach ($files as $file) { $this->_addDependency($pluginPrefix . $path . $file); } } return true; } elseif ($controller && $action) { // app/controllers/posts/edit_controller.js $paths[] = $path . Inflector::underscore($controller) . '/' . Inflector::underscore($action) . '_controller'; // app/controllers/posts_edit_controller.js $paths[] = $path . Inflector::underscore($controller) . '_' . Inflector::underscore($action) . '_controller'; } else { // app/controllers/posts/controller.js $paths[] = $path . Inflector::underscore($controller) . '/' . 'controller'; // app/controllers/posts_controller.js $paths[] = $path . Inflector::underscore($controller) . '_controller'; } foreach ($paths as $filePath) { if (file_exists($absolutePath . $filePath . '.js')) { $this->_addDependency($pluginPrefix . $filePath . '.js'); return true; } } return false; }
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-separated controller, TitleCased name. Posts.EditPermissions Posts.* (include all) @return bool
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) . '.js'; if (file_exists(JS . DS . $componentFile)) { $this->_addDependency($componentFile); return true; } return false; }
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->_dependencies[] = $controller; }
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 $file) { $this->_dependencies[] = 'app/components/' . $file; } } // Add Plugin Components foreach (Plugin::loaded() as $pluginName) { $pluginJsComponentsFolder = Plugin::path($pluginName) . '/webroot/js/app/components/'; if (is_dir($pluginJsComponentsFolder)) { $folder = new Folder($pluginJsComponentsFolder); $files = $folder->find('.*\.js'); foreach ($files as $file) { $this->_dependencies[] = '/' . Inflector::underscore($pluginName) . '/js/app/components/' . $file; } } } }
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('property') !== 'NOT_ACTIVE') { $valid = false; $this->error(self::ERROR_NO_RECORD_FOUND); } } return $valid; }
@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 */ $repo = $objectManager->getRepository($targetClass); return $repo->isUserValid4UserName($value); }
@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( "Tried to set non-existing property '{$property}' with value '{$value}' on " . get_class($this) ); } } $this->checkValidProperties(); $this->parseUrlParameters(); return $this; }
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\Exception('Methods are required and must be passed as an array.'); } return $this; }
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); } } return $this; }
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); } } return $this->values; }
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, '{}') . '}'; } } return implode('/', $urlParts); }
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($url); return $this->matchDirectly($correctedUrl); }
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); } return $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() !== JSON_ERROR_NONE) { parse_str($data, $data_parsed); } if (is_array($data_parsed)) { $this->setAll($data_parsed); } }
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 { $builtConditions[] = $condition->build(); } } $glue = ' ' . static::TYPE . ' '; $string = implode($glue, $builtConditions); if ($withParentheses) { $string = "({$string})"; } return $string; }
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; return $this; }
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->params['plugin']) ? $this->params['plugin'] : null; $this->BakeTemplate->set('controllerName', $controllerName); $this->BakeTemplate->set('actionName', $actionName); $content = $this->BakeTemplate->generate('FrontendBridge.webroot/js_controller'); $this->bake($controllerName, $actionName, $content); }
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->plugin ? $this->plugin . '.' : ''), $controllerName, $actionName), 1, Shell::QUIET); $path = $this->getPath(); $filename = $path . Inflector::underscore($controllerName) . '/' . Inflector::underscore($actionName) . '_controller.js'; $this->createFile($filename, $content); return $content; }
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 ])->addArgument('action', [ 'help' => 'Action Name, e.g. addPost', 'required' => true ]); return $parser; }
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) { return new $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(), $this->getErrorMode() ); $this->setInstance($instance); break; case static::TYPE_MYSQL: if (!$this->getUsername() || !$this->getPassword() || !$this->getDatabase()) { return null; } $instance = $this->createPDOMySQL( $this->getLocation(), $this->getDatabase(), $this->getUsername(), $this->getPassword(), $this->getErrorMode(), $this->getCharSet() ); $this->setInstance($instance); break; default: throw new \Parable\ORM\Exception("Database type was invalid: {$this->getType()}"); } } return $this->instance; }
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, $username, $password); $db->setAttribute(\PDO::ATTR_ERRMODE, $errorMode); return $db; }
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}'"; } return $this->getInstance()->quote($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)) { $this->{$method}($value); } else { throw new \Parable\ORM\Exception( "Tried to set non-existing property '{$property}' with value '{$value}' on " . get_class($this) ); } } return $this; }
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->isDonateAlreadyAdded($request)) { // no exception, or the other side spam the service ... throw new AlreadyAddedException('already added'); } // check if donate should add coins or remove $request->setAmount(abs($request->getAmount())); $coins = $this->isStatusSuccess($request) ? $request->getAmount() : -$request->getAmount(); $request->setAmount($this->paymentNotifyCoins->getAmount($user, (int)$coins)); // save the message if gamebackend-service is unavailable $errorMessage = ''; $throwable = null; try { $this->coinService->addCoins($user, $request->getAmount()); } catch (Throwable $throwable) { $request->setStatus($request::STATUS_ERROR); $errorMessage = $throwable->getMessage(); } if ($request->isReasonToBan()) { $expire = (int)$this->collectionOptions->getConfig()['payment-api']['ban-time'] + time(); $reason = 'Donate - ChargeBack'; $this->userBlockService->blockUser($user, $expire, $reason); } $this->saveDonateLog($request, $user, $errorMessage); if (null !== $throwable) { throw $throwable; } return true; }
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: $result = DonateLog::TYPE_SUPER_REWARD; break; case Request::PROVIDER_XSOLLA: $result = DonateLog::TYPE_XSOLLA; break; case Request::PROVIDER_PAY_PAL: $result = DonateLog::TYPE_PAY_PAL; break; case Request::PROVIDER_SOFORT: $result = DonateLog::TYPE_SOFORT; break; } return $result; }
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($request->getTransactionId(), $this->mapPaymentProvider2DonateType($request)); }
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->secretQuestionService->isAnswerAllowed($user, $value)) { $result = false; $this->error(self::ERROR_NOT_SAME); } return $result; }
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 impossible
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, 2); if (!empty($mimetype) && !empty($mimetype[0])) { $leaves = isset($mimetype[1]) && $mimetype[1] ? [$mimetype[0], $mimetype[1], "{$mimetype[0]}_{$mimetype[1]}"] : [$mimetype[0]]; } $leaves[] = 'attachment'; return $leaves; }
{@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); if (file_exists($actualPath)) { require_once $actualPath; return true; } } return false; }
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($this->content) && $this->content !== null) { $output = get_class($this->output); throw new \Parable\Http\Exception("Output class '{$output}' did not result in string or null content."); } if (!headers_sent()) { // @codeCoverageIgnoreStart header("{$this->request->getProtocol()} {$this->getHttpCode()} {$this->getHttpCodeText()}"); header("Content-type: {$this->getContentType()}"); foreach ($this->getHeaders() as $key => $value) { header("{$key}: {$value}"); } // @codeCoverageIgnoreEnd } if ($this->isHeaderAndFooterContentEnabled()) { echo $this->getHeaderContent(); } echo $this->getContent(); if ($this->isHeaderAndFooterContentEnabled()) { echo $this->getFooterContent(); } $this->terminate(); }
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->trigger(self::HOOK_ROUTE_MATCH_BEFORE, $currentUrl); $route = $this->router->matchUrl($currentUrl); $this->hook->trigger(self::HOOK_ROUTE_MATCH_AFTER, $route); if ($route) { $this->dispatchRoute($route); } else { $this->response->setHttpCode(404); $this->hook->trigger(self::HOOK_HTTP_404, $currentFullUrl); } $this->loadLayout(); $this->hook->trigger(self::HOOK_RESPONSE_SEND); $this->response->send(); return $this; }
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(); // Enable error reporting if debug is set to true if ($this->config->get('parable.debug') === true) { $this->setErrorReportingEnabled(true); } else { $this->setErrorReportingEnabled(false); } // Start the session if session.auto-enable is true if ($this->config->get('parable.session.auto-enable') !== false) { $this->startSession(); } // Init the database if it's configured if ($this->config->get('parable.database.type')) { $this->loadDatabase(); } // Set the basePath on the url based on the config if ($this->config->get('parable.app.homedir')) { $homedir = trim($this->config->get('parable.app.homedir'), DS); $this->url->setBasePath($homedir); } // See if there's any inits defined in the config if ($this->config->get('parable.inits')) { $this->loadInits(); } // Set the default timezone if it's set if ($this->config->get('parable.timezone')) { date_default_timezone_set($this->config->get('parable.timezone')); } // Build the base Url $this->url->buildBaseurl(); // Load the routes $this->loadRoutes(); // And set the class to initialized $this->initialized = true; return $this; }
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); } $this->errorReportingEnabled = $enabled; return $this; }
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 (!($routes instanceof \Parable\Framework\Routing\AbstractRouting)) { throw new \Parable\Framework\Exception( "{$routesClass} does not extend \Parable\Framework\Routing\AbstractRouting" ); } // Load the routes $routes->load(); } } else { $this->hook->trigger(self::HOOK_LOAD_ROUTES_NO_ROUTES_FOUND); } $this->hook->trigger(self::HOOK_LOAD_ROUTES_AFTER); return $this; }
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')); } $this->hook->trigger(self::HOOK_LOAD_INITS_AFTER); return $this; }
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); return $this; }
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')) ); } if ($this->config->get('parable.layout.footer')) { $this->response->setFooterContent( $this->view->partial($this->config->get('parable.layout.footer')) ); } $this->hook->trigger(self::HOOK_LOAD_LAYOUT_AFTER); return $this; }
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 $this; }
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) === 2 && class_exists($callable[0]) && !(new \ReflectionMethod($callable[0], $callable[1]))->isStatic() ) { $routeData['controller'] = $callable[0]; $routeData['action'] = $callable[1]; } else { $routeData['callable'] = $callable; } $this->router->addRouteFromArray( $name ?: uniqid('', true), $routeData ); return $this; }
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 class and a method (["Controller", "indexAction"]). In these cases, the action normally must be a static function. Parable solves this by checking whether the action is static or not. If it isn't, it doesn't set the Callable as a callable, but it sets it as Controller and Action separately to make sure things aren't loaded until they have to be. @param string[] $methods @param string $url @param callable $callable @param string|null $name @param string|null $templatePath @return $this
entailment