sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function notify(Throwable $throwable, FoundationRequest $request = null) : array { if (! $this->shouldReport($throwable)) { return []; } $notification = (new ExceptionNotification($this->config, $this->context)) ->make($throwable, $request); return $this->client->notification($notification); }
{@inheritdoc}
entailment
public function customNotification(array $payload) : array { if (empty($this->config['api_key'])) { return []; } $notification = (new CustomNotification($this->config, $this->context)) ->make($payload); return $this->client->notification($notification); }
{@inheritdoc}
entailment
public function rawNotification(callable $callable) : array { if (empty($this->config['api_key'])) { return []; } $notification = (new RawNotification($this->config, $this->context)) ->make($callable($this->config, $this->context)); return $this->client->notification($notification); }
{@inheritdoc}
entailment
protected function setConfig(Composer $composer) { return new SharedPackageInstallerConfig( $composer->getConfig()->get('vendor-dir'), $composer->getConfig()->get('vendor-dir', 1), $composer->getPackage()->getExtra() ); }
@param Composer $composer @return SharedPackageInstallerConfig
entailment
public function scopePimp(Builder $builder, $query = [], $sort = [], $relations = []) { $query = $query ?: array_except(Input::all(), [$this->sortParameterName, $this->withParameterName]); $builder->filtered($query)->sorted($sort)->withRelations($relations); }
Enable searchable, sortable and withable scopes @param Builder $builder query builder @param array $query
entailment
public function handle($code, $error, $file = null, $line = null) : void { $this->honeybadger->notify( new ErrorException($error, $code, 0, $file, $line) ); call_user_func($this->previousHandler, $code, $error, $file, $line); }
@param int $code @param string $error @param string $file @param int $line @return void @throws \Honeyhadger\Exceptions\ServiceException
entailment
public function addPackageUsage(PackageInterface $package) { $usageData = $this->getPackageUsage($package); $packageName = $this->composer->getPackage()->getName(); if (!in_array($packageName, $usageData)) { $usageData[] = $packageName; } $this->updatePackageUsageFile($package, $usageData); }
Add a row in the "packages.json" file, with the project name for the "package/version" key @param PackageInterface $package
entailment
public function removePackageUsage(PackageInterface $package) { $usageData = $this->getPackageUsage($package); $newUsageData = array(); $projectName = $this->composer->getPackage()->getName(); foreach ($usageData as $usage) { if ($projectName !== $usage) { $newUsageData[] = $usage; } } $this->updatePackageUsageFile($package, $newUsageData); }
Remove the row in the "packages.json" file @param PackageInterface $package
entailment
protected function initializePackageData() { $filePath = $this->vendorDir . DIRECTORY_SEPARATOR . self::PACKAGE_DATA_FILENAME; if (!is_file($filePath)) { $this->packagesData = array(); } else { $this->packagesData = json_decode(file_get_contents($filePath), true); } }
Initialize the package data array if not set
entailment
protected function getPackageDataKey(PackageInterface $package, $key, $defaultValue = null) { if (!isset($this->packagesData)) { $this->initializePackageData(); } $packageKey = $package->getPrettyName() . '/' . $package->getPrettyVersion(); if (!isset($this->packagesData[$packageKey]) || !isset($this->packagesData[$packageKey][$key])) { return $defaultValue; } return $this->packagesData[$packageKey][$key]; }
@param PackageInterface $package @param string $key @param mixed $defaultValue @return mixed
entailment
protected function setVendorDir($baseDir, array $extraConfigs) { $this->vendorDir = $extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['vendor-dir']; if (false !== getenv(static::ENV_PARAMETER_VENDOR_DIR)) { $this->vendorDir = getenv(static::ENV_PARAMETER_VENDOR_DIR); } if ('/' != $this->vendorDir[0]) { $this->vendorDir = $baseDir . $this->vendorDir; } }
@param string $baseDir @param array $extraConfigs @throws \InvalidArgumentException
entailment
protected function setSymlinkBasePath(array $extraConfigs) { if (isset($extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['symlink-base-path'])) { $this->symlinkBasePath = $extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['symlink-base-path']; if (false !== getenv(static::ENV_PARAMETER_SYMLINK_BASE_PATH)) { $this->symlinkBasePath = getenv(static::ENV_PARAMETER_SYMLINK_BASE_PATH); } // Remove the ending slash if exists if ('/' === $this->symlinkBasePath[strlen($this->symlinkBasePath) - 1]) { $this->symlinkBasePath = substr($this->symlinkBasePath, 0, -1); } } elseif (0 < strpos($extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['vendor-dir'], '/')) { $this->symlinkBasePath = $extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['vendor-dir']; } // Up to the project root directory if (0 < strpos($this->symlinkBasePath, '/')) { $this->symlinkBasePath = '../../' . $this->symlinkBasePath; } }
Allow to override symlinks base path. This is useful for a Virtual Machine environment, where directories can be different on the host machine and the guest machine. @param array $extraConfigs
entailment
protected function setIsSymlinkEnabled(array $extraConfigs) { if (isset($extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['symlink-enabled'])) { if (!is_bool($extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['symlink-enabled'])) { throw new \UnexpectedValueException('The configuration "symlink-enabled" should be a boolean'); } $this->isSymlinkEnabled = $extraConfigs[SharedPackageInstaller::PACKAGE_TYPE]['symlink-enabled']; } }
The symlink directory creation process can be disabled. This may mean that you work directly with the sources directory so the symlink directory is useless. @param array $extraConfigs
entailment
public function getOriginalVendorDir($endingSlash = false) { if ($endingSlash && null != $this->originalVendorDir) { return $this->originalVendorDir . '/'; } return $this->originalVendorDir; }
@param bool $endingSlash @return string
entailment
public function run($filename) { $this->result = null; $this->error = null; try { if (strpos($filename, 'http://') !== false || strpos($filename, 'https://') !== false) { $current = file_get_contents($filename); if ($current) { $path = \Yii::getAlias($this->pathTmp) . '/' . \Yii::$app->security->generateRandomString(); if (file_put_contents($path, $current)) { $filename = $path; } else { throw new Exception("Нет доступа для записи файла"); } } else { throw new Exception("Файл {$filename} не загрузился"); } } elseif (!file_exists($filename)) { throw new Exception("Файл {$filename} не найден"); } $postData = [ 'method' => 'post', 'key' => $this->apiKey, 'file' => (version_compare(PHP_VERSION, '5.5.0') >= 0) ? new \CURLFile($filename) : '@' . $filename, 'phrase' => $this->isPhrase, 'regsense' => $this->isRegSense, 'numeric' => $this->isNumeric, 'min_len' => $this->minLen, 'max_len' => $this->maxLen, 'language' => $this->language, 'soft_id' => 882, ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://{$this->domain}/in.php"); if (version_compare(PHP_VERSION, '5.5.0') >= 0 && version_compare(PHP_VERSION, '7.0') < 0) { curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); $result = curl_exec($ch); if (curl_errno($ch)) { throw new Exception("CURL вернул ошибку: " . curl_error($ch)); } curl_close($ch); $this->setError($result); list(, $this->captcha_id) = explode("|", $result); $waitTime = 0; sleep($this->requestTimeout); while (true) { $result = file_get_contents("http://{$this->domain}/res.php?key={$this->apiKey}&action=get&id={$this->captcha_id}"); $this->setError($result); if ($result == "CAPCHA_NOT_READY") { $waitTime += $this->requestTimeout; if ($waitTime > $this->maxTimeout) { break; } sleep($this->requestTimeout); } else { $ex = explode('|', $result); if (trim($ex[0]) == 'OK') { $this->result = trim($ex[1]); return true; } } } throw new Exception('Лимит времени превышен'); } catch (Exception $e) { $this->error = $e->getMessage(); return false; } }
Запуск распознавания капчи @param string $filename Путь до файла или ссылка на него @return bool
entailment
private function setError($error) { if (strpos($error, 'ERROR') !== false) { if (array_key_exists($error, $this->errors)) { throw new Exception($this->errors[$error]); } else { throw new Exception($error); } } }
Проверка на то произошла ли ошибка @param $error @throws Exception
entailment
protected function write(array $record) { $this->honeybadger->rawNotification(function ($config) use ($record) { return [ 'notifier' => array_merge($config['notifier'], ['name' => 'Honeybadger Log Handler']), 'error' => [ 'class' => $record['message'], 'message' => $record['formatted'], 'tags' => [ 'log', sprintf('%s.%s', $record['channel'], $record['level_name']), ], 'fingerprint' => md5($record['formatted']), ], 'request' => [ 'context' => [ 'context' => $record['context'], 'level_name' => $record['level_name'], 'log_channel' => $record['channel'], 'message' => $record['message'], ], ], ]; }); }
{@inheritdoc}
entailment
protected function getMethodTemplate($template_name, array $order, array $method) { if (empty($method['status']) || empty($method['template'][$template_name])) { return ''; } $settings = array(); $template = $method['template'][$template_name]; if (!empty($method['module'])) { $template = "{$method['module']}|$template"; $settings = $this->getModuleSettings($method['module']); } $data = array( 'order' => $order, 'method' => $method, 'settings' => $settings ); return $this->render($template, $data); }
Returns a rendered template for the shipping/payment method @param string $template_name @param array $order @param array $method @return string
entailment
public function getShippingMethodTemplate($template, array $order, $shipping_model) { if (empty($order['shipping'])) { return ''; } $method = $shipping_model->get($order['shipping']); return $this->getMethodTemplate($template, $order, $method); }
Returns a template for a shipping method @param string $template @param array $order @param \gplcart\core\models\Shipping $shipping_model @return string
entailment
public function getPaymentMethodTemplate($template, array $order, $payment_model) { if (empty($order['payment'])) { return ''; } $method = $payment_model->get($order['payment']); return $this->getMethodTemplate($template, $order, $method); }
Returns a template for a payment method @param string $template @param array $order @param \gplcart\core\models\Payment $payment_model @return string
entailment
public function boot() { if (true === $this->booted) { return $this; } if($this->isDebug()) { ExceptionHandler::register(true, 'UTF-8', 'PPI Framework', self::VERSION, true); } $this->serviceManager = $this->buildServiceManager(); $this->log('debug', sprintf('Booting %s ...', $this->name)); // Loading our Modules $this->getModuleManager()->loadModules(); if ($this->debug) { $modules = $this->getModuleManager()->getModules(); $this->log('debug', sprintf('All modules online (%d): "%s"', count($modules), implode('", "', $modules))); } // Lets get all the services our of our modules and start setting them in the ServiceManager $moduleServices = $this->serviceManager->get('ModuleDefaultListener')->getServices(); foreach ($moduleServices as $key => $service) { $this->serviceManager->setFactory($key, $service); } $this->booted = true; if ($this->debug) { $this->log('debug', sprintf('%s has booted (in %.3f secs)', $this->name, microtime(true) - $this->startTime)); } return $this; }
Run the boot process, load our modules and their dependencies. This method is automatically called by dispatch(), but you can use it to build all services when not handling a request. @return $this
entailment
public function run(HttpRequest $request = null, HttpResponse $response = null) { if (false === $this->booted) { $this->boot(); } if (null === $request) { $request = HttpRequest::createFromGlobals(); } if (null === $response) { $response = new HttpResponse(); } // Create a copy of request, as it's by-ref passed into $this->dispatch() and gets modified. $cleanRequest = clone $request; try { $response = $this->dispatch($request, $response); } catch (ResourceNotFoundException $e) { if($this->symfonyKernel === null) { throw $e; } $response = $this->symfonyKernel->handle($cleanRequest); } $response->send(); return $response; }
Run the application and send the response. @param HttpRequest|null $request @param HttpResponse|null $response @throws \Exception @return HttpResponse
entailment
public function dispatch(HttpRequest $request, HttpResponse $response) { if (false === $this->booted) { $this->boot(); } // cache like a mother fucker // if(!$this->hasRouteInCache($request)) { $routeParams = $this->handleRouting($request); // $this->setRouteInCache($request, $routeParams); // @todo - move these 2 lines to setRouteInCache() // $routingCache = $this->serviceManager->get('RoutingCache'); // $routingCache->set($request->getPathInfo(), $routeParams); // } else { // $routeParams = $this->getRouteFromCache($request); // } $request->attributes->add($routeParams); // Resolve our Controller $resolver = $this->serviceManager->get('ControllerResolver'); if (false === $controller = $resolver->getController($request)) { throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s".', $request->getPathInfo())); } $controllerArguments = $resolver->getArguments($request, $controller); $result = call_user_func_array( $controller, $controllerArguments ); if ($result === null) { throw new \Exception('Your action returned null. It must always return something'); } elseif (is_string($result)) { $response->setContent($result); } elseif ($result instanceof SymfonyResponse || $response instanceof HttpResponse) { $response = $result; } else { throw new \Exception('Invalid response type returned from controller'); } return $response; }
Decide on a route to use and dispatch our module's controller action. @param HttpRequest $request @param HttpResponse $response @throws \Exception @return HttpResponse
entailment
public function getName() { if (null === $this->name) { $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir)); } return $this->name; }
Gets the name of the application. @return string The application name @api
entailment
public function getRootDir() { if (null === $this->rootDir) { $this->rootDir = realpath(getcwd() . '/app'); } return $this->rootDir; }
Gets the application root dir. @return string The application root dir @api
entailment
public function getModuleManager() { if (null === $this->moduleManager) { $this->moduleManager = $this->serviceManager->get('ModuleManager'); } return $this->moduleManager; }
Returns the Module Manager. @return \Zend\ModuleManager\ModuleManager
entailment
public function locateResource($name, $dir = null, $first = true) { return $this->getModuleManager()->locateResource($name, $dir, $first); }
@see PPI\Framework\Module\ModuleManager::locateResource() @param string $name A resource name to locate @param string $dir A directory where to look for the resource first @param bool $first Whether to return the first path or paths for all matching bundles @throws \InvalidArgumentException if the file cannot be found or the name is not valid @throws \RuntimeException if the name contains invalid/unsafe @throws \RuntimeException if a custom resource is hidden by a resource in a derived bundle @return string|array The absolute path of the resource or an array if $first is false
entailment
public function getConfigManager() { if (null === $this->configManager) { $cachePath = $this->getCacheDir() . '/application-config-cache.' . $this->getName() . '.php'; $this->configManager = new ConfigManager($cachePath, !$this->debug, $this->rootDir . '/config'); } return $this->configManager; }
Returns a ConfigManager instance. @return \PPI\Framework\Config\ConfigManager
entailment
public function loadConfig($resource, $type = null) { $this->getConfigManager()->addConfig($resource, $type); return $this; }
Loads a configuration file or PHP array. @param $resource @param null $type @return App The current instance
entailment
protected function getAppParameters() { return array_merge( array( 'app.root_dir' => $this->rootDir, 'app.environment' => $this->environment, 'app.debug' => $this->debug, 'app.name' => $this->name, 'app.cache_dir' => $this->getCacheDir(), 'app.logs_dir' => $this->getLogDir(), 'app.charset' => $this->getCharset(), ), $this->getEnvParameters() ); }
Returns the application parameters. @return array An array of application parameters
entailment
protected function getEnvParameters() { $parameters = array(); foreach ($_SERVER as $key => $value) { if (0 === strpos($key, 'PPI__')) { $parameters[strtolower(str_replace('__', '.', substr($key, 5)))] = $value; } } return $parameters; }
Gets the environment parameters. Only the parameters starting with "PPI__" are considered. @return array An array of parameters
entailment
protected function buildServiceManager() { // ServiceManager creation $serviceManager = new ServiceManagerBuilder($this->getConfigManager()->getMergedConfig()); $serviceManager->build($this->getAppParameters()); $serviceManager->set('app', $this); return $serviceManager; }
Creates and initializes a ServiceManager instance. @return ServiceManager The compiled service manager
entailment
protected function handleRouting(HttpRequest $request) { $this->router = $this->serviceManager->get('Router'); $this->router->warmUp($this->getCacheDir()); try { // Lets load up our router and match the appropriate route $parameters = $this->router->matchRequest($request); if (!empty($parameters)) { if (null !== $this->logger) { $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->router->parametersToString($parameters))); } } } catch (ResourceNotFoundException $e) { $routeUri = $this->router->generate('Framework_404'); $parameters = $this->router->matchRequest($request::create($routeUri)); } catch (\Exception $e) { throw $e; } $parameters['_route_params'] = $parameters; return $parameters; }
Perform the matching of a route and return a set of routing parameters if a valid one is found. Otherwise exceptions get thrown. @param HttpRequest $request @throws \Exception @return array
entailment
protected function log($level, $message, array $context = array()) { if (null === $this->logger && $this->getServiceManager()->has('logger')) { $this->logger = $this->getServiceManager()->get('logger'); } if ($this->logger) { $this->logger->log($level, $message, $context); } }
Logs with an arbitrary level. @param mixed $level @param string $message @param array $context
entailment
public function language(array &$submitted, array $options = array()) { $this->options = $options; $this->submitted = &$submitted; $this->validateLanguage(); $this->validateWeight(); $this->validateBool('status'); $this->validateBool('default'); $this->validateNameLanguage(); $this->validateNativeNameLanguage(); $this->validateCodeLanguage(); $this->unsetSubmitted('update'); return $this->getResult(); }
Performs full language data validation @param array $submitted @param array $options @return array|boolean
entailment
protected function validateLanguage() { $id = $this->getUpdatingId(); if ($id === false) { return null; } $data = $this->language->get($id); if (empty($data)) { $this->setErrorUnavailable('update', $this->translation->text('Language')); return false; } $this->setUpdating($data); return true; }
Validates a language to be updated @return boolean
entailment
protected function validateCodeLanguage() { $field = 'code'; if ($this->isExcluded($field)) { return null; } $value = $this->getSubmitted($field); if ($this->isUpdating() && !isset($value)) { $this->unsetSubmitted($field); return null; } $label = $this->translation->text('Code'); if (empty($value)) { $this->setErrorRequired($field, $label); return false; } if (preg_match('/^[A-Za-z\\-]+$/', $value) !== 1) { $this->setErrorInvalid($field, $label); return false; } $updating = $this->getUpdating(); if (isset($updating['code']) && $updating['code'] === $value) { return true; } $language = $this->language->get($value); if (!empty($language)) { $this->setErrorExists($field, $label); return false; } return true; }
Validates a language code @return boolean|null
entailment
protected function validateNameLanguage() { $field = 'name'; if ($this->isExcluded($field)) { return null; } $value = $this->getSubmitted($field); if (!isset($value)) { $this->unsetSubmitted($field); return true; // If not set, code will be used instead } if (mb_strlen($value) > 50) { $this->setErrorLengthRange($field, $this->translation->text('Name'), 0, 50); return false; } return true; }
Validates a language name @return boolean|null
entailment
protected function createController($controller) { if (false === strpos($controller, '::')) { $count = substr_count($controller, ':'); if (2 == $count) { // controller in the a:b:c notation then $controller = $this->parser->parse($controller); } elseif (1 == $count) { // controller in the service:method notation list($service, $method) = explode(':', $controller, 2); return array($this->serviceManager->get($service), $method); } else { if ($this->serviceManager->has($controller) && method_exists($service = $this->serviceManager->get($controller), '__invoke')) { return $service; } else { throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller)); } } } return parent::createController($controller); }
Returns a callable for the given controller. @param string $controller A Controller string @throws \LogicException When the name could not be parsed @throws \InvalidArgumentException When the controller class does not exist @return mixed A PHP callable
entailment
protected function instantiateController($class) { $controller = parent::instantiateController($class); if ($controller instanceof ServiceLocatorAwareInterface) { $controller->setServiceLocator($this->serviceManager); } if($controller instanceof ContainerAwareInterface) { $controller->setContainer($this->serviceManager->get('SymfonyContainer')); } return $controller; }
@param string $class @return object
entailment
public function generate($name, $parameters = array(), $absolute = false) { return $this->generator->generate($name, $parameters, $absolute); }
Generates a URL from the given parameters. @param string $name The name of the route @param mixed $parameters An array of parameters @param bool $absolute Whether to generate an absolute URL @return string The generated URL
entailment
public function getList(array $options = array()) { $result = &gplcart_static(gplcart_array_hash(array('wishlist.list' => $options))); if (isset($result)) { return $result; } $this->hook->attach('wishlist.list.before', $options, $result, $this); if (isset($result)) { return $result; } $sql = 'SELECT w.*, u.name AS user_name, u.email'; if (!empty($options['count'])) { $sql = 'SELECT COUNT(w.wishlist_id)'; } $sql .= ' FROM wishlist w LEFT JOIN user u ON(w.user_id = u.user_id) LEFT JOIN product p ON(w.product_id = p.product_id) WHERE w.wishlist_id IS NOT NULL'; $conditions = array(); if (!empty($options['product_id'])) { settype($options['product_id'], 'array'); $placeholders = rtrim(str_repeat('?,', count($options['product_id'])), ','); $sql .= " AND w.product_id IN($placeholders)"; $conditions = array_merge($conditions, $options['product_id']); } if (isset($options['user_id'])) { $sql .= ' AND w.user_id = ?'; $conditions[] = $options['user_id']; } if (isset($options['store_id'])) { $sql .= ' AND w.store_id = ?'; $conditions[] = $options['store_id']; } if (isset($options['created'])) { $sql .= ' AND w.created = ?'; $conditions[] = $options['created']; } if (isset($options['product_status'])) { $sql .= ' AND p.status = ?'; $conditions[] = (int) $options['product_status']; } $allowed_order = array('asc', 'desc'); $allowed_sort = array('product_id', 'user_id', 'created'); if (isset($options['sort']) && in_array($options['sort'], $allowed_sort) && isset($options['order']) && in_array($options['order'], $allowed_order)) { $sql .= " ORDER BY w.{$options['sort']} {$options['order']}"; } else { $sql .= " ORDER BY w.created DESC"; } if (!empty($options['limit'])) { $sql .= ' LIMIT ' . implode(',', array_map('intval', $options['limit'])); } if (empty($options['count'])) { $result = $this->db->fetchAll($sql, $conditions, array('index' => 'wishlist_id')); } else { $result = (int) $this->db->fetchColumn($sql, $conditions); } $this->hook->attach('wishlist.list.after', $options, $result, $this); return $result; }
Returns an array of wishlist items or counts them @param array $options @return array|integer
entailment
public function exists(array $data) { if (empty($data['product_id'])) { return false; } $product_id = $data['product_id']; unset($data['product_id']); $items = (array) $this->getList($data); foreach ($items as $item) { if ($item['product_id'] == $product_id) { return true; } } return false; }
Whether a product ID already exists in the wishlist @param array $data @return boolean
entailment
public function exceedsLimit($user_id, $store_id) { if ($this->user->isSuperadmin($user_id)) { return false; // No limits for superadmin } $limit = $this->getLimit($user_id); if (empty($limit)) { return false; } $conditions = array( 'user_id' => $user_id, 'store_id' => $store_id ); $existing = $this->getList($conditions); return count($existing) > $limit; }
Whether the user exceeds the max allowed number of products in the wishlist @param integer|string $user_id @param integer $store_id @return boolean
entailment
public function getLimit($user_id) { if (is_numeric($user_id)) { $user = $this->user->get($user_id); if (isset($user['role_id'])) { return $this->getLimitByRole($user['role_id']); } } return $this->getDefaultLimit(); }
Returns a max number of items for the user @param integer|string $user_id @return integer
entailment
public function responseAjax() { if (!$this->isAjax()) { $this->response->outputError403(); } $action = $this->getPosted('action'); if (empty($action)) { $this->outputJson(array('error' => $this->text('Unknown action'))); } $this->outputJson(call_user_func(array($this, $action))); }
Page callback Entry point for all AJAX requests
entailment
public function getProductsAjax() { if (!$this->access('product')) { return array('error' => $this->text('No access')); } $params = array( 'status' => $this->getPosted('status'), 'title_sku' => $this->getPosted('term'), 'store_id' => $this->getPosted('store_id'), 'limit' => array(0, $this->config('autocomplete_limit', 10)) ); $products = (array) $this->sku->getList($params); $product_ids = array(); foreach ($products as $product) { $product_ids[] = $product['product_id']; } $options = array( 'entity' => 'product', 'entity_id' => $product_ids, 'template_item' => 'backend|content/product/suggestion' ); foreach ($products as &$product) { $this->setItemThumb($product, $this->image, $options); $this->setItemPriceFormatted($product, $this->price); $this->setItemRendered($product, array('item' => $product), $options); } return $products; }
Returns an array of products @return array
entailment
public function getUsersAjax() { if (!$this->access('user')) { return array('error' => $this->text('No access')); } $options = array( 'email_like' => $this->getPosted('term'), 'store_id' => $this->getPosted('store_id'), 'limit' => array(0, $this->config('autocomplete_limit', 10))); return $this->user->getList($options); }
Returns an array of users @return array
entailment
public function getStoreCategoriesAjax() { if (!$this->access('category')) { return array('error' => $this->text('No access')); } $options = array( 'store_id' => $this->getPosted('store_id', $this->store->getDefault()) ); return $this->getCategoryOptionsByStore($this->category, $this->category_group, $options); }
Returns an array of store categories @return array
entailment
public function switchProductOptionsAjax() { $product_id = $this->getPosted('product_id'); $field_value_ids = $this->getPosted('values', array(), true, 'array'); if (empty($product_id)) { return array(); } $product = $this->product->get($product_id); $response = $this->sku->selectCombination($product, $field_value_ids); $response += $product; $this->setItemPriceCalculated($response, $this->product); $this->setItemPriceFormatted($response, $this->price, $this->current_currency); return $response; }
Toggles product options @return array
entailment
public function getCollectionItemAjax() { $term = $this->getPosted('term'); $collection_id = $this->getPosted('collection_id'); if (empty($term) || empty($collection_id)) { return array('error' => $this->text('An error occurred')); } $collection = $this->collection->get($collection_id); if (empty($collection)) { return array('error' => $this->text('An error occurred')); } if (!$this->access($collection['type'])) { return array('error' => $this->text('No access')); } $conditions = array( 'status' => 1, 'title' => $term, 'store_id' => $collection['store_id'], 'limit' => array(0, $this->config('autocomplete_limit', 10)) ); return $this->collection_item->getListEntities($collection['type'], $conditions); }
Returns an array of suggested collection entities @return array
entailment
public function searchCityAjax() { $country = $this->getPosted('country'); $state_id = $this->getPosted('state_id'); if (empty($country) || empty($state_id)) { return array(); } $conditions = array( 'status' => 1, 'state_status' => 1, 'country_status' => 1, 'country' => $country, 'state_id' => $state_id, ); return (array) $this->city->getList($conditions); }
Returns an array of cities for the given country and state ID @return array
entailment
final public function redirect($url = '', $options = array(), $full = false, $nolangcode = false) { if (!isset($url)) { return null; } if (!empty($url) && ($full || $this->isAbsolute($url))) { $url = filter_var($url, FILTER_SANITIZE_URL); } else { $target = $this->request->get('target', '', 'string'); if (!empty($target)) { $url = (string) parse_url($target, PHP_URL_PATH); $parsed = parse_url($target, PHP_URL_QUERY); $options = is_array($parsed) ? $parsed : array(); } $url = $this->get($url, $options, false, $nolangcode); } header("Location: $url"); exit; }
Redirects the user to a new location @param string|null $url @param array $options @param boolean $full @param boolean $nolangcode @return null
entailment
public function get($path = '', $options = array(), $absolute = false, $nolangcode = false) { $pass_absolute = false; if (!empty($path)) { if ($absolute && $this->isAbsolute($path)) { $url = $path; $pass_absolute = true; } else { $url = $this->request->base($nolangcode) . trim($path, '/'); } } else { $url = $this->server->requestUri(); } $url = strtok($url, '?'); if ($absolute && !$pass_absolute) { $url = $this->server->httpScheme() . $this->server->httpHost() . $url; } $url = empty($options) ? $url : "$url?" . http_build_query($options); return filter_var($url, FILTER_SANITIZE_URL); }
Returns an internal or external URL @param string $path @param array $options @param boolean $absolute @param boolean $nolangcode @return string|false
entailment
public function language($code, $path = '', $options = array()) { $segments = $this->getSegments(true, $path); $langcode = $this->request->getLangcode(); if (isset($segments[0]) && $segments[0] === $langcode) { unset($segments[0]); } array_unshift($segments, $code); $url = $this->request->base(true) . trim(implode('/', $segments), '/'); $url = empty($options) ? $url : "$url?" . http_build_query($options); return filter_var($url, FILTER_SANITIZE_URL); }
Returns a URL with appended language code @param string $code @param string $path @param array $options @return string|false
entailment
public function getSegments($append_langcode = false, $path = '') { if (empty($path)) { $path = $this->path($append_langcode); } return explode('/', trim($path, '/')); }
Returns an array of path components @param boolean $append_langcode @param string $path @return array
entailment
public function path($append_langcode = false) { $urn = $this->server->requestUri(); return substr(strtok($urn, '?'), strlen($this->request->base($append_langcode))); }
Returns an internal path without query @param boolean $append_langcode @return string
entailment
public function getAccountId() { $segments = $this->getSegments(); if (reset($segments) === 'account' && isset($segments[1]) && ctype_digit($segments[1])) { return (int) $segments[1]; } return false; }
Returns a user ID from the path @return boolean|integer
entailment
public function file($path, $absolute = false) { return $this->get('files/' . trim($path, '/'), array(), $absolute, true); }
Creates a file URL from a path @param string $path @param bool $absolute @return string
entailment
public function image($path) { if (gplcart_path_is_absolute($path)) { $file = $path; $url = gplcart_path_relative($path); } else { $path = gplcart_path_normalize($path); $prefix = gplcart_path_relative(GC_DIR_FILE); if (strpos($path, "$prefix/") === 0) { $url = $path; $file = gplcart_file_absolute($path); } else { $url = "$prefix/$path"; $file = gplcart_path_absolute($path); } } $query = is_file($file) ? array('v' => filemtime($file)) : array(); return $this->get($url, $query, false, true); }
Returns a string containing an image path @param string $path Either relative to the root/file directory or an absolute server path @return string
entailment
public function collectionItem(array &$submitted, array $options = array()) { $this->options = $options; $this->submitted = &$submitted; $this->validateCollectionItem(); $this->validateBool('status'); $this->validateWeight(); $this->validateUrlCollectionItem(); $this->validateCollectionCollectionItem(); $this->validateEntityIdCollectionItem(); $this->validateEntityCollectionItem(); $this->validateData(); $this->unsetSubmitted('update'); $this->unsetSubmitted('collection'); return $this->getResult(); }
Performs full collection item entity validation @param array $submitted @param array $options @return boolean|array
entailment
protected function validateCollectionItem() { $id = $this->getUpdatingId(); if ($id === false) { return null; } $data = $this->collection_item->get($id); if (empty($data)) { $this->setErrorUnavailable('update', $this->translation->text('Collection item')); return false; } $this->setSubmitted('update', $data); return true; }
Validates a collection item to be updated @return boolean|null
entailment
protected function validateUrlCollectionItem() { $url = $this->getSubmitted('data.url'); if (isset($url) && mb_strlen($url) > 255) { $this->setErrorLengthRange('data.url', $this->translation->text('URL'), 0, 255); return false; } return true; }
Validates collection item URL @return boolean
entailment
protected function validateCollectionCollectionItem() { $field = 'collection_id'; if ($this->isExcluded($field)) { return null; } $collection_id = $this->getSubmitted($field); if ($this->isUpdating() && !isset($collection_id)) { return null; } $label = $this->translation->text('Collection'); if (empty($collection_id)) { $this->setErrorRequired($field, $label); return false; } if (!is_numeric($collection_id)) { $this->setErrorNumeric($field, $label); return false; } $collection = $this->collection->get($collection_id); if (empty($collection)) { $this->setErrorUnavailable($field, $label); return false; } $this->setSubmitted('collection', $collection); return true; }
Validates the collection data @return boolean
entailment
protected function validateEntityIdCollectionItem() { $field = 'entity_id'; if ($this->isExcluded($field)) { return null; } $value = $this->getSubmitted($field); if ($this->isUpdating() && !isset($value)) { return null; } $title = $this->getSubmitted('title'); if (is_numeric($title)) { $value = $title; } $label = $this->translation->text('Entity'); if (empty($value) || !is_numeric($value)) { $this->setErrorInvalid($field, $label); return false; } $update = $this->getUpdating(); if (isset($update['collection_item_id']) && $update[$field] == $value) { return null; } $conditions = array( 'type' => $this->getSubmitted('collection.type'), 'collection_id' => $this->getSubmitted('collection.collection_id') ); $existing = $this->collection_item->getItems($conditions); if (isset($existing[$value])) { $this->setErrorExists($field, $label); return false; } $this->setSubmitted($field, $value); return true; }
Validates submitted collection item entity ID @return boolean|null
entailment
protected function validateEntityCollectionItem() { if ($this->isError()) { return null; } $collection = $this->getSubmitted('collection'); $collection_id = $this->getSubmitted('collection_id'); if (empty($collection)) { if (!isset($collection_id)) { $updating = $this->getUpdating(); if (isset($updating['collection_id'])) { $collection_id = $updating['collection_id']; } } $collection = $this->collection->get($collection_id); } if (empty($collection['type'])) { $this->setErrorUnavailable('collection_id', $this->translation->text('Collection')); return false; } try { $entity_id = $this->getSubmitted('entity_id'); $handlers = $this->collection->getHandlers(); $result = static::call($handlers, $collection['type'], 'validate', array($entity_id)); } catch (Exception $ex) { $result = $ex->getMessage(); } if ($result === true) { return true; } $this->setError('entity_id', implode('<br>', (array) $result)); return false; }
Validates collection item entities @return boolean|null
entailment
public function validatePageCollectionItem($page_id) { $page = $this->page->get($page_id); if (empty($page['status'])) { return $this->translation->text('@name is unavailable', array('@name' => $this->translation->text('Page'))); } return true; }
Validates page collection item. Hook callback @param integer $page_id @return boolean|string
entailment
public function validateProductCollectionItem($product_id) { $product = $this->product->get($product_id); if (empty($product['status'])) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('Product'))); } return true; }
Validates product collection item. Hook callback @param integer $product_id @return boolean|string
entailment
public function validateFileCollectionItem($file_id) { $file = $this->file->get($file_id); if (empty($file)) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('File'))); } return true; }
Validates file collection item. Hook callback @param integer $file_id @return boolean|string
entailment
public function load($path) { if (!is_readable($path)) { throw new \InvalidArgumentException('Invalid laravel routes path found: ' . $path); } // localising the object so the $path file can reference $router; $router = $this->router; // The included file must return the laravel router include $path; if (!($router instanceof LaravelRouter)) { throw new \Exception('Invalid return value from ' . pathinfo($path, PATHINFO_FILENAME) . ' expected instance of LaravelRouter' ); } return $router; }
@param string $path @throws \Exception @return LaravelRouter
entailment
public function summary() { $options = array('count' => true); return array( 'user_total' => $this->user->getList($options), 'order_total' => $this->order->getList($options), 'review_total' => $this->review->getList($options), 'product_total' => $this->product->getList($options) ); }
Returns an array of summary items @return array
entailment
public function order() { $options = array( 'order' => 'desc', 'sort' => 'created', 'limit' => array(0, $this->config->get('dashboard_limit', 10))); $items = $this->order->getList($options); array_walk($items, function (&$item) { $this->setItemTotalFormatted($item, $this->price); $this->setItemOrderNew($item, $this->order_history); }); return $items; }
Returns an array of recent orders @return array
entailment
public function transaction() { $options = array( 'order' => 'desc', 'sort' => 'created', 'limit' => array(0, $this->config->get('dashboard_limit', 10))); $items = $this->transaction->getList($options); array_walk($items, function (&$item) { $this->setItemTotalFormatted($item, $this->price); }); return $items; }
Returns an array of recent transactions @return array
entailment
public function priceRule() { $options = array( 'status' => 1, 'order' => 'desc', 'sort' => 'created', 'limit' => array(0, $this->config->get('dashboard_limit', 10))); $items = $this->pricerule->getList($options); array_walk($items, function (&$item) { $item['value_formatted'] = $this->price->format($item['value'], $item['currency']); }); return $items; }
Returns an array of active price rules @return array
entailment
public function event() { $options = array( 'limit' => array(0, $this->config->get('dashboard_limit', 10)) ); $events = (array) $this->report->getList($options); foreach ($events as &$event) { $variables = empty($event['data']['variables']) ? array() : (array) $event['data']['variables']; $message = empty($event['translatable']) ? $event['text'] : $this->translation->text($event['text'], $variables); $event['message'] = strip_tags($message); } return $events; }
Returns an array of recent events @return array
entailment
public function percent(&$amount, array &$components, array $price_rule) { $value = $amount * ($price_rule['value'] / 100); $components[$price_rule['price_rule_id']] = array('rule' => $price_rule, 'price' => $value); return $amount += $value; }
Adds a percent price rule value to the original amount @param int $amount @param array $components @param array $price_rule @return int
entailment
public function fixed(&$amount, array &$components, array $price_rule, array $data) { $value = $this->convertValue($price_rule, $data['currency']); $components[$price_rule['price_rule_id']] = array('rule' => $price_rule, 'price' => $value); return $amount += $value; }
Adds a fixed price rule value to the original amount @param int $amount @param array $components @param array $price_rule @param array $data @return int
entailment
public function finalAmount(&$amount, array &$components, array $price_rule, array $data) { $value = $this->convertValue($price_rule, $data['currency']); $components[$price_rule['price_rule_id']] = array('rule' => $price_rule, 'price' => $value); return $amount = $value; }
Sets a final amount using the price rule value @param int $amount @param array $components @param array $price_rule @param array $data @return int
entailment
protected function convertValue(array $price_rule, $currency) { $amount = $this->price->amount(abs($price_rule['value']), $price_rule['currency']); $converted = $this->currency->convert($amount, $price_rule['currency'], $currency); return $price_rule['value'] < 0 ? -$converted : $converted; }
Converts a price rule value to the minor units considering the currency @param array $price_rule @param string $currency @return int
entailment
public function get($library_id) { $libraries = $this->getList(); return empty($libraries[$library_id]) ? array() : $libraries[$library_id]; }
Returns an array of a library @param string $library_id @return array
entailment
public function getList() { $libraries = &gplcart_static('library.list'); if (isset($libraries)) { return (array) $libraries; } $libraries = (array) gplcart_config_get(GC_FILE_CONFIG_LIBRARY); $this->hook->attach('library.list', $libraries, $this); $libraries = (array) $this->prepareList($libraries); return $libraries; }
Returns an array of libraries @return array
entailment
protected function prepareList(array $libraries) { foreach ($libraries as $library_id => &$library) { $this->prepareListItem($libraries, $library_id, $library); } $this->validateDependencies($libraries); $prepared = $this->graph->build($libraries); gplcart_array_sort($prepared); return $prepared; }
Validate/filter an array of libraries @param array $libraries @return array
entailment
protected function prepareListItem(array &$libraries, $library_id, array &$library) { if (empty($library['type'])) { unset($libraries[$library_id]); return null; } $types = $this->getTypes(); if (empty($types[$library['type']])) { unset($libraries[$library_id]); return null; } $library['id'] = $library_id; if (!isset($library['basepath'])) { if (isset($library['vendor'])) { $library['vendor'] = strtolower($library['vendor']); $library['basepath'] = GC_DIR_VENDOR . "/{$library['vendor']}"; } else if (isset($types[$library['type']]['basepath'])) { $library['basepath'] = "{$types[$library['type']]['basepath']}/$library_id"; } else { unset($libraries[$library_id]); return null; } } if ($library['type'] === 'php' && empty($library['files']) && !empty($library['vendor'])) { $library['files'] = array(GC_FILE_AUTOLOAD); } if (!isset($library['version'])) { $library['errors'][] = array('Unknown version', array()); } if (!$this->validateFiles($library)) { $library['errors'][] = array('Missing files', array()); } return null; }
Prepare a library list item @param array $libraries @param string $library_id @param array $library @return null
entailment
protected function validateFiles(array &$library) { if (empty($library['files'])) { return true; // Assume files will be loaded dynamically } $readable = $count = 0; foreach ($library['files'] as &$file) { $count++; if (!gplcart_path_is_absolute($file)) { $file = $library['basepath'] . "/$file"; } $readable += (int) (is_file($file) && is_readable($file)); } return $count == $readable; }
Validates library files @param array $library @return bool
entailment
public function getFiles($ids) { settype($ids, 'array'); $libraries = $this->getList(); $sorted = $this->graph->sort($ids, $libraries); if (empty($sorted)) { return array(); } return $this->prepareFiles($sorted, $libraries); }
Returns an array of sorted files for the given library IDs according to their dependencies @param string|array $ids @return array
entailment
public function load($ids) { settype($ids, 'array'); $types = $this->getTypes(); $libraries = $this->getList(); foreach ($ids as $key => $id) { if ($this->isLoaded($id)) { unset($ids[$key]); continue; } if (empty($libraries[$id]['type'])) { unset($ids[$key]); continue; } if (empty($types[$libraries[$id]['type']]['load'])) { unset($ids[$key]); } } $sorted = $this->graph->sort($ids, $libraries); if (empty($sorted)) { return false; } foreach ($this->prepareFiles($sorted, $libraries) as $file) { require_once $file; } $this->loaded = array_merge($this->loaded, $sorted); return true; }
Includes libraries files @param array|string $ids @return boolean
entailment
protected function prepareFiles(array $ids, array $libraries) { $prepared = array(); foreach ($ids as $id) { if (!empty($libraries[$id]['files'])) { $prepared = array_merge($prepared, $libraries[$id]['files']); } } return $prepared; }
Prepares files of the given libraries @param array $ids @param array $libraries @return array
entailment
public static function deserializeObject(array $data) { /** @var ServiceProviderConfig $result */ $result = self::deserializeCommonAttributes($data); if (isset($data['documentationUri'])) { $result->documentationUri = $data['documentationUri']; } $result->patch = SPC\Patch::deserializeObject($data['patch']); $result->bulk = SPC\Bulk::deserializeObject($data['bulk']); $result->filter = SPC\Filter::deserializeObject($data['filter']); $result->eTag = SPC\ETag::deserializeObject($data['etag']); $result->changePassword = SPC\ChangePassword::deserializeObject($data['changePassword']); $result->sort = SPC\Sort::deserializeObject($data['sort']); if (isset($data['authenticationSchemes'])) { foreach ($data['authenticationSchemes'] as $authenticationScheme) { $result->authenticationSchemes[] = SPC\AuthenticationScheme::deserializeObject($authenticationScheme); } } return $result; }
@param array $data @return ServiceProviderConfig
entailment
public function warm(OutputInterface $output, $limit = 50, $sharedCache = false) { // Find appropriate users. $userRepo = $this->userModel->getRepository(); $userPrefix = $userRepo->getTableAlias(); if (!empty($userPrefix)) { $userPrefix .= '.'; } $users = $this->userModel->getEntities( [ 'limit' => $limit, 'filter' => [ 'force' => [ [ 'column' => $userPrefix.'lastLogin', 'expr' => 'isNotNull', ], ], ], 'orderBy' => $userPrefix.'lastLogin', 'orderByDir' => 'DESC', 'ignore_paginator' => true, ] ); if (!$users) { $output->writeln('<error>No users found to warm the dashboard for.</error>'); return; } // Find appropriate widgets for those users. $widgetFilter = $this->dashboardModel->getDefaultFilter(); $widgetRepo = $this->dashboardModel->getRepository(); $widgetPrefix = $widgetRepo->getTableAlias(); if (!empty($widgetPrefix)) { $widgetPrefix .= '.'; } $i = 0; foreach ($users as $user) { $widgets = $this->dashboardModel->getEntities( [ 'limit' => ($limit - $i), 'filter' => [ 'force' => [ [ 'column' => $widgetPrefix.'isPublished', 'expr' => 'eq', 'value' => 1, ], [ 'column' => $widgetPrefix.'type', 'expr' => 'notIn', 'value' => $this->excludedWidgetTypes, ], [ 'column' => $widgetPrefix.'createdBy', 'expr' => 'eq', 'value' => $user->getId(), ], ], ], 'orderBy' => $widgetPrefix.'ordering', 'orderByDir' => 'ASC', 'ignore_paginator' => true, ] ); if (!$widgets) { $output->writeln('No widgets found for '.$user->getFirstName().' '.$user->getLastName()); continue; } // Generate widget content (including cache). $widgetTypes = []; foreach ($widgets as $id => $widget) { $key = $widget->getType().'_'.md5(json_encode($widget->getParams())); // Do not process the same widget and params twice. if ($sharedCache && isset($this->widgetsBuilt[$key])) { unset($widgets[$id]); continue; } $widgetTypes[] = $widget->getType(); $this->widgetsBuilt[$key] = $widget->getType(); } if (!$widgetTypes) { $output->writeln('No uncached widgets to warm for '.$user->getFirstName().' '.$user->getLastName()); continue; } $output->writeln( '<info>'. 'Warming dashboard widget cache for '.$user->getFirstName().' '.$user->getLastName(). ' Including: '.implode(', ', $widgetTypes). '</info>' ); $i += count($widgets); try { if ($sharedCache) { $user->getRole()->setIsAdmin(1); } $this->userHelper->setUser($user); $this->dashboardModel->setUserHelper($this->userHelper); $this->dashboardModel->populateWidgetsContent($widgets, $widgetFilter); } catch (\Exception $e) { $output->writeln( '<error>'. 'Unable to warm dashboard widget cache for '.$user->getFirstName().' '.$user->getLastName(). ' Including: '.implode(', ', $widgetTypes).' Error: '.$e->getMessage(). '</error>' ); $this->logger->error( 'Unable to warm dashboard widget cache for '.$user->getFirstName().' '.$user->getLastName(). ' Including: '.implode(', ', $widgetTypes).' Error: '.$e->getMessage() ); } // Do not process more widgets than the batch limit. if ($i >= $limit) { $output->writeln('Batch limit hit, stopping dashboard warm run.'); break; } } }
Warm the caches of dashboard widgets. @param OutputInterface $output @param int $limit @param bool $sharedCache
entailment
public function listCountryState($code) { $this->setCountry($code); $this->actionListCountryState(); $this->setTitleListCountryState(); $this->setBreadcrumbListCountryState(); $this->setFilterListCountryState(); $this->setPagerListCountryState(); $this->setData('country', $this->data_country); $this->setData('states', $this->getListCountryState()); $this->outputListCountryState(); }
Displays the country state overview page @param string $code
entailment
protected function setCountry($code) { $this->data_country = $this->country->get($code); if (empty($this->data_country)) { $this->outputHttpStatus(404); } }
Sets a country data @param string $code
entailment
protected function setCountryState($state_id) { $this->data_state = array(); if (is_numeric($state_id)) { $this->data_state = $this->state->get($state_id); if (empty($this->data_state)) { $this->outputHttpStatus(404); } } }
Sets a country state data @param integer $state_id
entailment
protected function actionListCountryState() { list($selected, $action, $value) = $this->getPostedAction(); $deleted = $updated = 0; foreach ($selected as $id) { if ($action === 'status' && $this->access('state_edit')) { $updated += (int) $this->state->update($id, array('status' => $value)); } if ($action === 'delete' && $this->access('state_delete')) { $deleted += (int) $this->state->delete($id); } } if ($updated > 0) { $text = $this->text('Updated %num item(s)', array('%num' => $updated)); $this->setMessage($text, 'success'); } if ($deleted > 0) { $text = $this->text('Deleted %num item(s)', array('%num' => $deleted)); $this->setMessage($text, 'success'); } }
Applies an action to the selected country states
entailment
protected function setPagerListCountryState() { $conditions = $this->query_filter; $conditions['count'] = true; $conditions['country'] = $this->data_country['code']; $pager = array( 'query' => $this->query_filter, 'total' => (int) $this->state->getList($conditions) ); return $this->data_limit = $this->setPager($pager); }
Set pager @return array
entailment
protected function getListCountryState() { $conditions = $this->query_filter; $conditions['limit'] = $this->data_limit; $conditions['country'] = $this->data_country['code']; return (array) $this->state->getList($conditions); }
Returns an array of country states for the country and filter conditions @return array
entailment
protected function setBreadcrumbListCountryState() { $breadcrumbs = array(); $breadcrumbs[] = array( 'url' => $this->url('admin'), 'text' => $this->text('Dashboard') ); $breadcrumbs[] = array( 'url' => $this->url('admin/settings/country'), 'text' => $this->text('Countries') ); $this->setBreadcrumbs($breadcrumbs); }
Sets breadcrumbs on the country state overview page
entailment
public function editCountryState($country_code, $state_id = null) { $this->setCountryState($state_id); $this->setCountry($country_code); $this->setTitleEditCountryState(); $this->setBreadcrumbEditCountryState(); $this->setData('state', $this->data_state); $this->setData('country', $this->data_country); $this->setData('zones', $this->getZonesCountryState()); $this->setData('can_delete', $this->canDeleteCountryState()); $this->submitEditCountryState(); $this->outputEditCountryState(); }
Displays the edit country state page @param string $country_code @param integer|null $state_id
entailment
protected function canDeleteCountryState() { return isset($this->data_state['state_id']) && $this->state->canDelete($this->data_state['state_id']) && $this->access('state_delete'); }
Whether the country state can be deleted @return boolean
entailment
protected function submitEditCountryState() { if ($this->isPosted('delete')) { $this->deleteCountryState(); } else if ($this->isPosted('save') && $this->validateEditCountryState()) { if (isset($this->data_state['state_id'])) { $this->updateCountryState(); } else { $this->addCountryState(); } } }
Handles a submitted country state data
entailment
protected function validateEditCountryState() { $this->setSubmitted('state'); $this->setSubmittedBool('status'); $this->setSubmitted('update', $this->data_state); $this->setSubmitted('country', $this->data_country['code']); $this->validateComponent('country_state'); return !$this->hasErrors(); }
Validates a submitted country state data @return boolean
entailment