sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function outputCommandHelp() { $command = $this->getParam(0); if (!empty($command)) { $this->outputHelp($command); $this->output(); } }
Displays help message for a command
entailment
public function from($value, $unit) { $this->base_unit = $this->value = null; $key = strtolower($unit); if (empty($this->units[$key]['base'])) { throw new OutOfBoundsException('Unit does not exist'); } if (!isset($this->units[$key]['conversion'])) { throw new OutOfBoundsException("Conversion is not set for unit $unit"); } $this->base_unit = $this->units[$key]['base']; $this->value = $this->toBase($value, $this->units[$key]); return $this; }
Set from conversion value / unit @param number $value @param string $unit @return $this @throws OutOfBoundsException
entailment
public function to($unit, $decimals = null, $round = true) { if (!isset($this->value)) { throw new InvalidArgumentException('From value not set'); } if (is_array($unit)) { return $this->toMany($unit, $decimals, $round); } $key = strtolower($unit); if (empty($this->units[$key]['base'])) { throw new OutOfBoundsException('Unit does not exist'); } if (!isset($this->base_unit)) { $this->base_unit = $this->units[$key]['base']; } if ($this->units[$key]['base'] != $this->base_unit) { throw new InvalidArgumentException('Cannot convert between units of different types'); } if (is_callable($this->units[$key]['conversion'])) { $result = $this->units[$unit]['conversion']($this->value, true); } else { $result = $this->value / $this->units[$key]['conversion']; } if (!isset($decimals)) { return $result; } if ($round) { return round($result, $decimals); } $shifter = $decimals ? pow(10, $decimals) : 1; return floor($result * $shifter) / $shifter; }
Convert from value to new unit @param string|array $unit @param null|integer $decimals @param bool $round @return mixed @throws OutOfBoundsException @throws InvalidArgumentException
entailment
public function toAll($decimals = null, $round = true) { if (!isset($this->value)) { throw new InvalidArgumentException('From value not set'); } if (empty($this->base_unit)) { throw new InvalidArgumentException('No from unit set'); } $units = array(); foreach ($this->units as $key => $data) { if ($data['base'] == $this->base_unit) { array_push($units, $key); } } return $this->toMany($units, $decimals, $round); }
Convert from value to all compatible units @param number $decimals @param bool $round @return array @throws InvalidArgumentException
entailment
public function getConversions($unit) { if (!isset($this->units[$unit]['base'])) { throw new OutOfBoundsException('Unit is not set'); } $units = array(); foreach ($this->units as $key => $value) { if (isset($value['base']) && $value['base'] === $this->units[$unit]['base']) { array_push($units, $key); } } return $units; }
List all available conversion units for given unit @param string $unit @return array @throws OutOfBoundsException
entailment
public function getUnits($type = null) { if (!isset($type)) { return $this->units; } $filtered = array(); foreach ($this->units as $key => $value) { if (isset($value['type']) && $value['type'] === $type) { $filtered[$key] = $value; } } return $filtered; }
Returns an array of units @param null|string $type Filter by this type @return array
entailment
public function getUnitNames($type = null) { $names = array(); foreach ($this->getUnits($type) as $key => $value) { $names[$key] = $value['name']; } return $names; }
Returns an array of unit names @param null|string $type @return array
entailment
public function convert($value, $from, $to, $decimals = 2) { return (float) $this->from($value, $from)->to($to, $decimals, !empty($decimals)); }
Shortcut method to convert units @param number $value @param string $from @param string $to @param integer $decimals @return float
entailment
protected function toBase($value, array $unit) { if (is_callable($unit['conversion'])) { return $unit['conversion']($value, false); } return $value * $unit['conversion']; }
Convert from value to its base unit @param number $value @param array $unit @return number
entailment
protected function toMany(array $units, $decimals = null, $round = true) { $results = array(); foreach ($units as $key) { $results[$key] = $this->to($key, $decimals, $round); } return $results; }
Iterate through multiple unit conversions @param array $units @param null|number $decimals @param bool $round @return array
entailment
public function userRole(array &$submitted, array $options = array()) { $this->options = $options; $this->submitted = &$submitted; $this->validateUserRole(); $this->validatePermissionsUserRole(); $this->validateRedirectUserRole(); $this->validateBool('status'); $this->validateName(); $this->unsetSubmitted('update'); return $this->getResult(); }
Performs full user role data validation @param array $submitted @param array $options @return array|boolean
entailment
protected function validateUserRole() { $id = $this->getUpdatingId(); if ($id === false) { return null; } $data = $this->role->get($id); if (empty($data)) { $this->setErrorUnavailable('update', $this->translation->text('Role')); return false; } $this->setUpdating($data); return true; }
Validates a user role to be updated @return boolean|null
entailment
protected function validatePermissionsUserRole() { $field = 'permissions'; if ($this->isExcluded($field)) { return null; } $value = $this->getSubmitted($field); if ($this->isUpdating() && !isset($value)) { $this->unsetSubmitted($field); return null; } if (empty($value)) { $this->setSubmitted($field, array()); return null; } if (!is_array($value)) { $this->setErrorInvalid($field, $this->translation->text('Permissions')); return false; } $permissions = $this->role->getPermissions(); $invalid = array_diff($value, array_keys($permissions)); if (!empty($invalid)) { $this->setErrorUnavailable($field, implode(',', $invalid)); return false; } return true; }
Validates permissions data @return boolean|null
entailment
protected function validateRedirectUserRole() { $value = $this->getSubmitted('redirect'); if (isset($value) && mb_strlen($value) > 255) { $this->setErrorLengthRange('redirect', $this->translation->text('Redirect'), 0, 255); return false; } return true; }
Validates a redirect path @return boolean
entailment
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); $appRootDir = $config['parameters']['app.root_dir']; return new FileLocator($serviceLocator->get('ModuleManager'), $appRootDir); }
Create and return the datasource service. @param ServiceLocatorInterface $serviceLocator @return \PPI\Framework\DataSource\DataSource;
entailment
protected function compare($a, $b, $operator) { settype($a, 'array'); settype($b, 'array'); if (in_array($operator, array('>=', '<=', '>', '<'))) { $a = reset($a); $b = reset($b); } switch ($operator) { case '>=': return $a >= $b; case '<=': return $a <= $b; case '>': return $a > $b; case '<': return $a < $b; case '=': return count(array_intersect($a, $b)) > 0; case '!=': return count(array_intersect($a, $b)) == 0; } return false; }
Compare two values using an operator @param mixed $a @param mixed $b @param string $operator @return boolean
entailment
final protected function accessControlAllowMethods( ServerRequestInterface $request, ResponseInterface $response, array &$headers ) : ResponseInterface { // check the allow methods $allowMethods = $this->parseItem('allowMethods', $request, false); if ('' === $allowMethods) { // if no methods are allowed, error $exception = new \DomainException('No methods configured to be allowed for request'); throw $exception; } // explode the allowed methods to trimmed arrays $methods = array_map('trim', explode(',', strtoupper((string) $allowMethods))); // check they have provided a method if ('' === $request->getHeaderLine('access-control-request-method')) { // if no methods provided, block it. $exception = new NoMethod('No method provided'); throw $exception; } // check the requested method is one of our allowed ones. Uppercase it. $requestedMethod = strtoupper($request->getHeaderLine('access-control-request-method')); // can we find the requested method (we are presuming they are only supplying one as per // the CORS specification) in our list of headers. if (false === in_array($requestedMethod, $methods)) { // no match, throw it. $exception = new MethodNotAllowed('Method not allowed'); $exception->setSent($requestedMethod) ->setAllowed($methods); throw $exception; } // if we've got this far, then our access-control-request-method header has been // validated so we should add our own outbound header. $headers['Access-Control-Allow-Methods'] = $allowMethods; // return the response object return $response; }
Handle the preflight requests for the access control headers. Logic is: - Read in our list of allowed methods, if there aren't any, throw an exception as that means a bad configuration setting has snuck in. - If the client has not provided an Access-Control-Request-Method, then block the request by throwing "Invalid options request - no method provided", - If the client provided method is not in our list of allowed methods, then block the request by throwing "Invalid options request - method not allowed: only ..." - If the client provided an allowed method, then list all the allowed methods on the header Access-Control-Allow-Methods and return the response object (which should not have been modified). @param ServerRequestInterface $request The server request information. @param ResponseInterface $response The response handler (should be filled in at end or on error). @param array $headers The headers we have already created. @throws \DomainException If there are no configured allowed methods. @throws NoMethod If no method was provided by the user. @throws MethodNotAllowed If the method provided by the user is not allowed. @return ResponseInterface
entailment
final protected function accessControlRequestHeaders( ServerRequestInterface $request, ResponseInterface $response, array &$headers ): ResponseInterface { // allow headers $allowHeaders = $this->parseItem('allowHeaders', $request, false); $requestHeaders = $request->getHeaderLine('access-control-request-headers'); $originalRequestHeaders = $requestHeaders; // they aren't requesting any headers, but let's send them our list if ('' === $requestHeaders) { $headers['Access-Control-Allow-Headers'] = $allowHeaders; // return the response return $response; } // at this point, they are requesting headers, however, we have no headers configured. if ('' === $allowHeaders) { // no headers configured, so let's block it. $exception = new NoHeadersAllowed('No headers are allowed'); $exception->setSent($requestHeaders); throw $exception; } // now parse the headers for comparison // change the string into an array (separated by ,) and trim spaces $requestHeaders = array_map('trim', explode(',', strtolower((string) $requestHeaders))); // and do the same with our allowed headers $allowedHeaders = array_map('trim', explode(',', strtolower((string) $allowHeaders))); // loop through each of their provided headers foreach ($requestHeaders as $header) { // if we are unable to find a match for the header, block it for security. if (false === in_array($header, $allowedHeaders, true)) { // block it $exception = new HeaderNotAllowed(sprintf('Header "%s" not allowed', $header)); $exception->setAllowed($allowedHeaders) ->setSent($originalRequestHeaders); throw $exception; } } // if we've got this far, then our access-control-request-headers header has been // validated so we should add our own outbound header. $headers['Access-Control-Allow-Headers'] = $allowHeaders; // return the response return $response; }
Handle the preflight requests for the access control headers. Logic is: - If there are headers configured, but they client hasn't said they are sending them, just add the list to the Access-Control-Allow-Headers header and return the response (which should not have been modified). - If there are no headers configured, but they client has said they are sending some, then call our blockedCallback with the "Invalid options request - header not allowed: (none)" message, empty any previously set headers (for security) and return the response object (which may have been modified by the blockedCallback). - If there are headers configured and the client has said they are sending them, go through each of the headers provided by the client matching up to our allow list. If we encounter one that is not on our allow list, call our blockedCallback with the "Invalid options request - header not allowed: only ..." message listing the allowed headers, empty any previously set headers (for security) and return the response object (which may have been modified by the blockedCallback). - If there are provided headers, and they all match our allow list (we may allow more headers than requested), then add the complete list to the Access-Control-Allow-Headers header and return the response (which should not have been modified). @param ServerRequestInterface $request The server request information. @param ResponseInterface $response The response handler (should be filled in at end or on error). @param array $headers The headers we have already created. @throws NoHeadersAllowed If headers are not allowed. @throws HeaderNotAllowed If a particular header is not allowed. @return ResponseInterface
entailment
public function listPriceRule() { $this->actionListPriceRule(); $this->setTitleListPriceRule(); $this->setBreadcrumbListPriceRule(); $this->setFilterListPriceRule(); $this->setPagerListPriceRule(); $this->setData('stores', $this->store->getList()); $this->setData('price_rules', $this->getListPriceRule()); $this->outputListPriceRule(); }
Displays the price rule overview page
entailment
protected function setPagerListPriceRule() { $conditions = $this->query_filter; $conditions['count'] = true; $pager = array( 'query' => $this->query_filter, 'total' => (int) $this->price_rule->getList($conditions) ); return $this->data_limit = $this->setPager($pager); }
Sets pager @return array
entailment
protected function actionListPriceRule() { list($selected, $action, $value) = $this->getPostedAction(); $deleted = $updated = 0; foreach ($selected as $rule_id) { if ($action === 'status' && $this->access('price_rule_edit')) { $updated += (int) $this->price_rule->update($rule_id, array('status' => $value)); } if ($action === 'delete' && $this->access('price_rule_delete')) { $deleted += (int) $this->price_rule->delete($rule_id); } } if ($updated > 0) { $message = $this->text('Updated %num item(s)', array('%num' => $updated)); $this->setMessage($message, 'success'); } if ($deleted > 0) { $message = $this->text('Deleted %num item(s)', array('%num' => $deleted)); $this->setMessage($message, 'success'); } }
Applies an action to the selected price rules
entailment
protected function getListPriceRule() { $conditions = $this->query_filter; $conditions['limit'] = $this->data_limit; return (array) $this->price_rule->getList($conditions); }
Returns an array of price rules @return array
entailment
public function editPriceRule($rule_id = null) { $this->setPriceRule($rule_id); $this->setTitleEditPriceRule(); $this->setBreadcrumbEditPriceRule(); $this->setData('price_rule', $this->data_rule); $this->setData('types', $this->price_rule->getTypes()); $this->setData('triggers', $this->getTriggersPriceRule()); $this->setData('currencies', $this->getCurrenciesPriceRule()); $this->submitEditPriceRule(); $this->outputEditPriceRule(); }
Displays the price rule edit form @param null|integer $rule_id
entailment
protected function getTriggersPriceRule() { $list = (array) $this->trigger->getList(); foreach ($list as &$item) { if (empty($item['status'])) { $item['name'] .= ' (' . $this->lower($this->text('Disabled')) . ')'; } } return $list; }
Returns an array of enabled triggers @return array
entailment
protected function setPriceRule($rule_id) { $this->data_rule = array(); if (is_numeric($rule_id)) { $this->data_rule = $this->price_rule->get($rule_id); if (empty($this->data_rule)) { $this->outputHttpStatus(404); } } }
Returns an array of price rule data @param null|integer $rule_id
entailment
protected function submitEditPriceRule() { if ($this->isPosted('delete')) { $this->deletePriceRule(); } else if ($this->isPosted('save') && $this->validateEditPriceRule()) { if (isset($this->data_rule['price_rule_id'])) { $this->updatePriceRule(); } else { $this->addPriceRule(); } } }
Handles a submitted price rule
entailment
protected function validateEditPriceRule() { $this->setSubmitted('price_rule', null, false); $this->setSubmittedBool('status'); $this->setSubmitted('update', $this->data_rule); $this->validateComponent('price_rule'); return !$this->hasErrors(); }
Validates a submitted price rule @return bool
entailment
protected function deletePriceRule() { $this->controlAccess('price_rule_delete'); if ($this->price_rule->delete($this->data_rule['price_rule_id'])) { $this->redirect('admin/sale/price', $this->text('Price rule has been deleted'), 'success'); } $this->redirect('', $this->text('Price rule has not been deleted'), 'warning'); }
Deletes a price rule
entailment
protected function updatePriceRule() { $this->controlAccess('price_rule_edit'); if ($this->price_rule->update($this->data_rule['price_rule_id'], $this->getSubmitted())) { $this->redirect('admin/sale/price', $this->text('Price rule has been updated'), 'success'); } $this->redirect('', $this->text('Price rule has not been updated'), 'warning'); }
Updates a price rule
entailment
protected function addPriceRule() { $this->controlAccess('price_rule_add'); if ($this->price_rule->add($this->getSubmitted())) { $this->redirect('admin/sale/price', $this->text('Price rule has been added'), 'success'); } $this->redirect('', $this->text('Price rule has not been added'), 'warning'); }
Adds a new price rule
entailment
protected function setTitleEditPriceRule() { if (isset($this->data_rule['price_rule_id'])) { $title = $this->text('Edit %name', array('%name' => $this->data_rule['name'])); } else { $title = $this->text('Add price rule'); } $this->setTitle($title); }
Sets title on the edit price rule page
entailment
protected function setBreadcrumbEditPriceRule() { $breadcrumbs = array(); $breadcrumbs[] = array( 'url' => $this->url('admin'), 'text' => $this->text('Dashboard') ); $breadcrumbs[] = array( 'text' => $this->text('Price rules'), 'url' => $this->url('admin/sale/price') ); $this->setBreadcrumbs($breadcrumbs); }
Sets breadcrumbs on the edit price rule page
entailment
public function price(array $values) { if (count($values) != 1) { return $this->translation->text('@field has invalid value', array( '@field' => $this->translation->text('Condition'))); } $components = array_map('trim', explode('|', reset($values))); if (count($components) > 2) { return $this->translation->text('@field has invalid value', array( '@field' => $this->translation->text('Condition'))); } if (!is_numeric($components[0])) { return $this->translation->text('@field must be numeric', array( '@field' => $this->translation->text('Price'))); } if (strlen($components[0]) > 8) { return $this->translation->text('@field must not be longer than @max characters', array( '@max' => 8, '@field' => $this->translation->text('Price'))); } if (empty($components[1])) { $components[1] = $this->currency->getDefault(); } $currency = $this->currency->get($components[1]); if (empty($currency)) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('Currency'))); } return true; }
Validates a price condition @param array $values @return boolean|string
entailment
public function getCategoryOptionsByStore($category_model, $category_group_model, array $options) { $groups = (array) $category_group_model->getList($options); $list = array(); foreach ($groups as $group) { $op = array('category_group_id' => $group['category_group_id']); $list[$group['title']] = $this->getCategoryOptions($category_model, $op); } return $list; }
Returns a list of categories per store to use directly in <select> @param \gplcart\core\models\Category $category_model @param \gplcart\core\models\CategoryGroup $category_group_model @param array $options @return array
entailment
public function getCategoryOptions($category_model, array $options) { $options += array( 'status' => 1, 'parent_id' => 0, 'hierarchy' => true ); $categories = $category_model->getTree($options); if (empty($categories)) { return array(); } $list = array(); foreach ($categories as $category) { $title = $category['title']; if (!empty($options['hierarchy'])) { $title = str_repeat('— ', $category['depth']) . $title; } $list[$category['category_id']] = $title; } return $list; }
Returns a list of categories to use directly in <select> @param \gplcart\core\models\Category $category_model @param array $options @return array
entailment
public function get($state_id) { $result = &gplcart_static("state.get.$state_id"); if (isset($result)) { return $result; } $this->hook->attach('state.get.before', $state_id, $result, $this); if (isset($result)) { return $result; } $result = $this->db->fetch('SELECT * FROM state WHERE state_id=?', array($state_id)); $this->hook->attach('state.get.after', $state_id, $result, $this); return $result; }
Loads a country state from the database @param integer $state_id @return array
entailment
public function delete($state_id, $check = true) { $result = null; $this->hook->attach('state.delete.before', $state_id, $check, $result, $this); if (isset($result)) { return (bool) $result; } if ($check && !$this->canDelete($state_id)) { return false; } $result = (bool) $this->db->delete('state', array('state_id' => $state_id)); if ($result) { $this->db->delete('city', array('state_id' => $state_id)); } $this->hook->attach('state.delete.after', $state_id, $check, $result, $this); return (bool) $result; }
Deletes a country state @param integer $state_id @param bool $check @return boolean
entailment
public function canDelete($state_id) { $sql = 'SELECT address_id FROM address WHERE state_id=?'; $result = $this->db->fetchColumn($sql, array($state_id)); return empty($result); }
Whether the country state can be deleted @param integer $state_id @return boolean
entailment
protected function setInstanceProperties() { $this->hook = $this->getInstance('gplcart\\core\\Hook'); $this->config = $this->getInstance('gplcart\\core\\Config'); $this->route = $this->getInstance('gplcart\\core\\CliRoute'); $this->cli = $this->getInstance('gplcart\\core\\helpers\Cli'); $this->user = $this->getInstance('gplcart\\core\\models\\User'); $this->language = $this->getInstance('gplcart\\core\\models\\Language'); $this->validator = $this->getInstance('gplcart\\core\\models\\Validator'); $this->translation = $this->getInstance('gplcart\\core\\models\\Translation'); }
Sets class instance properties
entailment
public function setLanguage($code = null) { if (!isset($code)) { $code = $this->config->get('cli_langcode', ''); } $this->langcode = $code; $this->translation->set($code, null); return $this; }
Sets the current language @param null|string $code @return $this
entailment
protected function setUser() { $this->uid = $this->getParam('u', null); if (isset($this->uid)) { $this->current_user = $this->user->get($this->uid); if (empty($this->current_user['status'])) { $this->errorAndExit($this->text('No access')); } } }
Sets the current user from the command using -u option
entailment
protected function setRouteProperties() { $this->current_route = $this->route->get(); $this->command = $this->current_route['command']; $this->params = gplcart_array_trim($this->current_route['params'], true); }
Sets route properties
entailment
protected function controlAccess($permission) { if (isset($this->uid) && !$this->user->access($permission, $this->uid)) { $this->errorAndExit($this->text('No access')); } }
Control access to the route @param string $permission
entailment
protected function controlOptions() { $allowed = array(); if (!empty($this->current_route['options'])) { foreach (array_keys($this->current_route['options']) as $options) { foreach (explode(',', $options) as $option) { $allowed[trim(trim($option, '-'))] = true; } } } $submitted = $this->getOptions(); if (!empty($submitted) && !array_intersect_key($submitted, $allowed)) { $this->errorAndExit($this->text('Unsupported command options')); } }
Controls supported command options
entailment
protected function controlArguments() { if (!empty($this->current_route['arguments'])) { $submitted = $this->getArguments(); if (!empty($submitted) && !array_intersect_key($submitted, $this->current_route['arguments'])) { $this->errorAndExit($this->text('Unsupported command arguments')); } } }
Controls supported command arguments
entailment
protected function controlRouteAccess() { if (!$this->config->get('cli_status', true)) { $this->errorAndExit($this->text('No access')); } $this->controlAccess('cli'); if (isset($this->current_route['access'])) { $this->controlAccess($this->current_route['access']); } }
Controls access to the current route
entailment
public function setSubmittedMapped(array $map, $params = null, array $default = array()) { $mapped = $this->mapParams($map, $params); $merged = gplcart_array_merge($default, $mapped); return $this->setSubmitted(null, $merged); }
Sets an array of submitted mapped data @param array $map @param null|array $params @param array $default @return array
entailment
public function setSubmitted($key, $data) { if (isset($key)) { gplcart_array_set($this->submitted, $key, $data); return $this->submitted; } return $this->submitted = (array) $data; }
Sets a submitted data @param null|string $key @param mixed $data @return array
entailment
public function getSubmitted($key = null, $default = null) { if (isset($key)) { $value = gplcart_array_get($this->submitted, $key); return isset($value) ? $value : $default; } return $this->submitted; }
Returns a submitted value @param string|array $key @param mixed $default @return mixed
entailment
public function getParam($key = null, $default = null) { if (!isset($key)) { return $this->params; } foreach ((array) $key as $k) { if (isset($this->params[$k])) { return $this->params[$k]; } } return $default; }
Returns a single parameter value @param string|array|null $key @param mixed $default @return mixed
entailment
public function isError($key = null) { $value = $this->getError($key); return is_array($value) ? !empty($value) : isset($value); }
Whether a error exists @param null|string $key @return boolean
entailment
public function date($timestamp, $full = true) { if ($full) { $format = $this->config->get('date_full_format', 'd.m.Y H:i'); } else { $format = $this->config->get('date_short_format', 'd.m.y'); } return date($format, $timestamp); }
Formats a local time/date @param integer $timestamp @param bool $full @return string
entailment
public function setError($key, $error) { if (isset($key)) { gplcart_array_set($this->errors, $key, $error); return $this->errors; } return $this->errors = (array) $error; }
Sets an error @param null|string $key @param mixed $error @return array
entailment
public function getError($key = null) { if (isset($key)) { return gplcart_array_get($this->errors, $key); } return $this->errors; }
Returns a single error or an array of all defined errors @param null|string $key @return mixed
entailment
public function errors($exit_on_error = false) { if (!empty($this->errors)) { foreach (gplcart_array_flatten($this->errors) as $error) { $this->error($error); } $this->errors = array(); if ($exit_on_error) { $this->abort(1); } } }
Print and clear up all existing errors @param boolean $exit_on_error
entailment
public function mapParams(array $map, $params = null) { if (!isset($params)) { $params = $this->params; } $mapped = array(); foreach ($params as $key => $value) { if (isset($map[$key]) && is_string($map[$key])) { gplcart_array_set($mapped, $map[$key], $value); } } return $mapped; }
Map the command line parameters to an array of submitted data to be passed to validators @param array $map @param null|array $params @return array
entailment
public function validateComponent($handler_id, array $options = array()) { $result = $this->validator->run($handler_id, $this->submitted, $options); if ($result === true) { return true; } $this->setError(null, $result); return $result; }
Validates a submitted data @param string $handler_id @param array $options @return mixed
entailment
public function isValidInput($input, $field, $handler_id) { $this->setSubmitted($field, $input); return $this->validateComponent($handler_id, array('field' => $field)) === true; }
Whether the user input passed the field validation @param mixed $input @param string $field @param string $handler_id @return bool
entailment
protected function validatePrompt($field, $label, $validator, $default = null) { $input = $this->prompt($label, $default); if (!$this->isValidInput($input, $field, $validator)) { $this->errors(); $this->validatePrompt($field, $label, $validator, $default); } }
Validates a user input from prompt @param string $field @param string $label @param string $validator @param string|null $default
entailment
protected function validateMenu($field, $label, $validator, array $options, $default = null) { $input = $this->menu($options, $default, $label); if (!$this->isValidInput($input, $field, $validator)) { $this->errors(); $this->validateMenu($field, $label, $validator, $options, $default); } }
Validates a chosen menu option @param string $field @param string $label @param string $validator @param array $options @param null|string $default
entailment
public function outputHelp($command = null) { $help_options = $this->config->get('cli_help_option', 'h'); if (isset($command) || $this->getParam($help_options)) { if (!isset($command)) { $command = $this->command; } $aliases = $this->route->getAliases(); if (isset($aliases[$command])) { $command = $aliases[$command]; } $routes = $this->route->getList(); if (empty($routes[$command])) { $this->errorAndExit($this->text('Unknown command')); } $this->printHelpText($routes[$command]); $this->output(); } }
Output help for a certain command or the current command if a help option is specified @param string|null $command
entailment
protected function printHelpText(array $command) { $shown = false; if (!empty($command['description'])) { $shown = true; $this->line($this->text($command['description'])); } if (!empty($command['usage'])) { $shown = true; $this->line()->line($this->text('Usage:')); foreach ($command['usage'] as $usage) { $this->line($usage); } } if (!empty($command['options'])) { $shown = true; $this->line()->line($this->text('Options:')); foreach ($command['options'] as $name => $description) { $vars = array('@option' => $name, '@description' => $this->text($description)); $this->line($this->text(' @option @description', $vars)); } } if (!$shown) { $this->line($this->text('No help found for the command')); } }
Print command help text @param array $command
entailment
public function selectLanguage($langcode = null) { $languages = array(); foreach ($this->language->getList() as $code => $language) { if ($code === 'en' || is_file($this->translation->getFile($code))) { $languages[$code] = $language['name']; } } if (count($languages) < 2 && !isset($langcode)) { return null; } if (isset($langcode)) { $selected = $langcode; } else { $selected = $this->menu($languages, 'en', $this->text('Language (enter a number)')); } if (empty($languages[$selected])) { $this->error($this->text('Invalid language')); $this->selectLanguage(); } else { $this->langcode = (string) $selected; $this->translation->set($this->langcode, null); $this->config->set('cli_langcode', $this->langcode); } return $this->langcode; }
Shows language selector and validates user's input @param null|string $langcode @return string
entailment
public function getTree(array $options) { $tree = &gplcart_static(gplcart_array_hash(array('category.tree' => $options))); if (isset($tree)) { return $tree; } $list = (array) $this->getList($options); $tree = $this->prepareTree($list, $options); $this->hook->attach('category.tree', $tree, $this); return $tree; }
Returns an array of categories with parent categories set @param array $options @return array
entailment
public function add(array $data) { $result = null; $this->hook->attach('category.add.before', $data, $result, $this); if (isset($result)) { return (int) $result; } $result = $data['category_id'] = $this->db->insert('category', $data); $this->setTranslations($data, $this->translation_entity, 'category', false); $this->setImages($data, $this->file, 'category'); $this->setAlias($data, $this->alias, 'category', false); $this->hook->attach('category.add.after', $data, $result, $this); return (int) $result; }
Adds a category @param array $data @return integer
entailment
public function update($category_id, array $data) { $result = null; $this->hook->attach('category.update.before', $category_id, $data, $result, $this); if (isset($result)) { return (bool) $result; } $updated = $this->db->update('category', $data, array('category_id' => $category_id)); $data['category_id'] = $category_id; $updated += (int) $this->setTranslations($data, $this->translation_entity, 'category'); $updated += (int) $this->setImages($data, $this->file, 'category'); $updated += (int) $this->setAlias($data, $this->alias, 'category'); $result = $updated > 0; $this->hook->attach('category.update.after', $category_id, $data, $result, $this); return (bool) $result; }
Updates a category @param integer $category_id @param array $data @return boolean
entailment
protected function deleteLinked($category_id) { $this->db->delete('category_translation', array('category_id' => $category_id)); $this->db->delete('file', array('entity' => 'category', 'entity_id' => $category_id)); $this->db->delete('alias', array('entity' => 'category', 'entity_id' => $category_id)); }
Delete all database records related to the category ID @param string $category_id
entailment
protected function prepareTree(array $categories, array $options) { $tree = array(); $parents_tree = array(); $children_tree = array(); $categories_tree = array(); $parent = isset($options['parent_id']) ? (int) $options['parent_id'] : 0; foreach ($categories as $category) { $children_tree[$category['parent_id']][] = $category['category_id']; $parents_tree[$category['category_id']][] = $category['parent_id']; $categories_tree[$category['category_id']] = $category; } $max_depth = isset($options['depth']) ? (int) $options['depth'] : count($children_tree); $process_parents = array(); $process_parents[] = $parent; while (count($process_parents)) { $parent = array_pop($process_parents); $depth = count($process_parents); if ($max_depth <= $depth || empty($children_tree[$parent])) { continue; } $has_children = false; $child = current($children_tree[$parent]); do { if (empty($child)) { break; } $category = $categories_tree[$child]; $category['depth'] = $depth; $category['parents'] = $parents_tree[$category['category_id']]; $tree[$category['category_id']] = $category; if (!empty($children_tree[$category['category_id']])) { $has_children = true; $process_parents[] = $parent; $process_parents[] = $category['category_id']; reset($categories_tree[$category['category_id']]); next($children_tree[$parent]); break; } } while ($child = next($children_tree[$parent])); if (!$has_children) { reset($children_tree[$parent]); } } return $tree; }
Create a tree structure from an array of categories @param array $categories @param array $options @return array
entailment
protected function parseRoute(RouteCollection $collection, $name, array $config, $path) { if (!empty($this->defaults)) { $config['defaults'] = array_merge($config['defaults'], $this->defaults); } parent::parseRoute($collection, $name, $config, $path); }
Parses a route and adds it to the RouteCollection. @param RouteCollection $collection A RouteCollection instance @param string $name Route name @param array $config Route definition @param string $path Full path of the YAML file being processed
entailment
public function listReportShipping() { $this->setTitleListReportShipping(); $this->setBreadcrumbListReportShipping(); $this->setFilterListReportShipping(); $this->setPagerListReportShipping(); $this->setData('methods', (array) $this->getListReportShipping()); $this->outputListReportShipping(); }
Displays the shipping method overview page
entailment
protected function setPagerListReportShipping() { $pager = array( 'query' => $this->query_filter, 'total' => (int) $this->getListReportShipping(true) ); return $this->data_limit = $this->setPager($pager); }
Sets pager @return array
entailment
protected function getListReportShipping($count = false) { $list = $this->shipping->getList(); $allowed = $this->getAllowedFiltersReportShipping(); $this->filterList($list, $allowed, $this->query_filter); $this->sortList($list, $allowed, $this->query_filter, array('id' => 'asc')); if ($count) { return count($list); } $this->limitList($list, $this->data_limit); return $list; }
Returns an array of shipping methods or counts them @param bool $count @return array|int
entailment
public function install() { $this->controlAccessInstall(); if ($this->getParam()) { $this->validateFastInstall(); } else { $this->validateWizardInstall(); } $this->processInstall(); $this->output(); }
Performs full system installation
entailment
protected function validateWizardInstall() { $this->selectLanguage(); $this->validateRequirementsInstall(); $this->validateInstallerInstall(); $this->validatePrompt('store.title', $this->text('Store title'), 'install', 'GPLCart'); $this->validatePrompt('user.email', $this->text('E-mail'), 'install'); $this->validatePrompt('user.password', $this->text('Password'), 'install'); $this->validatePrompt('store.host', $this->text('Host'), 'install', 'localhost'); $this->validatePrompt('store.basepath', $this->text('Installation subdirectory'), 'install', ''); $this->validateInputDbInstall(); $this->validateInputInstall(); }
Display simple installation wizard and validates user input
entailment
protected function validateFastInstall() { $mapping = $this->getMappingInstall(); $default = $this->getDefaultInstall(); $this->setSubmittedMapped($mapping, null, $default); $this->validateComponent('install'); $this->errors(true); }
Validates fast installation
entailment
protected function getDefaultInstall() { $data = array(); $data['database']['port'] = 3306; $data['database']['user'] = 'root'; $data['database']['type'] = 'mysql'; $data['database']['host'] = 'localhost'; $data['database']['password'] = ''; $data['store']['basepath'] = ''; $data['store']['title'] = 'GPL Cart'; $data['store']['host'] = 'localhost'; $data['store']['timezone'] = date_default_timezone_get(); return $data; }
Returns an array of default submitted values @return array
entailment
protected function processInstall() { if (!$this->isError()) { $settings = $this->getSubmitted(); $this->install->connectDb($settings['database']); $result = $this->install->process($settings, $this->current_route); if ($result['severity'] === 'success') { $this->line($result['message']); } else { $this->error($result['message']); } } }
Does installation
entailment
protected function validateInputInstall() { $this->setSubmitted('store.language', $this->langcode); $this->setSubmitted('store.timezone', date_default_timezone_get()); $this->validateComponent('install'); if ($this->isError('database')) { $this->errors(); $this->validateInputDbInstall(); } $this->errors(true); }
Validates all collected input
entailment
protected function validateInputDbInstall() { $this->validatePrompt('database.name', $this->text('Database name'), 'install'); $this->validatePrompt('database.user', $this->text('Database user'), 'install', 'root'); $this->validatePrompt('database.password', $this->text('Database password'), 'install', ''); $this->validatePrompt('database.port', $this->text('Database port'), 'install', '3306'); $this->validatePrompt('database.host', $this->text('Database port'), 'install', 'localhost'); $this->validateInputDbTypeInstall(); }
Validate database details input
entailment
protected function validateInputDbTypeInstall() { $drivers = PDO::getAvailableDrivers(); $title = $this->text('Database type (enter a number)'); $input = $this->menu(array_combine($drivers, $drivers), 'mysql', $title); if (!$this->isValidInput($input, 'database.type', 'install')) { $this->errors(); $this->validateInputDbTypeInstall(); } }
Validates a database port input
entailment
protected function validateInstallerInstall() { $handlers = $this->install->getHandlers(); if (count($handlers) >= 2) { $options = array(); foreach ($handlers as $id => $handler) { $options[$id] = $handler['title']; } $input = $this->menu($options, 'default', $this->text('Installation profile (enter a number)')); if (!$this->isValidInput($input, 'installer', 'install')) { $this->errors(); $this->validateInstallerInstall(); } } }
Validates installation profile input
entailment
public function getCartQuantity(array $options = array()) { $options += array( 'user_id' => $this->cart_uid, 'store_id' => $this->store_id ); return $this->cart->getQuantity($options); }
Returns the number of cart items for the current user @param array $options @return array|int
entailment
protected function setFrontendData() { $currencies = $this->currency->getList(array('enabled' => true)); $this->data['_currencies'] = $currencies; $this->data['_cart'] = $this->getCartQuantity(); $this->data['_wishlist'] = $this->getWishlist(); $this->data['_captcha'] = $this->getWidgetCaptcha(); $this->data['_comparison'] = $this->getProductComparison(); $this->data['_currency'] = $currencies[$this->current_currency]; $this->data['_menu'] = $this->getWidgetMenu(array('items' => $this->data_categories)); }
Sets default data for templates
entailment
protected function setFrontendInstancies() { $this->price = $this->getInstance('gplcart\\core\\models\\Price'); $this->trigger = $this->getInstance('gplcart\\core\\models\\Trigger'); $this->product = $this->getInstance('gplcart\\core\\models\\Product'); $this->wishlist = $this->getInstance('gplcart\\core\\models\\Wishlist'); $this->category = $this->getInstance('gplcart\\core\\models\\Category'); $this->currency = $this->getInstance('gplcart\\core\\models\\Currency'); $this->cart_action = $this->getInstance('gplcart\\core\\models\\CartAction'); $this->product_compare = $this->getInstance('gplcart\\core\\models\\ProductCompare'); $this->wishlist_action = $this->getInstance('gplcart\\core\\models\\WishlistAction'); $this->product_compare_action = $this->getInstance('gplcart\\core\\models\\ProductCompareAction'); }
Sets model instances
entailment
protected function setFrontendProperties() { if (!$this->isInstall()) { if (!$this->isInternalRoute()) { $this->triggered = $this->getTriggered(); $this->data_categories = $this->getCategories(); } $this->current_currency = $this->currency->getCode(); } }
Sets controller's properties
entailment
public function getCart(array $conditions = array()) { $conditions += array( 'user_id' => $this->cart_uid, 'store_id' => $this->store_id ); $cart = $this->cart->getContent($conditions); $this->prepareCart($cart); return $cart; }
Returns the current cart data @param array $conditions @return array
entailment
protected function prepareCart(array &$cart) { if (!empty($cart['items'])) { foreach ($cart['items'] as &$item) { $item['currency'] = $cart['currency']; $this->prepareCartItem($item); } $this->setItemTotalFormatted($cart, $this->price); } }
Prepares an array of cart items @param array $cart
entailment
public function getWishlist() { $conditions = array( 'product_status' => 1, 'user_id' => $this->cart_uid, 'store_id' => $this->store_id ); return (array) $this->wishlist->getList($conditions); }
Returns an array of wishlist items for the current user @return array
entailment
public function getCategories($conditions = array(), $options = array()) { $conditions += array( 'status' => 1, 'type' => 'catalog', 'store_id' => $this->store_id ); $options += array( 'entity' => 'category', 'imagestyle' => $this->configTheme('image_style_category_child', 3)); $categories = $this->category->getTree($conditions); $this->prepareEntityItems($categories, $options); return $categories; }
Returns an array of prepared categories @param array $conditions @param array $options @return array
entailment
public function getProducts($conditions = array(), $options = array()) { $conditions += array( 'status' => 1, 'store_id' => $this->store_id ); if (isset($conditions['product_id']) && empty($conditions['product_id'])) { return array(); } $options += array('entity' => 'product'); $products = (array) $this->product->getList($conditions); $this->prepareEntityItems($products, $options); return $products; }
Loads products from an array of product IDs @param array $conditions @param array $options @return array
entailment
protected function prepareEntityItems(array &$items, $options = array()) { if (!empty($items) && isset($options['entity'])) { if (!isset($options['view']) || !in_array($options['view'], array('list', 'grid'))) { $options['view'] = 'grid'; } $options += array( 'entity' => $options['entity'], 'entity_id' => array_keys($items), 'template_item' => "{$options['entity']}/item/{$options['view']}", 'imagestyle' => $this->configTheme("image_style_{$options['entity']}_{$options['view']}", 3) ); foreach ($items as &$item) { $this->prepareEntityItem($item, $options); } } }
Prepare an array of entity items like pages, products etc @param array $items @param array $options
entailment
protected function prepareEntityItem(array &$item, array $options) { $this->setItemEntityUrl($item, $options); $this->setItemThumb($item, $this->image, $options); if ($options['entity'] === 'product') { $this->prepareProductItem($item, $options); } else { $this->setItemIndentation($item); $this->setItemUrlActive($item); $this->setItemRendered($item, array('item' => $item), $options); } }
Prepare an entity item @param array $item @param array $options
entailment
protected function prepareProductItem(array &$product, array $options) { $this->setItemProductInComparison($product, $this->product_compare); $this->setItemPriceCalculated($product, $this->product); $this->setItemProductInWishlist($product, $this->wishlist); $this->setItemPriceFormatted($product, $this->price, $this->current_currency); $this->setItemProductBundle($product, $this->product, $this->image); $this->setItemRenderedProduct($product, $options); }
Prepare a product item @param array $product @param array $options
entailment
protected function prepareCartItem(array &$item) { $this->setItemImages($item['product'], 'product', $this->image); $this->setItemThumbCart($item, $this->image); $this->setItemPriceFormatted($item, $this->price, $this->current_currency); $this->setItemTotalFormatted($item, $this->price); $this->setItemProductBundle($item['product'], $this->product, $this->image); }
Prepare a cart item Prepare cart item @param array $item
entailment
public function add(array $data) { $result = null; $this->hook->attach('category.group.add.before', $data, $result, $this); if (isset($result)) { return (int) $result; } $result = $data['category_group_id'] = $this->db->insert('category_group', $data); $this->setTranslations($data, $this->translation_entity, 'category_group', false); $this->hook->attach('category.group.add.after', $data, $result, $this); return (int) $result; }
Adds a category group @param array $data @return integer
entailment
public function canDelete($category_group_id) { $sql = 'SELECT category_id FROM category WHERE category_group_id=?'; $result = $this->db->fetchColumn($sql, array($category_group_id)); return empty($result); }
Whether a category group can be deleted @param integer $category_group_id @return boolean
entailment
public function getTypes() { $types = array( 'brand' => $this->translation->text('Brand'), 'common' => $this->translation->text('Common'), 'catalog' => $this->translation->text('Catalog') ); $this->hook->attach('category.group.types', $types, $this); return $types; }
Returns an array of category group types @return array
entailment
protected function getFileName($name) { $name = (string) $name; try { $template = $this->parser->parse($name); $file = $this->locator->locate($template); } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('Unable to find template "%s".', $name)); } return $file; }
Helper function for getting a Mustache template file name. @param string $name @return string Template file name
entailment
public function addLog(string $string, array $logData = []) : bool { if (null !== $this->logger) { $this->logger->debug('CORs: '.$string, $logData); return true; } return false; }
Add a log string if we have a logger. @param string $string String to log. @param array $logData Additional data to log. @return bool True if logged, false if no logger.
entailment
public function setSettings(array $settings = []) : self { $this->settings = array_merge($this->settings, $settings); // loop through checking each setting foreach ($this->allowedSettings as $name => $allowed) { $this->validateSettings->__invoke($name, $this->settings[$name], $allowed); } return $this; }
Set the settings. @param array $settings The new settings to be merged in. @return self
entailment