sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function render($name, array $parameters = array())
{
try {
return $this->load($name)->render($parameters);
} catch (\Twig_Error $e) {
if ($name instanceof TemplateReference) {
try {
// try to get the real file name of the template where the
// error occurred
$e->setTemplateFile(sprintf('%s',
$this->locator->locate(
$this->parser->parse(
$e->getTemplateFile()
)
)
));
} catch (\Exception $ex) {
}
}
throw $e;
}
} | Renders a template.
@param mixed $name A template name
@param array $parameters An array of parameters to pass to the template
@throws \InvalidArgumentException if the template does not exist
@throws \RuntimeException if the template cannot be rendered
@return string The evaluated template as a string | entailment |
public function renderResponse($view, array $parameters = array(), Response $response = null)
{
if (null === $response) {
$response = new Response();
}
$response->setContent($this->render($view, $parameters));
return $response;
} | Renders a view and returns a Response.
@param string $view The view name
@param array $parameters An array of parameters to pass to the view
@param Response $response A Response instance
@return Response A Response instance | entailment |
protected function load($name)
{
if ($name instanceof \Twig_Template) {
return $name;
}
try {
return $this->environment->loadTemplate($name);
} catch (\Twig_Error_Loader $e) {
throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
} | Loads the given template.
@param mixed $name A template name or an instance of Twig_Template
@throws \InvalidArgumentException if the template does not exist
@return \Twig_TemplateInterface A \Twig_TemplateInterface instance | entailment |
public function generate($pattern, array $options = array())
{
$options += array(
'translit' => true,
'language' => null,
'placeholders' => array()
);
$result = null;
$this->hook->attach('alias.generate.before', $pattern, $options, $result);
if (isset($result)) {
return (string) $result;
}
$alias = $pattern;
if (!empty($options['placeholders'])) {
$alias = gplcart_string_replace($pattern, $options['placeholders'], $options);
}
if (!empty($options['translit'])) {
$alias = gplcart_string_slug($this->language->translit($alias, $options['language']));
}
$trimmed = mb_strimwidth(str_replace(' ', '-', trim($alias)), 0, 100, '');
$result = $this->getUnique($trimmed);
$this->hook->attach('alias.generate.after', $pattern, $options, $result);
return $result;
} | Generate a URL alias using a pattern and an array of data
@param string $pattern
@param array $options
@return string | entailment |
public function generateEntity($entity, array $data)
{
$handlers = $this->getHandlers();
if (isset($handlers[$entity]['mapping']) && isset($handlers[$entity]['pattern'])) {
$data += array('placeholders' => $handlers[$entity]['mapping']);
return $this->generate($handlers[$entity]['pattern'], $data);
}
return null;
} | Generates an alias for an entity
@param string $entity
@param array $data
@return string|null | entailment |
public function loadEntity($entity, $entity_id)
{
try {
$handlers = $this->getHandlers();
return Handler::call($handlers, $entity, 'data', array($entity_id));
} catch (Exception $ex) {
return array();
}
} | Returns an array of entity data
@param string $entity
@param int $entity_id
@return array | entailment |
public function getUnique($alias)
{
if (!$this->exists($alias)) {
return $alias;
}
$info = pathinfo($alias);
$ext = isset($info['extension']) ? '.' . $info['extension'] : '';
$counter = 0;
do {
$counter++;
$modified = $info['filename'] . '-' . $counter . $ext;
} while ($this->exists($modified));
return $modified;
} | Returns a unique alias using a base string
@param string $alias
@return string | entailment |
public function exists($path)
{
foreach ($this->route->getList() as $route) {
if (isset($route['pattern']) && $route['pattern'] === $path) {
return true;
}
}
return (bool) $this->get(array('alias' => $path));
} | Whether the alias path already exists
@param string $path
@return boolean | entailment |
protected function getSubmitted($key = null, $default = null)
{
if (!isset($key)) {
return $this->submitted;
}
$path = $this->getKeyPath($key);
if (isset($path)) {
$result = gplcart_array_get($this->submitted, $path);
return isset($result) ? $result : $default;
}
return $this->submitted;
} | Returns a submitted value
@param null|string $key
@param mixed $default
@return mixed | entailment |
public function setSubmitted($key, $value)
{
gplcart_array_set($this->submitted, $this->getKeyPath($key), $value);
} | Sets a value to an array of submitted values
@param string $key
@param mixed $value | entailment |
protected function getUpdatingId($key = 'update')
{
if (empty($this->submitted[$key]) || is_array($this->submitted[$key])) {
return false;
}
return $this->submitted[$key];
} | Returns either an ID of entity to be updated or false if no ID found (adding).
It also returns false if an array of updating entity has been loaded and set
@param string $key
@return boolean|string|integer | entailment |
protected function getKeyPath($key)
{
if (empty($this->options['parents'])) {
return $key;
}
if (is_string($this->options['parents'])) {
$this->options['parents'] = explode('.', $this->options['parents']);
}
if (is_string($key)) {
$key = explode('.', $key);
}
return array_merge((array) $this->options['parents'], (array) $key);
} | Returns an array that represents a path to a nested array value
@param string|array $key
@return array | entailment |
protected function isExcluded($field)
{
return isset($this->options['field']) && $this->options['field'] !== $this->getKey($field);
} | Whether the field should be excluded from validation
@param string $field
@return bool | entailment |
protected function setError($key, $error)
{
gplcart_array_set($this->errors, $this->getKeyPath($key), $error);
return $this->errors;
} | Sets a validation error
@param string|array $key
@param string $error
@return array | entailment |
protected function isError($key = null)
{
if (!isset($key)) {
return !empty($this->errors);
}
$result = $this->getError($key);
return !empty($result);
} | Whether an error exists
@param string|null $key
@return boolean | entailment |
protected function getResult()
{
$result = empty($this->errors) ? true : $this->errors;
$this->errors = array();
return $result;
} | Returns validation results
@return array|boolean | entailment |
public function product(array $condition, array $data)
{
$is_product = (int) isset($data['product_id']);
$value = (int) filter_var(reset($condition['value']), FILTER_VALIDATE_BOOLEAN);
return $this->compare($is_product, $value, $condition['operator']);
} | Whether the product scope condition is met
@param array $condition
@param array $data
@return boolean | entailment |
public function cart(array $condition, array $data)
{
$is_cart = (int) isset($data['cart_id']);
$value = (int) filter_var(reset($condition['value']), FILTER_VALIDATE_BOOLEAN);
return $this->compare($is_cart, $value, $condition['operator']);
} | Whether the cart scope condition is met
@param array $condition
@param array $data
@return boolean | entailment |
public function order(array $condition, array $data)
{
$is_order = (int) isset($data['order_id']);
$value = (int) filter_var(reset($condition['value']), FILTER_VALIDATE_BOOLEAN);
return $this->compare($is_order, $value, $condition['operator']);
} | Whether the order scope condition is met
@param array $condition
@param array $data
@return boolean | entailment |
public function editInstall()
{
$this->controlAccessInstall();
$this->translation->set($this->install_language, null);
$this->setTitleEditInstall();
$requirements = $this->getRequirementsInstall();
$issues = $this->getRequirementErrorsInstall($requirements);
$this->setData('issues', $issues);
$this->setData('requirements', $requirements);
$this->setData('settings.installer', 'default');
$this->setData('timezones', gplcart_timezones());
$this->setData('language', $this->install_language);
$this->setData('handlers', $this->install->getHandlers());
$this->setData('languages', $this->getLanguagesInstall());
$this->setData('severity', $this->getSeverityInstall($issues));
$this->setData('settings.store.language', $this->install_language);
$this->submitEditInstall();
$this->outputEditInstall();
} | Displays the installation page | entailment |
protected function getLanguagesInstall()
{
$languages = array();
foreach ($this->language->getList() as $code => $language) {
if ($code === 'en' || is_file($this->translation->getFile($code))) {
$languages[$code] = $language;
}
}
return $languages;
} | Returns an array of existing languages
@return array | entailment |
protected function processInstall()
{
$result = $this->install->process($this->getSubmitted());
$this->redirect($result['redirect'], $result['message'], $result['severity']);
} | Performs all needed operations to install the system | entailment |
protected function validateEditInstall()
{
$this->setSubmitted('settings');
$this->setSubmitted('store.host', $this->server->httpHost());
$this->setSubmitted('store.language', $this->install_language);
$this->setSubmitted('store.basepath', trim($this->request->base(true), '/'));
$this->validateComponent('install');
return !$this->hasErrors(false);
} | Validates an array of submitted form values
@return bool | entailment |
public function indexAccount($user_id)
{
$this->setUserAccount($user_id);
$this->setTitleIndexAccount();
$this->setBreadcrumbIndexAccount();
$this->setFilter();
$this->setPagerOrderIndexAccount();
$this->setData('user', $this->data_user);
$this->setData('orders', $this->getListOrderAccount());
$this->outputIndexAccount();
} | Page callback
Displays the user account page
@param integer $user_id | entailment |
protected function setPagerOrderIndexAccount()
{
$conditions = array(
'count' => true,
'user_id' => $this->data_user['user_id']
);
$pager = array(
'query' => $this->query_filter,
'total' => (int) $this->order->getList($conditions),
'limit' => $this->config('account_order_limit', 10)
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function getListOrderAccount()
{
$conditions = $this->query_filter;
$conditions['order'] = 'desc';
$conditions['sort'] = 'created';
$conditions['limit'] = $this->data_limit;
$conditions['user_id'] = $this->data_user['user_id'];
$list = (array) $this->order->getList($conditions);
$this->prepareListOrderAccount($list);
return $list;
} | Returns an array of orders for the user
@return array | entailment |
protected function prepareListOrderAccount(array &$list)
{
foreach ($list as &$item) {
$this->setItemTotalFormatted($item, $this->price);
$this->setItemOrderAddress($item, $this->address);
$this->setItemOrderStoreName($item, $this->store);
$this->setItemOrderStatusName($item, $this->order);
$this->setItemOrderPaymentName($item, $this->payment);
$this->setItemOrderShippingName($item, $this->shipping);
}
} | Prepare an array of orders
@param array $list | entailment |
public function editAccount($user_id)
{
$this->setUserAccount($user_id);
$this->controlAccessEditAccount();
$this->setTitleEditAccount();
$this->setBreadcrumbEditAccount();
$this->setData('user', $this->data_user);
$this->submitEditAccount();
$this->outputEditAccount();
} | Page callback
Displays the edit account page
@param integer $user_id | entailment |
protected function updateAccount()
{
$this->controlAccessEditAccount();
if ($this->user->update($this->data_user['user_id'], $this->getSubmitted())) {
$this->redirect('', $this->text('Account has been updated'), 'success');
}
$this->redirect('', $this->text('Account has not been updated'), 'warning');
} | Updates a user | entailment |
protected function setBreadcrumbEditAccount()
{
$breadcrumbs = array();
$breadcrumbs[] = array(
'url' => $this->url('/'),
'text' => $this->text('Shop')
);
$breadcrumbs[] = array(
'text' => $this->text('Account'),
'url' => $this->url("account/{$this->data_user['user_id']}")
);
$this->setBreadcrumbs($breadcrumbs);
} | Sets breadcrumbs on the edit account page | entailment |
public function init(Request $request, $group)
{
// Lets validate if the post type exists and if so, continue.
$postTypeModel = $this->getPostType($group);
if(!$postTypeModel){
$errorMessages = 'You are not authorized to do this.';
return $this->abort($errorMessages);
}
// Recieving the values
$configMeta = $request->all();
// Unsetting values which we do not need
$unsetValues = ['_token'];
foreach($unsetValues as $value){
unset($configMeta[$value]);
}
// Receiving validation rules from config
$validationRules = [];
foreach ($configMeta as $key => $value) {
// Setting the path to get the validation rules
if(strpos($key, '_repeater_') !== false) {
$explodedValue = explode('_', $key);
// Removing the old repeater values so we can resave them all, if we do
// not do this, it will keep having the old values in the database.
NikuConfig::where([
['option_name', 'like', $explodedValue[0] . '_' . $explodedValue[1] . '_%'],
['group', '=', $group]
])->delete();
// For each all groups to get the validation
foreach($postTypeModel->view as $templateKey => $template){
if(array_has($template, 'customFields.' . $explodedValue[0] . '.customFields.' . $explodedValue[3] . '.validation')){
$rule = $template['customFields'][$explodedValue[0]]['customFields'][$explodedValue[3]]['validation'];
}
}
} else {
// For each all groups to get the validation
foreach($postTypeModel->view as $templateKey => $template){
if(array_has($template, 'customFields.' . $key . '.validation')){
$rule = $template['customFields'][$key]['validation'];
}
}
}
// Appending the validation rules to the validation array
if(!empty($rule)){
$validationRules[$key] = $rule;
}
}
// Validate the request
if(!empty($validationRules)){
$this->validatePost($request, $validationRules);
}
// Lets update or create the fields in the post request
foreach($configMeta as $index => $value){
NikuConfig::updateOrCreate(
['option_name' => $index],
[
'option_value' => $value,
'group' => $group
]
);
}
$successMessage = 'Config succesfully updated.';
if(array_has($postTypeModel->successMessage, 'config_updated')){
$successMessage = $postTypeModel->successMessage['config_updated'];
}
// Lets return the response
return response()->json([
'code' => 'success',
'message' => $successMessage,
'action' => 'config_updated',
], 200);
} | The manager of the database communication for adding and manipulating posts | entailment |
public function editUserForgot()
{
$this->controlAccessUserForgot();
$this->setUserForgot();
$this->setTitleEditUserForgot();
$this->setBreadcrumbEditUserForgot();
$this->setData('forgetful_user', $this->data_user);
$this->setData('password_limit', $this->user->getPasswordLength());
$this->submitUserForgot();
$this->outputEditUserForgot();
} | Displays the password reset page | entailment |
protected function setUserForgot()
{
$token = $this->getQuery('key');
$user_id = $this->getQuery('user_id');
$this->data_user = array();
if (!empty($token) && is_numeric($user_id)) {
$this->data_user = $this->user->get($user_id);
$this->controlTokenUserForgot($this->data_user, $token);
}
} | Returns a user from the current reset password URL | entailment |
protected function controlTokenUserForgot($user, $token)
{
if (!empty($user['status'])) {
if (empty($user['data']['reset_password']['token'])) {
$this->redirect('forgot');
}
if (!gplcart_string_equals($user['data']['reset_password']['token'], $token)) {
$this->outputHttpStatus(403);
}
if (empty($user['data']['reset_password']['expires']) || $user['data']['reset_password']['expires'] < GC_TIME) {
$this->redirect('forgot');
}
}
} | Validates the token and its expiration time set for the user
@param array $user
@param string $token | entailment |
protected function resetPasswordUser()
{
$result = $this->user_action->resetPassword($this->getSubmitted());
$this->redirect($result['redirect'], $result['message'], $result['severity']);
} | Reset user's password | entailment |
protected function validateUserForgot()
{
$this->setSubmitted('user', null, false);
$this->filterSubmitted(array('email', 'password'));
$this->setSubmitted('user', $this->data_user);
$this->validateComponent('user_reset_password');
return !$this->hasErrors();
} | Validates a submitted data when a user wants to reset its password
@return boolean | entailment |
public function countryState(array $submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateCountryState();
$this->validateBool('status');
$this->validateCodeCountryState();
$this->validateName();
$this->validateCountryCountryState();
$this->validateZoneCountryState();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs full country state validation
@param array $submitted
@param array $options
@return array|boolean | entailment |
protected function validateCountryState()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null;
}
$data = $this->state->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('Country state'));
return false;
}
$this->setUpdating($data);
return true;
} | Validates a state to be updated
@return boolean|null | entailment |
public function validateCodeCountryState()
{
$field = 'code';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
$updating = $this->getUpdating();
if (isset($updating['code']) && $updating['code'] === $value) {
return true;
}
$label = $this->translation->text('Code');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
$existing = $this->state->getList(array('code' => $value, 'country' => $this->getSubmitted('country')));
if (!empty($existing)) {
$this->setErrorExists($field, $label);
return false;
}
return true;
} | Validates a state code
@return boolean | entailment |
protected function validateZoneCountryState()
{
$field = 'zone_id';
$value = $this->getSubmitted($field);
if (empty($value)) {
return null;
}
$label = $this->translation->text('Zone');
if (!is_numeric($value)) {
$this->setErrorNumeric($field, $label);
return false;
}
$zone = $this->zone->get($value);
if (empty($zone)) {
$this->setErrorUnavailable($field, $label);
return false;
}
return true;
} | Validates a zone ID
@return boolean|null | entailment |
public function required(array $submitted, array $options)
{
$options += array(
'field' => null,
'label' => null
);
$value = gplcart_array_get($submitted, $options['field']);
if (empty($value)) {
return $this->setErrorRequired($options['field'], $options['label']);
}
return true;
} | Validates the field/value is not empty
@param array $submitted
@param array $options
@return bool|array | entailment |
public function numeric(array $submitted, array $options)
{
$options += array(
'field' => null,
'label' => null
);
$value = gplcart_array_get($submitted, $options['field']);
if (is_numeric($value)) {
return true;
}
return $this->setErrorNumeric($options['field'], $options['label']);
} | Validates the field/value is numeric
@param array $submitted
@param array $options
@return bool|array | entailment |
public function integer(array $submitted, array $options)
{
$options += array(
'field' => null,
'label' => null
);
$value = gplcart_array_get($submitted, $options['field']);
if (filter_var($value, FILTER_VALIDATE_INT) === false) {
return $this->setErrorInteger($options['field'], $options['label']);
}
return true;
} | Validates the field/value contains only digits
@param array $submitted
@param array $options
@return bool|array | entailment |
public function length(array $submitted, array $options)
{
$options += array(
'field' => null,
'label' => null,
'arguments' => array()
);
$value = gplcart_array_get($submitted, $options['field']);
list($min, $max) = $options['arguments'] + array(1, 255);
$length = mb_strlen($value);
if ($min <= $length && $length <= $max) {
return true;
}
return $this->setErrorLengthRange($options['field'], $options['label'], $min, $max);
} | Validates the field/value length
@param array $submitted
@param array $options
@return bool|array | entailment |
public function regexp(array $submitted, array $options)
{
$options += array(
'field' => null,
'label' => null,
'arguments' => array()
);
$value = gplcart_array_get($submitted, $options['field']);
if (empty($options['arguments']) || preg_match(reset($options['arguments']), $value) !== 1) {
return $this->setErrorInvalid($options['field'], $options['label']);
}
return true;
} | Validates the field/value matches a regexp pattern
@param array $submitted
@param array $options
@return bool|array | entailment |
public function dateformat(array $submitted, array $options)
{
$options += array(
'field' => null,
'label' => null
);
$value = gplcart_array_get($submitted, $options['field']);
if (strtotime($value) === false) {
return $this->setErrorInvalid($options['field'], $options['label']);
}
return true;
} | Validates the date format
@param array $submitted
@param array $options
@link http://php.net/manual/en/function.strtotime.php
@return bool|array | entailment |
public function json(array $submitted, array $options)
{
$options += array(
'field' => null,
'label' => null
);
$value = gplcart_array_get($submitted, $options['field']);
json_decode($value);
if (json_last_error() === JSON_ERROR_NONE) {
return true;
}
return $this->setErrorInvalid($options['field'], $options['label']);
} | Validates the field/value is a JSON string
@param array $submitted
@param array $options
@return array|bool | entailment |
public function id(array $condition, array $data)
{
if (empty($data['product_id'])) {
return false;
}
return $this->compare($data['product_id'], $condition['value'], $condition['operator']);
} | Whether the product ID condition is met
@param array $condition
@param array $data
@return boolean | entailment |
public function categoryId(array $condition, array $data)
{
if (empty($data['product_id']) || empty($data['category_id'])) {
return false;
}
return $this->compare($data['category_id'], $condition['value'], $condition['operator']);
} | Whether the product category ID condition is met
@param array $condition
@param array $data
@return boolean | entailment |
public function brandCategoryId(array $condition, array $data)
{
if (empty(empty($data['product_id']) || $data['brand_category_id'])) {
return false;
}
return $this->compare($data['brand_category_id'], $condition['value'], $condition['operator']);
} | Whether the product brand condition is met
@param array $condition
@param array $data
@return boolean | entailment |
public function init(Request $request, $postType, $id)
{
// 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);
}
if(method_exists($postTypeModel, 'override_show_post')){
return $postTypeModel->override_show_post($id, $request, $postType);
}
$config = $this->getConfig($postTypeModel);
// 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, $config);
}
// Validate if we need to validate a other post type before showing this post type
$validateBefore = $this->validatePostTypeBefore($request, $postTypeModel, $id);
if($validateBefore['status'] === false){
$errorMessages = $validateBefore['message'];
return $this->abort($errorMessages, $validateBefore['config'], 'post_validation_error');
}
$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, $config);
}
// Converting the updated_at to the input picker in the front-end
$updatedAtCustomField = $this->getCustomFieldObject($postTypeModel, 'updated_at');
// If we have not set a custom date format, we will not touch this formatting
if(!empty($updatedAtCustomField['date_format_php'])){
$post->created = $post->updated_at->format($updatedAtCustomField['date_format_php']);
}
// Converting the created_at to the input picker in the front-end
$createdAtCustomField = $this->getCustomFieldObject($postTypeModel, 'created_at');
// If we have not set a custom date format, we will not touch this formatting
if(!empty($post->created_at)){
if(!empty($createdAtCustomField['date_format_php'])){
$post->created = $post->created_at->format($createdAtCustomField['date_format_php']);
}
}
// Retrieve all the post meta's and taxonomies
$postmeta = $this->retrieveConfigPostMetas($post, $postTypeModel);
$postArray = $post->toArray();
$postArraySanitized = [];
if(array_has($postArray, 'id')){
$postArraySanitized['id'] = $postArray['id'];
}
if(array_has($postArray, 'post_title')){
$postArraySanitized['post_title'] = $postArray['post_title'];
}
if(array_has($postArray, 'post_name')){
$postArraySanitized['post_name'] = $postArray['post_name'];
}
if(array_has($postArray, 'status')){
$postArraySanitized['status'] = $postArray['status'];
}
if(array_has($postArray, 'post_type')){
$postArraySanitized['post_type'] = $postArray['post_type'];
}
if(array_has($postArray, 'created_at')){
$postArraySanitized['created_at'] = $postArray['created_at'];
}
if(array_has($postArray, 'updated_at')){
$postArraySanitized['updated_at'] = $postArray['updated_at'];
}
// Format the collection
$collection = [
'post' => $postArraySanitized,
'postmeta' => $postmeta,
];
// Mergin the collection with the data and custom fields
$collection['templates'] = $this->mergeCollectionWithView($postTypeModel->view, $collection, $postTypeModel);
// Setting the config
$collection['config'] = $config;
// Lets check if there are any manipulators active
$collection = $this->showMutator($postTypeModel, $collection, $request);
if(method_exists($postTypeModel, 'on_show_mutator')){
$collection = $postTypeModel->on_show_mutator($postTypeModel, $post->id, $postmeta, $collection);
}
// Lets check if there are any manipulators active
$collection = $this->showConditional($postTypeModel, $collection);
// Cleaning up the output
unset($collection['postmeta']);
if(method_exists($postTypeModel, 'on_show_check')){
$onShowCheck = $postTypeModel->on_show_check($postTypeModel, $post->id, $postmeta);
if($onShowCheck['continue'] === false){
$errorMessages = 'You are not authorized to do this.';
if(array_key_exists('message', $onShowCheck)){
$errorMessages = $onShowCheck['message'];
}
return $this->abort($errorMessages, $config);
}
}
// Lets fire events as registered in the post type
$this->triggerEvent('on_show_event', $postTypeModel, $post->id, $postmeta);
$collection['instance'] = [
'post_type' => $postType,
'post_identifier' => $id,
];
// Returning the full collection
return response()->json($collection);
} | Display a single post | entailment |
protected function retrieveConfigPostMetas($post, $postTypeModel)
{
$metaKeys = [];
$metaTaxonomies = [];
$allKeys = $this->getValidationsKeys($postTypeModel);
foreach($allKeys as $key => $value){
$customFieldObject = $this->getCustomFieldObject($postTypeModel, $key);
if(isset($customFieldObject['type']) && $customFieldObject['type'] == 'taxonomy'){
// We need to get the values from the taxonomy table
if(array_key_exists('post_type', $customFieldObject)){
$customfieldPostTypes = $this->getPostTypeIdentifiers($customFieldObject['post_type']);
// Lets query the post to retrieve all the connected ids
$taxonomyIds = $post->taxonomies()->whereIn('post_type', $customfieldPostTypes)
->get();
// Lets foreach all the posts because we only need the id
$ids = [];
foreach($taxonomyIds as $value){
array_push($ids, $value->id);
}
$ids = json_encode($ids);
$metaTaxonomies[$key] = [
'meta_key' => $key,
'meta_value' => $ids,
];
}
// The other items are default
} else {
// Register it to the main array so we can query it later
array_push($metaKeys, $key);
}
}
// Lets query the database to get only the values where we have registered the meta keys
$postmetaSimple = $post->postmeta()
->whereIn('meta_key', $metaKeys)
->select(['meta_key', 'meta_value'])
->get()
->keyBy('meta_key')
->toArray();
// Lets attach the default post columns
$defaultPostData = [];
$defaultPostData['post_title'] = [
'meta_key' => 'post_title',
'meta_value' => $post->post_title,
];
$defaultPostData['post_name'] = [
'meta_key' => 'post_name',
'meta_value' => $post->post_name,
];
// Lets merge all the types of configs
$postmeta = array_merge($postmetaSimple, $metaTaxonomies, $defaultPostData);
// Return the post meta's
return $postmeta;
} | Get all the post meta keys of the post | entailment |
protected function mergeCollectionWithView($view, $collection, $postTypeModel)
{
$post = $collection['post'];
$postmeta = $collection['postmeta'];
// Foreaching all templates in the custom field configuration file
foreach($view as $templateKey => $template){
// If the array custom fields is not empty
if(!empty($template['customFields'])){
// We foreach all custom fields in this template section
foreach($template['customFields'] as $customFieldKey => $customField){
// Setting post data to the custom fields
switch($customFieldKey){
// If we find the customFieldKey created_at, we know it is in the config file
case 'created_at':
// Because of that we will add the post created_at value to the custom field
if(!empty($post['created_at'])){
$view[$templateKey]['customFields'][$customFieldKey]['id'] = $customFieldKey;
$view[$templateKey]['customFields'][$customFieldKey]['value'] = $post['created_at'];
}
break;
// If we find the customFieldKey updated_at, we know it is in the config file
case 'updated_at':
// Because of that we will add the post updated_at value to the custom field
if(!empty($post['updated_at'])){
$view[$templateKey]['customFields'][$customFieldKey]['id'] = $customFieldKey;
$view[$templateKey]['customFields'][$customFieldKey]['value'] = $post['updated_at'];
}
break;
// If we find the customFieldKey updated_at, we know it is in the config file
case 'status':
// Because of that we will add the post status value to the custom field
if(!empty($post['status'])){
$view[$templateKey]['customFields'][$customFieldKey]['id'] = $customFieldKey;
$view[$templateKey]['customFields'][$customFieldKey]['value'] = $post['status'];
}
break;
}
// Lets set the key to the array
$view[$templateKey]['customFields'][$customFieldKey]['id'] = $customFieldKey;
if(array_key_exists($customFieldKey, $postmeta)){
$view[$templateKey]['customFields'][$customFieldKey]['value'] = $postmeta[$customFieldKey]['meta_value'];
}
// When output is disabled, we need to remove the fields from the arrays
if(array_key_exists('output', $customField) && !$customField['output']){
unset($view[$templateKey]['customFields'][$customFieldKey]);
}
// If the array custom fields is not empty
if(!empty($customField['customFields'])){
// We foreach all custom fields in this template section
foreach($customField['customFields'] as $innerCustomFieldKey => $innerCustomField){
// Lets set the key to the array
$view[$templateKey]['customFields'][$customFieldKey]['customFields'][$innerCustomFieldKey]['id'] = $innerCustomFieldKey;
if(array_key_exists($innerCustomFieldKey, $postmeta)){
$view[$templateKey]['customFields'][$customFieldKey]['customFields'][$innerCustomFieldKey]['value'] = $postmeta[$innerCustomFieldKey]['meta_value'];
}
// When output is disabled, we need to remove the fields from the arrays
if(array_key_exists('output', $innerCustomField) && !$innerCustomField['output']){
unset($view[$templateKey]['customFields'][$customFieldKey]['customFields'][$innerCustomFieldKey]);
}
}
// If the array custom fields is not empty
if(!empty($innerCustomField['customFields'])){
// We foreach all custom fields in this template section
foreach($innerCustomField['customFields'] as $innerInnerCustomFieldKey => $innerInnerCustomField){
// Lets set the key to the array
$view[$templateKey]['customFields'][$customFieldKey]['customFields'][$innerCustomFieldKey]['customFields'][$innerInnerCustomFieldKey]['id'] = $innerInnerCustomFieldKey;
if(array_key_exists($innerInnerCustomFieldKey, $postmeta)){
$view[$templateKey]['customFields'][$customFieldKey]['customFields'][$innerCustomFieldKey]['customFields'][$innerInnerCustomFieldKey]['value'] = $postmeta[$innerInnerCustomFieldKey]['meta_value'];
}
// When output is disabled, we need to remove the fields from the arrays
if(array_key_exists('output', $innerInnerCustomField) && !$innerInnerCustomField['output']){
unset($view[$templateKey]['customFields'][$customFieldKey]['customFields'][$innerCustomFieldKey]['customFields'][$innerInnerCustomFieldKey]);
}
}
}
}
}
}
}
return $view;
} | Appending the key added in the config to the array
so we can use it very easliy in the component. | entailment |
public function productClassField(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateProductClassField();
$this->validateProductClassProductClassField();
$this->validateWeight();
$this->validateBool('required');
$this->validateBool('multiple');
$this->validateFieldIdProductClassField();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs full product class field validation
@param array $submitted
@param array $options
@return array|boolean | entailment |
protected function validateProductClassField()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null;
}
$data = $this->product_class_field->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('Address'));
return false;
}
$this->setUpdating($data);
return true;
} | Validates a product class field to be updated
@return boolean | entailment |
protected function validateProductClassProductClassField()
{
$field = 'product_class_id';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
$label = $this->translation->text('Product class');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
if (!is_numeric($value)) {
$this->setErrorInteger($field, $label);
return false;
}
$product_class = $this->product_class->get($value);
if (empty($product_class)) {
$this->setErrorUnavailable('update', $label);
return false;
}
return true;
} | Validates a product class ID
@return boolean|null | entailment |
protected function validateFieldIdProductClassField()
{
$field = 'field_id';
if ($this->isExcluded($field) || $this->isError('product_class_id')) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
$label = $this->translation->text('Fields');
if (empty($value)) {
$this->setErrorRequired($field, $label);
return false;
}
$updating = $this->getUpdating();
$product_class_id = $this->getSubmitted('product_class_id');
if (!isset($product_class_id) && isset($updating['product_class_id'])) {
$product_class_id = $updating['product_class_id'];
}
if (empty($product_class_id)) {
$this->setErrorUnavailable($field, $this->translation->text('Unknown product class ID'));
}
$existing = $this->product_class_field->getList(array(
'index' => 'field_id',
'product_class_id' => $product_class_id)
);
$processed = array();
foreach ((array) $value as $field_id) {
if (empty($field_id) || !is_numeric($field_id)) {
$this->setErrorInvalid($field, $label);
return false;
}
if (in_array($field_id, $processed)) {
$this->setErrorExists($field, $label);
return false;
}
if (isset($existing[$field_id])) {
$this->setErrorExists($field, $label);
return false;
}
$data = $this->field->get($field_id);
if (empty($data)) {
$this->setErrorUnavailable($field, $label);
return false;
}
$processed[] = $field_id;
}
return true;
} | Validates one or several field IDs
@return bool|null | entailment |
public function load($file, $type = null)
{
$path = $this->locator->locate($file);
$content = $this->loadFile($path);
// empty file
if (null === $content) {
return array();
}
// imports (Symfony)
$content = $this->parseImports($content, $path);
// @include (Zend)
$content = $this->parseIncludes($content, $path);
// not an array
if (!is_array($content)) {
throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
}
return $content;
} | Loads a Yaml file.
@param mixed $file The resource
@param string $type The resource type
@throws \InvalidArgumentException
@return array Array with configuration | entailment |
protected function parseImports($content, $file)
{
if (!isset($content['imports'])) {
return $content;
}
foreach ($content['imports'] as $import) {
$this->setCurrentDir(dirname($file));
$content = ArrayUtils::merge($this->import($import['resource'], null, isset($import['ignore_errors'])
? (Boolean) $import['ignore_errors'] : false, $file), $content);
}
unset($content['imports']);
return $content;
} | Parses all imports. We support this to make Symfony users happy.
@param array $content
@param string $file
@return array | entailment |
protected function parseIncludes(array $content, $file)
{
foreach ($content as $key => $value) {
if (is_array($value)) {
$content[$key] = $this->parseIncludes($value, $file);
}
if ('@include' === trim($key)) {
$this->setCurrentDir(dirname($file));
unset($content[$key]);
$content = array_replace_recursive($content, $this->import($value, null, false, $file));
}
}
return $content;
} | Process the array for @include. We support this to make Zend users happy.
@see http://framework.zend.com/manual/2.0/en/modules/zend.config.reader.html#zend-config-reader-yaml
@param array $content
@param string $file
@return array | entailment |
public function getAssetUrlBlock(array $parameters = array(), $path = null, $template, &$repeat)
{
// only output on the closing tag
if (!$repeat) {
$parameters = array_merge(array(
'package' => null,
), $parameters);
return $this->helper->getUrl($path, $parameters['package']);
}
} | Returns the public path of an asset. Absolute paths (i.e. http://...) are
returned unmodified.
@param array $parameters
@param type $path
@param type $template
@param type $repeat
@return string A public path which takes into account the base path and URL path | entailment |
public function getAssetsVersion(array $parameters = array(), \Smarty_Internal_Template $template)
{
$parameters = array_merge(array(
'package' => null,
), $parameters);
return $this->helper->getVersion($parameters['package']);
} | Returns the version of the assets in a package.
@param array $parameters
@param \Smarty_Internal_Template $template
@return int | entailment |
public function add(array $data)
{
$result = null;
$this->hook->attach('user.add.before', $data, $result, $this);
if (isset($result)) {
return (int) $result;
}
if (empty($data['name'])) {
$data['name'] = strtok($data['email'], '@');
}
$data['created'] = $data['modified'] = GC_TIME;
$data['hash'] = gplcart_string_hash($data['password']);
$result = $data['user_id'] = $this->db->insert('user', $data);
$this->setAddress($data);
$this->hook->attach('user.add.after', $data, $result, $this);
return (int) $result;
} | Adds a user
@param array $data
@return integer | entailment |
public function update($user_id, array $data)
{
$result = null;
$this->hook->attach('user.update.before', $user_id, $data, $result, $this);
if (isset($result)) {
return (bool) $result;
}
$data['modified'] = GC_TIME;
if (!empty($data['password'])) {
$data['hash'] = gplcart_string_hash($data['password']);
}
if ($this->isSuperadmin($user_id)) {
$data['status'] = 1;
}
$updated = $this->db->update('user', $data, array('user_id' => $user_id));
$data['user_id'] = $user_id;
$updated += (int) $this->setAddress($data);
$result = $updated > 0;
$this->hook->attach('user.update.after', $user_id, $data, $result, $this);
return (bool) $result;
} | Updates a user
@param integer $user_id
@param array $data
@return boolean * | entailment |
public function canDelete($user_id)
{
if ($this->isSuperadmin($user_id)) {
return false;
}
$result = $this->db->fetchColumn('SELECT * FROM orders WHERE user_id=?', array($user_id));
return empty($result);
} | Whether the user can be deleted
@param integer $user_id
@return boolean | entailment |
public function isSuperadmin($user_id = null)
{
if (isset($user_id)) {
return $this->getSuperadminId() == $user_id;
}
return $this->getSuperadminId() == $this->uid;
} | Whether the user is super admin
@param integer|null $user_id
@return boolean | entailment |
public function access($permission, $user_id = null)
{
if ($this->isSuperadmin($user_id)) {
return true;
}
if ($permission === GC_PERM_SUPERADMIN) {
return false;
}
return in_array($permission, $this->getPermissions($user_id));
} | Whether a user has an access to do something
@param string $permission
@param null|int $user_id
@return boolean | entailment |
public function getPermissions($user_id = null)
{
static $permissions = array();
if (!isset($user_id)) {
$user_id = $this->uid;
}
if (isset($permissions[$user_id])) {
return $permissions[$user_id];
}
$user = $this->get($user_id);
if (empty($user['role_id'])) {
return $permissions[$user_id] = array();
}
$role = array();
if (isset($user['role_permissions'])) {
$role['permissions'] = $user['role_permissions'];
} else {
$role = $this->role->get($user['role_id']);
}
if (empty($role['permissions'])) {
return $permissions[$user_id] = array();
}
return $permissions[$user_id] = (array) $role['permissions'];
} | Returns user permissions
@param null|integer $user_id
@return array | entailment |
public function getSession($key = null)
{
$user = $this->session->get('user', array());
if (isset($key)) {
return gplcart_array_get($user, $key);
}
return $user;
} | Returns the current user from the session
@param array|string $key
@return mixed | entailment |
public function passwordMatches($password, $user)
{
if (!is_array($user)) {
$user = $this->get($user);
}
if (empty($user['hash'])) {
return false;
}
return gplcart_string_equals($user['hash'], gplcart_string_hash($password, $user['hash'], 0));
} | Whether the password matches the user's password stored in the database
@param string $password
@param array|int $user
@return boolean | entailment |
protected function deleteLinked($user_id)
{
$this->db->delete('cart', array('user_id' => $user_id));
$this->db->delete('review', array('user_id' => $user_id));
$this->db->delete('history', array('user_id' => $user_id));
$this->db->delete('address', array('user_id' => $user_id));
$this->db->delete('wishlist', array('user_id' => $user_id));
$this->db->delete('rating_user', array('user_id' => $user_id));
$this->db->delete('dashboard', array('user_id' => $user_id));
} | Deletes all database records related to the user ID
@param int $user_id | entailment |
protected function setAddress(array $data)
{
if (empty($data['addresses'])) {
return false;
}
foreach ($data['addresses'] as $address) {
if (empty($address['address_id'])) {
$address['user_id'] = $data['user_id'];
$this->address->add($address);
} else {
$this->address->update($address['address_id'], $address);
}
}
return true;
} | Adds/updates addresses for the user
@param array $data
@return boolean | entailment |
public function set($cid, $data)
{
$result = null;
$this->hook->attach('cache.set.before', $cid, $data, $result, $this);
if (isset($result)) {
return $result;
}
if (is_array($cid)) {
$cid = gplcart_array_hash($cid);
}
$this->file = GC_DIR_CACHE . "/$cid.cache";
$result = false;
if (file_put_contents($this->file, serialize((array) $data)) !== false) {
chmod($this->file, 0600);
$result = true;
}
$this->hook->attach('cache.set.after', $cid, $data, $result, $this);
return (bool) $result;
} | Set cache
@param string|array $cid
@param mixed $data
@return boolean | entailment |
public function get($cid, $options = array())
{
$options += array(
'lifespan' => 0,
'default' => null
);
$result = null;
$this->hook->attach('cache.get.before', $cid, $options, $result, $this);
if (isset($result)) {
return $result;
}
if (is_array($cid)) {
$cid = gplcart_array_hash($cid);
}
$this->file = GC_DIR_CACHE . "/$cid.cache";
$result = $options['default'];
if (is_file($this->file)) {
$this->filemtime = filemtime($this->file);
if (empty($options['lifespan']) || ((GC_TIME - $this->filemtime) < $options['lifespan'])) {
$result = unserialize(file_get_contents($this->file));
}
}
$this->hook->attach('cache.get.after', $cid, $options, $result, $this);
return $result;
} | Returns a cached data
@param string|array $cid
@param array $options
@return mixed | entailment |
public function clear($cache_id, $options = array())
{
$result = null;
$options += array('pattern' => '.cache');
$this->hook->attach('cache.clear.before', $cache_id, $options, $result, $this);
if (isset($result)) {
return $result;
}
$result = true;
if ($cache_id === null) {
array_map('unlink', glob(GC_DIR_CACHE . '/*.cache'));
gplcart_static_clear();
} else {
if (is_array($cache_id)) {
$cache_id = gplcart_array_hash($cache_id);
}
array_map('unlink', glob(GC_DIR_CACHE . "/$cache_id{$options['pattern']}"));
gplcart_static_clear($cache_id);
}
$this->hook->attach('cache.clear.after', $cache_id, $options, $result, $this);
return (bool) $result;
} | Clears a cached data
@param string|null|array $cache_id
@param array $options
@return bool | entailment |
protected function getImageStyleFieldsSettings()
{
return array(
'image_style_category' => $this->text('Category page'),
'image_style_category_child' => $this->text('Category page (child)'),
'image_style_product' => $this->text('Product page'),
'image_style_page' => $this->text('Page'),
'image_style_product_grid' => $this->text('Product catalog (grid)'),
'image_style_product_list' => $this->text('Product catalog (list)'),
'image_style_cart' => $this->text('Cart'),
'image_style_option' => $this->text('Product option'),
'image_style_collection_file' => $this->text('File collection (banners)'),
'image_style_collection_page' => $this->text('Page collection (news/articles)'),
'image_style_collection_product' => $this->text('Product collection (featured products)'),
);
} | Returns an array of image style settings keys and their corresponding field labels
@return array | entailment |
protected function submitSettings()
{
if ($this->isPosted('reset')) {
$this->resetSettings();
} else if ($this->isPosted('save') && $this->validateSettings()) {
$this->updateSettings();
}
} | Saves the submitted settings | entailment |
protected function resetSettings()
{
$this->controlAccess('module_edit');
$this->module->setSettings('frontend', array());
$this->redirect('', $this->text('Settings have been reset to default values'), 'success');
} | Resets module settings to default values | entailment |
protected function setBreadcrumbEditSettings()
{
$breadcrumbs = array();
$breadcrumbs[] = array(
'text' => $this->text('Dashboard'),
'url' => $this->url('admin')
);
$breadcrumbs[] = array(
'text' => $this->text('Modules'),
'url' => $this->url('admin/module/list')
);
$this->setBreadcrumbs($breadcrumbs);
} | Sets bread crumbs on the module settings page | entailment |
public function editUserRole($role_id = null)
{
$this->setUserRole($role_id);
$this->setTitleEditUserRole();
$this->setBreadcrumbEditUserRole();
$this->setData('role', $this->data_role);
$this->setData('permissions', $this->getPermissionsUserRole(true));
$this->submitEditUserRole();
$this->outputEditUserRole();
} | Displays the user role edit page
@param integer|null $role_id | entailment |
protected function getPermissionsUserRole($chunked = false)
{
$permissions = $this->role->getPermissions();
return $chunked ? gplcart_array_split($permissions, 3) : $permissions;
} | Returns an array of permissions
@param bool $chunked
@return array | entailment |
protected function setUserRole($role_id)
{
$this->data_role = array();
if (is_numeric($role_id)) {
$this->data_role = $this->role->get($role_id);
if (empty($this->data_role)) {
$this->outputHttpStatus(404);
}
}
} | Returns a user role data
@param integer|null $role_id | entailment |
protected function submitEditUserRole()
{
if ($this->isPosted('delete')) {
$this->deleteUserRole();
} else if ($this->isPosted('save') && $this->validateEditUserRole()) {
if (isset($this->data_role['role_id'])) {
$this->updateUserRole();
} else {
$this->addUserRole();
}
}
} | Handles a submitted user role data | entailment |
protected function validateEditUserRole()
{
$this->setSubmitted('role');
$this->setSubmittedBool('status');
$this->setSubmitted('update', $this->data_role);
if (!$this->getSubmitted('permissions')) {
$this->setSubmitted('permissions', array());
}
$this->validateComponent('user_role');
return !$this->hasErrors();
} | Validates a submitted user role data
@return boolean | entailment |
protected function deleteUserRole()
{
$this->controlAccess('user_role_delete');
if ($this->role->delete($this->data_role['role_id'])) {
$this->redirect('admin/user/role', $this->text('Role has been deleted'), 'success');
}
$this->redirect('', $this->text('Role has not been deleted'), 'warning');
} | Deletes a user role | entailment |
protected function updateUserRole()
{
$this->controlAccess('user_role_edit');
if ($this->role->update($this->data_role['role_id'], $this->getSubmitted())) {
$this->redirect('admin/user/role', $this->text('Role has been updated'), 'success');
}
$this->redirect('', $this->text('Role has not been updated'), 'warning');
} | Updates a user role | entailment |
protected function addUserRole()
{
$this->controlAccess('user_role_add');
if ($this->role->add($this->getSubmitted())) {
$this->redirect('admin/user/role', $this->text('Role has been added'), 'success');
}
$this->redirect('', $this->text('Role has not been added'), 'warning');
} | Adds a new user role | entailment |
protected function setTitleEditUserRole()
{
if (isset($this->data_role['role_id'])) {
$title = $this->text('Edit %name', array('%name' => $this->data_role['name']));
} else {
$title = $this->text('Add role');
}
$this->setTitle($title);
} | Sets titles on the user role edit page | entailment |
protected function setBreadcrumbEditUserRole()
{
$breadcrumbs = array();
$breadcrumbs[] = array(
'url' => $this->url('admin'),
'text' => $this->text('Dashboard')
);
$breadcrumbs[] = array(
'text' => $this->text('Roles'),
'url' => $this->url('admin/user/role')
);
$this->setBreadcrumbs($breadcrumbs);
} | Sets breadcrumbs on the user role edit page | entailment |
public function listUserRole()
{
$this->actionListUserRole();
$this->setTitleListUserRole();
$this->setBreadcrumbListUserRole();
$this->setFilterListUserRole();
$this->setPagerListUserRole();
$this->setData('user_roles', $this->getListUserRole());
$this->outputListUserRole();
} | Displays the user role overview page | entailment |
protected function setPagerListUserRole()
{
$options = $this->query_filter;
$options['count'] = true;
$pager = array(
'query' => $this->query_filter,
'total' => (int) $this->role->getList($options)
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function actionListUserRole()
{
list($selected, $action, $value) = $this->getPostedAction();
$deleted = $updated = 0;
foreach ($selected as $role_id) {
if ($action === 'status' && $this->access('user_role_edit')) {
$updated += (int) $this->role->update($role_id, array('status' => $value));
}
if ($action === 'delete' && $this->access('user_role_delete')) {
$deleted += (int) $this->role->delete($role_id);
}
}
if ($updated > 0) {
$text = $this->text('Updated %num item(s)', array('%num' => $updated));
$this->setMessage($text, 'success');
}
if ($deleted > 0) {
$text = $this->text('Deleted %num item(s)', array('%num' => $deleted));
$this->setMessage($text, 'success');
}
} | Applies an action to the selected user roles | entailment |
protected function getListUserRole()
{
$conditions = $this->query_filter;
$conditions['limit'] = $this->data_limit;
$list = (array) $this->role->getList($conditions);
$this->prepareListUserRole($list);
return $list;
} | Returns an array of user roles
@return array | entailment |
protected function prepareListUserRole(array &$roles)
{
$permissions = $this->getPermissionsUserRole();
foreach ($roles as &$role) {
if (!empty($role['permissions'])) {
$list = array_intersect_key($permissions, array_flip($role['permissions']));
$role['permissions_list'] = array_chunk($list, 20);
}
}
} | Prepare an array of user roles
@param array $roles | entailment |
protected static function deserializeCommonAttributes(array $data)
{
$result = new static(isset($data['id']) ? $data['id'] : null);
if ($result->getResourceType() != $data['meta']['resourceType']) {
throw new \RuntimeException(sprintf('Error deserializing resource type "%s" into class "%s"', $data['meta']['resourceType'], get_class($result)));
}
$result->meta = Meta::deserializeObject($data['meta']);
if (isset($arr['externalId'])) {
$result->externalId = $data['externalId'];
}
if (isset($data['schemas'])) {
foreach ($data['schemas'] as $schemaId) {
if ($schemaId != $result->getSchemaId()) {
$result->extensions[$schemaId] = isset($data[$schemaId]) ? $data[$schemaId] : null;
}
}
}
return $result;
} | @param array $data
@return static | entailment |
public function setTranslations(array $data, $model, $entity, $delete_existing = true)
{
if (empty($data['translation']) || empty($data["{$entity}_id"]) || !$model->isSupportedEntity($entity)) {
return null;
}
foreach ($data['translation'] as $language => $translation) {
if ($delete_existing) {
$conditions = array(
'entity' => $entity,
'language' => $language,
"{$entity}_id" => $data["{$entity}_id"]
);
$model->delete($conditions);
}
$translation['entity'] = $entity;
$translation['language'] = $language;
$translation["{$entity}_id"] = $data["{$entity}_id"];
$model->add($translation);
}
return true;
} | Deletes and/or adds translations
@param array $data
@param \gplcart\core\models\TranslationEntity $model
@param string $entity
@param bool $delete_existing
@return boolean | entailment |
public function handle($request, Closure $next, $acceptedGroups)
{
$acceptedGroups = explode('|', $acceptedGroups);
// Lets verify that we are authorized to use this post type
if(!in_array($request->route('group'), $acceptedGroups)){
$message = $request->route('post_type') . ' config group is not supported. ';
$hint = 'Verify if you are authorized to use this config group.';
return response()->json([
'code' => 'unsupported_config_group',
'errors' => [
'unsupported_config_group' => [
0 => $message . $hint,
],
],
'hint' => $hint,
], 400);
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed | entailment |
public function init(Request $request, $postType, $id, $customFieldKey)
{
$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);
}
// Disable editting of form
if($postTypeModel->disableEdit){
$errorMessages = 'The post type does not support editting.';
if(array_has($postTypeModel->errorMessages, 'post_type_identifier_does_not_support_edit')){
$errorMessages = $postTypeModel->errorMessages['post_type_identifier_does_not_support_edit'];
}
return $this->abort($errorMessages);
}
// Validate if we need to validate a other post type before showing this post type
$validateBefore = $this->validatePostTypeBefore($request, $postTypeModel, $id);
if($validateBefore['status'] === false){
$errorMessages = $validateBefore['message'];
return $this->abort($errorMessages, $validateBefore['config']);
}
$sanitizedKeys = $this->getValidationsKeys($postTypeModel);
foreach($sanitizedKeys as $saniKey => $saniValue){
$sanitizedKeys[$saniKey] = '';
}
$verifiedFields = [];
$reloadFields = [];
$reloadFieldsMethod = 'none';
// For each custom field given, we need to validate the permission
foreach($request->all() as $key => $value){
// Lets check if the custom field exists and if we got permission
$customFieldObject = $this->getCustomFieldObject($postTypeModel, $key);
if(array_has($customFieldObject, 'single_field_updateable.active')){
if($customFieldObject['single_field_updateable']['active']){
$verifiedFields[] = $key;
if(array_has($customFieldObject, 'single_field_updateable.reload_fields')){
if(is_array($customFieldObject['single_field_updateable']['reload_fields'])){
$reloadFieldsMethod = 'specific';
$reloadFields[] = $customFieldObject['single_field_updateable']['reload_fields'];
} else if ($customFieldObject['single_field_updateable']['reload_fields'] == '*'){
$reloadFieldsMethod = 'all';
$reloadFields[] = $sanitizedKeys;
}
}
}
}
}
// If updating all specific fields is enabled, we override the verified fields
if($postTypeModel->enableAllSpecificFieldsUpdate){
$whitelistedCustomFields = $this->getWhitelistedCustomFields($postTypeModel, $request->all());
$reloadFields = $sanitizedKeys;
// If there is a exlusion active, lets progress that
if(is_array($postTypeModel->excludeSpecificFieldsFromUpdate)){
foreach($postTypeModel->excludeSpecificFieldsFromUpdate as $excludeKey => $excludeValue){
unset($whitelistedCustomFields[$excludeValue]);
unset($reloadFields[$excludeValue]);
}
}
} else {
$whitelistedCustomFields = $this->getWhitelistedCustomFields($postTypeModel, $request->only($verifiedFields));
}
$toValidateKeys = [];
foreach($whitelistedCustomFields as $whiteKey => $whiteValue){
$customFieldObject = $this->getCustomFieldObject($postTypeModel, $whiteKey);
if(is_array($customFieldObject)){
if(array_key_exists('saveable', $customFieldObject) && $customFieldObject['saveable'] == false){
} else {
$toValidateKeys[$whiteKey] = $customFieldObject;
}
}
}
// Validating the request
$validationRules = $this->validatePostFields($toValidateKeys, $request, $postTypeModel, true);
// Get the post instance
$post = $this->findPostInstance($postTypeModel, $request, $postType, $id, 'specific_field_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);
}
// Need to remove validations if the logic is false
$logicValidations = $this->removeValidationsByConditionalLogic($whitelistedCustomFields, $postTypeModel, $post);
foreach($logicValidations as $postmetaKey => $postmetaValue){
if($postmetaValue === false){
if(array_key_exists($postmetaKey, $validationRules)){
unset($validationRules[$postmetaKey]);
unset($whitelistedCustomFields[$postmetaKey]);
}
}
}
$this->validatePost($request, $post, $validationRules);
// Setting a full request so we can show to the front-end what values were given
$fullRequest = $request;
// Regenerate the request to pass it thru existing code
$request = $this->resetRequestValues($request);
foreach($whitelistedCustomFields as $postmetaKey => $postmetaValue){
$request[$postmetaKey] = $postmetaValue;
}
// Manipulate the request so we can empty out the values where the conditional field is not shown
$whitelistedCustomFields = $this->removeValuesByConditionalLogic($whitelistedCustomFields, $postTypeModel, $post);
if(method_exists($postTypeModel, 'on_edit_single_field_event')){
$onCheck = $postTypeModel->on_edit_single_field_event($postTypeModel, $post->id, $whitelistedCustomFields);
if($onCheck['continue'] === false){
$errorMessages = 'You are not authorized to do this.';
if(array_key_exists('message', $onCheck)){
$errorMessages = $onCheck['message'];
}
return $this->abort($errorMessages);
}
}
// Saving the post values to the database
$post = $this->savePostToDatabase('edit', $post, $postTypeModel, $request, $postType, true);
// Saving the post meta values to the database
$this->savePostMetaToDatabase($whitelistedCustomFields, $postTypeModel, $post, $fullRequest, $customFieldKey);
// Lets fire events as registered in the post type
$this->triggerEvent('on_edit_single_field_event', $postTypeModel, $post->id, $whitelistedCustomFields);
$successMessage = 'Field succesfully updated.';
if(array_has($postTypeModel->successMessage, 'field_updated')){
$successMessage = $postTypeModel->successMessage['field_updated'];
}
$show = (new ShowPostController)->init($request, $postType, $id);
$showResponse = json_decode($show->getContent());
// Lets return the response
return response()->json([
'code' => 'success',
'show_response' => $showResponse,
'message' => $successMessage,
'action' => 'edit',
'post' => [
'id' => $post->id,
'post_title' => $post->post_title,
'post_name' => $post->post_name,
'status' => $post->status,
'post_type' => $post->post_type,
'created_at' => $post->created_at,
'updated_at' => $post->updated_at,
],
'fields_updated' => $whitelistedCustomFields,
'fields_given' => $fullRequest->all(),
'reload_fields_method' => $reloadFieldsMethod,
'reload_fields' => $reloadFields,
], 200);
} | The manager of the database communication for adding and manipulating posts | entailment |
protected function validatePost($request, $post, $validationRules)
{
$currentValidationRuleKeys = [];
foreach($request->all() as $requestKey => $requestValue){
$currentValidationRuleKeys[$requestKey] = $requestKey;
}
$validationRules = $this->validateFieldByConditionalLogic($validationRules, $post, $post);
// Lets receive the current items from the post type validation array
if(array_key_exists('post_name', $validationRules) && !is_array($validationRules['post_name'])){
$exploded = explode('|', $validationRules['post_name']);
$validationRules['post_name'] = [];
foreach($exploded as $key => $value){
$validationRules['post_name'][] = $value;
}
}
// Lets validate if a post_name is required.
if(!$post->disableDefaultPostName){
// If we are edditing the current existing post, we must remove the unique check
if($request->get('post_name') == $post->post_name){
$validationRules['post_name'] = 'required';
// If this is not a existing post name, we need to validate if its unique. They are changing the post name.
} else {
// Make sure that only the post_name of the requested post_type is unique
$validationRules['post_name'][] = 'required';
$validationRules['post_name'][] = Rule::unique('cms_posts')->where(function ($query) use ($post) {
return $query->where('post_type', $post->identifier);
});
}
}
$newValidationRules = [];
foreach($currentValidationRuleKeys as $finalKeys => $finalValues){
if(array_key_exists($finalKeys, $validationRules)){
$newValidationRules[$finalKeys] = $validationRules[$finalKeys];
}
}
return $this->validate($request, $newValidationRules);
} | Validating the creation and change of a post | entailment |
public function listCity($country_code, $state_id)
{
$this->setStateCity($state_id);
$this->setCountryCity($country_code);
$this->actionListCity();
$this->setTitleListCity();
$this->setBreadcrumbListCity();
$this->setFilterListCity();
$this->setPagerListCity();
$this->setData('state', $this->data_state);
$this->setData('country', $this->data_country);
$this->setData('cities', $this->getListCity());
$this->outputListCity();
} | Displays the city overview page
@param string $country_code
@param integer $state_id | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.