sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function wishlist(array &$submitted, array $options) { $this->options = $options; $this->submitted = &$submitted; $this->validateWishlist(); $this->validateProductWishlist(); $this->validateUserCartId(); $this->validateStoreId(); $this->unsetSubmitted('update'); return $this->getResult(); }
Performs full wishlist data validation @param array $submitted @param array $options @return array|boolean
entailment
protected function validateWishlist() { $id = $this->getUpdatingId(); if ($id === false) { return null; } $data = $this->wishlist->get($id); if (empty($data)) { $this->setErrorUnavailable('update', $this->translation->text('Wishlist')); return false; } $this->setUpdating($data); return true; }
Validates wishlist data to be updated @return boolean|null
entailment
public function listCategory($category_group_id) { $this->setCategoryGroup($category_group_id); $this->actionListCategory(); $this->setTitleListCategory(); $this->setBreadcrumbListCategory(); $this->setFilterListCategory(); $this->setPagerListCategory(); $this->setData('categories', $this->getListCategory()); $this->setData('category_group_id', $category_group_id); $this->outputListCategory(); }
Displays the category overview page @param integer $category_group_id
entailment
protected function setPagerListCategory() { $options = $this->query_filter; $options['count'] = true; $pager = array( 'query' => $this->query_filter, 'total' => (int) $this->category->getList($options) ); return $this->data_limit = $this->setPager($pager); }
Sets pager @return array
entailment
protected function setCategoryGroup($category_group_id) { $this->data_category_group = $this->category_group->get($category_group_id); if (empty($this->data_category_group)) { $this->outputHttpStatus(404); } }
Sets an array of category group data @param integer $category_group_id
entailment
protected function actionListCategory() { list($selected, $action, $value) = $this->getPostedAction(); $updated = $deleted = 0; foreach ($selected as $category_id) { if ($action === 'status' && $this->access('category_edit')) { $updated += (int) $this->category->update($category_id, array('status' => $value)); } if ($action === 'delete' && $this->access('category_delete')) { $deleted += (int) $this->category->delete($category_id); } } if ($updated > 0) { $message = $this->text('Updated %num item(s)', array('%num' => $updated)); $this->setMessage($message, 'success'); } if ($deleted > 0) { $message = $this->text('Deleted %num item(s)', array('%num' => $deleted)); $this->setMessage($message, 'success'); } }
Applies an action to the selected categories
entailment
protected function getListCategory() { $conditions = $this->query_filter; $conditions['category_group_id'] = $this->data_category_group['category_group_id']; $list = $this->category->getTree($conditions); $this->prepareListCategory($list); return $list; }
Returns an array of categories for a given group @return array
entailment
protected function prepareListCategory(array &$categories) { foreach ($categories as &$category) { $this->setItemIndentation($category, '— '); $this->setItemUrlEntity($category, $this->store, 'category'); } }
Adds extra data to an array of categories @param array $categories
entailment
protected function setBreadcrumbListCategory() { $breadcrumbs = array(); $breadcrumbs[] = array( 'url' => $this->url('admin'), 'text' => $this->text('Dashboard') ); $breadcrumbs[] = array( 'url' => $this->url('admin/content/category-group'), 'text' => $this->text('Category groups') ); $this->setBreadcrumbs($breadcrumbs); }
Sets breadcrumbs to the category overview page
entailment
public function editCategory($category_group_id, $category_id = null) { $this->setCategory($category_id); $this->setCategoryGroup($category_group_id); $this->setTitleEditCategory(); $this->setBreadcrumbEditCategory(); $this->setData('category', $this->data_category); $this->setData('can_delete', $this->canDeleteCategory()); $this->setData('category_group', $this->data_category_group); $this->setData('parent_id', $this->getQuery('parent_id')); $this->setData('categories', $this->getOptionsCategory($category_group_id)); $this->setData('languages', $this->language->getList(array('enabled' => true))); $this->submitEditCategory(); $this->setDataImagesEditCategory(); $this->setDataCategoriesEditCategory(); $this->outputEditCategory(); }
Displays the add/edit category form @param integer $category_group_id @param integer|null $category_id
entailment
protected function canDeleteCategory() { return isset($this->data_category['category_id']) && $this->category->canDelete($this->data_category['category_id']) && $this->access('category_delete'); }
Whether the category can be deleted @return boolean
entailment
protected function setCategory($category_id) { $this->data_category = array(); if (is_numeric($category_id)) { //Set unexisting language code to get original titles. //Otherwise it will be translated to the current language $conditions = array( 'language' => 'und', 'category_id' => $category_id ); $this->data_category = $this->category->get($conditions); if (empty($this->data_category)) { $this->outputHttpStatus(404); } $this->prepareCategory($this->data_category); } }
Sets an array of category data @param integer $category_id
entailment
protected function prepareCategory(array &$category) { $this->setItemAlias($category, 'category', $this->alias); $this->setItemImages($category, 'category', $this->image); $this->setItemTranslation($category, 'category', $this->translation_entity); if (!empty($category['images'])) { foreach ($category['images'] as &$file) { $this->setItemTranslation($file, 'file', $this->translation_entity); } } }
Prepares an array of category data @param array $category
entailment
protected function submitEditCategory() { if ($this->isPosted('delete')) { $this->deleteCategory(); } else if ($this->isPosted('save') && $this->validateEditCategory()) { $this->deleteImagesCategory(); if (isset($this->data_category['category_id'])) { $this->updateCategory(); } else { $this->addCategory(); } } }
Saves a submitted category
entailment
protected function deleteImagesCategory() { $this->controlAccess('category_edit'); $file_ids = $this->getPosted('delete_images', array(), true, 'array'); return $this->image->delete($file_ids); }
Delete category images @return boolean
entailment
protected function validateEditCategory() { $this->setSubmitted('category', null, false); $this->setSubmitted('form', true); $this->setSubmittedBool('status'); $this->setSubmitted('update', $this->data_category); $this->setSubmitted('category_group_id', $this->data_category_group['category_group_id']); $this->validateComponent('category'); return !$this->hasErrors(); }
Validates a submitted category @return bool
entailment
protected function deleteCategory() { $this->controlAccess('category_delete'); if ($this->category->delete($this->data_category['category_id'])) { $url = "admin/content/category/{$this->data_category_group['category_group_id']}"; $this->redirect($url, $this->text('Category has been deleted'), 'success'); } $this->redirect('', $this->text('Category has not been deleted'), 'warning'); }
Deletes a category
entailment
protected function updateCategory() { $this->controlAccess('category_edit'); if ($this->category->update($this->data_category['category_id'], $this->getSubmitted())) { $url = "admin/content/category/{$this->data_category_group['category_group_id']}"; $this->redirect($url, $this->text('Category has been updated'), 'success'); } $this->redirect('', $this->text('Category has not been updated'), 'warning'); }
Updates a category
entailment
protected function addCategory() { $this->controlAccess('category_add'); if ($this->category->add($this->getSubmitted())) { $url = "admin/content/category/{$this->data_category_group['category_group_id']}"; $this->redirect($url, $this->text('Category has been added'), 'success'); } $this->redirect('', $this->text('Category has not been added'), 'warning'); }
Adds a new category
entailment
protected function setDataCategoriesEditCategory() { $category_id = $this->getData('category.category_id'); if (isset($category_id)) { $category_group_id = $this->getData('category_group.category_group_id'); $options = array( 'parent_id' => $category_id, 'category_group_id' => $category_group_id ); $children = $this->category->getTree($options); $exclude = array($category_id); foreach ($children as $child) { $exclude[] = $child['category_id']; } $categories = $this->getData('categories'); $modified = array_diff_key($categories, array_flip($exclude)); $this->setData('categories', $modified); } }
Adds list of categories on the edit category page
entailment
protected function setTitleEditCategory() { if (isset($this->data_category['category_id'])) { $title = $this->text('Edit %name', array('%name' => $this->data_category['title'])); } else { $parent_category_id = $this->getQuery('parent_id'); $parent_category = array(); if (!empty($parent_category_id)) { $parent_category = $this->category->get($parent_category_id); } $vars = array('%name' => $this->data_category_group['title']); if (isset($parent_category['title'])) { $vars['%category'] = $parent_category['title']; $title = $this->text('Add sub-category to %name / %category', $vars); } else { $title = $this->text('Add category to %name', $vars); } } $this->setTitle($title); }
Sets titles on the category edit page
entailment
protected function setBreadcrumbEditCategory() { $breadcrumbs = array(); $breadcrumbs[] = array( 'url' => $this->url('admin'), 'text' => $this->text('Dashboard') ); $breadcrumbs[] = array( 'url' => $this->url('admin/content/category-group'), 'text' => $this->text('Category groups') ); $breadcrumbs[] = array( 'url' => $this->url("admin/content/category/{$this->data_category_group['category_group_id']}"), 'text' => $this->text('Categories of group %name', array('%name' => $this->data_category_group['title'])) ); $this->setBreadcrumbs($breadcrumbs); }
Sets breadcrumbs on the category edit page
entailment
public function set($product_id, $user_id) { $list = (array) $this->getList(array('user_id' => $user_id)); foreach ($list as $item) { if ($item['product_id'] == $product_id) { return $list; } } $limit = $this->getLimit(); if (!empty($limit)) { $exceeding = array_slice($list, $limit - 1, null, true); } if (!empty($exceeding)) { foreach (array_keys($exceeding) as $product_view_id) { $this->delete($product_view_id); } } $data = array( 'user_id' => $user_id, 'product_id' => $product_id ); $this->add($data); return $list; }
Add a viewed product for a user @param int $product_id @param int $user_id @return array
entailment
public function getAlias() { $className = get_class($this); if (substr($className, -6) != 'Config') { throw new \BadMethodCallException('This Config class does not follow the naming convention; you must overwrite the getAlias() method.'); } $classBaseName = substr(strrchr($className, '\\'), 1, -6); return strtolower($classBaseName); }
Returns the mandatory prefix to use when using YAML. This convention is to remove the "Config" postfix from the class name and then lowercase and underscore the result. So: AcmeHelloConfig becomes acme_hello This can be overridden in a sub-class to specify the alias manually. @throws \BadMethodCallException When the extension name does not follow conventions @return string The alias
entailment
public static function field($descriptor, $name = null) { if (is_a($descriptor, 'frictionlessdata\\tableschema\\Fields\\BaseField')) { return $descriptor; } else { if (Utils::isJsonString($descriptor)) { $descriptor = json_decode($descriptor); } elseif (is_array($descriptor)) { $descriptor = json_decode(json_encode($descriptor)); } if (!isset($descriptor->name) && !is_null($name)) { $descriptor->name = $name; } foreach (static::$fieldClasses as $fieldClass) { /** @var BaseField $fieldClass */ if ($field = $fieldClass::inferDescriptor($descriptor)) { return $field; } } throw new FieldValidationException([ new SchemaValidationError( SchemaValidationError::SCHEMA_VIOLATION, 'Could not find a valid field for descriptor: '.json_encode($descriptor)), ]); } }
get a new field object in the correct type according to the descriptor. @param object|array $descriptor @return BaseField @throws \Exception
entailment
public static function infer($val, $descriptor = null, $lenient = false) { foreach (static::$fieldClasses as $fieldClass) { /** @var BaseField $fieldClass */ if ($field = $fieldClass::infer($val, $descriptor, $lenient)) { return $field; } } throw new FieldValidationException([ new SchemaValidationError( SchemaValidationError::SCHEMA_VIOLATION, 'Could not find a valid field for value: '.json_encode($val)), ]); }
@param $val @param null $descriptor @return mixed @throws FieldValidationException
entailment
public function id(array $values) { $count = count($values); $ids = array_filter($values, 'ctype_digit'); if ($count != count($ids)) { return $this->translation->text('@field has invalid value', array( '@field' => $this->translation->text('Condition'))); } $existing = array_filter($values, function ($user_id) { if ($user_id == 0) { return true; // 0 also valid if we check that user is logged in } $user = $this->user->get($user_id); return isset($user['user_id']); }); if ($count != count($existing)) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('User'))); } return true; }
Validates the user ID condition @param array $values @return boolean|string
entailment
public function roleId(array $values) { $count = count($values); $ids = array_filter($values, 'ctype_digit'); if ($count != count($ids)) { return $this->translation->text('@field has invalid value', array( '@field' => $this->translation->text('Condition'))); } $exists = array_filter($values, function ($role_id) { if ($role_id == 0) { return true; } $role = $this->role->get($role_id); return isset($role['role_id']); }); if ($count != count($exists)) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('Role'))); } return true; }
Validates the role ID condition @param array $values @return boolean|string
entailment
public function get($job_id) { $result = null; $this->hook->attach('job.get.before', $job_id, $result, $this); if (isset($result)) { return $result; } $result = $this->getSession($job_id); $this->hook->attach('job.get.after', $job_id, $result, $this); return $result; }
Returns a job array from the session @param string $job_id @return array
entailment
public function set(array $job) { $result = null; $this->hook->attach('job.set.before', $job, $result, $this); if (isset($result)) { return (array) $result; } $default = $this->getDefault(); $result = gplcart_array_merge($default, $job); $existing = $this->getSession($result['id']); if (!empty($existing)) { return (array) $existing; } $this->setSession($result); $this->hook->attach('job.set.after', $job, $result, $this); return (array) $result; }
Sets a job to the session @param array $job @return array
entailment
protected function getDefault() { $current_url = $this->url->get(); return array( 'id' => uniqid(), 'status' => true, 'title' => '', 'url' => '', 'total' => 0, 'errors' => 0, 'done' => 0, 'inserted' => 0, 'updated' => 0, 'context' => array( 'offset' => 0, 'line' => 1, ), 'data' => array(), 'message' => array( 'start' => $this->translation->text('Starting...'), 'finish' => $this->translation->text('Finished'), 'process' => $this->translation->text('Processing...') ), 'redirect' => array( 'finish' => $current_url, 'errors' => $current_url, 'no_results' => $current_url ), 'redirect_message' => array( 'finish' => '', 'errors' => '', 'no_results' => '' ), 'log' => array( 'errors' => '' ) ); }
Returns an array of default job values @return array
entailment
public function delete($job_id = null) { $result = null; $this->hook->attach('job.delete.before', $job_id, $result, $this); if (isset($result)) { return (bool) $result; } $result = $this->session->delete("jobs.$job_id"); $this->hook->attach('job.delete.after', $job_id, $result, $this); return (bool) $result; }
Deletes a job from the session @param mixed $job_id @return boolean
entailment
public function process(array $job) { $this->hook->attach('job.process.before', $job, $this); if (empty($job['status'])) { return $this->getResult($job, array('finish' => true)); } $progress = 0; $start_time = microtime(true); while (round((microtime(true) - $start_time) * 1000, 2) < self::LIMIT) { $this->processIteration($job); if (empty($job['status'])) { break; } $progress = round($job['done'] * 100 / $job['total']); if ($job['done'] < $job['total']) { continue; } $job['status'] = false; break; } $result = array( 'progress' => $progress, 'done' => $job['done'], 'errors' => $job['errors'], 'finish' => empty($job['status']), 'message' => $job['message']['process'] ); $response = $this->getResult($job, $result); $this->hook->attach('job.process.after', $job, $result, $response, $this); return $response; }
Processes one job iteration @param array $job @return array
entailment
protected function processIteration(array &$job) { try { $handlers = $this->getHandlers(); $callback = Handler::get($handlers, $job['id'], 'process'); call_user_func_array($callback, array(&$job)); } catch (Exception $ex) { $job['status'] = false; $job['errors']++; } }
Call a handler processor @param array $job
entailment
public function getTotal($handler_id, array $arguments = array()) { try { $handlers = $this->getHandlers(); return (int) Handler::call($handlers, $handler_id, 'total', array($arguments)); } catch (Exception $ex) { return 0; } }
Returns total number of items to be processed @param string $handler_id @param array $arguments @return integer
entailment
protected function getResult(array $job, array $result = array()) { $result += array( 'done' => 0, 'errors' => 0, 'progress' => 0, 'finish' => false, 'message' => $job['message']['process'] ); if (!empty($result['finish'])) { $this->setFinishData($result, $job); } $this->setSession($job); return $result; }
Returns an array of data to be send to the user @param array $job @param array $result @return array
entailment
protected function setFinishData(array &$result, array &$job) { $result['message'] = $job['message']['finish']; $this->setFinishDataErrors($result, $job); $this->setFinishDataNoErrors($result, $job); }
Sets finish redirect and message @param array $result @param array $job
entailment
protected function setFinishDataErrors(array &$result, array &$job) { if (!empty($job['errors'])) { if (!empty($job['redirect']['errors'])) { $result['redirect'] = $job['redirect']['errors']; } if (empty($job['redirect_message']['errors'])) { $vars = array('%total' => $job['total'], '%errors' => $job['errors']); $message = $this->translation->text('Processed %total items, errors: %errors', $vars); } else { $vars = array('%total' => $job['total'], '%errors' => $job['errors'], '%inserted' => $job['inserted'], '%updated' => $job['updated']); $message = $this->translation->text($job['redirect_message']['errors'], $vars); } $this->session->setMessage($message, 'danger'); } }
Sets finish redirect and message when an error occurred @param array $result @param array $job
entailment
protected function setFinishDataNoErrors(array &$result, array &$job) { if (empty($job['errors'])) { if (!empty($job['redirect']['finish'])) { $result['redirect'] = $job['redirect']['finish']; } else if (!empty($job['redirect']['no_results']) && empty($job['inserted']) && empty($job['updated'])) { $result['redirect'] = $job['redirect']['no_results']; } if (empty($job['redirect_message']['finish'])) { $vars = array('%total' => $job['total']); $message = $this->translation->text('Successfully processed %total items', $vars); } else { $vars = array('%total' => $job['total'], '%inserted' => $job['inserted'], '%updated' => $job['updated']); $message = $this->translation->text($job['redirect_message']['finish'], $vars); } if (!empty($job['redirect_message']['no_results']) && empty($job['inserted']) && empty($job['updated'])) { $vars = array('%total' => $job['total']); $message = $this->translation->text($job['redirect_message']['no_results'], $vars); } $this->session->setMessage($message, 'success'); } }
Sets finish redirect and message when no errors occurred @param array $result @param array $job
entailment
public function submit($job) { $this->delete($job['id']); if (!empty($job['log']['errors'])) { file_put_contents($job['log']['errors'], ''); } $this->set($job); $this->url->redirect('', array('job_id' => $job['id'])); }
Submits a new job @param array $job
entailment
public function setImages(array &$data, $file_model, $entity) { if (empty($data['images']) || empty($data[$entity . '_id'])) { return false; } foreach ($data['images'] as &$image) { if (empty($image['file_id'])) { $image['entity'] = $entity; $image['entity_id'] = $data[$entity . '_id']; $image['file_id'] = (int) $file_model->add($image); } else { $file_model->update($image['file_id'], $image); } } return true; }
Set entity images @param array $data @param \gplcart\core\models\File $file_model @param string $entity @return bool
entailment
public function listFieldValue($field_id) { $this->setFieldFieldValue($field_id); $this->actionListFieldValue(); $this->setTitleListFieldValue(); $this->setBreadcrumbListFieldValue(); $this->setFilterListFieldValue(); $this->setPagerListFieldValue(); $this->setData('field', $this->data_field); $this->setData('values', $this->getListFieldValue()); $this->outputListFieldValue(); }
Displays the field value overview page @param integer $field_id
entailment
protected function setFieldFieldValue($field_id) { $this->data_field = $this->field->get($field_id); if (empty($this->data_field)) { $this->outputHttpStatus(404); } }
Set a field data @param integer $field_id
entailment
protected function actionListFieldValue() { list($selected, $action) = $this->getPostedAction(); $deleted = 0; foreach ($selected as $field_value_id) { if ($action === 'delete' && $this->access('field_value_delete')) { $deleted += (int) $this->field_value->delete($field_value_id); } } if ($deleted > 0) { $message = $this->text('Deleted %num item(s)', array('%num' => $deleted)); $this->setMessage($message, 'success'); } }
Applies an action to the selected field values
entailment
protected function setPagerListFieldValue() { $conditions = $this->query_filter; $conditions['count'] = true; $conditions['field_id'] = $this->data_field['field_id']; $pager = array( 'query' => $this->query_filter, 'total' => (int) $this->field_value->getList($conditions) ); return $this->data_limit = $this->setPager($pager); }
Sets pager @return array
entailment
protected function getListFieldValue() { $conditions = $this->query_filter; $conditions['limit'] = $this->data_limit; $conditions['field_id'] = $this->data_field['field_id']; $list = (array) $this->field_value->getList($conditions); $this->prepareListFieldValue($list); return $list; }
Returns an array of field values for a given field @return array
entailment
protected function prepareListFieldValue(array &$list) { foreach ($list as &$item) { $this->setItemThumb($item, $this->image, array('placeholder' => false)); } }
Prepare an array of field values @param array $list
entailment
protected function setBreadcrumbListFieldValue() { $breadcrumbs = array(); $breadcrumbs[] = array( 'url' => $this->url('admin'), 'text' => $this->text('Dashboard') ); $breadcrumbs[] = array( 'url' => $this->url('admin/content/field'), 'text' => $this->text('Fields') ); $this->setBreadcrumbs($breadcrumbs); }
Sets breadcrumbs on the field values overview page
entailment
public function editFieldValue($field_id, $field_value_id = null) { $this->setFieldFieldValue($field_id); $this->setFieldValue($field_value_id); $this->setTitleEditFieldValue(); $this->setBreadcrumbEditFieldValue(); $this->setData('field', $this->data_field); $this->setData('field_value', $this->data_field_value); $this->setData('widget_types', $this->field->getWidgetTypes()); $this->setData('languages', $this->language->getList(array('enabled' => true))); $this->submitEditFieldValue(); $this->setDataImagesEditFieldValue(); $this->outputEditFieldValue(); }
Displays the field value edit form @param integer $field_id @param integer|null $field_value_id
entailment
protected function setDataImagesEditFieldValue() { $options = array( 'single' => true, 'entity' => 'field_value', 'images' => $this->getData('field_value.images', array()) ); $this->setItemThumb($options, $this->image); $this->setData('attached_images', $this->getWidgetImages($this->language, $options)); }
Adds images on the edit field value page
entailment
protected function submitEditFieldValue() { if ($this->isPosted('delete')) { $this->deleteFieldValue(); } else if ($this->isPosted('save') && $this->validateEditFieldValue()) { $this->deleteImageFieldValue(); if (isset($this->data_field_value['field_value_id'])) { $this->updateFieldValue(); } else { $this->addFieldValue(); } } }
Handles a submitted field value data
entailment
protected function validateEditFieldValue() { $this->setSubmitted('field_value'); $this->setSubmitted('update', $this->data_field_value); $this->setSubmitted('field_id', $this->data_field['field_id']); $this->validateComponent('field_value'); return !$this->hasErrors(); }
Validates a submitted field value @return bool
entailment
protected function setFieldValue($field_value_id) { $this->data_field_value = array(); if (is_numeric($field_value_id)) { $conditions = array( 'language' => 'und', 'field_value_id' => $field_value_id ); $this->data_field_value = $this->field_value->get($conditions); if (empty($this->data_field_value)) { $this->outputHttpStatus(404); } $this->prepareFieldValue($this->data_field_value); } }
Set a field value data @param integer $field_value_id
entailment
protected function prepareFieldValue(array &$field_value) { $this->setItemImages($field_value, 'field_value', $this->image); $this->setItemTranslation($field_value, 'field_value', $this->translation_entity); if (!empty($field_value['images'])) { foreach ($field_value['images'] as &$file) { $this->setItemTranslation($file, 'file', $this->translation_entity); } } }
Prepare an array of field value data @param array $field_value
entailment
protected function deleteFieldValue() { $this->controlAccess('field_value_delete'); if ($this->field_value->delete($this->data_field_value['field_value_id'])) { $url = "admin/content/field/value/{$this->data_field['field_id']}"; $this->redirect($url, $this->text('Field value has been deleted'), 'success'); } $this->redirect('', $this->text('Field value has not been deleted'), 'warning'); }
Deletes a field value
entailment
protected function deleteImageFieldValue() { $this->controlAccess('field_value_edit'); $file_ids = $this->getPosted('delete_images', array(), true, 'array'); if (!empty($file_ids) && isset($this->data_field_value['field_value_id'])) { $db = $disk = 0; $file_id = reset($file_ids); $this->file->deleteAll($file_id, $db, $disk, false); $this->field_value->update($this->data_field_value['field_value_id'], array('file_id' => 0)); } }
Deletes a field value image
entailment
protected function updateFieldValue() { $this->controlAccess('field_value_edit'); if ($this->field_value->update($this->data_field_value['field_value_id'], $this->getSubmitted())) { $url = "admin/content/field/value/{$this->data_field['field_id']}"; $this->redirect($url, $this->text('Field value has been updated'), 'success'); } $this->redirect('', $this->text('Field value has not been updated'), 'warning'); }
Updates a field value
entailment
protected function addFieldValue() { $this->controlAccess('field_value_add'); if ($this->field_value->add($this->getSubmitted())) { $url = "admin/content/field/value/{$this->data_field['field_id']}"; $this->redirect($url, $this->text('Field value has been added'), 'success'); } $this->redirect('', $this->text('Field value has not been added'), 'warning'); }
Adds a new field value
entailment
protected function setTitleEditFieldValue() { if (isset($this->data_field_value['field_value_id'])) { $title = $this->text('Edit %name', array('%name' => $this->data_field_value['title'])); } else { $title = $this->text('Add value for field %name', array('%name' => $this->data_field['title'])); } $this->setTitle($title); }
Sets titles on the edit field value page
entailment
protected function setBreadcrumbEditFieldValue() { $breadcrumbs = array(); $breadcrumbs[] = array( 'url' => $this->url('admin'), 'text' => $this->text('Dashboard') ); $breadcrumbs[] = array( 'url' => $this->url('admin/content/field'), 'text' => $this->text('Fields') ); $breadcrumbs[] = array( 'url' => $this->url("admin/content/field/value/{$this->data_field['field_id']}"), 'text' => $this->text('Values of %name', array('%name' => $this->data_field['title'])) ); $this->setBreadcrumbs($breadcrumbs); }
Sets breadcrumbs on the edit field value page
entailment
protected function getPostType($post_type) { // Receive the config variable where we have whitelisted all models $nikuConfig = config('niku-cms'); // Validating if the model exists in the array if(array_key_exists($post_type, $nikuConfig['post_types'])){ // Setting the model class $postTypeModel = new $nikuConfig['post_types'][$post_type]; // Lets validate if the request has got the correct authorizations set if(!$this->authorizations($postTypeModel)){ return false; } return $postTypeModel; } else { return false; } }
Validating if the post type exists and returning the model.
entailment
protected function sanitizeUrl($url) { $url = $url; $url = preg_replace('~[^\\pL0-9_]+~u', '-', $url); // substitutes anything but letters, numbers and '_' with separator $url = trim($url, "-"); $url = iconv("utf-8", "us-ascii//TRANSLIT", $url); // TRANSLIT does the whole job $url = strtolower($url); $url = preg_replace('~[^-a-z0-9_]+~', '', $url); // keep only letters, numbers, '_' and separator return $url; }
Function for sanitizing slugs
entailment
protected function removeUnregistratedFields($request, $postTypeModel) { $whitelisted = []; $whitelisted[] = 'template'; foreach($request->all() as $requestKey => $requestValue){ $customField = $this->getCustomFieldObject($postTypeModel, $requestKey); if($customField){ if(array_key_exists('saveable', $customField) && $customField['saveable'] == false){ } else { $whitelisted[] = $requestKey; } } } $newRequest = $request->only($whitelisted); $request = $this->resetRequestValues($request); foreach($newRequest as $key => $value){ $request[$key] = $value; } return $request; }
Removing request values, based on input when they are not saveable
entailment
public function savePostMetaToDatabase($postmeta, $postTypeModel, $post, $request = [], $customFieldKey = '') { // Presetting a empty array so we can append pivot values to the sync function. $pivotValue = []; $object = []; $postmeta = $this->removeUnrequiredMetas($postmeta, $postTypeModel); if(!empty($customFieldKey)){ if($request->hasFile('file')){ $postmeta[$customFieldKey] = ''; } } // Saving the meta values to the database. foreach($postmeta as $key => $value){ $customFieldObject = $this->getCustomFieldObject($postTypeModel, $key); if($customFieldObject){ if(array_key_exists('saveable', $customFieldObject)){ if($customFieldObject['saveable'] === false){ continue; } } } // Lets validate if there is a mutator for this value. $value = $this->saveMutator($postTypeModel, $key, $value, $post, $postmeta, $request); // If the custom field does not exist, we may not save it. $customFieldObject = $this->getCustomFieldObject($postTypeModel, $key); if(!is_array($customFieldObject)){ continue; } $type = 'simple'; if(array_key_exists('type', $customFieldObject)){ $type = $customFieldObject['type']; } switch($type){ case 'taxonomy': if(!array_key_exists('post_type', $customFieldObject) && empty($customFieldObject['post_type'])){ continue; } $customfieldPostTypes = $this->getPostTypeIdentifiers($customFieldObject['post_type']); if(!is_array($customfieldPostTypes)){ continue; } if(!is_array($value)){ $value = json_decode($value, true); } // Yes, double. if(!is_array($value)){ continue; } foreach($value as $valueKey => $valueItem){ $where = []; if($postTypeModel->userCanOnlySeeHisOwnPosts){ $where[] = ['post_author', '=', Auth::user()->id]; } $where[] = ['id', '=', $valueItem]; // For each post id give, we need to query the database and validate if this // taxonomie of the connect post does exist and we got permission to it. $taxonomyPost = NikuPosts::where($where) ->whereIn('post_type', $customfieldPostTypes) ->first(); // If there is a taxonomy result, we can safely add it to the pivot. if($taxonomyPost) { $pivotValue[$valueItem] = ['taxonomy' => $key]; } } $post->taxonomies()->sync($pivotValue); break; default: $object[$key] = $value; break; } } $post->saveMetas($object); return $post; }
Saving the post meta to the database
entailment
protected function saveMutator($postTypeModel, $key, $value, $post, $postmeta, $request = []) { $post = $post->toArray(); $postmeta = $postmeta; $postRequest = array_merge($post, $postmeta); // Receiving the custom field $customField = $this->getCustomFieldObject($postTypeModel, $key); if(!empty($customField)){ // Lets see if we have a mutator registered if(array_has($customField, 'mutator') && !empty($customField['mutator'])){ if(method_exists(new $customField['mutator'], 'in')){ $mutatorValue = (new $customField['mutator'])->in($customField, $postRequest, $value, $key, $postTypeModel, $request); // Lets set the new value to the existing value $value = $mutatorValue; } } } return $value; }
Lets check if there are any manipulators active for showing the post
entailment
protected function getPostTypeIdentifiers($postTypes) { $postTypeIdentifiers = []; foreach($postTypes as $postTypeKey => $value){ $postTypeModel = $this->getPostType($value); if($postTypeModel){ // Add the real identifier to the array array_push($postTypeIdentifiers, $postTypeModel->identifier); } } return $postTypeIdentifiers; }
Get the post type real identifiers how it is saved in the database
entailment
public function getCustomFieldObject($postTypeModel, $key) { $allKeys = $this->getValidationsKeys($postTypeModel); if(array_key_exists($key, $allKeys)){ return $allKeys[$key]; } return false; }
Return the custom field object based on the identifier
entailment
public function triggerEvent($action, $postTypeModel, $post, $postmeta) { if(method_exists($postTypeModel, $action)){ $postTypeModel->$action($postTypeModel, $post, $postmeta); } }
Integrate events based on the action
entailment
public function abort($message = 'Not authorized.', $config = '', $code = 'error') { return response()->json([ 'code' => $code, 'errors' => [ $code => [ 0 => $message, ], ], 'config' => $config, ], 430); }
Abort the request
entailment
protected function removeValidationsByConditionalLogic($postmeta, $postTypeModel, $collection) { $allKeys = $this->getValidationsKeys($postTypeModel); foreach($allKeys as $key => $customField){ if(array_key_exists($key, $postmeta)){ $postmeta[$key] = true; } $display = $this->validateValueForLogic($customField, $postTypeModel, $collection); if($display === false){ $postmeta[$key] = false; } else { $postmeta[$key] = true; } } return $postmeta; }
Returning false values by array keys of the items which we need to exclude out of the validation array
entailment
public function showMutator($postTypeModel, $collection, $request) { foreach($collection['templates'] as $groupKey => $groupValue){ foreach($groupValue['customFields'] as $key => $value){ $customField = $this->getCustomFieldObject($postTypeModel, $key); if(array_has($customField, 'mutator') && !empty($customField['mutator'])){ if(method_exists(new $customField['mutator'], 'out')){ if(array_key_exists('value', $collection['templates'][$groupKey]['customFields'][$key])){ $holdValue = $collection['templates'][$groupKey]['customFields'][$key]['value']; } else { $holdValue = ''; } $customField = (new $customField['mutator'])->out($customField, $collection, $key, $postTypeModel, $holdValue, $request); $collection['templates'][$groupKey]['customFields'][$key] = $customField; } } if(array_key_exists('customFields', $value)){ foreach($value['customFields'] as $innerKey => $innerValue){ $customField = $this->getCustomFieldObject($postTypeModel, $innerKey); if(array_has($customField, 'mutator') && !empty($customField['mutator'])){ if(method_exists(new $customField['mutator'], 'out')){ $holdValue = $collection['templates'][$groupKey]['customFields'][$key]['customFields'][$innerKey]['value']; $customField = (new $customField['mutator'])->out($customField, $collection, $innerKey, $postTypeModel, $holdValue, $request); $collection['templates'][$groupKey]['customFields'][$key]['customFields'][$innerKey] = $customField; } } if(array_key_exists('customFields', $innerValue)){ foreach($innerValue['customFields'] as $innerInnerKey => $innerInnerValue){ $customField = $this->getCustomFieldObject($postTypeModel, $innerInnerKey); if(array_has($customField, 'mutator') && !empty($customField['mutator'])){ if(method_exists(new $customField['mutator'], 'out')){ $holdValue = $collection['templates'][$groupKey]['customFields'][$key]['customFields'][$innerKey]['customFields'][$innerInnerKey]['value']; $customField = (new $customField['mutator'])->out($customField, $collection, $innerInnerKey, $postTypeModel, $holdValue, $request); $collection['templates'][$groupKey]['customFields'][$key]['customFields'][$innerKey]['customFields'][$innerInnerKey] = $customField; } } } } } } } } return $collection; }
Lets check if there are any manipulators active for showing the post
entailment
public function getList(array $options) { $result = null; $this->hook->attach('product.related.list.before', $options, $result, $this); if (isset($result)) { return $result; } $result = array(); if (isset($options['product_id'])) { $sql = 'SELECT item_product_id FROM product_related WHERE product_id=?'; if (!empty($options['limit'])) { $sql .= ' LIMIT ' . implode(',', array_map('intval', $options['limit'])); } $result = $this->db->fetchColumnAll($sql, array($options['product_id'])); } $this->hook->attach('product.related.list.after', $options, $result, $this); return $result; }
Returns an array of related products for the given product ID @param array $options @return array
entailment
public function delete($product_id) { $result = null; $this->hook->attach('product.related.delete.before', $product_id, $result, $this); if (isset($result)) { return (bool) $result; } foreach (array('product_id', 'item_product_id') as $field) { if (!$this->db->delete('product_related', array($field => $product_id))) { return false; } } $this->hook->attach('product.related.delete.after', $product_id, $result, $this); return (bool) $result; }
Deletes product relations @param int $product_id @return bool
entailment
public function add($related_product_id, $product_id) { $result = null; $this->hook->attach('product.related.add.before', $related_product_id, $product_id, $result, $this); if (isset($result)) { return (bool) $result; } $this->db->insert('product_related', array('product_id' => $product_id, 'item_product_id' => $related_product_id)); $this->db->insert('product_related', array('product_id' => $related_product_id, 'item_product_id' => $product_id)); $this->hook->attach('product.related.add.after', $related_product_id, $product_id, $result, $this); return (bool) $result; }
Adds product relations @param int $related_product_id @param int $product_id @return bool
entailment
public function configureServiceManager(ServiceManager $serviceManager) { $configs = $serviceManager->get('Config'); $configs['parameters'] = array_merge(array( "monolog.logger.class" => "PPI\Framework\Log\Logger", "monolog.gelf.publisher.class" => "Gelf\MessagePublisher", "monolog.handler.stream.class" => "Monolog\Handler\StreamHandler", "monolog.handler.group.class" => "Monolog\Handler\GroupHandler", "monolog.handler.buffer.class" => "Monolog\Handler\BufferHandler", "monolog.handler.rotating_file.class" => "Monolog\Handler\RotatingFileHandler", "monolog.handler.syslog.class" => "Monolog\Handler\SyslogHandler", "monolog.handler.null.class" => "Monolog\Handler\NullHandler", "monolog.handler.test.class" => "Monolog\Handler\TestHandler", "monolog.handler.gelf.class" => "Monolog\Handler\GelfHandler", "monolog.handler.firephp.class" => "Symfony\Bridge\Monolog\Handler\FirePHPHandler", "monolog.handler.chromephp.class" => "Symfony\Bridge\Monolog\Handler\ChromePhpHandler", "monolog.handler.debug.class" => "Symfony\Bridge\Monolog\Handler\DebugHandler", "monolog.handler.swift_mailer.class" => "Monolog\Handler\SwiftMailerHandler", "monolog.handler.native_mailer.class" => "Monolog\Handler\NativeMailerHandler", "monolog.handler.socket.class" => "Monolog\Handler\SocketHandler", "monolog.handler.pushover.class" => "Monolog\Handler\PushoverHandler", "monolog.handler.fingers_crossed.class" => "Monolog\Handler\FingersCrossedHandler", "monolog.handler.fingers_crossed.error_level_activation_strategy.class" => "Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy", ), $configs['parameters']); $config = $this->processConfiguration($configs, $serviceManager); $handlersToChannels = array(); if (isset($config['handlers'])) { $handlers = array(); foreach ($config['handlers'] as $name => $handler) { $handlers[$handler['priority']][] = array( 'id' => $this->buildHandler($serviceManager, $configs['parameters'], $name, $handler), 'channels' => isset($handler['channels']) ? $handler['channels'] : null, ); } $sortedHandlers = array(); foreach ($handlers as $priorityHandlers) { foreach (array_reverse($priorityHandlers) as $handler) { $sortedHandlers[] = $handler; } } foreach ($sortedHandlers as $handler) { if (!in_array($handler['id'], $this->nestedHandlers)) { $handlersToChannels[$handler['id']] = $handler['channels']; } } } $loggerClass = $configs['parameters']['monolog.logger.class']; $serviceManager->setFactory('monolog.logger', function ($serviceManager) use ($loggerClass, $handlersToChannels) { $logger = new $loggerClass('app'); foreach ($handlersToChannels as $handler => $channels) { $logger->pushHandler($serviceManager->get($handler)); } return $logger; }); }
Create and return the logger. @see https://github.com/symfony/MonologBundle/blob/master/DependencyInjection/MonologExtension.php {@inheritdoc}
entailment
protected function processConfiguration(array $configs, ServiceManager $serviceManager = null) { $alias = $this->getAlias(); if (!isset($configs[$alias])) { return array(); } $parameterBag = $serviceManager->get('application_parameters'); $config = $configs[$alias]; if (isset($config['handlers'])) { foreach (array_keys($config['handlers']) as $k) { if (!isset($config['handlers'][$k]['priority'])) { $config['handlers'][$k]['priority'] = 0; } if (!isset($config['handlers'][$k]['bubble'])) { $config['handlers'][$k]['bubble'] = true; } if (isset($config['handlers'][$k]['path'])) { $config['handlers'][$k]['path'] = $parameterBag->resolveString($config['handlers'][$k]['path']); } } } return $config; }
{@inheritDoc}
entailment
public function getList(array $options) { $options += array('active' => true); $sql = 'SELECT * FROM dashboard'; $conditions = array(); if (isset($options['user_id'])) { $sql .= ' WHERE user_id=?'; $conditions[] = $options['user_id']; } $list = $this->db->fetch($sql, $conditions, array('unserialize' => 'data')); $result = $this->prepareList($list, $options); $this->hook->attach('dashboard.get.user', $result, $this); return $result; }
Returns a dashboard record by a user ID @param array $options @return array
entailment
public function set($user_id, array $data) { $existing = $this->getList(array('user_id' => $user_id)); if (isset($existing['dashboard_id'])) { return $this->update($existing['dashboard_id'], array('data' => $data)); } return $this->add(array('user_id' => $user_id, 'data' => $data)); }
Add/update a dashboard record for a user @param integer $user_id @param array $data @return bool|integer
entailment
public function callHandler($handler_id, $method = 'data', array $arguments = array()) { $handlers = $this->getHandlers(); return Handler::call($handlers, $handler_id, $method, $arguments); }
Call a dashboard handler @param string $handler_id @param string $method @param array $arguments @return mixed
entailment
protected function prepareList($result, array $options) { $handlers = $this->getHandlers(); if (empty($result['data'])) { $result['data'] = $handlers; } else { $result['data'] = array_replace_recursive($handlers, $result['data']); } foreach ($result['data'] as $handler_id => &$handler) { if (!empty($options['active']) && empty($handler['status'])) { unset($result['data'][$handler_id]); continue; } try { $handler['data'] = (array) $this->callHandler($handler_id); } catch (Exception $ex) { $handler['data'] = array(); } } gplcart_array_sort($result['data']); return $result; }
Prepare an array of dashboard items @param array $result @param array $options @return array
entailment
public function createService(ServiceLocatorInterface $serviceLocator) { $parser = $serviceLocator->get('ControllerNameParser'); $logger = $serviceLocator->has('Logger') ? $serviceLocator->get('Logger') : null; return new ControllerResolver($serviceLocator, $parser, $logger); }
Create and return a ControllerResolver instance. @param ServiceLocatorInterface $serviceLocator @return \PPI\Framework\Module\Controller\ControllerResolver
entailment
public function getHandlers() { $handlers = &gplcart_static('install.handlers'); if (isset($handlers)) { return $handlers; } $handlers = array(); $this->hook->attach('install.handlers', $handlers, $this); foreach ($handlers as $id => &$handler) { if (empty($handler['module'])) { unset($handlers[$id]); continue; } $info = $this->module->getInfo($handler['module']); if (empty($info['type']) || $info['type'] !== 'installer') { unset($handlers[$id]); continue; } $handler['id'] = $id; $handler['weight'] = isset($handler['weight']) ? $handler['weight'] : 0; } $handlers = array_merge($handlers, $this->getDefaultHandler()); gplcart_array_sort($handlers); return $handlers; }
Returns an array of defined handlers @return array
entailment
public function getHandler($handler_id) { $handlers = $this->getHandlers(); return empty($handlers[$handler_id]) ? array() : $handlers[$handler_id]; }
Returns an installer handler @param string $handler_id @return array
entailment
public function callHandler($handler_id, array $data) { try { $handlers = $this->getHandlers(); $method = isset($data['step']) ? 'install_' . $data['step'] : 'install'; $result = Handler::call($handlers, $handler_id, $method, array($data, $this->db)); } catch (Exception $ex) { $result = array(); } return (array) $result; }
Process installation by calling a handler @param string $handler_id @param array $data @return array
entailment
public function getRequirements() { $requirements = &gplcart_static('install.requirements'); if (isset($requirements)) { return (array) $requirements; } $requirements = (array) gplcart_config_get(GC_FILE_CONFIG_REQUIREMENT); $this->hook->attach('install.requirements', $requirements); return (array) $requirements; }
Returns an array of requirements @return array
entailment
public function getRequirementErrors(array $requirements) { $errors = array(); foreach ($requirements as $items) { foreach ($items as $name => $info) { if (empty($info['status'])) { $errors[$info['severity']][] = $name; } } } return $errors; }
Returns an array of requirements errors @param array $requirements @return array
entailment
public function connectDb(array $settings) { try { $this->db = new Database; $this->db->init($settings); } catch (Exception $ex) { $this->db = null; return $this->translation->text($ex->getMessage()); } return $this->validateDb(); }
Tries to connect to the database @param array $settings @return boolean|string
entailment
public function validateDb() { $existing = $this->db->query('SHOW TABLES')->fetchColumn(); if (empty($existing)) { return true; } return $this->translation->text('The database you specified already has tables'); }
Validate the database is ready for installation process @return boolean|string
entailment
public function process(array $data, array $cli_route = array()) { $result = null; $this->hook->attach('install.before', $data, $result, $cli_route, $this); $default_result = array( 'message' => '', 'severity' => '', 'redirect' => null ); if (isset($result)) { return array_merge($default_result, (array) $result); } $result = $this->callHandler($data['installer'], $data); $this->hook->attach('install.after', $data, $result, $cli_route, $this); return array_merge($default_result, (array) $result); }
Performs full system installation @param array $data @param array $cli_route @return array
entailment
protected function setErrorRequired($field, $label) { $error = $this->translation->text('@field is required', array('@field' => $label)); return $this->setError($field, $error); }
Set "Field required" error @param string $field @param string $label @return array
entailment
protected function setErrorNumeric($field, $label) { $error = $this->translation->text('@field must be numeric', array('@field' => $label)); return $this->setError($field, $error); }
Set "Field not numeric" error @param string $field @param string $label @return array
entailment
protected function setErrorInteger($field, $label) { $error = $this->translation->text('@field must be integer', array('@field' => $label)); return $this->setError($field, $error); }
Set "Field not integer" error @param string $field @param string $label @return array
entailment
protected function setErrorUnavailable($field, $label) { $error = $this->translation->text('@name is unavailable', array('@name' => $label)); return $this->setError($field, $error); }
Set "Object unavailable" error @param string $field @param string $label @return array
entailment
protected function setErrorLengthRange($field, $label, $min = 1, $max = 255) { $vars = array('@min' => $min, '@max' => $max, '@field' => $label); $error = $this->translation->text('@field must be @min - @max characters long', $vars); return $this->setError($field, $error); }
Set "Length must be between min and max" error @param string $field @param string $label @param int $min @param int $max @return array
entailment
protected function setErrorInvalid($field, $label) { $error = $this->translation->text('@field has invalid value', array('@field' => $label)); return $this->setError($field, $error); }
Set "Invalid value" error @param string $field @param string $label @return array
entailment
protected function setErrorExists($field, $label) { $error = $this->translation->text('@name already exists', array('@name' => $label)); return $this->setError($field, $error); }
Set "Object already exists" error @param string $field @param string $label @return array
entailment
public function validateInteger(array $values) { if (count($values) != 1) { $vars = array('@field' => $this->translation->text('Condition')); return $this->translation->text('@field has invalid value', $vars); } $value = reset($values); if (strlen($value) > 10) { $vars = array('@max' => 10, '@field' => $this->translation->text('Value')); return $this->translation->text('@field must not be longer than @max characters', $vars); } if (ctype_digit($value)) { return true; } $vars = array('@field' => $this->translation->text('Condition')); return $this->translation->text('@field has invalid value', $vars); }
Validates an integer value @param array $values @return boolean|string
entailment
public function id(array $values) { $count = count($values); $ids = array_filter($values, 'ctype_digit'); if ($count != count($ids)) { return $this->translation->text('@field has invalid value', array( '@field' => $this->translation->text('Condition'))); } $existing = array_filter($values, function ($product_id) { $product = $this->product->get($product_id); return isset($product['product_id']); }); if ($count != count($existing)) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('Product'))); } return true; }
Validates the product ID condition @param array $values @return boolean|string
entailment
public function categoryId(array $values) { $count = count($values); $ids = array_filter($values, 'ctype_digit'); if ($count != count($ids)) { return $this->translation->text('@field has invalid value', array( '@field' => $this->translation->text('Condition'))); } $existing = array_filter($values, function ($category_id) { $category = $this->category->get($category_id); return isset($category['category_id']); }); if ($count != count($existing)) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('Category'))); } return true; }
Validates the category ID condition @param array $values @return boolean|string
entailment
public function sku(array $values) { $count = count($values); $existing = array_filter($values, function ($sku) { $sku = $this->sku->get(array('sku' => $sku)); return !empty($sku); }); if ($count != count($existing)) { return $this->translation->text('@name is unavailable', array( '@name' => $this->translation->text('SKU'))); } return true; }
Validates the SKU condition @param array $values @return boolean|string
entailment