sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function selectMultipleOptionsInChosen($label, $options) { $select = $this->findField($label); $selectID = $select->getAttribute('id'); $chosenSelectID = $selectID . '_chzn'; foreach ($options as $option) { $this->debug("I open the $label chosen selector"); $this->click(array('xpath' => "//div[@id='$chosenSelectID']/ul")); $this->debug("I select $option"); $this->click(array('xpath' => "//div[@id='$chosenSelectID']//li[contains(text()[normalize-space()], '$option')]")); // Gives time to chosen to close $this->wait(1); } }
Selects one or more options in a Chosen Multiple Select based on its label @param string $label Label of the select field @param array $options Array of options to be selected @return void @since 3.0.0
entailment
public function doAdministratorLogout() { $this->click(array('xpath' => "//ul[@class='nav nav-user pull-right']//li//a[@class='dropdown-toggle']")); $this->debug("I click on Top Right corner toggle to Logout from Admin"); $this->waitForElement(array('xpath' => "//li[@class='dropdown open']/ul[@class='dropdown-menu']//a[text() = 'Logout']"), TIMEOUT); $this->click(array('xpath' => "//li[@class='dropdown open']/ul[@class='dropdown-menu']//a[text() = 'Logout']")); $this->waitForElement(array('id' => 'mod-login-username'), TIMEOUT); $this->waitForText('Log in', TIMEOUT, array('xpath' => "//fieldset[@class='loginform']//button")); }
Function to Logout from Administrator Panel in Joomla! @return void @since 3.0.0 @throws \Exception
entailment
public function enablePlugin($pluginName) { $this->amOnPage('/administrator/index.php?option=com_plugins'); $this->debug('I check for Notices and Warnings'); $this->checkForPhpNoticesOrWarnings(); $this->searchForItem($pluginName); $this->waitForElement($this->searchResultPluginName($pluginName), 30); $this->checkExistenceOf($pluginName); $this->click(array('xpath' => "//input[@id='cb0']")); $this->click(array('xpath' => "//div[@id='toolbar-publish']/button")); $this->see(' enabled', '#system-message-container'); }
Function to Enable a Plugin @param String $pluginName Name of the Plugin @return void @since 3.0.0 @throws \Exception
entailment
public function uninstallExtension($extensionName) { $this->amOnPage('/administrator/index.php?option=com_installer&view=manage'); $this->waitForText('Extensions: Manage', '30', array('css' => 'H1')); $this->searchForItem($extensionName); $this->waitForElement(array('id' => 'manageList'), '30'); $this->click(array('xpath' => "//input[@id='cb0']")); $this->click(array('xpath' => "//div[@id='toolbar-delete']/button")); $this->acceptPopup(); $this->waitForText('was successful', '30', array('id' => 'system-message-container')); $this->see('was successful', '#system-message-container'); $this->searchForItem($extensionName); $this->waitForText( 'There are no extensions installed matching your query.', TIMEOUT, array('class' => 'alert-no-items') ); $this->see('There are no extensions installed matching your query.', '.alert-no-items'); $this->debug('Extension successfully uninstalled'); }
Uninstall Extension based on a name @param string $extensionName Is important to use a specific @return void @since 3.0.0 @throws \Exception
entailment
public function searchForItem($name = null) { if ($name) { $this->debug("Searching for $name"); $this->fillField(array('id' => "filter_search"), $name); $this->click(array('xpath' => "//button[@type='submit' and @data-original-title='Search']")); return; } $this->debug('clearing search filter'); $this->click(array('xpath' => "//button[@type='button' and @data-original-title='Clear']")); }
Function to Search For an Item in Joomla! Administrator Lists views @param String $name Name of the Item which we need to Search @return void @since 3.0.0
entailment
public function installLanguage($languageName) { $this->amOnPage('administrator/index.php?option=com_installer&view=languages'); $this->debug('I check for Notices and Warnings'); $this->checkForPhpNoticesOrWarnings(); $this->debug('Refreshing languages'); $this->click(array('xpath' => "//div[@id='toolbar-refresh']/button")); $this->waitForElement(array('id' => 'j-main-container'), 30); $this->searchForItem($languageName); $this->waitForElement($this->searchResultLanguageName($languageName), 30); $this->click(array('id' => "cb0")); $this->click(array('xpath' => "//div[@id='toolbar-upload']/button")); $this->waitForText('was successful.', TIMEOUT, array('id' => 'system-message-container')); $this->see('No Matching Results', '.alert-no-items'); $this->debug($languageName . ' successfully installed'); }
Function to install a language through the interface @param string $languageName Name of the language you want to install @return void @throws \Exception
entailment
public function setModulePosition($module, $position = 'position-7') { $this->amOnPage('administrator/index.php?option=com_modules'); $this->searchForItem($module); $this->click(array('link' => $module)); $this->waitForText("Modules: $module", 30, array('css' => 'h1.page-title')); $this->click(array('link' => 'Module')); $this->waitForElement(array('id' => 'general'), 30); $this->selectOptionInChosen('Position', $position); $this->click(array('xpath' => "//div[@id='toolbar-apply']/button")); $this->waitForText('Module saved', 30, array('id' => 'system-message-container')); }
Publishes a module on frontend in given position @param string $module The full name of the module @param string $position The template position of a module. Right position by default @return void @throws \Exception
entailment
public function publishModule($module) { $this->amOnPage('administrator/index.php?option=com_modules'); $this->searchForItem($module); $this->checkAllResults(); $this->click(array('xpath' => "//div[@id='toolbar-publish']/button")); $this->waitForText(' published.', 30, array('id' => 'system-message-container')); }
Publishes a module on all frontend pages @param string $module The full name of the module @return void @since 3.0.0 @throws \Exception
entailment
public function displayModuleOnAllPages($module) { $this->amOnPage('administrator/index.php?option=com_modules'); $this->searchForItem($module); $this->click(array('link' => $module)); $this->waitForElement(array('link' => 'Menu Assignment'), 30); $this->click(array('link' => 'Menu Assignment')); $this->waitForElement(array('id' => 'jform_menus-lbl'), 30); $this->click(array('id' => 'jform_assignment_chzn')); $this->click(array('xpath' => "//li[@data-option-array-index='0']")); $this->click(array('xpath' => "//div[@id='toolbar-apply']/button")); $this->waitForText('Module saved', 30, array('id' => 'system-message-container')); }
Changes the module Menu assignment to be shown on all the pages of the website @param string $module The full name of the module @return void @since 3.0.0 @throws \Exception
entailment
public function clickToolbarButton($button) { $input = strtolower($button); $screenSize = explode("x", $this->config['window_size']); if ($screenSize[0] <= 480) { $this->click('Toolbar'); } switch ($input) { case "new": $this->click(array('xpath' => "//div[@id='toolbar-new']//button")); break; case "edit": $this->click(array('xpath' => "//div[@id='toolbar-edit']//button")); break; case "publish": $this->click(array('xpath' => "//div[@id='toolbar-publish']//button")); break; case "unpublish": $this->click(array('xpath' => "//div[@id='toolbar-unpublish']//button")); break; case "archive": $this->click(array('xpath' => "//div[@id='toolbar-archive']//button")); break; case "check-in": $this->click(array('xpath' => "//div[@id='toolbar-checkin']//button")); break; case "batch": $this->click(array('xpath' => "//div[@id='toolbar-batch']//button")); break; case "rebuild": $this->click(array('xpath' => "//div[@id='toolbar-refresh']//button")); break; case "trash": $this->click(array('xpath' => "//div[@id='toolbar-trash']//button")); break; case "save": $this->click(array('xpath' => "//div[@id='toolbar-apply']//button")); break; case "save & close": $this->click(array('xpath' => "//div[@id='toolbar-save']//button")); break; case "save & new": $this->click(array('xpath' => "//div[@id='toolbar-save-new']//button")); break; case "cancel": $this->click(array('xpath' => "//div[@id='toolbar-cancel']//button")); break; case "options": $this->click(array('xpath' => "//div[@id='toolbar-options']//button")); break; case "empty trash": $this->click(array('xpath' => "//div[@id='toolbar-delete']//button")); break; } }
Function to select Toolbar buttons in Joomla! Admin Toolbar Panel @param string $button The full name of the button @return void @since 3.0.0
entailment
public function createMenuItem($menuTitle, $menuCategory, $menuItem, $menu = 'Main Menu', $language = 'All') { $this->debug("I open the menus page"); $this->amOnPage('administrator/index.php?option=com_menus&view=menus'); $this->waitForText('Menus', TIMEOUT, array('css' => 'H1')); $this->checkForPhpNoticesOrWarnings(); $this->debug("I click in the menu: $menu"); $this->click(array('link' => $menu)); $this->waitForText('Menus: Items', TIMEOUT, array('css' => 'H1')); $this->checkForPhpNoticesOrWarnings(); $this->debug("I click new"); $this->click("New"); $this->waitForText('Menus: New Item', TIMEOUT, array('css' => 'h1')); $this->checkForPhpNoticesOrWarnings(); $this->fillField(array('id' => 'jform_title'), $menuTitle); $this->debug("Open the menu types iframe"); $this->click(array('link' => "Select")); $this->waitForElement(array('id' => 'menuTypeModal'), TIMEOUT); $this->wait(1); $this->switchToIFrame("Menu Item Type"); $this->debug("Open the menu category: $menuCategory"); // Open the category $this->wait(1); $this->waitForElement(array('link' => $menuCategory), TIMEOUT); $this->click(array('link' => $menuCategory)); $this->debug("Choose the menu item type: $menuItem"); $this->wait(1); $this->waitForElement(array('xpath' => "//a[contains(text()[normalize-space()], '$menuItem')]"), TIMEOUT); $this->click(array('xpath' => "//div[@id='collapseTypes']//a[contains(text()[normalize-space()], '$menuItem')]")); $this->debug('I switch back to the main window'); $this->switchToIFrame(); $this->debug('I leave time to the iframe to close'); $this->wait(2); $this->selectOptionInChosen('Language', $language); $this->waitForText('Menus: New Item', '30', array('css' => 'h1')); $this->debug('I save the menu'); $this->click("Save"); $this->waitForText('Menu item saved', TIMEOUT, array('id' => 'system-message-container')); }
Creates a menu item with the Joomla menu manager, only working for menu items without additional required fields @param string $menuTitle The menu item title @param string $menuCategory The category of the menu type (for example Weblinks) @param string $menuItem The menu item type / link text (for example List all Web Link Categories) @param string $menu The menu where the item should be created @param string $language If you are using Multilingual feature, the language for the menu @return void @since 3.0.0 @throws \Exception
entailment
public function setFilter($label, $value) { $label = strtolower($label); $filters = array( "select status" => "filter_published", "select access" => "filter_access", "select language" => "filter_language", "select tag" => "filter_tag", "select max levels" => "filter_level" ); $this->click(array('xpath' => "//button[@data-original-title='Filter the list items.']")); $this->debug('I try to select the filters'); foreach ($filters as $fieldName => $id) { if ($fieldName == $label) { $this->selectOptionInChosenByIdUsingJs($id, $value); } } $this->debug('Applied filters'); }
Function to filter results in Joomla! Administrator. @param string $label Label of the Filter you want to use. @param string $value Value you want to set in the filters. @return void @since 3.0.0
entailment
public function verifyAvailableTabs($expectedTabs, $tabsLocator = array('xpath' => "//ul[@id='myTabTabs']/li/a")) { $actualArrayOfTabs = $this->grabMultiple($tabsLocator); $this->debug("Fetch the current list of Tabs in the edit view which is: " . implode(", ", $actualArrayOfTabs)); $url = $this->grabFromCurrentUrl(); $this->assertEquals($expectedTabs, $actualArrayOfTabs, "Tab Labels do not match on edit view of" . $url); $this->debug('Verify the Tabs'); }
Function to Verify the Tabs on a Joomla! screen @param array $expectedTabs Expected Tabs on the Page @param Mixed $tabsLocator Locator for the Tabs in Edit View @return void @since 3.0.0
entailment
public function disableStatistics() { $this->debug('I click on never'); $this->wait(1); $this->waitForElement(array('link' => 'Never'), TIMEOUT); $this->click(array('link' => 'Never')); }
Hide the statistics info message {@internal doAdminLogin() before} @return void @since 3.5.0 @throws \Exception
entailment
public function createCategory($title, $extension = '') { $this->debug('Category creation in /administrator/'); $this->doAdministratorLogin(); if (!empty($extension)) { $extension = '&extension=' . $extension; } $this->amOnPage('administrator/index.php?option=com_categories' . $extension); $this->waitForElement(array('class' => 'page-title')); $this->checkForPhpNoticesOrWarnings(); $this->debug('Click new category button'); $this->click($this->locator->adminToolbarButtonNew); $this->waitForElement(array('class' => 'page-title')); $this->checkForPhpNoticesOrWarnings(); $this->fillField(array('id' => 'jform_title'), $title); $this->debug('Click new category apply button'); $this->click($this->locator->adminToolbarButtonApply); $this->debug('see a success message after saving the category'); $this->see('Category saved', '#system-message-container'); $this->checkForPhpNoticesOrWarnings(); }
Create a new category @param string $title Title of the new category @param string $extension Optional extension to use @return void @since 3.7.5 @throws \Exception
entailment
public function createUser($name, $username, $password, $email, $userGroup = 'Super Users') { $this->debug('User creation'); $this->doAdministratorLogin(); $this->amOnPage('administrator/index.php?option=com_users'); $this->waitForElement(array('class' => 'page-title')); $this->checkForPhpNoticesOrWarnings(); $this->debug('Click new user button'); $this->click($this->locator->adminToolbarButtonNew); $this->checkForPhpNoticesOrWarnings(); $this->debug('I fill up the new user information'); $this->fillField(array('id' => 'jform_name'), $name); $this->fillField(array('id' => 'jform_username'), $username); $this->fillField(array('id' => 'jform_password'), $password); $this->fillField(array('id' => 'jform_password2'), $password); $this->fillField(array('id' => 'jform_email'), $email); $this->debug('I open the Assigned User Groups Tab and assign the user group'); $this->click(array('link' => 'Assigned User Groups')); $this->click(array('xpath' => "//label[contains(text()[normalize-space()], '$userGroup')]")); $this->debug('Click new user apply button'); $this->click($this->locator->adminToolbarButtonApply); $this->debug('see a success message after saving the user'); $this->see('User saved', '#system-message-container'); $this->checkForPhpNoticesOrWarnings(); }
Create a user in the administrator site @param string $name Name @param string $username User name (login) @param string $password Password @param string $email Email @param string $userGroup Group id to attach to the user @return void @since 3.8.11 @throws \Exception
entailment
public function leaves(\WP_Query $query) { /** @var \stdClass $term */ $term = $query->get_queried_object(); if (!isset($term->slug) || !isset($term->term_id)) { return ['category']; } return [ "category-{$term->slug}", "category-{$term->term_id}", 'category', ]; }
{@inheritdoc}
entailment
public function dispatch(\Parable\Routing\Route $route) { $this->dispatchedRoute = $route; $this->hook->trigger(self::HOOK_DISPATCH_BEFORE, $route); $controller = null; // Start output buffering and set $returnContent to null $returnContent = null; $this->response->startOutputBuffer(); // Build the parameters array $parameters = []; foreach ($route->getValues() as $value) { $parameters[] = $value; } // Call the relevant code if ($route->hasControllerAndAction()) { $controller = \Parable\DI\Container::get($route->getController()); $returnContent = $controller->{$route->getAction()}(...$parameters); } elseif ($route->hasCallable()) { $callable = $route->getCallable(); $returnContent = $callable(...$parameters); } $this->hook->trigger(self::HOOK_DISPATCH_TEMPLATE_BEFORE, $route); // If the route has no template path, attempt to build one based on controller/action.phtml if (!$route->hasTemplatePath() && $route->hasControllerAndAction()) { $reflection = new \ReflectionClass($controller); $controllerName = str_replace('\\', '/', $reflection->getName()); $controllerName = str_replace('Controller/', '', $controllerName); $templatePathGenerated = $this->path->getDir( "app/View/{$controllerName}/{$route->getAction()}.phtml" ); if (file_exists($templatePathGenerated)) { $route->setTemplatePath($templatePathGenerated); } } // And check again, now that we might have a magic template path if ($route->hasTemplatePath()) { $templatePath = $this->path->getDir($route->getTemplatePath()); $this->view->setTemplatePath($templatePath); $this->view->render(); } // If the callback or controller/action returned content, we need to handle it if ($returnContent) { if ($this->response->getOutput()->acceptsContent($returnContent)) { $this->response->setContent($returnContent); } else { $type = gettype($returnContent); $output = get_class($this->response->getOutput()); // Stop the output buffer we've started above and throw $this->response->stopOutputBuffer(); throw new \Parable\Framework\Exception( "Route returned value of type '{$type}', which output class '{$output}' cannot handle." ); } } // Any rendered content was from before the returnContent was set, so we prepend it if there's any $renderedContent = $this->response->returnOutputBuffer(); if ($renderedContent) { $this->response->prependContent($renderedContent); } $this->hook->trigger(self::HOOK_DISPATCH_TEMPLATE_AFTER, $route); $this->hook->trigger(self::HOOK_DISPATCH_AFTER, $route); return $this; }
Dispatch the provided route. @param \Parable\Routing\Route $route @return $this
entailment
public function image($path, array $options = array()) { if ('text' == $this->getType()) { return null; } return parent::image($path, $this->_mergeAttributes($options, $this->config('attributes.image'))); }
{@inheritdoc}
entailment
public function link($title, $url = null, array $options = array()) { $url = Router::url($url, ['full' => true]); if ('html' == $this->getType()) { return parent::link($title, $url, $this->_mergeAttributes($options, $this->config('attributes.link'))); } if (empty($url)) { return $title; } $options += ['templates' => []]; $options['templates'] += ['link' => ':title: :url']; return Text::insert($options['templates']['link'], compact('title', 'url')); }
{@inheritdoc}
entailment
public function media($path, array $options = array()) { if ('text' == $this->getType()) { return; } return parent::media($path, $this->_mergeAttributes($options, $this->config('attributes.media'))); }
{@inheritdoc}
entailment
public function para($class, $text, array $options = array()) { if ('text' == $this->getType()) { return $this->_eol() . $this->_eol() . $text . $this->_eol() . $this->_eol(); } return parent::para($class, $text, $this->_mergeAttributes($options, $this->config('attributes.para'))); }
{@inheritdoc}
entailment
public function table($content, $options = array()) { if ('text' == $this->getType()) { return $content; } if (false === $options) { return $this->config('templates.tableend'); } $tag = 'table'; if (is_null($content)) { $tag = 'tablestart'; } $templater = $this->templater(); return $templater->format('table', [ 'attrs' => $templater->formatAttributes($this->_mergeAttributes($options, $this->config('attributes.table'))), 'content' => $content ]); }
Creates table. @param string $content @param array $options @return string
entailment
public function viewport($content = null) { if (empty($content)) { $content = 'width=device-width, initial-scale=1.0'; } if (is_array($content)) { $content = implode(', ', $content); } return $this->meta(array('name' => 'viewport', 'content' => $content)); }
Viewport meta. @param mixed $content @return string
entailment
protected function _mergeAttributes($attrs, $merge) { $appendable = array( 'class' => array('separator' => ' ', 'match' => 'full'), 'style' => array('separator' => ';', 'match' => 'part'), ); foreach ((array)$merge as $attr => $values) { if ( !array_key_exists($attr, $attrs) || empty($attrs[$attr]) && false !== $attrs[$attr] ) { $attrs[$attr] = $values; continue; } elseif (!in_array($attr, array_keys($appendable))) { continue; } if (!is_array($attrs[$attr])) { $attrs[$attr] = explode($appendable[$attr]['separator'], $attrs[$attr]); $implode = true; } if (!is_array($values)) { $values = explode($appendable[$attr]['separator'], $attrs[$attr]); } switch ($appendable[$attr]['match']) { case 'full': foreach ($values as $value) { if (!in_array($value, $attrs[$attr])) { $attrs[$attr][] = $value; } } break; case 'part': foreach ($attrs[$attr] as $k => $haystack) { if (empty($haystack)) { unset($attrs[$attr][$k]); continue; } if (false === strpos($haystack, $appendable[$attr]['separator'])) { $attrs[$attr][$k] = $haystack . $appendable[$attr]['separator']; } foreach ($values as $n => $value) { $needle = current(explode(':', $value)) . ':'; if (0 === strpos($haystack, $needle) || false !== strpos($haystack, ';' . $needle) || false !== strpos($haystack, '; ' . $needle) ) { unset($values[$n]); } } } foreach (array_keys($values) as $key) { if (false === strpos($values[$key], $appendable[$attr]['separator'])) { $values[$key] = $values[$key] . $appendable[$attr]['separator']; } $attrs[$attr][] = $values[$key]; } break; default: } if (isset($implode)) { $attrs[$attr] = implode(' ', $attrs[$attr]); } } return $attrs; }
Merge attributes. @param array $attrs Passed attributes. @param array $merge Default attributes. @return array
entailment
public function setCode4User(UserInterface $userEntity, $type, $expire = null) { $entityManager = $this->entityManager; $this->getRepositoryManager()->deleteCodes4User($userEntity->getId(), $type); do { $found = false; $code = $this->formatService->getCode(); if ($this->getRepositoryManager()->getCode($code)) { $found = true; } } while ($found); $userCodesEntity = new Entity(); $userCodesEntity->setCode($code) ->setUser($userEntity) ->setType($type); if (!$expire) { $expireOption = $this->collectionOptions->getUserCodesOptions()->getExpire(); $expire = $expireOption[$type] ?? $expireOption['general']; } if ($expire) { $dateTime = new DateTime(); $userCodesEntity->setExpire($dateTime->setTimestamp(time() + $expire)); } $entityManager->persist($userCodesEntity); $entityManager->flush(); return $code; }
@param UserInterface $userEntity @param string $type @param int|null $expire @return string
entailment
public function deleteCode(Entity $userCode) { $entityManager = $this->entityManager; $entityManager->remove($userCode); $entityManager->flush(); }
delete a userCode from database @param Entity $userCode
entailment
public function cleanExpireCodes($limit = 100) { $codeList = $this->getRepositoryManager()->getExpiredCodes($limit); $result = 0; if ($codeList) { $result = $this->cleanExpireCodes4List($codeList); } return $result; }
@param int $limit @return int
entailment
protected function cleanExpireCodes4List(array $codeList) { $i = 0; $entityManager = $this->entityManager; foreach ($codeList as $code) { try { $entityManager->remove($code); // if we have a register-code, so we have to remove the user too if ($code->getType() == $code::TYPE_REGISTER) { $user = $code->getUser(); /** @var \PServerCore\Entity\Repository\Logs $logRepository */ $logRepository = $entityManager->getRepository( $this->collectionOptions->getEntityOptions()->getLogs() ); $logRepository->setLogsNull4User($user); /** @var \PServerCore\Entity\Repository\UserExtension $extensionRepository */ $extensionRepository = $entityManager->getRepository( $this->collectionOptions->getEntityOptions()->getUserExtension() ); $extensionRepository->deleteExtension($user); // secret question if ($this->collectionOptions->getPasswordOptions()->isSecretQuestion()) { /** @var \PServerCore\Entity\Repository\SecretAnswer $answerRepository */ $answerRepository = $entityManager->getRepository( $this->collectionOptions->getEntityOptions()->getSecretAnswer() ); $answerRepository->deleteAnswer4User($user); } $entityManager->remove($user); } $entityManager->flush(); ++$i; } catch (\Throwable $exception) { // skip this exception } } return $i; }
@param Entity[] $codeList @return int
entailment
protected function entityToString($entity) { return method_exists($entity, '__toString') ? (string) $entity : get_class($entity) . '@' . spl_object_hash($entity); }
@param object $entity @return string
entailment
private function parse(\WP_Query $query = null) { (is_null($query) && isset($GLOBALS['wp_query'])) and $query = $GLOBALS['wp_query']; $data = (object)['hierarchy' => [], 'templates' => [], 'query' => $query]; $branches = self::$branches; // make the branches filterable, but assuring each item still implement branch interface if ($this->flags & self::FILTERABLE) { $branches = array_filter( (array)apply_filters('brain.hierarchy.branches', $branches), function ($branch) { return is_subclass_of($branch, Branch\BranchInterface::class, true); } ); } // removed indexes, we added them to make filtering easier $branches = array_values($branches); if ($query instanceof \WP_Query) { $data = array_reduce($branches, [$this, 'parseBranch'], $data); } $data->hierarchy = $this->addIndexLeaves($data->hierarchy); $data->templates[] = 'index'; $data->templates = array_values(array_unique($data->templates)); return $data; }
Parse all branches. @param \WP_Query $query @return \stdClass
entailment
private function parseBranch(\stdClass $data, $branchClass) { /** @var \Brain\Hierarchy\Branch\BranchInterface $branch */ $branch = new $branchClass(); $name = $branch->name(); $isFilterable = ($this->flags & self::FILTERABLE) > 0; // When branches are filterable, we need this for core compatibility. $isFilterable and $name = preg_replace('|[^a-z0-9-]+|', '', $name); if ($branch->is($data->query) && ! isset($data->hierarchy[$name])) { $leaves = $branch->leaves($data->query); // this filter was introduced in WP 4.7 $isFilterable and $leaves = apply_filters("{$name}_template_hierarchy", $leaves); $data->hierarchy[$name] = $leaves; $data->templates = array_merge($data->templates, $leaves); } return $data; }
@param string $branchClass @param \stdClass $data @return \stdClass
entailment
public function setCurrentPlayer($extraPlayer = 0) { try { $player = $this->gameBackendService->getCurrentPlayerNumber(); } catch (\Exception $e) { $player = 0; } if ($player > 0) { $player += $extraPlayer; } $class = $this->collectionOptions->getEntityOptions()->getPlayerHistory(); /** @var \PServerCore\Entity\PlayerHistory $playerHistory */ $playerHistory = new $class(); $playerHistory->setPlayer($player); $this->entityManager->persist($playerHistory); $this->entityManager->flush(); }
read from GameBackend the current player [or] as param and save them in database @param int $extraPlayer
entailment
public function outputCurrentPlayerImage() { $playerNumber = $this->getCurrentPlayer(); $image = imagecreate(250, 50); //set the background color of the image $color = $this->collectionOptions->getGeneralOptions()->getImagePlayer()['background_color']; imagecolorallocate($image, $color[0], $color[1], $color[2]); //set the color for the text $color = $this->collectionOptions->getGeneralOptions()->getImagePlayer()['font_color']; $fontColor = imagecolorallocate($image, $color[0], $color[1], $color[2]); //adf the string to the image $maxPlayer = $this->collectionOptions->getGeneralOptions()->getMaxPlayer(); if ($maxPlayer > 0) { $text = sprintf('%s/%s Player Online', $playerNumber, $maxPlayer); } else { $text = sprintf('%s Player Online', $playerNumber); } $this->imageCenterString($image, 5, $text, $fontColor); imagepng($image); imagedestroy($image); }
output the player online image
entailment
public function pageAction() { $type = $this->params()->fromRoute('type'); $pageInfo = $this->pageInfoService->getPage4Type($type); if (!$pageInfo) { return $this->redirect()->toRoute('PServerCore'); } return [ 'pageInfo' => $pageInfo ]; }
DynamicPages
entailment
public function getStatisticData($lastDays = 10) { $timestamp = DateTimer::getZeroTimeStamp(strtotime('-' . $lastDays - 1 . ' days')); $dateTime = DateTimer::getDateTime4TimeStamp($timestamp); $donateEntity = $this->getDonateLogEntity(); $typList = $donateEntity->getDonateTypes(); $donateHistory = $donateEntity->getDonateHistorySuccess($dateTime); $result = []; // set some default values $range = DateTimer::getDateRange4Period($dateTime, new \DateTime()); foreach ($range as $date) { foreach ($typList as $type) { $result[$date->format('Y-m-d')][$type] = [ 'amount' => 0, 'coins' => 0 ]; } } if ($donateHistory) { foreach ($donateHistory as $donateData) { /** @var \DateTime $date */ $date = $donateData['created']; $result[$date->format('Y-m-d')][$donateData['type']]['amount'] += $donateData['amount']; $result[$date->format('Y-m-d')][$donateData['type']]['coins'] += $donateData['coins']; } } return $result; }
@param int $lastDays @return array
entailment
public function createQuery() { $query = \Parable\ORM\Query::createInstance(); $query->setTableName($this->getTableName()); return $query; }
Generate a query set to use the current Model's table name & key. @return \Parable\ORM\Query
entailment
public function save() { $array = $this->toArrayWithoutEmptyValues(); $query = $this->createQuery(); $now = (new \DateTime())->format('Y-m-d H:i:s'); if ($this->{$this->getTableKey()}) { $query->setAction('update'); $query->where($query->buildAndSet([ [$this->getTableKey(), "=", $this->id], ])); foreach ($array as $key => $value) { $query->addValue($key, $value); } // Since it's an update, add updated_at if the model implements it if (property_exists($this, 'updated_at')) { $query->addValue('updated_at', $now); $this->updated_at = $now; } } else { $query->setAction('insert'); foreach ($array as $key => $value) { if ($key !== $this->tableKey) { $query->addValue($key, $value); } } // Since it's an insert, add created_at if the model implements it if (property_exists($this, 'created_at')) { $query->addValue('created_at', $now); $this->created_at = $now; } } $result = $this->database->query($query); if ($result && $query->getAction() === 'insert') { $this->id = $this->database->getInstance()->lastInsertId(); } return $result ? true : false; }
Saves the model, either inserting (no id) or updating (id). @return bool
entailment
public function delete() { $query = $this->createQuery(); $query->setAction('delete'); $query->where($query->buildAndSet([$this->getTableKey(), '=', $this->id])); $result = $this->database->query($query); return $result ? true : false; }
Deletes the current model from the database. @return bool
entailment
public function populate(array $data) { foreach ($data as $property => $value) { if (property_exists($this, $property)) { $this->{$property} = $value; } } return $this; }
Populates the current model with the data provided. @param array $data @return $this;
entailment
public function toArray($keepNullValue = false) { $reflection = new \ReflectionClass(static::class); $arrayData = []; foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { $value = $property->getValue($this); // We don't want to add either static properties or when the value evaluates to regular empty but isn't a 0 if ($property->isStatic()) { continue; } // If it's specifically decreed that it's a null value, we leave it in, which will set it to NULL in the db if (!$keepNullValue && $value === \Parable\ORM\Database::NULL_VALUE) { $value = null; } $arrayData[$property->getName()] = $value; } if ($this->getMapper()) { $arrayData = $this->toMappedArray($arrayData); } return $arrayData; }
Generates an array of the current model, without the protected values. @param bool $keepNullValue @return array @throws \ReflectionException
entailment
public function toArrayWithoutEmptyValues() { $array = $this->removeEmptyValues($this->toArray(true)); foreach ($array as $key => $value) { if ($value === \Parable\ORM\Database::NULL_VALUE) { $array[$key] = null; } } return $array; }
Generates an array of the current model, but removes empty values. @return array
entailment
public function toMappedArray(array $array) { $mappedArray = []; foreach ($this->getMapper() as $from => $to) { $mappedArray[$to] = $array[$from]; } return $mappedArray; }
Attempts to use stored mapper array to map fields from the current model's properties to what is set in the array. @param array $array @return array
entailment
public function exportToArray() { $data = $this->toArray(); if (count($this->exportable) === 0) { return $data; } $exportData = []; foreach ($data as $key => $value) { if (in_array($key, $this->exportable)) { $exportData[$key] = $data[$key]; } } return $exportData; }
Export to array, which will exclude unexportable keys @return array
entailment
public function reset() { $reflection = new \ReflectionClass(static::class); foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { if (!$property->isStatic()) { $this->{$property->getName()} = null; } } return $this; }
Reset all public properties to null. @return $this @throws \ReflectionException
entailment
public function isCountryAllowedForUser($userId, $country) { $query = $this->createQueryBuilder('p') ->select('p') ->where('p.user = :userId') ->setParameter('userId', $userId) ->getQuery(); $data = $query->getResult(); $return = false; foreach ($data as $availableCountries) { /** @var \PServerCore\Entity\AvailableCountries $availableCountries */ if ($availableCountries->getCntry() == $country) { $return = true; break; } } return $return; }
@param $userId @param $country @return bool
entailment
public function setRequired($required) { if (!in_array( $required, [ \Parable\Console\Parameter::PARAMETER_REQUIRED, \Parable\Console\Parameter::PARAMETER_OPTIONAL, ] )) { throw new \Parable\Console\Exception('Required must be one of the PARAMETER_* constants.'); } $this->required = $required; return $this; }
Set whether this argument is required. @param int $required @return $this @throws \Parable\Console\Exception
entailment
public function init() { parent::init(); self::$plugin = $this; Craft::$app->getView()->registerTwigExtension(new EnvironmentLabelTwigExtension()); Event::on( View::class, View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE, function (Event $event) { EnvironmentLabel::$plugin->label->doItBaby(); } ); }
Initializes the plugin, sets its static self-reference, registers the Twig extension, and adds the environment label as appropriate.
entailment
public function send($to, $subject, $body, $headers) { return mail( $to, $subject, $body, $headers ); }
Send using PHPs built-in Mail interface @inheritdoc @codeCoverageIgnore
entailment
protected function loadCommands(PackageInterface $package) { if (!$package->getCommands() || APP_CONTEXT !== 'console') { return $this; } $commandLoader = \Parable\DI\Container::create(\Parable\Framework\Loader\CommandLoader::class); $commandLoader->load($package->getCommands()); return $this; }
Load all Commands from package. @param PackageInterface $package @return $this @throws \Parable\DI\Exception
entailment
public function registerPackages() { foreach ($this->packages as $packageName) { $package = \Parable\DI\Container::create($packageName); $this->loadCommands($package); $this->loadInits($package); } return $this; }
Register all packages with Parable. @return $this @throws \Parable\DI\Exception
entailment
protected function loadInits(PackageInterface $package) { if (!$package->getInits()) { return $this; } $initLoader = \Parable\DI\Container::create(\Parable\Framework\Loader\InitLoader::class); $initLoader->load($package->getInits()); return $this; }
Load all Inits from package. @param PackageInterface $package @return $this @throws \Parable\DI\Exception
entailment
public function load(array $commandClasses) { foreach ($commandClasses as $commandClass) { $command = \Parable\DI\Container::create($commandClass); $this->consoleApp->addCommand($command); } return $this; }
Add all commands passed to the console app. @param string[] $commandClasses @return $this @throws \Parable\DI\Exception
entailment
public function up() { Schema::create('ipn_orders', function (Blueprint $table) { $table->increments('id'); $table->string('notify_version', 64)->nullable(); $table->string('verify_sign', 127)->nullable(); $table->integer('test_ipn')->nullable(); $table->string('protection_eligibility', 24)->nullable(); $table->string('charset', 127)->nullable(); $table->string('btn_id', 40)->nullable(); $table->string('address_city', 40)->nullable(); $table->string('address_country', 64)->nullable(); $table->string('address_country_code', 2)->nullable(); $table->string('address_name', 128)->nullable(); $table->string('address_state', 40)->nullable(); $table->string('address_status', 20)->nullable(); $table->string('address_street', 200)->nullable(); $table->string('address_zip', 20)->nullable(); $table->string('first_name', 64)->nullable(); $table->string('last_name', 64)->nullable(); $table->string('payer_business_name', 127)->nullable(); $table->string('payer_email', 127)->nullable(); $table->string('payer_id', 13)->nullable(); $table->string('payer_status', 20)->nullable(); $table->string('contact_phone', 20)->nullable(); $table->string('residence_country', 2)->nullable(); $table->string('business', 127)->nullable(); $table->string('receiver_email', 127)->nullable(); $table->string('receiver_id', 64)->nullable(); $table->string('custom', 255)->nullable(); $table->string('invoice', 127)->nullable(); $table->string('memo', 255)->nullable(); $table->decimal('tax', 9, 2)->nullable(); $table->string('auth_id', 19)->nullable(); $table->string('auth_exp', 28)->nullable(); $table->decimal('auth_amount', 9, 2)->nullable(); $table->string('auth_status', 20)->nullable(); $table->integer('num_cart_items')->nullable(); $table->string('parent_txn_id', 19)->nullable(); $table->string('payment_date', 28)->nullable(); $table->string('payment_status', 20)->nullable(); $table->string('payment_type', 10)->nullable(); $table->string('pending_reason', 20)->nullable(); $table->string('reason_code', 20)->nullable(); $table->string('remaining_settle', 9, 2)->nullable(); $table->string('shipping_method', 64)->nullable(); $table->string('shipping', 9, 2)->nullable(); $table->string('transaction_entity', 20)->nullable(); $table->string('txn_id', 19)->nullable(); $table->string('txn_type', 20)->nullable(); $table->string('exchange_rate', 9, 2)->nullable(); $table->string('mc_currency', 3)->nullable(); $table->string('mc_fee', 9, 2)->nullable(); $table->string('mc_gross', 9, 2)->nullable(); $table->string('mc_handling', 9, 2)->nullable(); $table->string('mc_shipping', 9, 2)->nullable(); $table->string('payment_fee', 9, 2)->nullable(); $table->string('payment_gross', 9, 2)->nullable(); $table->string('settle_amount', 9, 2)->nullable(); $table->string('settle_currency', 3)->nullable(); $table->string('auction_buyer_id', 64)->nullable(); $table->string('auction_closing_date', 28)->nullable(); $table->integer('auction_multi_item')->nullable(); $table->string('for_auction', 10)->nullable(); $table->string('subscr_date', 28)->nullable(); $table->string('subscr_effective', 28)->nullable(); $table->string('period1', 10)->nullable(); $table->string('period2', 10)->nullable(); $table->string('period3', 10)->nullable(); $table->decimal('amount1', 9, 2)->nullable(); $table->decimal('amount2', 9, 2)->nullable(); $table->decimal('amount3', 9, 2)->nullable(); $table->decimal('mc_amount1', 9, 2)->nullable(); $table->decimal('mc_amount2', 9, 2)->nullable(); $table->decimal('mc_amount3', 9, 2)->nullable(); $table->string('reattempt', 1)->nullable(); $table->string('retry_at', 28)->nullable(); $table->integer('recur_times')->nullable(); $table->string('username', 64)->nullable(); $table->string('password', 24)->nullable(); $table->string('subscr_id', 19)->nullable(); $table->string('case_id', 28)->nullable(); $table->string('case_type', 28)->nullable(); $table->string('case_creation_date', 28)->nullable(); $table->string('order_status')->nullable(); $table->decimal('discount', 9, 2)->nullable(); $table->decimal('shipping_discount', 9, 2)->nullable(); $table->string('ipn_track_id', 127)->nullable(); $table->string('transaction_subject', 255)->nullable(); $table->text('full_ipn'); $table->timestamps(); $table->softDeletes(); }); }
Run the migrations. @return void
entailment
public function addCommand(\Parable\Console\Command $command) { $command->prepare($this, $this->output, $this->input, $this->parameter); $this->commands[$command->getName()] = $command; return $this; }
Add a command to the application. @param \Parable\Console\Command $command @return $this
entailment
public function setDefaultCommand(\Parable\Console\Command $command) { $this->addCommand($command); $this->setDefaultCommandByName($command->getName()); return $this; }
Set the default command to use if no command is given. Also adds the command. @param \Parable\Console\Command $command @return $this
entailment
public function run() { $defaultCommand = null; $command = null; if ($this->defaultCommand) { $defaultCommand = $this->getCommand($this->defaultCommand); } if (!$this->shouldOnlyUseDefaultCommand()) { $commandName = $this->parameter->getCommandName(); if ($commandName) { $command = $this->getCommand($commandName); } $this->parameter->enableCommandName(); } else { $this->parameter->disableCommandName(); } // Use $command or $defaultCommand, since they're mutually exclusive $command = $command ?: $defaultCommand; if (!$command) { throw new \Parable\Console\Exception('No valid commands found.'); } $this->activeCommand = $command; $this->parameter->setCommandArguments($command->getArguments()); $this->parameter->checkCommandArguments(); $this->parameter->setCommandOptions($command->getOptions()); $this->parameter->checkCommandOptions(); return $command->run(); }
Run the application. @return mixed @throws \Parable\Console\Exception
entailment
public function getOrder() { $request = $this->getRequestHandler(); $listener = new PayPalListener($request); $listener->setMode($this->getEnvironment()); if ($listener->verifyIpn()) { return $this->store($request->getData()); } else { throw new InvalidIpnException("PayPal as responded with INVALID"); } }
Listens for and stores PayPal IPN requests. @return IpnOrder @throws InvalidIpnException @throws UnexpectedResponseBodyException @throws UnexpectedResponseStatusException
entailment
public function getRequestHandler() { $config = Config::get('paypal-ipn-laravel::request_handler', 'auto'); if ($config == 'curl' || ($config == 'auto' && is_callable('curl_init'))) { return new CurlRequest(Input::all()); } else { return new SocketRequest(Input::all()); } }
Get the request handler. @return Request
entailment
private function store($data) { if (array_key_exists('txn_id', $data)) { $order = IpnOrder::firstOrNew(array('txn_id' => $data['txn_id'])); $order->fill($data); } else { $order = new IpnOrder($data); } $order->full_ipn = json_encode(Input::all()); $order->save(); $this->storeOrderItems($order, $data); return $order; }
Stores the IPN contents and returns the IpnOrder object. @param array $data @return IpnOrder
entailment
private function storeOrderItems($order, $data) { $cart = isset($data['num_cart_items']); $numItems = (isset($data['num_cart_items'])) ? $data['num_cart_items'] : 1; for ($i = 0; $i < $numItems; $i++) { $suffix = ($numItems > 1 || $cart) ? ($i + 1) : ''; $suffixUnderscore = ($numItems > 1 || $cart) ? '_' . $suffix : $suffix; $item = new IpnOrderItem(); if (isset($data['item_name' . $suffix])) $item->item_name = $data['item_name' . $suffix]; if (isset($data['item_number' . $suffix])) $item->item_number = $data['item_number' . $suffix]; if (isset($data['quantity' . $suffix])) $item->quantity = $data['quantity' . $suffix]; if (isset($data['mc_gross' . $suffixUnderscore])) $item->mc_gross = $data['mc_gross' . $suffixUnderscore]; if (isset($data['mc_handling' . $suffix])) $item->mc_handling = $data['mc_handling' . $suffix]; if (isset($data['mc_shipping' . $suffix])) $item->mc_shipping = $data['mc_shipping' . $suffix]; if (isset($data['tax' . $suffix])) $item->tax = $data['tax' . $suffix]; $order->items()->save($item); // Set the order item options if any // $count = 7 because PayPal allows you to set a maximum of 7 options per item // Reference: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_Appx_websitestandard_htmlvariables for ($ii = 1, $count = 7; $ii < $count; $ii++) { if (isset($data['option_name' . $ii . '_' . $suffix])) { $option = new IpnOrderItemOption(); $option->option_name = $data['option_name' . $ii . '_' . $suffix]; if (isset($data['option_selection' . $ii . '_' . $suffix])) { $option->option_selection = $data['option_selection' . $ii . '_' . $suffix]; } $item->options()->save($option); } } } }
Stores the order items from the IPN contents. @param IpnOrder $order @param array $data
entailment
private function postType(\WP_Query $query) { $type = $query->get('post_type'); is_array($type) and $type = reset($type); $object = get_post_type_object($type); (is_object($object) && $object->has_archive) or $type = ''; return $type; }
@param \WP_Query $query @return mixed|string
entailment
public function trigger($event = null, &$payload = null) { // Disallow calling a trigger on global docks if ($event === '*') { return $this; } // Get all global docks $globalDocks = []; if (isset($this->docks['*']) && count($this->docks['*']) > 0) { $globalDocks = $this->docks['*']; } // Check if the event exists and has callables to run if (!isset($this->docks[$event]) || count($this->docks[$event]) === 0) { // There are no specific docks, but maybe there's global docks? if (count($globalDocks) === 0) { // There is nothing to do here return $this; } $docks = $globalDocks; } else { $docks = $this->docks[$event]; $docks = array_merge($docks, $globalDocks); } // All good, let's call those callables foreach ($docks as $dock) { $dock['callable']($event, $payload); // And include the template if we have one. Data should be passed to the template through // outside means like through the session or \Parable\GetSet or one of its sub-types. if ($dock['templatePath'] && file_exists($dock['templatePath'])) { ob_start(); require $dock['templatePath']; $return = ob_get_clean(); echo $return; } } return $this; }
Trigger $event and run through all docks referenced, passing along $payload to all $callables. @param null|string $event @param null|mixed $payload @return $this|bool
entailment
public function isValid($value) { $result = true; $this->setValue($value); $type = $this->getOption('type'); $blackList = $this->config['blacklisted'][$type]; if (!$blackList) { return $result; } foreach ($blackList as $entry) { if (stripos($value, $this->editBlackListedData($entry, $type)) === false) { continue; } $result = false; $this->error(self::ERROR_BLACKLIST); break; } 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
protected function editBlackListedData(string $data, string $type): string { if ($type == self::TYPE_EMAIL) { $data = sprintf('@%s', $data); } return $data; }
@param string $data @return string
entailment
public function add($cacheKey, $content, $status = 200, $headers = [], $expires = Cache::HOUR) { $file = File::create(); $file->setStatus($status); $file->setContent($content); $file->setRoute($cacheKey); $file->setHeaders($headers); if ($expires > 0) { $file->setExpires(time() + $expires); } else { $file->setExpires($expires); } $this->fileHandler->write($file); }
Adds a cache entry with a given key, content and for a set amount of time The time by default for the cache is an hour @param $cacheKey @param $content @param int $status @param array $headers @param int $expires @throws CacheFileSystemException
entailment
public function setQuery(\Parable\ORM\Query $query) { $this->query = $query; $this->setTableName($query->getTableName()); return $this; }
Set the query. @param \Parable\ORM\Query $query @return $this
entailment
public function setShouldCompareFields($shouldCompareFields) { // We need to set shouldQuoteValues to the opposite of shouldCompareFields $this->shouldQuoteValues = !$shouldCompareFields; $this->shouldCompareFields = (bool)$shouldCompareFields; return $this; }
Set whether the fields should be compared rather than values. If so, quoteValues is set to inverted value. @param bool $shouldCompareFields @return $this
entailment
public function build() { $value = $this->getValue(); $this->uppercaseComparator(); // Check for IS/IS NOT and set the value to NULL if it is. if ($this->isComparatorIsNotNullIsNull()) { $value = null; } // Check for IN/NOT IN and build a nice comma-separated list. if (!$this->isComparatorIsNotNullIsNull() && $this->isComparatorInNotIn() && is_array($value)) { $this->uppercaseComparator(); $valueArray = []; foreach ($value as $valueItem) { if ($this->shouldQuoteValues()) { $valueArray[] = $this->query->quote($valueItem); } else { $valueArray[] = $valueItem; } } $value = '(' . implode(',', $valueArray) . ')'; } // Now check if we need to still quote the value. if (!$this->isComparatorIsNotNullIsNull() && !$this->isComparatorInNotIn() && $this->shouldQuoteValues()) { $value = $this->query->quote($value); } // If we don't have IN/NOT IN, IS/NOT IS, and we shouldn't quote, we assume we're checking fields. if ($this->shouldCompareFields()) { $valueBuild = [ $this->query->quoteIdentifier($this->getTableName()), '.', $this->query->quoteIdentifier($value), ]; $value = implode($valueBuild); } $tableName = $this->getTableName(); if ($this->getJoinTableName()) { $tableName = $this->getJoinTableName(); } $tableName = $this->query->quoteIdentifier($tableName); $returnArray = [ $tableName . '.' . $this->query->quoteIdentifier($this->getKey()), $this->getComparator(), $value, ]; $returnString = implode(' ', $returnArray); return trim($returnString); }
Build the condition to a string. @return string
entailment
public function get($configString, $default = false) { // Check if we have a cache if (isset($this->cache[$configString])) { return $this->cache[$configString]; } $valueList = explode('.', $configString); $config = $this->config; foreach ($valueList as $value) { if (!isset($config[$value])) { $config = $default; break; } $config = $config[$value]; } // save @ cache $this->cache[$configString] = $config; return $config; }
@param $configString @param bool $default @return mixed
entailment
public function load(array $initClasses) { foreach ($initClasses as $initClass) { \Parable\DI\Container::create($initClass); } return $this; }
Load array of init classes. @param string[] $initClasses @return $this @throws \Parable\DI\Exception
entailment
public function getCountryCode4Ip(int $decimalIp): string { $query = $this->createQueryBuilder('p') ->select('p') ->where('p.ipMin <= :ip') ->andWhere('p.ipMax >= :ip') ->setParameter('ip', $decimalIp) ->getQuery(); /** @var \PServerCore\Entity\CountryList $result */ $result = $query->getOneOrNullResult(); if (!$result) { return 'ZZZ'; } return $result->getCntry(); }
@param int $decimalIp @return string
entailment
public function getDescription4CountryCode(string $cntry): string { $query = $this->createQueryBuilder('p') ->select('p') ->where('p.cntry = :sCntry') ->setParameter('sCntry', $cntry) ->setMaxResults(1) ->getQuery(); /** @var \PServerCore\Entity\CountryList $result */ $result = $query->getOneOrNullResult(); // no country found if (!$result) { return 'ZZZ'; } return $result->getCountry(); }
@param string $cntry @return string
entailment
public function getNews4Id($newsId) { $query = $this->createQueryBuilder('p') ->select('p') ->where('p.id = :newsId') ->setParameter('newsId', $newsId) ->getQuery(); return $query->getOneOrNullResult(); }
@param $newsId @return null|\PServerCore\Entity\News
entailment
private function enableCompilation(ContainerBuilder $builder): bool { $path = $this->definitions[$this::CONFIG][$this::DI_CACHE_PATH] ?? null; if ($path) { $builder->enableCompilation($path); return is_file(rtrim($path, '/') . '/CompiledContainer.php'); } return false; }
@param ContainerBuilder $builder @return bool true if compilation is enabled and CompiledContainer exists.
entailment
private function parseArgs(array $args) { if (! count($args)) { return $this->createHelpArgument(); } $arg1 = array_shift($args); if (in_array($arg1, ['-h', '--help', 'help'], true)) { return $this->createHelpArgument(); } if (! count($args)) { return $this->createErrorArgument('Missing class name'); } $configFile = $arg1; switch (file_exists($configFile)) { case true: $config = require $configFile; if (! is_array($config)) { return $this->createErrorArgument(sprintf( 'Configuration at path "%s" does not return an array.', $configFile )); } break; case false: // fall-through default: if (! is_writable(dirname($configFile))) { return $this->createErrorArgument(sprintf( 'Cannot create configuration at path "%s"; not writable.', $configFile )); } $config = []; break; } $class = array_shift($args); if (! class_exists($class)) { return $this->createErrorArgument(sprintf( 'Class "%s" does not exist or could not be autoloaded.', $class )); } return $this->createArguments(self::COMMAND_DUMP, $configFile, $config, $class); }
@param array $args @return \stdClass
entailment
private function help($resource = STDOUT) { $this->helper->writeLine(sprintf( self::HELP_TEMPLATE, $this->scriptName ), true, $resource); }
@param resource $resource Defaults to STDOUT @return void
entailment
public function findFirst(array $templates, $type) { $found = ''; while (!empty($templates) && $found === '') { $found = $this->find(array_shift($templates), $type) ?: ''; } return $found; }
@param array $templates @param string $type @return string @see \Brain\Hierarchy\Finder\TemplateFinderInterface::findFirst()
entailment
public function doAuthentication(UserInterface $user) { /** @var \PServerCore\Entity\Repository\User $repository */ $repository = $this->entityManager->getRepository($this->getUserEntityClassName()); // fix if we have a proxy we don´t have a valid entity, so we have to clear before we can create a new select $username = $user->getUsername(); $repository->clear(); $userNew = $repository->getUser4UserName($username); $authService = $this->getAuthService(); $authService->getStorage()->write($userNew); }
Login with a User @param UserInterface $user
entailment
protected function bCrypt($password) { if ($this->isSamePasswordOption()) { $result = $this->gameDataService->hashPassword($password); } else { $bCrypt = new Bcrypt(); $result = $bCrypt->create($password); } return $result; }
We want to crypt a password =) @param $password @return string
entailment
public function leaves(\WP_Query $query) { /** @var \WP_Post $post */ $post = $query->get_queried_object(); if (!$post instanceof \WP_Post || ! $post->ID) { return ['single']; } $leaves = [ "single-{$post->post_type}-{$post->post_name}", "single-{$post->post_type}", 'single', ]; $decoded = urldecode($post->post_name); if ($decoded !== $post->post_name) { array_unshift($leaves, "single-{$post->post_type}-{$decoded}"); } $template = $this->postTemplates->findFor($post); $template and array_unshift($leaves, $template); return $leaves; }
{@inheritdoc}
entailment
protected function fetchControllerSuffix() { // Validate that we have a map to handle the given HTTP method. if (!isset($this->suffixMap[$this->input->getMethod()])) { throw new \RuntimeException(sprintf('Unable to support the HTTP method `%s`.', $this->input->getMethod()), 404); } // Check if request method is POST if ($this->methodInPostRequest == true && strcmp(strtoupper($this->input->server->getMethod()), 'POST') === 0) { // Get the method from input $postMethod = $this->input->get->getWord('_method'); // Validate that we have a map to handle the given HTTP method from input if ($postMethod && isset($this->suffixMap[strtoupper($postMethod)])) { return ucfirst($this->suffixMap[strtoupper($postMethod)]); } } return ucfirst($this->suffixMap[$this->input->getMethod()]); }
Get the controller class suffix string. @return string @since 1.0 @throws \RuntimeException @deprecated 2.0 Use the base Router class instead
entailment
protected function parseRoute($route) { $name = parent::parseRoute($route); // Append the HTTP method based suffix. $name .= $this->fetchControllerSuffix(); return $name; }
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 @deprecated 2.0 Use the base Router class instead
entailment
public static function get($className, $parentClassName = '') { $className = self::cleanName($className); // We store the relationship between class & parent to prevent cyclical references if ($parentClassName) { self::$relations[$className][$parentClassName] = true; } // And we check for cyclical references to prevent infinite loops if ($parentClassName && isset(self::$relations[$parentClassName]) && isset(self::$relations[$parentClassName][$className]) ) { $message = "Cyclical dependency found: {$className} depends on {$parentClassName}"; $message .= " but is itself a dependency of {$parentClassName}."; throw new \Parable\DI\Exception($message); } if (!self::isStored($className)) { self::store(self::create($className, $parentClassName)); } return self::$instances[$className]; }
Return an already instantiated instance or create a new one. @param string $className @param string $parentClassName @return mixed @throws \Parable\DI\Exception
entailment
protected static function createInstance($className, $parentClassName = '', $createAll = false) { $className = self::cleanName($className); try { $dependencies = self::getDependenciesFor($className, $createAll); } catch (\Parable\DI\Exception $e) { $message = $e->getMessage(); if ($parentClassName) { $message .= ", required by '{$parentClassName}'"; } throw new \Parable\DI\Exception($message); } return new $className(...$dependencies); }
Instantiate a class and fulfill its dependency requirements. @param string $className @param string $parentClassName @param bool $createAll @return mixed @throws \Parable\DI\Exception
entailment
public static function getDependenciesFor($className, $createAll = false) { try { $reflection = new \ReflectionClass($className); } catch (\Exception $e) { $message = "Could not create instance of '{$className}'"; throw new \Parable\DI\Exception($message); } $construct = $reflection->getConstructor(); if (!$construct) { return []; } $parameters = $construct->getParameters(); $dependencies = []; foreach ($parameters as $parameter) { $subClassName = $parameter->name; try { $class = $parameter->getClass(); if (is_object($class)) { $subClassName = $class->name; } } catch (\ReflectionException $e) { } if ($createAll) { $dependencies[] = self::createAll($subClassName, $className); } else { $dependencies[] = self::get($subClassName, $className); } } return $dependencies; }
Retrieve and instantiate all dependencies for the provided $className @param string $className @param bool $createAll @return array @throws \Parable\DI\Exception
entailment
public static function store($instance, $name = null) { if (!$name) { $name = get_class($instance); } $name = self::cleanName($name); self::$instances[$name] = $instance; }
Store an instance under either the provided $name or its class name. @param object $instance @param string|null $name
entailment
public static function clearExcept(array $keepInstanceNames) { foreach (self::$instances as $name => $instance) { if (!in_array($name, $keepInstanceNames)) { self::clear($name); } } }
Remove all stored instances but KEEP the passed instance names. @param string[] $keepInstanceNames
entailment
public function discardUpperMigrations(Bundle $bundle) { $drivers = array_keys($this->getAvailablePlatforms()); $currentVersion = $this->migrator->getCurrentVersion($bundle); $this->log("Deleting migration classes above version {$currentVersion} for '{$bundle->getName()}'..."); $hasDeleted = false; foreach ($drivers as $driver) { $deletedVersions = $this->writer->deleteUpperMigrationClasses($bundle, $driver, $currentVersion); if (count($deletedVersions) > 0) { $hasDeleted = true; foreach ($deletedVersions as $version) { $this->log(" - Deleted {$version} for driver {$driver}"); } } } if (!$hasDeleted) { $this->log('Nothing to discard: there are no migrations classes above the current version'); } }
Deletes migration classes which are above the current version of a bundle. @param \Symfony\Component\HttpKernel\Bundle\Bundle $bundle
entailment
public function getAvailablePlatforms() { $platforms = array(); foreach ($this->getSupportedDrivers() as $driverName => $driverClass) { $driver = new $driverClass; $platforms[$driverName] = $driver->getDatabasePlatform(); } return $platforms; }
Returns the list of available driver platforms. Note: this method is public for testing purposes only @return array[AbstractPlatform]
entailment
public static function getDateRange4Period(DateTime $beginDate, DateTime $endDate) { $result = []; if ($beginDate < $endDate) { do { $result[] = clone $beginDate; $beginDate->modify('+1 day'); } while ($beginDate <= $endDate); } return $result; }
@param DateTime $beginDate @param DateTime $endDate @return DateTime[]
entailment
public function load($templatePath) { $production = !defined('WP_DEBUG') || !WP_DEBUG; ob_start(); if (!$production) { /** @noinspection PhpIncludeInspection */ require $templatePath; } elseif (file_exists($templatePath)) { /** @noinspection PhpIncludeInspection */ require $templatePath; } $content = trim(ob_get_clean()); return $content; }
{@inheritdoc}
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]); $template = $this->postTemplates->findFor($post); $pagename = $query->get('pagename'); (!$pagename && $post->ID) and $pagename = $post->post_name; $leaves = $template ? [$template] : []; $baseLeaves = $post->ID ? ["page-{$post->ID}", 'page'] : ['page']; if (!$pagename) { return array_merge($leaves, $baseLeaves); } $pagenameDecoded = urldecode($pagename); if ($pagenameDecoded !== $pagename) { $leaves[] = "page-{$pagenameDecoded}"; } $leaves[] = "page-{$pagename}"; return array_merge($leaves, $baseLeaves); }
{@inheritdoc}
entailment
public static function parseExtensions($extensions, $trimPattern = ". \t\n\r\0\x0B") { $parsed = []; $extensions = is_string($extensions) ? explode('|', $extensions) : (array) $extensions; foreach ($extensions as $extension) { if (is_string($extension)) { $extension = strtolower(trim($extension, $trimPattern)); in_array($extension, $parsed, true) or $parsed[] = $extension; } } return $parsed; }
@param string|string[] $extensions @param string $trimPattern @return \string[]
entailment
public function getHeader($key) { foreach ($this->headers as $header => $content) { if (strtolower($key) === strtolower($header)) { return $content; } } return null; }
Return header by key if it exists. @param string $key @return null|string
entailment
public function getScheme() { if (isset($_SERVER['REQUEST_SCHEME'])) { // Apache 2.4+ return $_SERVER['REQUEST_SCHEME']; } if (isset($_SERVER['REDIRECT_REQUEST_SCHEME'])) { return $_SERVER['REDIRECT_REQUEST_SCHEME']; } if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { // Sometimes available in proxy-forwarded requests return $_SERVER['HTTP_X_FORWARDED_PROTO']; } if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { // Old-style but compatible with IIS return 'https'; } if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) { // This doesn't say much, but this is our last attempt, so why not try return 'https'; } return 'http'; }
Return the current scheme. This is surprisingly annoying due to unreliable availability of $_SERVER values. @return string
entailment
public function getHttpHost() { if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['SERVER_NAME']) && $_SERVER['HTTP_HOST'] === $_SERVER['SERVER_NAME'] ) { return $_SERVER['HTTP_HOST']; } if (isset($_SERVER['HTTP_HOST'])) { return $_SERVER['HTTP_HOST']; } // This is the least reliable, due to the ability to spoof it if (isset($_SERVER['SERVER_NAME'])) { return $_SERVER['SERVER_NAME']; } return null; }
Return the http host, if possible. @return null|string
entailment
public function getAll() { if (!$this->getResource()) { return []; } if ($this->useLocalResource) { return $this->localResource; } // If we're attempting to use a global resource but it doesn't exist, we've got a problem. if (!isset($GLOBALS[$this->getResource()])) { throw new \Parable\GetSet\Exception( "Attempting to use global resource '{$this->getResource()}' but resource not available." ); } return $GLOBALS[$this->getResource()]; }
Return all from resource if resource is set. @return array @throws \Parable\GetSet\Exception
entailment
public function get($key, $default = null) { $resource = $this->getAll(); $keys = explode('.', $key); foreach ($keys as $key) { if (!isset($resource[$key])) { $resource = $default; break; } $resource = &$resource[$key]; } return $resource; }
Return specific value by key if resource set. If not found, return default. $getSet->get("one.two.three", "value") would return $resource["one"]["two"]["three"] or "value"; @param string $key @param mixed|null $default @return mixed|null
entailment
public function getAndRemove($key) { $data = $this->get($key); if ($data) { $this->remove($key); } return $data; }
Return specific value by key and then clear it. @param string $key @return mixed|null
entailment