sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function setCliMessage($message)
{
if (GC_CLI) {
$this->cli->line($this->translation->text($message));
}
} | Sets a message line in CLI mode
@param string $message | entailment |
protected function initConfig()
{
Container::unregister();
$this->config = Container::get('gplcart\\core\\Config');
$this->config->init();
$this->db = $this->config->getDb();
} | Init configuration
It makes sure that we're using the database connection defined in the configuration file | entailment |
public function country(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateCountry();
$this->validateWeight();
$this->validateBool('status');
$this->validateCodeCountry();
$this->validateName();
$this->validateNativeNameCountry();
$this->validateZoneCountry();
$this->validateFormatCountry();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs full validation of submitted country data
@param array $submitted
@param array $options
@return array|bool | entailment |
protected function validateCountry()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null;
}
$data = $this->country->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('Country'));
return false;
}
$this->setUpdating($data);
return true;
} | Validates the country to be updated
@return boolean|null | entailment |
protected function validateFormatCountry()
{
$field = 'format';
$format = $this->getSubmitted($field);
if (!isset($format)) {
$this->unsetSubmitted($field);
return null;
}
$label = $this->translation->text('Format');
if (!is_array($format)) {
$this->setErrorInvalid($field, $label);
return false;
}
$default = $this->country->getDefaultFormat();
if (!array_intersect_key($format, $default)) {
$this->setErrorInvalid($field, $label);
return false;
}
foreach ($format as $key => $value) {
if (!is_array($value) || !array_intersect_key($value, $default[$key])) {
$this->setErrorInvalid($field, $label);
return false;
}
foreach ($value as $v) {
if (!in_array(gettype($v), array('string', 'integer', 'boolean'))) {
$this->setErrorInvalid($field, $label);
return false;
}
}
}
return true;
} | Validates country format
@return boolean | entailment |
public function install(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateRequirementsInstall();
if ($this->isError()) {
return $this->getError();
}
$this->validateUserEmailInstall();
$this->validateUserPasswordInstall();
$this->validateStoreHostInstall();
$this->validateStoreTitleInstall();
$this->validateStoreBasepathInstall();
$this->validateStoreTimezoneInstall();
$this->validateInstallerInstall();
$this->validateDbNameInstall();
$this->validateDbUserInstall();
$this->validateDbPasswordInstall();
$this->validateDbHostInstall();
$this->validateDbTypeInstall();
$this->validateDbPortInstall();
$this->validateDbConnectInstall();
return $this->getResult();
} | Performs full installation data validation
@param array $submitted
@param array $options
@return array|boolean | entailment |
protected function validateRequirementsInstall()
{
if ($this->isExcluded('requirements')) {
return null;
}
if ($this->config->isInitialized()) {
$error = $this->translation->text('System already installed');
$this->setError('installed', $error);
return false;
}
$requirements = $this->install->getRequirements();
$errors = $this->install->getRequirementErrors($requirements);
if (empty($errors['danger'])) {
return true;
}
$messages = array();
$messages[] = $this->translation->text('Please fix all critical errors in your environment');
foreach ($requirements as $items) {
foreach ($items as $name => $info) {
if (in_array($name, $errors['danger'])) {
$status = empty($info['status']) ? $this->translation->text('No') : $this->translation->text('Yes');
$messages[] = " {$info['message']} - $status";
}
}
}
$this->setError('requirements', implode(PHP_EOL, $messages));
return false;
} | Checks system requirements
@return boolean | entailment |
protected function validateUserEmailInstall()
{
if ($this->isExcluded('user.email')) {
return null;
}
$options = $this->options;
$this->options['parents'] = 'user';
$result = $this->validateEmail();
$this->options = $options; // Restore original
return $result;
} | Validates a user E-mail
@return boolean | entailment |
protected function validateUserPasswordInstall()
{
$field = 'user.password';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
$label = $this->translation->text('Password');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
list($min, $max) = $this->user->getPasswordLength();
$length = mb_strlen($value);
if ($length < $min || $length > $max) {
$this->setErrorLengthRange($field, $label, $min, $max);
return false;
}
return true;
} | Validates a user password
@return boolean|null | entailment |
protected function validateStoreTitleInstall()
{
$field = 'store.title';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if (empty($value) || mb_strlen($value) > 255) {
$this->setErrorLengthRange($field, $this->translation->text('Title'));
return false;
}
return true;
} | Validates a store title
@return boolean | entailment |
protected function validateStoreTimezoneInstall()
{
$field = 'store.timezone';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if (empty($value)) {
$this->setSubmitted($field, date_default_timezone_get());
return true;
}
$timezones = gplcart_timezones();
if (empty($timezones[$value])) {
$this->setErrorInvalid($field, $this->translation->text('Timezone'));
return false;
}
return true;
} | Validates the store time zone
@return boolean | entailment |
protected function validateInstallerInstall()
{
$field = 'installer';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if (empty($value)) {
$this->setSubmitted('installer', 'default');
return null;
}
$installer = $this->install->getHandler($value);
if (empty($installer)) {
$this->setErrorInvalid('installer', $this->translation->text('Installer'));
return false;
}
return true;
} | Validates an installer ID
@return boolean|null | entailment |
protected function validateDbNameInstall()
{
$field = 'database.name';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if (empty($value)) {
$this->setErrorRequired($field, $this->translation->text('Database name'));
return false;
}
return true;
} | Validates a database name
@return boolean | entailment |
protected function validateDbPasswordInstall()
{
$field = 'database.password';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if (!isset($value)) {
$this->setSubmitted($field, '');
return null;
}
return true;
} | Validates a database password
@return boolean|null | entailment |
protected function validateDbTypeInstall()
{
$field = 'database.type';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if (empty($value)) {
$this->setErrorRequired($field, $this->translation->text('Database type'));
return false;
}
$drivers = \PDO::getAvailableDrivers();
if (in_array($value, $drivers)) {
return true;
}
$error = $this->translation->text('Unsupported database driver. Available drivers: @list', array(
'@list' => implode(',', $drivers)));
$this->setError($field, $error);
return false;
} | Validates a database driver
@return boolean | entailment |
protected function validateDbPortInstall()
{
$field = 'database.port';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
$label = $this->translation->text('Database port');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
if (!is_numeric($value)) {
$this->setErrorNumeric($field, $label);
return false;
}
return true;
} | Validates a database port
@return boolean | entailment |
protected function validateDbConnectInstall()
{
if ($this->isError()) {
return null;
}
$field = 'database.connect';
if ($this->isExcluded($field)) {
return null;
}
$settings = $this->getSubmitted('database');
$result = $this->install->connectDb($settings);
if ($result === true) {
return true;
}
if (empty($result)) {
$result = $this->translation->text('Could not connect to database');
}
$this->setError($field, (string) $result);
return false;
} | Validates database connection
@return boolean | entailment |
public function hookTheme(Controller $controller)
{
if ($controller->isCurrentTheme('backend') && !$controller->isInternalRoute()) {
$this->setAssets($controller);
$this->setMetaTags($controller);
}
} | Implements hook "theme"
@param \gplcart\core\Controller $controller | entailment |
protected function setAssets(Controller $controller)
{
$controller->addAssetLibrary('jquery_ui');
$controller->addAssetLibrary('bootstrap');
$controller->addAssetLibrary('html5shiv', array('condition' => 'if lt IE 9'));
$controller->addAssetLibrary('respond', array('condition' => 'if lt IE 9'));
$controller->addAssetLibrary('font_awesome');
$controller->setJs(__DIR__ . '/js/common.js');
$controller->setCss(__DIR__ . '/css/common.css');
} | Adds theme specific assets
@param Controller $controller | entailment |
protected function setMetaTags(Controller $controller)
{
$controller->setMeta(array('charset' => 'utf-8'));
$controller->setMeta(array('http-equiv' => 'X-UA-Compatible', 'content' => 'IE=edge'));
$controller->setMeta(array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1'));
$controller->setMeta(array('name' => 'author', 'content' => 'GPLCart'));
} | Adds meta tags
@param Controller $controller | entailment |
public function boot()
{
$config = dirname(__DIR__) . '/config/form.php';
$this->mergeConfigFrom($config, 'form');
$this->publishes([$config => config_path('form.php')], 'config');
$presenter = config('form.presenter', 'Laraplus\Form\Presenters\Bootstrap3Presenter');
$this->app->bind('Laraplus\Form\Contracts\FormPresenter', $presenter);
$this->app->singleton('laraplus.form', 'Laraplus\Form\Form');
} | Boot the service provider | entailment |
public function get($role_id)
{
$result = &gplcart_static("user.role.get.$role_id");
if (isset($result)) {
return $result;
}
$this->hook->attach('user.role.get.before', $role_id, $result, $this);
if (isset($result)) {
return $result;
}
$sql = 'SELECT * FROM role WHERE role_id=?';
$result = $this->db->fetch($sql, array($role_id), array('unserialize' => 'permissions'));
$this->hook->attach('user.role.get.after', $role_id, $result, $this);
return $result;
} | Loads a role from the database
@param integer $role_id
@return array | entailment |
public function update($role_id, array $data)
{
$result = null;
$this->hook->attach('user.role.update.before', $role_id, $data, $result, $this);
if (isset($result)) {
return (bool) $result;
}
$result = (bool) $this->db->update('role', $data, array('role_id' => $role_id));
$this->hook->attach('user.role.update.after', $role_id, $data, $result, $this);
return (bool) $result;
} | Updates a role
@param integer $role_id
@param array $data
@return boolean | entailment |
public function getPermissions()
{
$permissions = &gplcart_static('user.role.permissions');
if (isset($permissions)) {
return $permissions;
}
$permissions = (array) gplcart_config_get(GC_FILE_CONFIG_PERMISSION);
asort($permissions);
$this->hook->attach('user.role.permissions', $permissions, $this);
return $permissions;
} | Returns an array of all defined permissions
@return array | entailment |
public function log($type, $data, $severity = 'info', $translatable = true)
{
$message = '';
if (is_string($data)) {
$message = $data;
} elseif (isset($data['message'])) {
$message = (string) $data['message'];
}
$values = array(
'text' => $message,
'data' => (array) $data,
'translatable' => $translatable,
'type' => mb_substr($type, 0, 255),
'severity' => mb_substr($severity, 0, 255)
);
return $this->add($values);
} | Writes a log message to the database
@param string $type
@param array|string $data
@param string $severity
@param boolean $translatable
@return boolean | entailment |
public function add(array $data)
{
if (!$this->isDb()) {
return false;
}
$data += array(
'created' => GC_TIME,
'log_id' => gplcart_string_random(6)
);
try {
$result = (bool) $this->db->insert('log', $data);
} catch (Exception $ex) {
$result = false;
}
return $result;
} | Adds a log record
@param array $data
@return bool | entailment |
public function selectErrors($limit = null)
{
if (!$this->isDb()) {
return array();
}
$sql = "SELECT * FROM log WHERE type LIKE ? ORDER BY created DESC";
if (isset($limit)) {
settype($limit, 'integer');
$sql .= " LIMIT 0,$limit";
}
try {
$results = $this->db->fetchAll($sql, array('php_%'), array('unserialize' => 'data'));
} catch (Exception $ex) {
return array();
}
$list = array();
foreach ($results as $result) {
$list[] = $result['data'];
}
return $list;
} | Returns an array of logged PHP errors from the database
@param integer|null $limit
@return array | entailment |
public function errorHandler($code, $message, $file = '', $line = '')
{
if ($this->error_to_exception) {
if (ob_get_length() > 0) {
ob_end_clean(); // Fix templates
}
throw new Exception($message);
}
$error = array(
'code' => $code,
'file' => $file,
'line' => $line,
'message' => $message,
'backtrace' => $this->log_backtrace ? gplcart_backtrace() : array()
);
$print = $this->print_error || !$this->isDb();
if (in_array($code, $this->getFatalErrorTypes())) {
if ($print) {
return false; // Let it fall through to the standard PHP error handler
}
$this->log('php_shutdown', $error, 'danger', false);
return true;
}
$key = md5(json_encode($error));
if (isset($this->errors[$key])) {
return true;
}
$this->errors[$key] = $error;
if ($print) {
echo $this->getFormattedError($error);
}
$this->log('php_error', $error, 'warning', false);
return true;
} | Error handler
@param integer $code
@param string $message
@param string $file
@param string $line
@throws Exception
@return bool | entailment |
public function shutdownHandler()
{
$error = error_get_last();
if (isset($error['type']) && in_array($error['type'], $this->getFatalErrorTypes())) {
$this->log('php_shutdown', $error, 'danger', false);
}
} | Shutdown handler | entailment |
public function exceptionHandler(Exception $exc)
{
$error = array(
'code' => $exc->getCode(),
'file' => $exc->getFile(),
'line' => $exc->getLine(),
'message' => $exc->getMessage(),
'backtrace' => $this->log_backtrace ? gplcart_backtrace() : array()
);
$this->log('php_exception', $error, 'danger', false);
echo $this->getFormattedError($error, 'Exception');
} | Common exception handler
@param Exception $exc | entailment |
public function getFormattedError(array $error, $header = '')
{
$output = "<table style='background:#fcf8e3;
color:#8a6d3b;
width:100%;
margin-bottom:10px;
border: 1px solid #faebcc;
border-collapse: collapse;'>";
if (!empty($header)) {
$output .= "<tr>
<td colspan='2' style='border-bottom: 1px solid #faebcc;'><b>$header</b></td>
</tr>\n";
}
$output .= "<tr>
<td style='background-color: #faebcc;'>Message </td>
<td style='border-bottom: 1px solid #faebcc;'>{$error['message']}</td>
</tr>\n";
if (isset($error['code'])) {
$output .= "<tr>
<td style='background-color: #faebcc;'>Code </td>
<td style='border-bottom: 1px solid #faebcc;'>{$error['code']}</td>
</tr>\n";
}
if (isset($error['type'])) {
$output .= "<tr>
<td style='background-color: #faebcc;'>Type </td>
<td style='border-bottom: 1px solid #faebcc;'>{$error['type']}</td>
</tr>\n";
}
$output .= "<tr>
<td style='background-color: #faebcc;'>File </td>
<td style='border-bottom: 1px solid #faebcc;'>{$error['file']}</td>
</tr>
<tr>
<td style='background-color: #faebcc;'>Line </td>
<td style='border-bottom: 1px solid #faebcc;'>{$error['line']}</td>
</tr>\n";
if ($this->print_backtrace && !empty($error['backtrace'])) {
$error['backtrace'] = implode("<br>\n", $error['backtrace']);
$output .= "<tr>
<td style='background-color: #faebcc;'>Backtrace </td>
<td style='border-bottom: 1px solid #faebcc;'>{$error['backtrace']}</td>
</tr>\n";
}
$output .= '</table>';
return GC_CLI ? preg_replace("/(\n| )+/", "$1", trim(strip_tags($output))) : $output;
} | Formats an error message
@param array $error
@param string $header
@return string | entailment |
public function getErrors($format = true)
{
if (!$format) {
return $this->errors;
}
$formatted = array();
foreach ($this->errors as $error) {
$formatted[] = $this->getFormattedError($error);
}
return $formatted;
} | Returns an array of collected PHP errors
@param boolean $format
@return array | entailment |
protected function getProductsWishlist()
{
$list = $this->getWishlist();
if (empty($list)) {
return array();
}
$ids = array();
foreach ((array) $list as $result) {
$ids[] = $result['product_id'];
}
$conditions = array('product_id' => $ids);
$options = array(
'buttons' => array(
'cart_add', 'wishlist_remove', 'compare_add')
);
return $this->getProducts($conditions, $options);
} | Returns an array of wishlist items for the current user
@return array | entailment |
public function set($entity, $entity_id, $created, $user_id = null)
{
if (!isset($user_id)) {
$user_id = $this->user->getId(); // Current user
}
if ($this->exists($entity, $entity_id, $user_id)) {
return true;
}
if ((GC_TIME - $created) >= $this->getLifespan()) {
return true; // Expired and was removed
}
$data = array(
'entity' => $entity,
'user_id' => $user_id,
'entity_id' => $entity_id
);
return $this->add($data);
} | Set a history record
@param string $entity
@param int $entity_id
@param int $created
@param null|int $user_id
@return boolean | entailment |
public function exists($entity, $entity_id, $user_id)
{
$sql = 'SELECT history_id FROM history WHERE entity=? AND entity_id=? AND user_id=?';
return (bool) $this->db->fetchColumn($sql, array($entity, $entity_id, $user_id));
} | Whether a record exists in the history table
@param string $entity
@param int $entity_id
@param int $user_id
@return bool | entailment |
public function isNew($entity_creation_time, $history_creation_time)
{
$lifespan = $this->getLifespan();
if (empty($history_creation_time)) {
return (GC_TIME - $entity_creation_time) <= $lifespan;
}
return (GC_TIME - $history_creation_time) > $lifespan;
} | Whether an entity is new
@param int $entity_creation_time
@param int|null $history_creation_time
@return bool | entailment |
public static function call($handlers, $handler_id, $method, $arguments = array())
{
$callback = static::get($handlers, $handler_id, $method);
return call_user_func_array($callback, $arguments);
} | Call a handler
@param array $handlers
@param string|null $handler_id
@param string $method
@param array $arguments
@return mixed | entailment |
public static function get($handlers, $handler_id, $name)
{
$callable = static::getCallable($handlers, $handler_id, $name);
if (is_array($callable)) {
if (is_callable($callable)) {
$callable[0] = Container::get($callable[0]);
return $callable;
}
throw new BadMethodCallException(implode('::', $callable) . ' is not callable');
}
if ($callable instanceof \Closure) {
return $callable;
}
throw new UnexpectedValueException('Unexpected handler format');
} | Returns a handler
@param array $handlers
@param string|null $handler_id
@param string $name
@return object|array
@throws BadMethodCallException
@throws UnexpectedValueException | entailment |
protected static function getCallable($handlers, $handler_id, $name)
{
if (isset($handler_id)) {
if (empty($handlers[$handler_id]['handlers'][$name])) {
throw new OutOfRangeException("Unknown handler ID $handler_id and/or method name $name");
}
return $handlers[$handler_id]['handlers'][$name];
}
if (empty($handlers['handlers'][$name])) {
throw new OutOfRangeException("Unknown handler method name $name");
}
return $handlers['handlers'][$name];
} | Returns a callable data from the handler array
@param array $handlers
@param string|null $handler_id
@param string $name
@return array|object
@throws OutOfRangeException | entailment |
public function notifyCreated(array $order)
{
$this->mail->set('order_created_admin', array($order));
if (is_numeric($order['user_id']) && !empty($order['user_email'])) {
return $this->mail->set('order_created_customer', array($order));
}
return false;
} | Notify when an order has been created
@param array $order
@return boolean | entailment |
public function notifyUpdated(array $order)
{
if (is_numeric($order['user_id']) && !empty($order['user_email'])) {
return $this->mail->set('order_updated_customer', array($order));
}
return false;
} | Notify when an order has been updated
@param array $order
@return boolean | entailment |
public function add(array $data, array $options = array())
{
$result = array();
$this->hook->attach('order.submit.before', $data, $options, $result, $this);
if (!empty($result)) {
return (array) $result;
}
$data['order_id'] = $this->order->add($data);
if (empty($data['order_id'])) {
return $this->getResultError();
}
$order = $this->order->get($data['order_id']);
$this->setBundledProducts($order, $data);
if (empty($options['admin'])) {
$this->setPriceRules($order);
$this->updateCart($order, $data['cart']);
$this->notifyCreated($order);
$result = $this->getResultAdded($order);
} else {
$this->cloneCart($order, $data['cart']);
$result = $this->getResultAddedAdmin($order);
}
$this->hook->attach('order.submit.after', $data, $options, $result, $this);
return (array) $result;
} | Adds an order
@param array $data
@param array $options
@return array | entailment |
protected function setBundledProducts(array $order, array $data)
{
$update = false;
foreach ($data['cart']['items'] as $item) {
if (empty($item['product']['bundled_products'])) {
continue;
}
foreach ($item['product']['bundled_products'] as $product) {
$cart = array(
'sku' => $product['sku'],
'user_id' => $data['user_id'],
'quantity' => $item['quantity'],
'store_id' => $data['store_id'],
'order_id' => $order['order_id'],
'product_id' => $product['product_id'],
);
$this->cart->add($cart);
$update = true;
$order['data']['components']['cart']['items'][$product['sku']]['price'] = 0;
}
}
if ($update) {
$this->order->update($order['order_id'], array('data' => $order['data']));
}
} | Adds bundled products
@param array $order
@param array $data | entailment |
protected function cloneCart(array $order, array $cart)
{
foreach ($cart['items'] as $item) {
$cart_id = $item['cart_id'];
unset($item['cart_id']);
$item['user_id'] = $order['user_id'];
$item['order_id'] = $order['order_id'];
$this->cart->add($item);
$this->cart->delete($cart_id);
}
} | Clone an order
@param array $order
@param array $cart | entailment |
protected function updateCart(array $order, array $cart)
{
foreach ($cart['items'] as $item) {
$data = array(
'user_id' => $order['user_id'],
'order_id' => $order['order_id']
);
$this->cart->update($item['cart_id'], $data);
}
} | Update cart items after order was created
@param array $order
@param array $cart | entailment |
protected function setPriceRules(array $order)
{
foreach (array_keys($order['data']['components']) as $component_id) {
if (is_numeric($component_id)) {
$rule = $this->price_rule->get($component_id);
if (isset($rule['code']) && $rule['code'] !== '') {
$this->price_rule->setUsed($rule['price_rule_id']);
}
}
}
} | Sets price rules after the order was created
@param array $order | entailment |
public function set($filename)
{
$this->image = null;
$this->filename = $filename;
$info = getimagesize($this->filename);
if (empty($info)) {
throw new UnexpectedValueException('Failed to get image dimensions');
}
$this->width = $info[0];
$this->height = $info[1];
$this->format = preg_replace('/^image\//', '', $info['mime']);
$this->image = $this->callFunction('imagecreatefrom', $this->format, array($this->filename));
if (!is_resource($this->image)) {
throw new UnexpectedValueException('Image file handle is not a valid resource');
}
imagesavealpha($this->image, true);
imagealphablending($this->image, true);
return $this;
} | Load an image
@param string $filename
@return $this
@throws UnexpectedValueException | entailment |
public function getSupportedFormats()
{
$formats = array();
foreach (gd_info() as $name => $status) {
if (strpos($name, 'Support') !== false && $status) {
$formats[] = strtolower(strtok($name, ' '));
}
}
return array_unique($formats);
} | Returns an array of supported image formats
@return array | entailment |
protected function callFunction($prefix, $format, array $arguments)
{
$function = "$prefix$format";
if (!in_array($format, $this->getSupportedFormats())) {
throw new RuntimeException("Unsupported image format $format");
}
if (!function_exists($function)) {
throw new BadFunctionCallException("Function $function does not exist");
}
return call_user_func_array($function, $arguments);
} | Call a function which name is constructed from prefix and image format
@param string $prefix
@param string $format
@param array $arguments
@return mixed
@throws RuntimeException
@throws BadFunctionCallException | entailment |
public function thumbnail($width, $height = null)
{
if (!isset($height)) {
$height = $width;
}
if (($height / $width) > ($this->height / $this->width)) {
$this->fitToHeight($height);
} else {
$this->fitToWidth($width);
}
$left = floor(($this->width / 2) - ($width / 2));
$top = floor(($this->height / 2) - ($height / 2));
return $this->crop($left, $top, $width + $left, $height + $top);
} | Create image thumbnail keeping aspect ratio
@param int $width
@param int|null $height
@return $this | entailment |
public function fitToHeight($height)
{
$width = $height / ($this->height / $this->width);
return $this->resize($width, $height);
} | Proportionally resize to the specified height
@param int $height
@return $this | entailment |
public function fitToWidth($width)
{
$height = $width * ($this->height / $this->width);
return $this->resize($width, $height);
} | Proportionally resize to the specified width
@param int $width
@return $this | entailment |
public function crop($x1, $y1, $x2, $y2)
{
if ($x2 < $x1) {
list($x1, $x2) = array($x2, $x1);
}
if ($y2 < $y1) {
list($y1, $y2) = array($y2, $y1);
}
$crop_width = $x2 - $x1;
$crop_height = $y2 - $y1;
$new = imagecreatetruecolor($crop_width, $crop_height);
if (empty($new)) {
throw new UnexpectedValueException('Failed to create an image identifier');
}
imagealphablending($new, false);
imagesavealpha($new, true);
if (!imagecopyresampled($new, $this->image, 0, 0, $x1, $y1, $crop_width, $crop_height, $crop_width, $crop_height)) {
throw new UnexpectedValueException('Failed to copy and resize part of an image with resampling');
}
$this->image = $new;
$this->width = $crop_width;
$this->height = $crop_height;
return $this;
} | Crop an image
@param int $x1
@param int $y1
@param int $x2
@param int $y2
@return $this
@throws UnexpectedValueException | entailment |
public function resize($width, $height)
{
$new = imagecreatetruecolor($width, $height);
if (empty($new)) {
throw new UnexpectedValueException('Failed to create an image identifier');
}
if ($this->format === 'gif') {
$transparent_index = imagecolortransparent($this->image);
$palletsize = imagecolorstotal($this->image);
if ($transparent_index >= 0 && $transparent_index < $palletsize) {
$transparent_color = imagecolorsforindex($this->image, $transparent_index);
$transparent_index = imagecolorallocate($new, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
imagefill($new, 0, 0, $transparent_index);
imagecolortransparent($new, $transparent_index);
}
} else {
imagealphablending($new, false);
imagesavealpha($new, true);
}
if (!imagecopyresampled($new, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height)) {
throw new UnexpectedValueException('Failed to copy and resize part of an image with resampling');
}
$this->image = $new;
$this->width = $width;
$this->height = $height;
return $this;
} | Resize an image to the specified dimensions
@param int $width
@param int $height
@return $this
@throws UnexpectedValueException | entailment |
public function save($filename = '', $quality = 100, $format = '')
{
if (empty($filename)) {
$filename = $this->filename;
}
if (empty($format)) {
$format = $this->format;
}
$arguments = array($this->image, $filename);
if (in_array($format, array('jpg', 'jpeg'))) {
$format = 'jpeg';
imageinterlace($this->image, true);
$arguments = array($this->image, $filename, round($quality));
} else if ($format === 'png') {
$arguments = array($this->image, $filename, round(9 * $quality / 100));
}
return $this->callFunction('image', $format, $arguments);
} | Save an image
@param string $filename
@param int|null $quality
@param string $format
@return bool | entailment |
public function indexDashboard()
{
$this->toggleIntroIndexDashboard();
$this->setDashboard(true);
$this->setTitleIndexDashboard();
$this->setDataContentIndexDashboard();
$this->outputIndexDashboard();
} | Displays the dashboard page | entailment |
protected function setDataContentIndexDashboard()
{
$columns = $this->config('dashboard_columns', 2);
$this->setData('columns', $columns);
$this->setData('dashboard', gplcart_array_split($this->data_dashboard['data'], $columns));
$stores = $this->store->getList(array('status' => 1));
$this->setData('no_enabled_stores', empty($stores));
if ($this->config('intro', false) && $this->isSuperadmin()) {
$this->setData('intro', $this->render('dashboard/intro'));
}
} | Sets a dashboard template data | entailment |
public function editDashboard()
{
$this->setDashboard(false);
$this->setTitleEditDashboard();
$this->setBreadcrumbEditDashboard();
$this->setData('dashboard', $this->data_dashboard);
$this->submitEditDashboard();
$this->outputEditDashboard();
} | Displays the edit dashboard page | entailment |
protected function setDashboard($active)
{
$dashboard = $this->dashboard->getList(array('user_id' => $this->uid, 'active' => $active));
$this->data_dashboard = $this->prepareDashboard($dashboard);
} | Sets an array of dashboard items
@param bool $active | entailment |
protected function prepareDashboard(array $dashboard)
{
foreach ($dashboard['data'] as &$item) {
$this->setItemRendered($item, array('content' => $item), array('template_item' => $item['template']));
}
return $dashboard;
} | Prepare an array of dashboard items
@param array $dashboard
@return array | entailment |
protected function submitEditDashboard()
{
if ($this->isPosted('save')) {
$this->validateEditDashboard();
$this->saveDashboard();
} else if ($this->isPosted('delete') && isset($this->data_dashboard['dashboard_id'])) {
$this->deleteDashboard();
}
} | Handles an array of submitted data | entailment |
protected function validateEditDashboard()
{
$submitted = $this->setSubmitted('dashboard');
foreach ($submitted as &$item) {
$item['status'] = !empty($item['status']);
$item['weight'] = intval($item['weight']);
}
$this->setSubmitted(null, $submitted);
} | Validates an array of submitted data | entailment |
protected function saveDashboard()
{
$this->controlAccess('dashboard_edit');
if ($this->dashboard->set($this->uid, $this->getSubmitted())) {
$this->redirect('', $this->text('Your dashboard has been updated'), 'success');
}
$this->redirect('', $this->text('Your dashboard has not been updated'), 'warning');
} | Saves submitted data | entailment |
protected function deleteDashboard()
{
$this->controlAccess('dashboard_edit');
if ($this->dashboard->delete($this->data_dashboard['dashboard_id'])) {
$message = $this->text('Your dashboard has been reset');
$this->redirect('', $message, 'success');
}
$this->redirect('admin', $this->text('Your dashboard has not been reset'), 'warning');
} | Deletes a saved a dashboard record | entailment |
public function set($path, array $data)
{
$data += array('path' => $path);
$bookmark = $this->get($data);
return empty($bookmark) ? (bool) $this->add($data) : false;
} | Add a bookmark if it doesn't exists for the path
@param string $path
@param array $data
@return boolean | entailment |
public static function register($debug = true, $charset = null, $fileLinkFormat = null)
{
$handler = new static($debug, $charset, $fileLinkFormat);
set_exception_handler(array($handler, 'handle'));
return $handler;
} | Registers the exception handler.
@param bool $debug
@return ExceptionHandler The registered exception handler | entailment |
public function handle(\Exception $exception)
{
// We need to make sure there are output buffers before we try to clean
$status = ob_get_status();
if (!empty($status)) {
ob_clean();
}
if (class_exists('PPI\Framework\Http\Response')) {
$this->createResponse($exception)->send();
} else {
$this->sendPhpResponse($exception);
}
} | Sends a response for the given Exception.
If you have the PPI Http component installed,
this method will use it to create and send the response. If not,
it will fallback to plain PHP functions.
@param \Exception $exception An \Exception instance
@see sendPhpResponse
@see createResponse | entailment |
public function sendPhpResponse($exception)
{
if (!$exception instanceof FlattenException) {
$exception = FlattenException::create($exception);
}
header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
foreach ($exception->getHeaders() as $name => $value) {
header($name . ': ' . $value, false);
}
echo $this->decorate($this->getContent($exception, $this->showAllExceptions), $this->getStylesheet($exception));
} | Sends the error associated with the given Exception as a plain PHP response.
This method uses plain PHP functions like header() and echo to output
the response.
@param \Exception|FlattenException $exception An \Exception instance | entailment |
public function createResponse($exception)
{
if (!$exception instanceof FlattenException) {
$exception = FlattenException::create($exception);
}
return new Response($this->decorate($this->getContent($exception, $this->showAllExceptions), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders());
} | Creates the error Response associated with the given Exception.
@param \Exception|FlattenException $exception An \Exception instance
@return Response A Response instance | entailment |
public function getContent(FlattenException $exception, $showAll = true)
{
switch ($exception->getStatusCode()) {
case 404:
$title = "The page you are looking for could not be found";
break;
default:
$title = "Oh noes, something's broken";
}
$content = '';
if ($this->debug) {
try {
$exceptions = $exception->toArray();
if (false === $showAll) {
$exceptions = array_slice($exceptions, -1, 1);
$count = 1;
$total = 1;
} else {
$count = count($exception->getAllPrevious());
$total = $count + 1;
}
foreach ($exceptions as $position => $e) {
$i = 0;
$class = $this->abbrClass($e['class']);
$message = nl2br($e['message']);
if (false === $showAll) {
$content .= sprintf(<<<EOT
<div>
<h3 class="alert alert-error">%s: %s</h3>
</div>
EOT
, $class, $message);
} else {
$ind = $count - $position + 1;
$content .= sprintf(<<<EOT
<div>
<h3 class="alert alert-error">%d/%d %s: %s</h3>
</div>
EOT
, $ind, $total, $class, $message);
}
$content .= <<<EOT
<div>
<table class="table table-bordered table-striped"><tbody>
EOT;
foreach ($e['trace'] as $trace) {
$i++;
$content .= ' <tr><td>' . $i . '</td><td>';
if ($trace['function']) {
$content .= sprintf('at %s%s%s(%s)', $this->abbrClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
}
if (isset($trace['file']) && isset($trace['line'])) {
if ($linkFormat = ini_get('xdebug.file_link_format')) {
$link = str_replace(array('%f', '%l'), array($trace['file'], $trace['line']), $linkFormat);
$content .= sprintf(' in <a href="%s" title="Go to source">%s line %s</a>', $link, $trace['file'], $trace['line']);
} else {
$content .= sprintf(' in %s line %s', $trace['file'], $trace['line']);
}
}
$content .= "</td</tr>\n";
}
$content .= " </tbody></table>\n</div>\n";
}
} catch (\Exception $e) {
// something nasty happened and we cannot throw an exception anymore
if ($this->debug) {
$title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($exception), $exception->getMessage());
} else {
$title = "Uh oh something's broken";
}
}
}
list($quote, $author) = $this->getQuote();
$statusCode = $exception->getStatusCode();
$ppiLogo = $this->getPpiLogo();
return <<<EOF
<div class="page-header well">
<h1 title="An exception has occurred - Code $statusCode"><img src="$ppiLogo" height="56" width="89"> $title.</h1>
<p class="muted quote"><i>"$quote"</i> — $author</p>
</div>
<div class="ppi-container well">
$content
</div>
EOF;
} | Gets the HTML content associated with the given exception.
@param FlattenException $exception A FlattenException instance
@param bool $showAll Show all exceptions or just the last one
@return string The content as a string | entailment |
private function formatArgs(array $args)
{
$result = array();
foreach ($args as $key => $item) {
if ('object' === $item[0]) {
$formattedValue = sprintf("<em>object</em>(%s)", $this->abbrClass($item[1]));
} elseif ('array' === $item[0]) {
$formattedValue = sprintf("<em>array</em>(%s)", is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
} elseif ('string' === $item[0]) {
$formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES | ENT_SUBSTITUTE, $this->charset));
} elseif ('null' === $item[0]) {
$formattedValue = '<em>null</em>';
} elseif ('boolean' === $item[0]) {
$formattedValue = '<em>' . strtolower(var_export($item[1], true)) . '</em>';
} elseif ('resource' === $item[0]) {
$formattedValue = '<em>resource</em>';
} else {
$formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES | ENT_SUBSTITUTE, $this->charset), true));
}
$result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
}
return implode(', ', $result);
} | Formats an array as a string.
@param array $args The argument array
@return string | entailment |
private function _loadDatabase()
{
if (!isset(self::$db[$this->name])) {
$config = Config::config()->{$this->name};
if(!is_array($config))
throw new \Exception ($config . ' not a valid db config');
// Load database
$db = new Database($config);
self::$db[$this->name] = $db;
self::$prefix = isset($config['prefix']) ? $config['prefix'] : '';
}
return $this->getDb();
} | Load database connection | entailment |
public function query($sql, $param = array(), $fetchAll = true)
{
if ($fetchAll)
$result = $this->getDb()->query($sql, $param)->fetchAll(\PDO::FETCH_OBJ);
else
$result = $this->getDb()->query($sql, $param)->fetch(\PDO::FETCH_OBJ);
if($result){
$this->_resetOperate(); // 清除options操作记录和绑定变量数组
}
return $result;
} | 读操作,从库操作用query | entailment |
public function execute($sql, $param = array())
{
$result = $this->getDb()->execute($sql, $param);
if($result) $this->_resetOperate(); // 清除options操作记录和绑定变量数组
return $result;
} | 写操作,主库操作用execute | entailment |
public function increment($increment = null, $value = null)
{
if(!isset($this->options['increment'])) $this->options['increment'] = array();
if(is_string($increment) && is_numeric($value))
$this->options['increment'][$increment] = $value;
elseif(is_array($increment) && is_null($value))
foreach($increment as $k => $v)
if(is_string($k) && is_numeric($v))
$this->options['increment'][$k] = $v;
return $this;
} | // For example:
$model->increment('foo', 1);
// Similarly:
$model->increment(['foo' => -1, 'bar' => 5]); | entailment |
public function findOne($id = NULL)
{
$this->options['limit']['0'] = 1;
if (!is_null($id)) {
$this->options['where']['0'] = $this->key . ' = ?';
$this->options['where']['1'] = array($id);
}
return $this->query($this->_parseSql(), $this->prepareParam, false);
} | 按主键查找一条记录,用链式操作 | entailment |
public function save($data = NULL, $replace = false)
{
if (is_null($data)) $data = $this->_data;
if (!$data) return NULL;
$this->createdAt && $data['created_at'] = $this->_getTime();
$this->updatedAt && $data['updated_at'] = $this->_getTime();
$columns = implode('`, `', array_keys($data));
$type = $replace ? 'REPLACE INTO' : 'INSERT INTO';
$sql = $type . ' ' . $this->getTableName() . ' (`' . $columns . '`) VALUES (' . rtrim(str_repeat('?, ', count($data)), ', ') . ')';
return $this->execute($sql, array_values($data)) ? $this->getDb()->pdo['master']->lastInsertId() : NULL;
} | 增加记录,支持传data数组或__set
@param array $data data array
@param boolean $replace if use replace into
@return int insert id | entailment |
public function batchSave($data = null)
{
if (is_null($data)) $data = $this->_data;
if (!$data) return NULL;
$one = current($data);
$num = count($one);
$columns = implode('`, `', array_keys($one));
$this->createdAt && $columns .= '`, `created_at`, `';
$this->updatedAt && $columns .= '`, `updated_at`, `';
$sql = 'INSERT INTO' . ' ' . $this->getTableName() . ' (`' . $columns . '`) VALUES ';
$param = array();
foreach($data as $v){
$sql .= '(' . rtrim(str_repeat('?, ', $num), ', ');
$this->createdAt && $sql .= ", '{$this->_getTime()}'";
$this->updatedAt && $sql .= ", '{$this->_getTime()}'";
$sql .= '), ';
$param = array_merge($param, array_values($v));
}
$sql = rtrim($sql, ', ');
return $this->execute($sql, $param) ? $this->getDb()->pdo['master']->lastInsertId() : NULL;
} | 批量插入到数据库 | entailment |
public function update($data = null, $all = false)
{
if (is_null($data)) $data = $this->_data;
if (!$data && !isset($this->options['increment'])) return NULL;
$this->updatedAt && $data['updated_at'] = $this->_getTime();
if($data)
$columns = '`' . implode('` = ?, `', array_keys($data)). '` = ?,';
else
$columns = '';
$increment = '';
if(isset($this->options['increment']) && $this->options['increment']) {
foreach ($this->options['increment'] as $field => $value)
$increment .= "`{$field}` = `$field` + {$value},";
$increment = rtrim($increment, ',');
}else{
$columns = rtrim($columns, ',');
}
$sql = 'UPDATE ' . $this->getTableName() . ' SET ' . $columns . $increment . ' WHERE ';
$params = array();
// 如果有设置主键
if (isset($data[$this->key])) {
$where = $this->key . ' = ?';
$params = array($data[$this->key]);
} elseif (isset($this->options['where']['0'])) { // 或者有设置where
$where = $this->options['where']['0'];
if (isset($this->options['where']['1'])) $params = $this->options['where']['1'];
} elseif ($all) { // 更新所有数据,慎用!
$where = '1 = 1';
} else {
return NULL;
}
if ($statement = $this->execute($sql . $where, $data ? array_merge(array_values($data), $params) : $params))
return $statement->rowCount();
else
return NULL;
} | 修改记录,支持传data数组或__set
@param array $data data array
@param boolean $all if update all record
@return mixed affect num rows | entailment |
public function delete($id = NULL, $all = false)
{
$params = array();
// 如果有指定id
if (!is_null($id)) {
$where = $this->key . ' = ?';
$params = array($id);
} elseif (isset($this->options['where']['0'])) { // 或者有设置where
$where = $this->options['where']['0'];
if (isset($this->options['where']['1'])) $params = $this->options['where']['1'];
} elseif ($all) // 删除所有数据,慎用!
$where = '1 = 1';
else
return NULL;
$sql = 'DELETE FROM ' . $this->getTableName() . ' WHERE ' . $where;
if ($statement = $this->execute($sql, $params))
return $statement->rowCount();
else
return NULL;
} | 删除数据,支持主键删除或where条件
@param int $id key id
@param boolean $all if update all record
@return mixed affect num rows | entailment |
private function _count($method, $column = NULL)
{
$this->options['limit']['0'] = 1;
if($method == 'distinct')
if(is_null($column)) // 默认id
$this->options['field']['0'] = 'count(' . $method . ' `' . $this->key . '`) as count';
else
$this->options['field']['0'] = 'count(' . $method . ' `' . $column . '`) as count';
elseif(is_null($column) && $method == 'count') // 默认*
$this->options['field']['0'] = $method . '(*) as count';
elseif($column)
$this->options['field']['0'] = $method . '(`' . $column . '`) as count';
else // 默认id
$this->options['field']['0'] = $method . '(`' . $this->key . '`) as count';
$result = $this->query($this->_parseSql(), $this->prepareParam, false);
return isset($result->count) ? $result->count : 0;
} | field()无效,不指定column时count(*),指定类似count('column_name'); // 不要加别名! | entailment |
private function _parseReturn($method, $operate = '', $options = null)
{
if ($operate) $operate = ' ' . $operate . ' ';
$string = (is_null($options) && isset($this->options[$method]['0'])) ? $this->options[$method]['0'] : $options;
if (isset($string)) {
if (in_array($method, array('table', 'join'))) {
$config = Config::config()->{$this->name};
$prefix = $config['prefix'];
unset($config);
$string = preg_replace_callback('/__([A-Z_-]+)__/sU', function ($match) use ($prefix) {
return '`' . $prefix . strtolower($match[1]) . '`';
}, $string);
}
return $operate . $string;
} else
return '';
} | $options为是否指定options的string内容,用在允许多次执行里面 | entailment |
protected function parametersToString(array $parameters)
{
$pieces = array();
foreach ($parameters as $key => $val) {
$pieces[] = sprintf('"%s": "%s"', $key, (is_string($val) ? $val : json_encode($val)));
}
return implode(', ', $pieces);
} | @param array $parameters
@return string | entailment |
public function addRows($rows)
{
foreach ($rows as $row) {
$this->inputRows[] = $row;
$inferredRow = $this->inferRow($row);
foreach ($this->getFieldNames() as $fieldName) {
/** @var BaseField $inferredField */
$inferredField = $inferredRow[$fieldName];
$inferredFieldType = $inferredField->getInferIdentifier($this->lenient);
if (!array_key_exists($fieldName, $this->fieldsPopularity)) {
$this->fieldsPopularity[$fieldName] = [];
$this->fieldsPopularityObjects[$fieldName] = [];
}
if (!array_key_exists($inferredFieldType, $this->fieldsPopularity[$fieldName])) {
$this->fieldsPopularity[$fieldName][$inferredFieldType] = 0;
$this->fieldsPopularityObjects[$fieldName][$inferredFieldType] = $inferredField;
}
++$this->fieldsPopularity[$fieldName][$inferredFieldType];
arsort($this->fieldsPopularity[$fieldName]);
}
}
} | add rows and updates the fieldsPopularity array - to make the inferred fields more accurate.
@param $rows
@throws FieldValidationException | entailment |
public function infer()
{
$bestInferredFields = [];
foreach ($this->fieldsPopularity as $fieldName => $fieldTypesPopularity) {
$bestInferredFields[$fieldName] = $this->inferField($fieldName, $fieldTypesPopularity);
}
return $bestInferredFields;
} | return the best inferred fields along with the best value casting according to the rows received so far.
@return array field name => inferred field object
@throws FieldValidationException | entailment |
protected function inferRow($row)
{
$rowFields = [];
foreach ($row as $k => $v) {
$rowFields[$k] = FieldsFactory::infer($v, (object) ['name' => $k], $this->lenient);
}
return $rowFields;
} | infer field objects for the given row
raises exception if fails to infer a field.
@param $row array field name => value to infer by
@return array field name => inferred field object
@throws FieldValidationException | entailment |
protected function inferField($fieldName, $fieldTypesPopularity)
{
// the $fieldTypesPopularity array is already sorted with most popular fields first
$inferredField = null;
foreach (array_keys($fieldTypesPopularity) as $inferredFieldType) {
/** @var BaseField $inferredField */
$inferredField = $this->fieldsPopularityObjects[$fieldName][$inferredFieldType];
try {
$rowNum = 0;
foreach ($this->inputRows as $inputRow) {
if (!array_key_exists($rowNum, $this->castRows)) {
$this->castRows[$rowNum] = [];
}
$this->castRows[$rowNum][$fieldName] = $inferredField->castValue($inputRow[$fieldName]);
++$rowNum;
}
break;
} catch (FieldValidationException $e) {
// a row failed validation for this field type, will continue to the next one according to popularity
continue;
}
}
return $inferredField;
} | finds the best inferred fields for the given field name according to the popularity
also updates the castRows array with the latest cast values.
@param $fieldName
@param $fieldTypesPopularity
@return BaseField|null | entailment |
public static function exec($command, array $params = array(), $mergeStdErr=true)
{
if (empty($command)) {
throw new \InvalidArgumentException('Command line is empty');
}
$command = self::bindParams($command, $params);
if ($mergeStdErr) {
// Redirect stderr to stdout to include it in $output
$command .= ' 2>&1';
}
exec($command, $output, $code);
if (count($output) === 0) {
$output = $code;
} else {
$output = implode(PHP_EOL, $output);
}
if ($code !== 0) {
throw new CommandException($command, $output, $code);
}
return $output;
} | Execute command with params.
@param string $command
@param array $params
@return bool|string
@throws \Exception | entailment |
public static function bindParams($command, array $params)
{
$wrappers = array();
$converters = array();
foreach ($params as $key => $value) {
// Escaped
$wrappers[] = '{' . $key . '}';
$converters[] = escapeshellarg(is_array($value) ? implode(' ', $value) : $value);
// Unescaped
$wrappers[] = '{!' . $key . '!}';
$converters[] = is_array($value) ? implode(' ', $value) : $value;
}
return str_replace($wrappers, $converters, $command);
} | Bind params to command.
@param string $command
@param array $params
@return string | entailment |
public function listSection($parent)
{
$this->controlAccess('admin');
$this->setTitleListSection($parent);
$this->setBreadcrumbListSection();
$this->setDataListSection($parent);
$this->outputListSection();
} | Displays the admin section page
@param string $parent | entailment |
protected function setDataListSection($parent)
{
$options = array(
'parent_url' => $parent,
'template' => 'section/menu'
);
$this->setData('menu', $this->getWidgetAdminMenu($this->route, $options));
} | Sets template data on the admin section page
@param string $parent | entailment |
protected function setTitleListSection($parent)
{
foreach ($this->route->getList() as $route) {
if (isset($route['menu']['admin']) && isset($route['arguments']) && in_array($parent, $route['arguments'])) {
$this->setTitle($route['menu']['admin']);
break;
}
}
} | Sets titles on the admin section page
@param string $parent | entailment |
protected function findTemplate($template)
{
$logicalName = (string) $template;
if (isset($this->cache[$logicalName])) {
return $this->cache[$logicalName];
}
$file = null;
$previous = null;
try {
$template = $this->parser->parse($template);
try {
$file = $this->locator->locate($template);
} catch (\InvalidArgumentException $e) {
$previous = $e;
}
} catch (\Exception $e) {
try {
$file = parent::findTemplate($template);
} catch (\Twig_Error_Loader $e) {
$previous = $e;
}
}
if (false === $file || null === $file) {
throw new \Twig_Error_Loader(sprintf('Unable to find template "%s".', $logicalName), -1, null, $previous);
}
return $this->cache[$logicalName] = $file;
} | Returns the path to the template file.
The file locator is used to locate the template when the naming convention
is the symfony one (i.e. the name can be parsed).
Otherwise the template is located using the locator from the twig library.
@param string|TemplateReferenceInterface $template The template
@throws \Twig_Error_Loader if the template could not be found
@return string The path to the template file | entailment |
public function listUser()
{
$this->actionListUser();
$this->setTitleListUser();
$this->setBreadcrumbListUser();
$this->setFilterListUser();
$this->setPagerListUser();
$this->setData('roles', $this->role->getList());
$this->setData('users', $this->getListUser());
$this->outputListUser();
} | Displays the users overview page | entailment |
protected function setPagerListUser()
{
$options = $this->query_filter;
$options['count'] = true;
$pager = array(
'query' => $this->query_filter,
'total' => (int) $this->user->getList($options)
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function actionListUser()
{
list($selected, $action, $value) = $this->getPostedAction();
$deleted = $updated = 0;
foreach ($selected as $uid) {
if ($this->isSuperadmin($uid)) {
continue;
}
if ($action === 'status' && $this->access('user_edit')) {
$updated += (int) $this->user->update($uid, array('status' => $value));
}
if ($action === 'delete' && $this->access('user_delete')) {
$deleted += (int) $this->user->delete($uid);
}
}
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 users | entailment |
protected function getListUser()
{
$conditions = $this->query_filter;
$conditions['limit'] = $this->data_limit;
$list = (array) $this->user->getList($conditions);
$this->prepareListUser($list);
return $list;
} | Returns an array of users
@return array | entailment |
protected function prepareListUser(array &$list)
{
$stores = $this->store->getList();
foreach ($list as &$item) {
$item['url'] = '';
if (isset($stores[$item['store_id']])) {
$item['url'] = $this->store->getUrl($stores[$item['store_id']]) . "/account/{$item['user_id']}";
}
}
} | Prepare an array of users
@param array $list | entailment |
public function editUser($user_id = null)
{
$this->setUser($user_id);
$this->setTitleEditUser();
$this->setBreadcrumbEditUser();
$this->controlAccessEditUser($user_id);
$this->setData('user', $this->data_user);
$this->setData('roles', $this->role->getList());
$this->setData('can_delete', $this->canDeleteUser());
$this->setData('is_superadmin', $this->isSuperadminUser());
$this->setData('password_limit', $this->user->getPasswordLength());
$this->submitEditUser();
$this->outputEditUser();
} | Displays the user edit page
@param integer|null $user_id | entailment |
protected function canDeleteUser()
{
return isset($this->data_user['user_id'])
&& $this->access('user_delete')
&& $this->user->canDelete($this->data_user['user_id']);
} | Whether the user can be deleted
@return boolean | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.