sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function setAddressFormCheckout()
{
$this->show_payment_address_form = $this->isSubmitted('address.payment');
$this->show_shipping_address_form = $this->isSubmitted('address.shipping');
$actions = array(
'get_states' => true,
'add_address' => true,
'cancel_address_form' => false
);
foreach ($actions as $field => $action) {
$value = $this->getPosted($field, '', true, 'string');
if (isset($value)) {
$this->{"show_{$value}_address_form"} = $action;
}
}
} | Controls state of address forms (open/closed) | entailment |
protected function submitAddAddressCheckout()
{
$type = $this->getPosted('save_address', '', true, 'string');
if (empty($type)) {
return null;
}
$errors = $this->validateAddressCheckout($type);
if (empty($errors)) {
$this->addAddressCheckout($type);
$this->{"show_{$type}_address_form"} = false;
}
} | Saves a submitted address | entailment |
protected function loginCheckout()
{
$result = $this->user_action->login($this->getSubmitted('user'));
if (isset($result['user'])) {
$result = $this->cart_action->login($result['user'], $this->data_cart);
}
if (!empty($result['user'])) {
$this->redirect($result['redirect'], $result['message'], $result['severity']);
}
$this->setError('login', $result['message']);
} | Log in a customer during checkout | entailment |
protected function validateCouponCheckout()
{
$price_rule_id = $this->getPosted('check_pricerule', null, true, 'integer');
if (empty($price_rule_id)) {
return null;
}
$code = $this->getSubmitted('data.pricerule_code', '');
if ($code === '') {
return null;
}
if (!$this->order->priceRuleCodeMatches($price_rule_id, $code)) {
$this->setError('pricerule_code', $this->text('Invalid code'));
$this->setMessageFormCheckout('components.danger', $this->text('Invalid code'));
}
} | Validates a coupon code | entailment |
protected function submitCartItemsCheckout()
{
$items = $this->getSubmitted('cart.items');
if (empty($items)) {
return null;
}
$errors = array();
foreach ($items as $sku => $item) {
$errors += $this->validateCartItemCheckout($sku, $item);
if (empty($errors)) {
$this->updateCartQuantityCheckout($sku, $item);
}
}
if (empty($errors)) {
$this->setSubmitted('cart.action.update', true);
} else {
$this->setMessageFormCheckout('cart.danger', $errors);
}
} | Applies an action to the cart items | entailment |
protected function setMessageFormCheckout($key, $message)
{
gplcart_array_set($this->data_form['messages'], $key, $this->format($message));
} | Sets an array of messages on the checkout form
@param string $key
@param string|array $message | entailment |
protected function updateCartQuantityCheckout($sku, array $item)
{
if (isset($this->data_cart['items'][$sku]['cart_id'])) {
$cart_id = $this->data_cart['items'][$sku]['cart_id'];
$this->cart->update($cart_id, array('quantity' => $item['quantity']));
}
} | Updates cart quantity
@param string $sku
@param array $item | entailment |
protected function validateCartItemCheckout($sku, $item)
{
$item += array(
'sku' => $sku,
'increment' => false,
'admin' => !empty($this->admin),
'user_id' => $this->order_user_id,
'store_id' => $this->order_store_id
);
$this->setSubmitted('update', $item);
$this->setSubmitted("cart.items.$sku", $item);
return $this->validateComponent('cart', array('parents' => "cart.items.$sku"));
} | Validates a cart item and returns possible errors
@param string $sku
@param array $item
@return array | entailment |
protected function deleteCartCheckout()
{
$cart_id = $this->getSubmitted('cart.action.delete');
if (!empty($cart_id)) {
$this->setSubmitted('cart.action.update', true);
$this->cart->delete($cart_id);
}
} | Deletes an item from the cart | entailment |
protected function submitOrderCheckout()
{
if (!$this->isPosted('save')) {
return null;
}
$errors = array();
foreach (array('payment', 'shipping') as $type) {
$address_errors = $this->validateAddressCheckout($type);
if (!empty($address_errors)) {
$errors = gplcart_array_merge($errors, $address_errors);
}
if (empty($address_errors)) {
$this->addAddressCheckout($type);
}
}
$order_errors = $this->validateOrderCheckout();
$errors = gplcart_array_merge($errors, $order_errors);
if (empty($errors)) {
$this->addOrderCheckout();
} else {
$this->setError(null, $errors);
}
} | Saves an order to the database | entailment |
protected function validateOrderCheckout()
{
if ($this->same_payment_address) {
$this->unsetSubmitted('address.payment');
}
$this->setSubmitted('update', array());
$this->setSubmitted('store_id', $this->store_id);
$this->setSubmitted('user_id', $this->order_user_id);
$this->setSubmitted('creator', $this->admin_user_id);
if ($this->admin) {
$this->setSubmitted('status', $this->order->getStatusInitial());
}
return $this->validateComponent('order');
} | Validates an array of submitted data before creating an order
@return array | entailment |
protected function addAddressCheckout($type)
{
$submitted = $this->getSubmitted("address.$type");
if ($this->{"show_{$type}_address_form"} && !empty($submitted)) {
$address_id = $this->address->add($submitted);
$this->setSubmitted("{$type}_address", $address_id);
foreach ($this->address->getExceeded($this->order_user_id) as $address) {
$this->address->delete($address['address_id']);
}
}
} | Adds a submitted address
@param string $type | entailment |
protected function addOrderCheckout()
{
$submitted = $this->getSubmittedOrderCheckout();
$result = $this->order_action->add($submitted, array('admin' => $this->admin));
$this->finishOrderCheckout($result);
} | Adds a new order | entailment |
protected function finishOrderCheckout(array $result)
{
if ($this->admin === 'add') {
$this->finishAddOrderCheckout($result);
} else if ($this->admin === 'clone') {
$this->finishCloneOrderCheckout($result);
}
$this->redirect($result['redirect'], $result['message'], $result['severity']);
} | Performs final tasks after an order has been created
@param array $result | entailment |
protected function finishAddOrderCheckout(array $result)
{
if (!empty($result['order']['order_id'])) {
$vars = array(
'@num' => $result['order']['order_id'],
'@name' => $result['order']['customer_name'],
'@status' => $this->order->getStatusName($result['order']['status'])
);
$message = $this->text('Order #@num has been created for user @name. Order status: @status', $vars);
$this->redirect("admin/sale/order/{$result['order']['order_id']}", $message, 'success');
}
} | Performs final tasks after an order has been added for a user
@param array $result | entailment |
protected function finishCloneOrderCheckout(array $result)
{
if (!empty($result['order']['order_id'])) {
$log = array(
'user_id' => $this->uid,
'order_id' => $this->data_order['order_id'],
'text' => $this->text('Cloned into order #@num', array('@num' => $result['order']['order_id']))
);
$this->order_history->add($log);
$vars = array(
'@num' => $this->data_order['order_id'],
'@url' => $this->url("admin/sale/order/{$this->order_id}"),
'@status' => $this->order->getStatusName($result['order']['status'])
);
$message = $this->text('Order has been cloned from order <a href="@url">@num</a>. Order status: @status', $vars);
$this->redirect("admin/sale/order/{$result['order']['order_id']}", $message, 'success');
}
} | Performs final tasks after an order has been cloned
@param array $result | entailment |
protected function getSubmittedOrderCheckout()
{
$submitted = $this->getSubmitted();
$submitted += $this->data_form['order'];
$submitted['cart'] = $this->data_cart;
$submitted['data']['user'] = array(
'ip' => $this->server->remoteAddr(),
'agent' => $this->server->userAgent()
);
if (empty($this->admin)) {
return $submitted;
}
// Convert decimal prices from inputs in admin mode
$submitted['total'] = $this->price->amount($submitted['total'], $submitted['currency']);
if (empty($submitted['data']['components'])) {
return $submitted;
}
$this->prepareSubmittedOrderComponentsCheckout($submitted);
return $submitted;
} | Returns an array of prepared submitted order data
@return array | entailment |
protected function prepareSubmittedOrderComponentsCheckout(array &$submitted)
{
foreach ($submitted['data']['components'] as $id => &$component) {
if (!isset($component['price'])) {
continue;
}
if (empty($component['price'])) {
unset($submitted['data']['components'][$id]);
continue;
}
$component['currency'] = $submitted['currency'];
$component['price'] = $this->price->amount($component['price'], $submitted['currency']);
}
} | Prepare submitted order components
@param array $submitted | entailment |
protected function prepareOrderComponentsCheckout($calculated)
{
$component_types = $this->order->getComponentTypes();
$components = array();
foreach ($calculated['components'] as $type => $component) {
$components[$type] = array(
'price' => $component['price'],
'price_decimal' => $this->price->decimal($component['price'], $calculated['currency']),
'price_formatted' => $this->price->format($component['price'], $calculated['currency'])
);
if (empty($component['rule'])) {
$components[$type]['name'] = $component_types[$type];
continue;
}
$components[$type]['rule'] = $component['rule'];
$components[$type]['name'] = $component['rule']['name'];
}
return $components;
} | Prepares an array of price rule components
@param array $calculated
@return array | entailment |
protected function setDataFormCheckout()
{
$form = $this->render('checkout/form', $this->data_form, true);
if ($this->isAjax()) {
$this->response->outputHtml($form);
}
$this->setData('checkout_form', $form);
} | Sets form on the checkout page | entailment |
public static function add($key, $path)
{
self::$_registeredNamespaces[$key] = true;
self::$_options['loader']->addPsr4($key, $path);
} | Add a namespace to the autoloader path.
@param string $key
@param string $path
@static | entailment |
public function setContext($context, array $options = array())
{
if (!isset($context)) {
$context = stream_context_create((array) $context, $options);
}
if (!is_resource($context)) {
throw new UnexpectedValueException('Stream context is not a valid resource');
}
$this->context = $context;
return $this;
} | Sets the context resource
@param resource|array $context
@param array $options
@return $this
@throws UnexpectedValueException | entailment |
public function setUri($uri)
{
if (!is_array($uri)) {
$uri = parse_url($uri);
}
$this->uri = $uri;
return $this;
} | Sets the request URI
@param string|array $uri
@return $this | entailment |
public function setSocket()
{
if (empty($this->uri['scheme'])) {
throw new OutOfBoundsException('Unknown URL scheme');
}
if ($this->uri['scheme'] === 'http') {
$port = 80;
$protocol = 'tcp';
} else if ($this->uri['scheme'] === 'https') {
$port = 443;
$protocol = 'ssl';
} else {
throw new UnexpectedValueException("Unsupported URL scheme: {$this->uri['scheme']}");
}
if (isset($this->uri['port'])) {
$port = $this->uri['port'];
}
$this->socket = "$protocol://{$this->uri['host']}:$port";
if (!isset($this->headers['Host'])) {
$this->headers['Host'] = "{$this->uri['host']}:$port";
}
return $this;
} | Sets a socket depending on the current URI parameters
@return $this
@throws OutOfBoundsException
@throws UnexpectedValueException | entailment |
public function exec()
{
$this->response = '';
$errno = $errstr = null;
if (isset($this->context)) {
$this->stream = stream_socket_client($this->socket, $errno, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $this->context);
} else {
$this->stream = stream_socket_client($this->socket, $errno, $errstr, $this->timeout);
}
if (!empty($errstr)) {
throw new UnexpectedValueException($errstr);
}
fwrite($this->stream, $this->getRequestBody());
while (!feof($this->stream)) {
$this->response .= fgets($this->stream, 1024);
}
fclose($this->stream);
$this->stream = null;
return $this;
} | Open Internet or Unix domain socket connection and execute a query
@throws UnexpectedValueException
@return $this | entailment |
protected function getRequestBody()
{
if (is_array($this->data)) {
$this->data = http_build_query($this->data);
}
$this->prepareHeaders();
$path = isset($this->uri['path']) ? $this->uri['path'] : '/';
if (isset($this->uri['query'])) {
$path .= "?{$this->uri['query']}";
}
$body = "{$this->method} $path HTTP/1.0\r\n";
foreach ($this->headers as $name => $value) {
$body .= "$name: " . trim($value) . "\r\n";
}
$body .= "\r\n{$this->data}";
return $body;
} | Returns the request body
@return string | entailment |
protected function prepareHeaders()
{
if (!isset($this->headers['Content-Length'])) {
$content_length = strlen($this->data);
if ($content_length > 0 || $this->method === 'POST' || $this->method === 'PUT') {
$this->headers['Content-Length'] = $content_length;
}
}
if (isset($this->uri['user']) && !isset($this->headers['Authorization'])) {
$pass = isset($this->uri['pass']) ? ':' . $this->uri['pass'] : ':';
$this->headers['Authorization'] = 'Basic ' . base64_encode($this->uri['user'] . $pass);
}
} | Prepare request headers | entailment |
public function getFormattedResponse()
{
list($header, $data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $this->response, 2);
$headers = preg_split("/\r\n|\n|\r/", $header);
$status = explode(' ', trim(reset($headers)), 3);
$result = array(
'status' => '',
'http' => $status[0],
'code' => $status[1]
);
if (isset($status[2])) {
$result['status'] = $status[2];
}
return array('data' => $data, 'status' => $result);
} | Returns an array of formatted response
@return array | entailment |
public function request($url, array $options = array())
{
$options += array(
'data' => null,
'timeout' => 30,
'context' => null,
'method' => 'GET',
'headers' => array()
);
if ($options['method'] === 'POST' && empty($options['headers'])) {
$options['headers'] = array('Content-Type' => 'application/x-www-form-urlencoded');
}
if (!empty($options['query'])) {
$url = strtok($url, '?') . '?' . http_build_query($options['query']);
}
return $this->setUri($url)
->setHeaders($options['headers'])
->setMethod($options['method'])
->setData($options['data'])
->setTimeOut($options['timeout'])
->setContext($options['context'])
->setSocket()
->exec()
->getFormattedResponse();
} | Shortcut method to perform an HTTP request
@param string $url
@param array $options
@return array | entailment |
public function get($condition)
{
$result = null;
$this->hook->attach('collection.get.before', $condition, $result, $this);
if (isset($result)) {
return $result;
}
if (!is_array($condition)) {
$condition = array('collection_id' => $condition);
}
$condition['limit'] = array(0, 1);
$list = (array) $this->getList($condition);
$result = empty($list) ? array() : reset($list);
$this->hook->attach('collection.get.after', $condition, $result, $this);
return $result;
} | Loads a collection from the database
@param array|int|string $condition
@return array | entailment |
public function canDelete($collection_id)
{
$sql = 'SELECT collection_item_id FROM collection_item WHERE collection_id=?';
$result = $this->db->fetchColumn($sql, array($collection_id));
return empty($result);
} | Whether a collection can be deleted
@param integer $collection_id
@return boolean | entailment |
public function getTypes()
{
$handlers = $this->getHandlers();
$types = array();
foreach ($handlers as $handler_id => $handler) {
$types[$handler_id] = $handler['title'];
}
return $types;
} | Returns an array of collection type names keyed by a handler ID
@return array | entailment |
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('ApplicationConfig');
$allConnections = $libraryToConnMap = $configMap = array();
// Early return
if (!isset($config['datasource']['connections'])) {
return new ConnectionManager($allConnections, $this->connectionClassMap);
}
foreach ($config['datasource']['connections'] as $name => $config) {
$allConnections[$name] = $config;
$configMap[$config['library']][$name] = $config;
}
return new ConnectionManager($allConnections, $this->connectionClassMap);
} | Create and return the datasource service.
@param ServiceLocatorInterface $serviceLocator
@return \PPI\Framework\DataSource\DataSource; | entailment |
public function display($tpl = '')
{
$tpl || $tpl = Url::pathInfo();
if($this->layout){
self::$content = $this->_getContent($tpl);
$content = $this->_getContent($this->layout);
}else
$content = $this->_getContent($tpl);
$this->addToken($content);
headers_sent() || header('Content-Type: text/html; charset=utf-8');
echo $content;
} | 模板显示
指定layout的情况下使用子模板模式,不指定直接显示当前模板 | entailment |
public function includeTpl($tpl)
{
foreach ($this->tplVar as $k => $v) $$k = $v;
require(Config::$viewDir . $tpl . '.php');
} | 模板文件中包含其他模板文件方法 | entailment |
private function _buildToken()
{
if (!Session::get($this->tokenName))
Session::set($this->tokenName, array());
$tokenKey = md5($_SERVER['REQUEST_URI']);
$tName = Session::get($this->tokenName);
if (isset($tName[$tokenKey])) // 相同页面不重复生成session
$tokenValue = $tName[$tokenKey];
else {
$tokenValue = md5(microtime(TRUE));
Session::set($this->tokenName, array($tokenKey => $tokenValue), true);
}
$token = '<input type="hidden" name="' . $this->tokenName . '" value="' . $tokenKey . '_' . $tokenValue . '" />';
return $token;
} | 创建表单令牌 | entailment |
public function index($product)
{
if (is_numeric($product)) {
$product = $this->product->get($product);
}
if (empty($product)) {
return false;
}
$indexed = 0;
$indexed += (int) $this->indexProduct($product);
$indexed += (int) $this->indexProductTranslations($product);
return $indexed > 0;
} | Indexes a product
@param integer|array $product
@return boolean | entailment |
public function search($query, array $data)
{
$sql = 'SELECT si.entity_id';
if (!empty($data['count'])) {
$sql = 'SELECT COUNT(si.entity_id)';
}
$conditions = array($query, $data['language'], 'und', 'product');
$sql .= ' FROM search_index si
LEFT JOIN product p ON(p.product_id = si.entity_id)
WHERE MATCH(si.text) AGAINST (? IN BOOLEAN MODE)
AND (si.language=? OR si.language=?)
AND si.entity=? AND p.product_id IS NOT NULL';
if (isset($data['status'])) {
$sql .= ' AND p.status=?';
$conditions[] = (int) $data['status'];
}
if (isset($data['store_id'])) {
$sql .= ' AND p.store_id=?';
$conditions[] = (int) $data['store_id'];
}
if (empty($data['count'])) {
$sql .= ' GROUP BY si.entity_id';
}
if (!empty($data['limit'])) {
$sql .= ' LIMIT ' . implode(',', array_map('intval', $data['limit']));
}
if (!empty($data['count'])) {
return $this->config->getDb()->fetchColumn($sql, $conditions);
}
$data['product_id'] = $this->config->getDb()->fetchColumnAll($sql, $conditions);
if (empty($data['product_id'])) {
return array();
}
unset($data['language']);
return $this->product->getList($data);
} | Returns an array of suggested products for a given query
@param string $query
@param array $data
@return array | entailment |
protected function indexProduct(array $product)
{
$snippet = $this->search->getSnippet($product, 'und');
return $this->search->setIndex($snippet, 'product', $product['product_id'], 'und');
} | Adds the main product data to the search index
@param array $product
@return boolean | entailment |
protected function indexProductTranslations(array $product)
{
if (empty($product['translation'])) {
return false;
}
$indexed = 0;
foreach ($product['translation'] as $language => $translation) {
$translation += $product;
$snippet = $this->search->getSnippet($translation, $language);
$indexed += (int) $this->search->setIndex($snippet, 'product', $product['product_id'], $language);
}
return $indexed > 0;
} | Adds product translations to the search index
@param array $product
@return boolean | entailment |
public function init($config)
{
$this->pdo = null;
$dns = '';
if (is_array($config)) {
$config += array('user' => null, 'password' => null);
$dns = "{$config['type']}:host={$config['host']};port={$config['port']};dbname={$config['name']}";
} else if (is_string($config)) {
$dns = $config;
} else if ($config instanceof PDO) {
$this->pdo = $config;
return $this;
}
try {
// Use pipe for merging fields - sqlite compatibility
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode='PIPES_AS_CONCAT'");
$this->pdo = new PDO($dns, $config['user'], $config['password'], $options);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
$this->pdo = null;
throw new RuntimeException('Cannot connect to database: ' . $ex->getMessage());
}
return $this;
} | Set up database connection
@param mixed $config
@throws RuntimeException
@return $this | entailment |
public function query($sql)
{
$result = $this->pdo->query($sql);
$this->executed[] = $sql;
return $result;
} | Executes an SQL statement, returning a result set as a PDOStatement object
@param string $sql
@return \PDOStatement|false | entailment |
public function exec($sql)
{
$result = $this->pdo->exec($sql);
$this->executed[] = $sql;
return $result;
} | Execute an SQL statement and return the number of affected rows
@param string $sql
@return integer | entailment |
public function fetchColumn($sql, array $params = array(), $pos = 0)
{
return $this->run($sql, $params)->fetchColumn($pos);
} | Returns a single column
@param string $sql
@param array $params
@param integer $pos
@return mixed | entailment |
public function run($sql, array $params = array())
{
$sth = $this->pdo->prepare($sql);
foreach ($params as $key => $value) {
$key = is_numeric($key) ? $key + 1 : ":$key";
$sth->bindValue($key, $value);
}
$sth->execute($params);
$this->executed[] = $sql;
return $sth;
} | Runs a SQL query with an array of placeholders
@param string $sql
@param array $params
@return \PDOStatement | entailment |
public function fetchColumnAll($sql, array $params = array(), $pos = 0)
{
return $this->run($sql, $params)->fetchAll(PDO::FETCH_COLUMN, $pos);
} | Returns a simple array of columns
@param string $sql
@param array $params
@param integer $pos
@return mixed | entailment |
public function fetch($sql, array $params, array $options = array())
{
$sth = $this->run($sql, $params);
$result = $sth->fetch(PDO::FETCH_ASSOC);
$this->prepareResult($result, $options);
return empty($result) ? array() : (array) $result;
} | Returns a single array indexed by column name
@param string $sql
@param array $params
@param array $options
@return array | entailment |
protected function prepareResult(&$data, array $options)
{
if (!empty($options['unserialize']) && !empty($data)) {
foreach ((array) $options['unserialize'] as $field) {
$data[$field] = empty($data[$field]) ? array() : unserialize($data[$field]);
}
}
} | Prepares a single result
@param mixed $data
@param array $options | entailment |
public function fetchAll($sql, array $params, array $options = array())
{
$result = $this->run($sql, $params)->fetchAll(PDO::FETCH_ASSOC);
$this->prepareResults($result, $options);
return empty($result) ? array() : (array) $result;
} | Returns an array of database records
@param string $sql
@param array $params
@param array $options
@return array | entailment |
protected function prepareResults(array &$results, array $options)
{
$reindexed = array();
foreach ($results as &$result) {
$this->prepareResult($result, $options);
if (!empty($options['index'])) {
$reindexed[$result[$options['index']]] = $result;
}
}
if (!empty($options['index'])) {
$results = $reindexed;
}
} | Prepares an array of results
@param array $results
@param array $options | entailment |
public function insert($table, array $data, $prepare = true)
{
if ($prepare) {
$data = $this->prepareInsert($table, $data);
}
if (empty($data)) {
return '0';
}
$keys = array_keys($data);
$fields = implode(',', $keys);
$values = ':' . implode(',:', $keys);
$this->run("INSERT INTO $table ($fields) VALUES ($values)", $data);
return $this->pdo->lastInsertId();
} | Performs an INSERT query
@param $table
@param array $data
@param bool $prepare
@return string | entailment |
public function update($table, array $data, array $conditions, $filter = true)
{
if ($filter) {
$data = $this->filterValues($table, $data);
}
if (empty($data)) {
return 0;
}
$farray = array();
foreach (array_keys($data) as $key) {
$farray[] = "$key=:$key";
}
$carray = array();
foreach (array_keys($conditions) as $key) {
$carray[] = "$key=:$key";
}
$fields = implode(',', $farray);
$sql = "UPDATE $table SET $fields WHERE " . implode(' AND ', $carray);
$stmt = $this->pdo->prepare($sql);
foreach ($data as $key => $value) {
$stmt->bindValue(":$key", $value);
}
foreach ($conditions as $key => $value) {
$stmt->bindValue(":$key", $value);
}
$stmt->execute();
$this->executed[] = $sql;
return $stmt->rowCount();
} | Performs a UPDATE query
@param $table
@param array $data
@param array $conditions
@param bool $filter
@return integer | entailment |
public function delete($table, array $conditions)
{
if (empty($conditions)) {
return 0;
}
$carray = array();
foreach (array_keys($conditions) as $key) {
$carray[] = "$key=:$key";
}
$sql = "DELETE FROM $table WHERE " . implode(' AND ', $carray);
return $this->run($sql, $conditions)->rowCount();
} | Performs a DELETE query
@param string $table
@param array $conditions
@return integer | entailment |
public function prepareInsert($table, array $data)
{
$data += $this->getDefaultValues($table);
return $this->filterValues($table, $data);
} | Returns an array of prepared values ready to insert into the database
@param string $table
@param array $data
@return array | entailment |
public function getDefaultValues($table)
{
$scheme = $this->getScheme($table);
$values = array();
foreach ($scheme['fields'] as $name => $info) {
if (array_key_exists('default', $info)) {
$values[$name] = $info['default'];
continue;
}
if (!empty($info['serialize'])) {
$values[$name] = array();
}
}
return $values;
} | Returns an array of default field values for the given table
@param string $table
@return array | entailment |
public function getScheme($table = null)
{
$default = (array) gplcart_config_get(GC_FILE_CONFIG_DATABASE);
$scheme = array_merge($this->scheme, $default);
if (isset($table)) {
if (empty($scheme[$table]['fields'])) {
throw new OutOfBoundsException("Database table $table either does not exist or has invalid structure");
}
return $scheme[$table];
}
return $scheme;
} | Returns an array of database scheme
@param string|null $table
@return array
@throws OutOfBoundsException | entailment |
protected function filterValues($table, array $data)
{
$scheme = $this->getScheme($table);
$values = array_intersect_key($data, $scheme['fields']);
if (empty($values)) {
return array();
}
foreach ($values as $field => &$value) {
if (!empty($scheme['fields'][$field]['auto_increment'])) {
unset($values[$field]);
continue;
}
if (is_null($value) && !empty($scheme['fields'][$field]['not_null'])) {
unset($values[$field]);
continue;
}
if (!empty($scheme['fields'][$field]['serialize'])) {
if (!is_array($value)) {
$value = array();
}
$value = serialize($value);
}
}
return $values;
} | Filters an array of data according to existing scheme for the given table
@param string $table
@param array $data
@return array | entailment |
public function tableExists($table)
{
$result = $this->query("SHOW TABLES LIKE " . $this->pdo->quote($table));
return $result->rowCount() > 0;
} | Check if a table already exists
@param string $table
@return bool | entailment |
public function import(array $tables)
{
foreach ($tables as $table => $data) {
if (!$this->query($this->getSqlCreateTable($table, $data))) {
throw new RuntimeException("Failed to import database table $table");
}
$alter = $this->getSqlAlterTable($table, $data);
if (!empty($alter) && !$this->query($alter)) {
throw new RuntimeException("Failed to alter table $table");
}
}
} | Creates tables using an array of scheme data
@param array $tables
@throws RuntimeException | entailment |
public function importScheme($table, array $scheme)
{
if ($this->tableExists($table)) {
throw new RuntimeException('Table already exists');
}
try {
$this->import($scheme);
} catch (Exception $ex) {
$this->deleteTable($table);
throw new RuntimeException("Failed to import database table $table: " . $ex->getMessage());
}
} | Install a database table using the scheme
@param string $table
@param array $scheme
@throws RuntimeException | entailment |
protected function getSqlFields(array $fields)
{
$sql = array();
foreach ($fields as $name => $info) {
if (strpos($info['type'], 'text') !== false || $info['type'] === 'blob') {
unset($info['default']);
}
$string = "{$info['type']}";
if (isset($info['length'])) {
$string .= "({$info['length']})";
}
if (!empty($info['not_null'])) {
$string .= " NOT NULL";
}
if (isset($info['default'])) {
$string .= " DEFAULT '{$info['default']}'";
}
if (!empty($info['primary'])) {
$string .= " PRIMARY KEY";
}
if (!empty($info['auto_increment'])) {
$string .= " /*!40101 AUTO_INCREMENT */"; // SQLite will ignore this comment
}
$sql[] = $name . ' ' . trim($string);
}
return implode(',', $sql);
} | Returns a SQL that describes table fields.
Used to create tables
@param array $fields
@return string | entailment |
public function listZone()
{
$this->actionListZone();
$this->setTitleListZone();
$this->setBreadcrumbListZone();
$this->setFilterListZone();
$this->setPagerListZone();
$this->setData('zones', $this->getListZone());
$this->outputListZone();
} | Displays the zone overview page | entailment |
public function setPagerListZone()
{
$options = $this->query_filter;
$options['count'] = true;
$pager = array(
'query' => $this->query_filter,
'total' => (int) $this->zone->getList($options)
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function getListZone()
{
$conditions = $this->query_filter;
$conditions['limit'] = $this->data_limit;
return $this->zone->getList($conditions);
} | Returns an array of zones
@return array | entailment |
public function editZone($zone_id = null)
{
$this->setZone($zone_id);
$this->setTitleEditZone();
$this->setBreadcrumbEditZone();
$this->setData('zone', $this->data_zone);
$this->setData('can_delete', $this->canDeleteZone());
$this->submitEditZone();
$this->outputEditZone();
} | Displays the zone edit page
@param null|integer $zone_id | entailment |
protected function canDeleteZone()
{
return isset($this->data_zone['zone_id'])
&& $this->zone->canDelete($this->data_zone['zone_id'])
&& $this->access('zone_delete');
} | Whether the zone can be deleted
@return bool | entailment |
protected function setZone($zone_id)
{
$this->data_zone = array();
if (is_numeric($zone_id)) {
$this->data_zone = $this->zone->get($zone_id);
if (empty($this->data_zone)) {
$this->outputHttpStatus(404);
}
}
} | Sets a zone data
@param integer $zone_id | entailment |
protected function submitEditZone()
{
if ($this->isPosted('delete')) {
$this->deleteZone();
} else if ($this->isPosted('save') && $this->validateEditZone()) {
if (isset($this->data_zone['zone_id'])) {
$this->updateZone();
} else {
$this->addZone();
}
}
} | Handles a submitted zone data | entailment |
protected function validateEditZone()
{
$this->setSubmitted('zone');
$this->setSubmittedBool('status');
$this->setSubmitted('update', $this->data_zone);
$this->validateComponent('zone');
return !$this->hasErrors();
} | Validates a submitted zone
@return bool | entailment |
protected function deleteZone()
{
$this->controlAccess('zone_delete');
if ($this->zone->delete($this->data_zone['zone_id'])) {
$this->redirect('admin/settings/zone', $this->text('Zone has been deleted'), 'success');
}
$this->redirect('', $this->text('Zone has not been deleted'), 'danger');
} | Deletes a zone | entailment |
protected function updateZone()
{
$this->controlAccess('zone_edit');
if ($this->zone->update($this->data_zone['zone_id'], $this->getSubmitted())) {
$this->redirect('admin/settings/zone', $this->text('Zone has been updated'), 'success');
}
$this->redirect('', $this->text('Zone has not been updated'), 'warning');
} | Updates a zone | entailment |
protected function addZone()
{
$this->controlAccess('zone_add');
if ($this->zone->add($this->getSubmitted())) {
$this->redirect('admin/settings/zone', $this->text('Zone has been added'), 'success');
}
$this->redirect('', $this->text('Zone has not been added'), 'warning');
} | Adds a new zone | entailment |
protected function setTitleEditZone()
{
if (isset($this->data_zone['zone_id'])) {
$title = $this->text('Edit %name', array('%name' => $this->data_zone['title']));
} else {
$title = $this->text('Add zone');
}
$this->setTitle($title);
} | Sets titles on the edit zone page | entailment |
protected function setBreadcrumbEditZone()
{
$breadcrumbs = array();
$breadcrumbs[] = array(
'url' => $this->url('admin'),
'text' => $this->text('Dashboard')
);
$breadcrumbs[] = array(
'text' => $this->text('Zones'),
'url' => $this->url('admin/settings/zone')
);
$this->setBreadcrumbs($breadcrumbs);
} | Sets breadcrumbs on the edit zone page | entailment |
protected function setImage(array $data, $field_value_id = null)
{
if (!empty($data['images']) && !empty($field_value_id)) {
$this->file->delete(array('entity' => 'field_value', 'entity_id' => $field_value_id));
}
return $this->setImages($data, $this->file, 'field_value');
} | Sets a single image
@param array $data
@param null|int $field_value_id
@return bool | entailment |
protected function deleteLinked($field_value_id)
{
$this->db->delete('product_field', array('field_value_id' => $field_value_id));
$this->db->delete('field_value_translation', array('field_value_id' => $field_value_id));
$this->db->delete('file', array('entity' => 'field_value', 'entity_id' => $field_value_id));
} | Deletes all database records related to the field value ID
@param int $field_value_id | entailment |
protected function canDelete($field_value_id)
{
$sql = 'SELECT c.product_id
FROM product_field pf
LEFT JOIN cart c ON(pf.product_id = c.product_id)
WHERE pf.field_value_id=?';
$result = $this->db->fetchColumn($sql, array($field_value_id));
return empty($result);
} | Whether the field value can be deleted
@param integer $field_value_id
@return boolean | entailment |
public function setInvokableClass($name, $invokableClass, $shared = null)
{
parent::setInvokableClass($name, $invokableClass, $shared);
if ($name != $invokableClass) {
$this->setAlias($invokableClass, $name);
}
return $this;
} | Override setInvokableClass().
Performs normal operation, but also auto-aliases the class name to the
service name. This ensures that providing the FQCN does not trigger an
abstract factory later.
@param string $name
@param string $invokableClass
@param null|bool $shared
@return RoutePluginManager | entailment |
public function validatePlugin($plugin)
{
if ($plugin instanceof RouteInterface) {
// we're okay
return;
}
throw new RuntimeException(sprintf(
'Plugin of type %s is invalid; must implement %s\RouteInterface',
(is_object($plugin) ? get_class($plugin) : gettype($plugin)),
__NAMESPACE__
));
} | Validate the plugin.
Checks that the filter loaded is either a valid callback or an instance
of FilterInterface.
@param mixed $plugin
@throws RuntimeException if invalid | entailment |
protected function createFromInvokable($canonicalName, $requestedName)
{
$invokable = $this->invokableClasses[$canonicalName];
if (!class_exists($invokable)) {
throw new RuntimeException(sprintf(
'%s: failed retrieving "%s%s" via invokable class "%s"; class does not exist',
__METHOD__,
$canonicalName,
($requestedName ? '(alias: ' . $requestedName . ')' : ''),
$invokable
));
}
if (!static::isSubclassOf($invokable, __NAMESPACE__ . '\RouteInterface')) {
throw new RuntimeException(sprintf(
'%s: failed retrieving "%s%s" via invokable class "%s"; class does not implement %s\RouteInterface',
__METHOD__,
$canonicalName,
($requestedName ? '(alias: ' . $requestedName . ')' : ''),
$invokable,
__NAMESPACE__
));
}
return $invokable::factory($this->creationOptions);
} | Attempt to create an instance via an invokable class.
Overrides parent implementation by invoking the route factory,
passing $creationOptions as the argument.
@param string $canonicalName
@param string $requestedName
@throws Exception\RuntimeException If resolved class does not exist, or does not implement RouteInterface
@return null|\stdClass | entailment |
public function date(array $values)
{
if (count($values) != 1) {
$vars = array('@field' => $this->translation->text('Condition'));
return $this->translation->text('@field has invalid value', $vars);
}
$timestamp = strtotime(reset($values));
if (empty($timestamp)) {
$vars = array('@field' => $this->translation->text('Condition'));
return $this->translation->text('@field has invalid value', $vars);
}
return true;
} | Validates the date condition
@param array $values
@return boolean|string | entailment |
public static function validate($dataSource, $schema, $numPeekRows = 10, $csvDialect = null)
{
try {
$table = new static($dataSource, $schema, $csvDialect);
} catch (Exceptions\DataSourceException $e) {
return [new SchemaValidationError(SchemaValidationError::LOAD_FAILED, $e->getMessage())];
}
if ($numPeekRows > 0) {
$i = 0;
try {
foreach ($table as $row) {
if (++$i > $numPeekRows) {
break;
}
}
} catch (Exceptions\DataSourceException $e) {
// general error in getting the next row from the data source
return [new SchemaValidationError(SchemaValidationError::ROW_VALIDATION, [
'row' => $i,
'error' => $e->getMessage(),
])];
} catch (Exceptions\FieldValidationException $e) {
// validation error in one of the fields
return array_map(function ($validationError) use ($i) {
return new SchemaValidationError(SchemaValidationError::ROW_FIELD_VALIDATION, [
'row' => $i + 1,
'field' => $validationError->extraDetails['field'],
'error' => $validationError->extraDetails['error'],
'value' => $validationError->extraDetails['value'],
]);
}, $e->validationErrors);
}
}
return [];
} | @param DataSources\DataSourceInterface $dataSource
@param Schema $schema
@param int $numPeekRows
@return array of validation errors | entailment |
public function current()
{
if (count($this->castRows) > 0) {
$row = array_shift($this->castRows);
} else {
$row = $this->schema->castRow($this->dataSource->getNextLine());
foreach ($this->schema->fields() as $field) {
if ($field->unique()) {
if (!array_key_exists($field->name(), $this->uniqueFieldValues)) {
$this->uniqueFieldValues[$field->name()] = [];
}
$value = $row[$field->name()];
if (in_array($value, $this->uniqueFieldValues[$field->name()])) {
throw new DataSourceException('field must be unique', $this->currentLine);
} else {
$this->uniqueFieldValues[$field->name()][] = $value;
}
}
}
}
return $row;
} | called on each iteration to get the next row
does validation and casting on the row.
@return mixed[]
@throws Exceptions\FieldValidationException
@throws Exceptions\DataSourceException | entailment |
public static function deserializeObject(array $data)
{
return new static(
$data['type'],
$data['name'],
$data['description'],
isset($data['specUri']) ? $data['specUri'] : null,
isset($data['documentationUri']) ? $data['documentationUri'] : null
);
} | @param array $data
@return AuthenticationScheme | entailment |
public function submitCart($cart_action_model)
{
$this->setSubmitted('product');
$this->filterSubmitted(array('product_id'));
if ($this->isPosted('add_to_cart')) {
$this->validateAddToCart();
$this->addToCart($cart_action_model);
} else if ($this->isPosted('remove_from_cart')) {
$this->setSubmitted('cart');
$this->deleteFromCart($cart_action_model);
}
} | Handles product cart submissions
@param \gplcart\core\models\CartAction $cart_action_model | entailment |
public function validateAddToCart()
{
$this->setSubmitted('user_id', $this->getCartUid());
$this->setSubmitted('store_id', $this->getStoreId());
$this->setSubmitted('quantity', $this->getSubmitted('quantity', 1));
$this->validateComponent('cart');
} | Validates adding a product to cart | entailment |
public function addToCart($cart_action_model)
{
$errors = $this->error();
if (empty($errors)) {
$submitted = $this->getSubmitted();
$result = $cart_action_model->add($submitted['product'], $submitted);
} else {
$result = array(
'redirect' => '',
'severity' => 'warning',
'message' => $this->format($errors)
);
}
if ($this->isAjax()) {
$result['modal'] = $this->getCartPreview();
$this->outputJson($result);
}
$this->redirect($result['redirect'], $result['message'], $result['severity']);
} | Adds a product to the cart
@param \gplcart\core\models\CartAction $cart_action_model | entailment |
public function deleteFromCart($cart_action_model)
{
$result = $cart_action_model->delete($this->getSubmitted('cart_id'));
if (empty($result['quantity'])) {
$result['message'] = '';
}
if ($this->isAjax()) {
$result['modal'] = $this->getCartPreview();
$this->outputJson($result);
}
$this->redirect($result['redirect'], $result['message'], $result['severity']);
} | Deletes a submitted cart item
@param \gplcart\core\models\CartAction $cart_action_model | entailment |
public function listBlog()
{
$this->setTitleListBlog();
$this->setBreadcrumbListBlog();
$this->setTotalListBlog();
$this->setPagerListBlog();
$this->setData('pages', $this->getPagesBlog());
$this->outputListBlog();
} | Page callback
Displays the blog page | entailment |
protected function setTotalListBlog()
{
$conditions = $this->query_filter;
$conditions['status'] = 1;
$conditions['count'] = true;
$conditions['blog_post'] = 1;
$conditions['store_id'] = $this->store_id;
return $this->data_total = (int) $this->page->getList($conditions);
} | Sets a total number of posts found
@return int | entailment |
protected function getPagesBlog()
{
$conditions = $this->query_filter;
$conditions['status'] = 1;
$conditions['blog_post'] = 1;
$conditions['limit'] = $this->data_limit;
$conditions['store_id'] = $this->store_id;
$list = (array) $this->page->getList($conditions);
$this->preparePagesBlog($list);
return $list;
} | Returns an array of blog posts
@return array | entailment |
protected function preparePagesBlog(array &$list)
{
foreach ($list as &$item) {
list($teaser, $body) = $this->explodeText($item['description']);
if ($body !== '') {
$item['teaser'] = strip_tags($teaser);
}
$this->setItemEntityUrl($item, array('entity' => 'page'));
}
} | Prepare an array of pages
@param array $list | entailment |
protected function setPagerListBlog()
{
$pager = array(
'total' => $this->data_total,
'query' => $this->query_filter,
'limit' => $this->configTheme('blog_limit', 20)
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$verbose = OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity();
$invoke = $input->getOption('invoke');
$sm = $this->getServiceManager()->get('ServiceManager');
$registeredServices = $sm->getRegisteredServicesReal();
$lines = array();
$pad = array(
'id' => 0,
'type' => strlen('Instance '),
'class' => strlen('Class name|type|alias'),
);
$serviceTypeToColumnName = array(
'invokableClasses' => 'Invokable',
'factories' => 'Factory',
'aliases' => 'Alias',
'instances' => 'Instance',
);
foreach ($registeredServices as $type => $services) {
foreach ($services as $key => $service) {
$lines[$key]['type'] = $serviceTypeToColumnName[$type];
if (strlen($key) > $pad['id']) {
$pad['id'] = strlen($key);
}
if (is_object($service)) {
// As of PHP 5.4 you can rely on Closure being a Closure: php.net/manual/en/class.closure.php
if ($service instanceof \Closure) {
$r = new \ReflectionFunction($service);
if ($ns = $r->getNamespaceName()) {
$filename = basename($r->getFileName(), '.php');
$lines[$key]['class'] = $ns . '\\' . $filename . '\{closure}';
} else {
$lines[$key]['class'] = 'Closure in ' . $r->getFileName();
}
} else {
$r = new \ReflectionObject($service);
$lines[$key]['class'] = $r->getName();
}
} elseif (is_array($service)) {
$lines[$key]['class'] = 'Array';
} elseif (is_string($service) && ($type != 'aliases')) {
$r = new \ReflectionClass($service);
$lines[$key]['class'] = $r->getName();
} else { // Alias
$lines[$key]['class'] = $service;
}
$len = strlen($lines[$key]['class']);
if ('aliases' == $type) {
$len += 10; // add the "alias for " prefix
}
if ($len > $pad['class']) {
$pad['class'] = $len;
}
}
}
ksort($lines);
$output->write(sprintf('<comment>%s</comment> <comment>%s</comment> <comment>%s</comment>',
str_pad('Service Id', $pad['id']),
str_pad('Type', $pad['type']),
str_pad('Class Name|Type|Alias', $pad['class'])));
$output->writeln($invoke ? ' <comment>Invokation Status [result]</comment>' : '');
foreach ($lines as $id => $line) {
$output->write(sprintf('<info>%s</info> ', str_pad($id, $pad['id'])));
$output->write(sprintf('%s ', str_pad($line['type'], $pad['type'])));
if ('Alias' == $line['type']) {
$output->write(sprintf('<comment>alias for</comment> <info>%s </info>', str_pad($line['class'], $pad['class'] - 10)));
} else {
$output->write(sprintf('%s ', str_pad($line['class'], $pad['class'])));
}
if ($invoke) {
try {
$service = $sm->get($id);
$output->write(sprintf(' <info>OK</info> [%s]', is_object($service) ? get_class($service) : gettype($service)));
} catch (\Exception $e) {
$output->write(' <error>FAIL</error> [' . $e->getMessage() . ']');
}
}
$output->writeln('');
}
} | {@inheritdoc}
@throws \LogicException | entailment |
public function init(Request $request, $postType, $id, $subPostType)
{
// Lets validate if the post type exists and if so, continue.
$postTypeModel = $this->getPostType($postType);
if(!$postTypeModel){
$errorMessages = 'You are not authorized to do this.';
return $this->abort($errorMessages);
}
// Check if the post type has a identifier
if(empty($postTypeModel->identifier)){
$errorMessages = 'The post type does not have a identifier.';
if(array_has($postTypeModel->errorMessages, 'post_type_identifier_does_not_exist')){
$errorMessages = $postTypeModel->errorMessages['post_type_identifier_does_not_exist'];
}
return $this->abort($errorMessages);
}
$post = $this->findPostInstance($postTypeModel, $request, $postType, $id, 'show_post');
if(!$post){
$errorMessages = 'Post does not exist.';
if(array_has($postTypeModel->errorMessages, 'post_does_not_exist')){
$errorMessages = $postTypeModel->errorMessages['post_does_not_exist'];
}
return $this->abort($errorMessages);
}
// Lets get the post type of the sub post type object
$subPostTypeModel = $this->getPostType($subPostType);
if(!$subPostTypeModel){
$errorMessages = 'You are not authorized to do this.';
if(array_has($postTypeModel->errorMessages, 'sub_post_type_does_not_exist')){
$errorMessages = $postTypeModel->errorMessages['sub_post_type_does_not_exist'];
}
return $this->abort($errorMessages);
}
$collection = collect([
'objects' => $post->posts()->where('post_type', '=', $subPostTypeModel->identifier)->get()->toArray(),
]);
// Returning the full collection
return response()->json($collection);
} | Display a single post | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$cacheDir = $this->getServiceManager()->getParameter('app.cache_dir');
$filesystem = $this->getServiceManager()->getService('filesystem');
if (!is_writable($cacheDir)) {
throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $cacheDir));
}
$app = $this->getServiceManager()->get('app');
$output->writeln(sprintf('Clearing the cache for the <info>%s</info> environment with debug <info>%s</info>', $app->getEnvironment(), var_export($app->isDebug(), true)));
if (!$filesystem->exists($cacheDir)) {
return;
}
$filesystem->remove(glob($cacheDir . '/*'));
} | {@inheritdoc} | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
if (!$this->checkRunStatus($input, $output)) {
return 0;
}
$limit = (int) $input->getOption('limit');
/** @var SettingsHelper $settingsHelper */
$settingsHelper = $container->get('mautic.dashboardwarm.helper.settings');
$sharedCache = (bool) $settingsHelper->getShareCaches();
/** @var DashboardWarmModel $model */
$model = $container->get('mautic.dashboardwarm.model.warm');
$model->warm($output, $limit, $sharedCache);
$this->completeRun();
return 0;
} | @param InputInterface $input
@param OutputInterface $output
@return int|null | entailment |
public function review(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateReview();
$this->validateBool('status');
$this->validateTextReview();
$this->validateCreatedReview();
$this->validateProductReview();
$this->validateEmailReview();
$this->validateUserId();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs full review data validation
@param array $submitted
@param array $options
@return array|boolean | entailment |
protected function validateReview()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null;
}
$data = $this->review->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('Review'));
return false;
}
$this->setUpdating($data);
return true;
} | Validates a review to be updated
@return boolean|null | entailment |
protected function validateTextReview()
{
$field = 'text';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
$label = $this->translation->text('Text');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
$length = mb_strlen($value);
list($min, $max) = $this->review->getLimits();
if ($length < $min || $length > $max) {
$this->setErrorLengthRange($field, $label, $min, $max);
return false;
}
return true;
} | Validates a review text
@return boolean|null | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.