_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q2200
Currency.setDefault
train
public function setDefault(CurrencyUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $currency = CurrencyQuery::create()->findPk($event->getCurrencyId())) { // Reset default status CurrencyQuery::create()->filterByByDefault(true)->update(array('ByDefault' => false)); $currency ->setDispatcher($dispatcher) ->setVisible($event->getVisible()) ->setByDefault($event->getIsDefault()) ->save() ; // Update rates when setting a new default currency if ($event->getIsDefault()) { $updateRateEvent = new CurrencyUpdateRateEvent(); $dispatcher->dispatch(TheliaEvents::CURRENCY_UPDATE_RATES, $updateRateEvent); } $event->setCurrency($currency); } }
php
{ "resource": "" }
q2201
Currency.delete
train
public function delete(CurrencyDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== ($currency = CurrencyQuery::create()->findPk($event->getCurrencyId()))) { if ($currency->getByDefault()) { throw new \RuntimeException( Translator::getInstance()->trans('It is not allowed to delete the default currency') ); } $currency ->setDispatcher($dispatcher) ->delete() ; $event->setCurrency($currency); } }
php
{ "resource": "" }
q2202
Activity.getActivityConfigs
train
public function getActivityConfigs( $activity, $config_path ) { $configs = array(); if ( file_exists( $config_path ) ) { $configs = require $config_path; } return isset( $configs[ $activity ] ) ? $configs[ $activity ] : array(); }
php
{ "resource": "" }
q2203
Activity.getActivityCount
train
public function getActivityCount( $activity ) { $plugin_activities = $this->getPluginActivities(); return empty( $plugin_activities[ $activity ] ) ? 0 : $plugin_activities[ $activity ]; }
php
{ "resource": "" }
q2204
Activity.getPluginActivities
train
public function getPluginActivities() { $activities = $this->getActivities(); if ( ! isset( $activities[ $this->plugin ] ) ) { $activities[ $this->plugin ] = array(); } return $activities[ $this->plugin ]; }
php
{ "resource": "" }
q2205
Activity.maybeAddRatingPrompt
train
public function maybeAddRatingPrompt( $activity, $config_path ) { $added = false; $configs = $this->getActivityConfigs( $activity, $config_path ); if ( isset( $configs['threshold'] ) && $this->getActivityCount( $activity ) >= $configs['threshold'] ) { $rating_prompt = new \Boldgrid\Library\Library\RatingPrompt(); $added = $rating_prompt->addPrompt( $configs['prompt'] ); } return $added; }
php
{ "resource": "" }
q2206
Activity.savePluginActivities
train
public function savePluginActivities( $plugin_activities ) { $activities = $this->getActivities(); $activities[ $this->plugin ] = $plugin_activities; return $this->saveActivities( $activities ); }
php
{ "resource": "" }
q2207
ParserContext.cleanFormData
train
protected function cleanFormData(array $data) { foreach ($data as $key => $value) { if (\is_array($value)) { $data[$key] = $this->cleanFormData($value); } elseif (\is_object($value)) { unset($data[$key]); } } return $data; }
php
{ "resource": "" }
q2208
ParserContext.addForm
train
public function addForm(BaseForm $form) { $formErrorInformation = $this->getSession()->getFormErrorInformation(); // Get form field error details $formFieldErrors = []; /** @var Form $field */ foreach ($form->getForm()->getIterator() as $field) { $errors = $field->getErrors(); if (\count($errors) > 0) { $formFieldErrors[$field->getName()] = []; /** @var FormError $error */ foreach ($errors as $error) { $formFieldErrors[$field->getName()][] = [ 'message' => $error->getMessage(), 'template' => $error->getMessageTemplate(), 'parameters' => $error->getMessageParameters(), 'pluralization' => $error->getMessagePluralization() ]; } } } $this->set(\get_class($form) . ":" . $form->getType(), $form); // Set form error information $formErrorInformation[\get_class($form) . ":" . $form->getType()] = [ 'data' => $this->cleanFormData($form->getForm()->getData()), 'hasError' => $form->hasError(), 'errorMessage' => $form->getErrorMessage(), 'method' => $this->requestStack->getCurrentRequest()->getMethod(), 'timestamp' => time(), 'validation_groups' => $form->getForm()->getConfig()->getOption('validation_groups'), 'field_errors' => $formFieldErrors ]; $this->getSession()->setFormErrorInformation($formErrorInformation); return $this; }
php
{ "resource": "" }
q2209
ParserContext.getForm
train
public function getForm($formId, $formClass, $formType) { if (isset($this->store[$formClass . ":" . $formType]) && $this->store[$formClass . ":" . $formType] instanceof BaseForm) { return $this->store[$formClass . ":" . $formType]; } $formErrorInformation = $this->getSession()->getFormErrorInformation(); if (isset($formErrorInformation[$formClass.":".$formType])) { $formInfo = $formErrorInformation[$formClass.":".$formType]; if (\is_array($formInfo['data'])) { $form = $this->formFactory->createForm( $formId, $formType, $formInfo['data'], [ 'validation_groups' => $formInfo['validation_groups'] ] ); // If the form has errors, perform a validation, to restore the internal error context // A controller (as the NewsletterController) may use the parserContext to redisplay a // validated (not errored) form. In such cases, another validation may cause unexpected // results. if (true === $formInfo['hasError']) { try { $this->formValidator->validateForm($form, $formInfo['method']); } catch (\Exception $ex) { // Ignore the exception. } // Manually set the form fields error information, if validateForm() did not the job, // which is the case when the user has been redirected. foreach ($formInfo['field_errors'] as $fieldName => $errors) { /** @var Form $field */ $field = $form->getForm()->get($fieldName); if (null !== $field && \count($field->getErrors()) == 0) { foreach ($errors as $errorData) { $error = new FormError( $errorData['message'], $errorData['template'], $errorData['parameters'], $errorData['pluralization'] ); $field->addError($error); } } } } $form->setError($formInfo['hasError']); // Check if error message is empty, as BaseForm::setErrorMessage() always set form error flag to true. if (! empty($formInfo['errorMessage'])) { $form->setErrorMessage($formInfo['errorMessage']); } return $form; } } return null; }
php
{ "resource": "" }
q2210
ParserContext.clearForm
train
public function clearForm(BaseForm $form) { $formErrorInformation = $this->getSession()->getFormErrorInformation(); $formClass = \get_class($form) . ':' . $form->getType(); if (isset($formErrorInformation[$formClass])) { unset($formErrorInformation[$formClass]); $this->getSession()->setFormErrorInformation($formErrorInformation); } return $this; }
php
{ "resource": "" }
q2211
ParserContext.cleanOutdatedFormErrorInformation
train
protected function cleanOutdatedFormErrorInformation() { $formErrorInformation = $this->getSession()->getFormErrorInformation(); if (! empty($formErrorInformation)) { $now = time(); // Cleanup obsolete form information, and try to find the form data foreach ($formErrorInformation as $name => $formData) { if ($now - $formData['timestamp'] > self::FORM_ERROR_LIFETIME_SECONDS) { unset($formErrorInformation[$name]); } } $this->getSession()->setFormErrorInformation($formErrorInformation); } return $this; }
php
{ "resource": "" }
q2212
MailerFactory.sendEmailToShopManagers
train
public function sendEmailToShopManagers($messageCode, $messageParameters = [], $replyTo = []) { $storeName = ConfigQuery::getStoreName(); // Build the list of email recipients $recipients = ConfigQuery::getNotificationEmailsList(); $to = []; foreach ($recipients as $recipient) { $to[$recipient] = $storeName; } $this->sendEmailMessage( $messageCode, [ConfigQuery::getStoreEmail() => $storeName], $to, $messageParameters, null, [], [], $replyTo ); }
php
{ "resource": "" }
q2213
MailerFactory.createEmailMessage
train
public function createEmailMessage($messageCode, $from, $to, $messageParameters = [], $locale = null, $cc = [], $bcc = [], $replyTo = []) { if (null !== $message = MessageQuery::getFromName($messageCode)) { if ($locale === null) { $locale = Lang::getDefaultLanguage()->getLocale(); } $message->setLocale($locale); // Assign parameters foreach ($messageParameters as $name => $value) { $this->parser->assign($name, $value); } $this->parser->assign('locale', $locale); $instance = $this->getMessageInstance(); $this->setupMessageHeaders($instance, $from, $to, $cc, $bcc, $replyTo); $message->buildMessage($this->parser, $instance); return $instance; } throw new \RuntimeException( Translator::getInstance()->trans( "Failed to load message with code '%code%', propably because it does'nt exists.", [ '%code%' => $messageCode ] ) ); }
php
{ "resource": "" }
q2214
MailerFactory.createSimpleEmailMessage
train
public function createSimpleEmailMessage($from, $to, $subject, $htmlBody, $textBody, $cc = [], $bcc = [], $replyTo = []) { $instance = $this->getMessageInstance(); $this->setupMessageHeaders($instance, $from, $to, $cc, $bcc, $replyTo); $instance->setSubject($subject); // If we do not have an HTML message if (empty($htmlMessage)) { // Message body is the text message $instance->setBody($textBody, 'text/plain'); } else { // The main body is the HTML messahe $instance->setBody($htmlBody, 'text/html'); // Use the text as a message part, if we have one. if (! empty($textMessage)) { $instance->addPart($textBody, 'text/plain'); } } return $instance; }
php
{ "resource": "" }
q2215
Template.create
train
public function create(TemplateCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $template = new TemplateModel(); $template ->setDispatcher($dispatcher) ->setLocale($event->getLocale()) ->setName($event->getTemplateName()) ->save() ; $event->setTemplate($template); }
php
{ "resource": "" }
q2216
Template.duplicate
train
public function duplicate(TemplateDuplicateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $source = TemplateQuery::create()->findPk($event->getSourceTemplateId())) { $source->setLocale($event->getLocale()); $createEvent = new TemplateCreateEvent(); $createEvent ->setLocale($event->getLocale()) ->setTemplateName( Translator::getInstance()->trans("Copy of %tpl", ["%tpl" => $source->getName() ]) ); $dispatcher->dispatch(TheliaEvents::TEMPLATE_CREATE, $createEvent); $clone = $createEvent->getTemplate(); $attrList = AttributeTemplateQuery::create()->findByTemplateId($source->getId()); /** @var $feat AttributeTemplate */ foreach ($attrList as $feat) { $dispatcher->dispatch( TheliaEvents::TEMPLATE_ADD_ATTRIBUTE, new TemplateAddAttributeEvent($clone, $feat->getAttributeId()) ); } $featList = FeatureTemplateQuery::create()->findByTemplateId($source->getId()); /** @var $feat FeatureTemplate */ foreach ($featList as $feat) { $dispatcher->dispatch( TheliaEvents::TEMPLATE_ADD_FEATURE, new TemplateAddFeatureEvent($clone, $feat->getFeatureId()) ); } $event->setTemplate($clone); } }
php
{ "resource": "" }
q2217
Template.update
train
public function update(TemplateUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $template = TemplateQuery::create()->findPk($event->getTemplateId())) { $template ->setDispatcher($dispatcher) ->setLocale($event->getLocale()) ->setName($event->getTemplateName()) ->save(); $event->setTemplate($template); } }
php
{ "resource": "" }
q2218
Template.delete
train
public function delete(TemplateDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== ($template = TemplateQuery::create()->findPk($event->getTemplateId()))) { // Check if template is used by a product $productCount = ProductQuery::create()->findByTemplateId($template->getId())->count(); if ($productCount <= 0) { $con = Propel::getWriteConnection(TemplateTableMap::DATABASE_NAME); $con->beginTransaction(); try { $template ->setDispatcher($dispatcher) ->delete($con); // We have to also delete any reference of this template in category tables // We can't use a FK here, as the DefaultTemplateId column may be NULL // so let's take care of this. CategoryQuery::create() ->filterByDefaultTemplateId($event->getTemplateId()) ->update([ 'DefaultTemplateId' => null], $con); $con->commit(); } catch (\Exception $ex) { $con->rollback(); throw $ex; } } $event->setTemplate($template); $event->setProductCount($productCount); } }
php
{ "resource": "" }
q2219
DoctrineEntityMappingAutodiscoverer.autodiscover
train
public function autodiscover(): void { $entityMappings = []; foreach ($this->fileSystem->getEntityDirectories() as $entityDirectory) { $namespace = $this->namespaceDetector->detectFromDirectory($entityDirectory); if (! $namespace) { continue; } $entityMappings[] = [ 'name' => $namespace, // required name 'prefix' => $namespace, 'type' => 'annotation', 'dir' => $entityDirectory->getRealPath(), 'is_bundle' => false, // performance ]; } $xmlNamespaces = []; $directoryByNamespace = $this->resolveDirectoryByNamespace($this->fileSystem->getEntityXmlFiles()); foreach ($directoryByNamespace as $namespace => $directory) { if (in_array($namespace, $xmlNamespaces, true)) { continue; } $xmlNamespaces[] = $namespace; $entityMappings[] = [ 'name' => $namespace, // required name 'prefix' => $namespace, 'type' => 'xml', 'dir' => $directory, 'is_bundle' => false, ]; } if (! count($entityMappings)) { return; } // @see https://symfony.com/doc/current/reference/configuration/doctrine.html#mapping-entities-outside-of-a-bundle $this->containerBuilder->prependExtensionConfig('doctrine', [ 'orm' => ['mappings' => $entityMappings], ]); }
php
{ "resource": "" }
q2220
AddressController.createFormDataArray
train
protected function createFormDataArray($object) { return array( "label" => $object->getLabel(), "title" => $object->getTitleId(), "firstname" => $object->getFirstname(), "lastname" => $object->getLastname(), "address1" => $object->getAddress1(), "address2" => $object->getAddress2(), "address3" => $object->getAddress3(), "zipcode" => $object->getZipcode(), "city" => $object->getCity(), "country" => $object->getCountryId(), "state" => $object->getStateId(), "cellphone" => $object->getCellphone(), "phone" => $object->getPhone(), "company" => $object->getCompany() ); }
php
{ "resource": "" }
q2221
AddressController.renderEditionTemplate
train
protected function renderEditionTemplate() { return $this->render('customer-edit', array( "address_id" => $this->getRequest()->get('address_id'), "page" => $this->getRequest()->get('page'), "customer_id" => $this->getCustomerId() )); }
php
{ "resource": "" }
q2222
ToolTemplateController.renderToolTemplateHeaderRefreshAction
train
public function renderToolTemplateHeaderRefreshAction() { $melisKey = $this->params()->fromRoute('melisKey', ''); $view = new ViewModel(); $view->melisKey = $melisKey; return $view; }
php
{ "resource": "" }
q2223
ToolTemplateController.renderToolTemplateContentFiltersSitesAction
train
public function renderToolTemplateContentFiltersSitesAction() { $translator = $this->getServiceLocator()->get('translator'); $siteTable = $this->getServiceLocator()->get('MelisEngineTableSite'); $sites = array(); $sites[] = '<option value="">'. $translator->translate('tr_meliscms_tool_templates_tpl_label_choose') .'</option>'; foreach($siteTable->fetchAll() as $site){ $siteName = !empty($site->site_label) ? $site->site_label : $site->site_name; $sites[] = '<option value="'.$site->site_id.'">'. $siteName .'</option>'; } $view = new ViewModel(); $view->sites = $sites; return $view; }
php
{ "resource": "" }
q2224
ToolTemplateController.renderToolTemplatesModalAddHandlerAction
train
public function renderToolTemplatesModalAddHandlerAction() { $melisKey = $this->params()->fromRoute('melisKey', ''); // declare the Tool service that we will be using to completely create our tool. $melisTool = $this->getServiceLocator()->get('MelisCoreTool'); // tell the Tool what configuration in the app.tool.php that will be used. $melisTool->setMelisToolKey('meliscms', 'meliscms_tool_templates'); $view = new ViewModel(); $view->addModalHandler = $melisTool->getModal('meliscms_tool_template_add_modal'); $view->melisKey = $melisKey; return $view; }
php
{ "resource": "" }
q2225
ToolTemplateController.renderToolTemplatesModalEditHandlerAction
train
public function renderToolTemplatesModalEditHandlerAction() { $melisKey = $this->params()->fromRoute('melisKey', ''); // declare the Tool service that we will be using to completely create our tool. $melisTool = $this->getServiceLocator()->get('MelisCoreTool'); // tell the Tool what configuration in the app.tool.php that will be used. $melisTool->setMelisToolKey('meliscms', 'meliscms_tool_templates'); $view = new ViewModel(); $view->editModalHandler = $melisTool->getModal('meliscms_tool_template_edit_modal'); $view->melisKey = $melisKey; return $view; }
php
{ "resource": "" }
q2226
ToolTemplateController.renderToolTemplatesModalEmptyHandlerAction
train
public function renderToolTemplatesModalEmptyHandlerAction() { $melisKey = $this->params()->fromRoute('melisKey', ''); $view = new ViewModel(); $view->melisKey = $melisKey; return $view; }
php
{ "resource": "" }
q2227
ToolTemplateController.modalTabToolTemplateAddAction
train
public function modalTabToolTemplateAddAction() { // declare the Tool service that we will be using to completely create our tool. $melisTool = $this->getServiceLocator()->get('MelisCoreTool'); // tell the Tool what configuration in the app.tool.php that will be used. $melisTool->setMelisToolKey('meliscms', 'meliscms_tool_templates'); $view = new ViewModel(); $view->setVariable('meliscms_tool_template_add', $melisTool->getForm('meliscms_tool_template_generic_form')); return $view; }
php
{ "resource": "" }
q2228
ToolTemplateController.getTemplateByPageIdAction
train
public function getTemplateByPageIdAction() { $success = 0; $request = $this->getRequest(); $data = array(); if($request->isPost()) { $template = $this->getServiceLocator()->get("MelisPageTemplate"); $success = 2; $data = $template->getTemplate($pageId); } return $data; }
php
{ "resource": "" }
q2229
ToolTemplateController.getControllers
train
protected function getControllers(string $controllersPath) : array { $controllers = []; // List all controller files inside the ..src/controller folder if (is_dir($controllersPath)) { foreach (scandir($controllersPath) as $controller) { // Skip directory pointers if ($controller == '.' || $controller == '..' || is_dir($controllersPath . '/' . $controller)) { continue; } // Check if file's extension is ".php" $filePath = $controllersPath . '/' . $controller; $fileExt = pathinfo($filePath)['extension']; if ($fileExt == 'php' && is_file($filePath)) { $controllers[] = $controller; } } } return $controllers; }
php
{ "resource": "" }
q2230
ToolTemplateController.getTemplateDataByIdAction
train
public function getTemplateDataByIdAction() { $request = $this->getRequest(); $data = array(); if($request->isPost()) { $templatesModel = $this->getServiceLocator()->get('MelisEngineTableTemplate'); $templateId = $request->getPost('templateId'); if(is_numeric($templateId)) $data = $templatesModel->getEntryById($templateId); } return new JsonModel($data); }
php
{ "resource": "" }
q2231
License.ajaxClear
train
public function ajaxClear() { $plugin = ! empty( $_POST['plugin'] ) ? sanitize_text_field( $_POST['plugin'] ) : null; if ( empty( $plugin ) ) { wp_send_json_error( __( 'Unknown plugin.', 'boldgrid-library' ) ); } if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( __( 'Access denied.', 'boldgrid-library' ) ); } $success = $this->clearTransient(); if ( ! $success ) { wp_send_json_error( array( 'string' => sprintf( // translators: 1 The name of a transient that we were unable to delete. __( 'Failed to clear license data. Unable to delete site transient "%1$s".', 'boldgrid-library' ), $this->getKey() ), )); } $this->initLicense(); $return = array( 'isPremium' => $this->isPremium( $plugin ), 'string' => $this->licenseString, ); wp_send_json_success( $return ); }
php
{ "resource": "" }
q2232
License.registerScripts
train
public function registerScripts() { $handle = 'bglib-license'; wp_register_script( $handle, Library\Configs::get( 'libraryUrl' ) . 'src/assets/js/license.js', 'jQuery' ); $translations = array( 'unknownError' => __( 'Unknown error', 'boldgrid-library' ), ); wp_localize_script( $handle, 'bglibLicense', $translations ); }
php
{ "resource": "" }
q2233
License.setLicense
train
private function setLicense() { if ( ! $this->getApiKey() ) { $license = 'Missing Connect Key'; } else if ( ! ( $license = $this->getTransient() ) || ! $this->isVersionValid( $license ) ) { delete_site_transient( $this->getKey() ); $license = $this->getRemoteLicense(); } return $this->license = $license; }
php
{ "resource": "" }
q2234
License.setTransient
train
private function setTransient() { return ! $this->getTransient() && set_site_transient( $this->getKey(), $this->getLicense(), $this->getExpiration( $this->getData() ) ); }
php
{ "resource": "" }
q2235
License.isValid
train
private function isValid() { $data = $this->getTransient(); $valid = array( 'key', 'cipher', 'iv', 'data' ); if ( is_object( $data ) ) { $props = array_keys( get_object_vars( $data ) ); $valid = array_diff( $valid, $props ); } return empty( $valid ); }
php
{ "resource": "" }
q2236
License.setData
train
private function setData() { if ( $license = $this->getLicense() ) { $data = json_decode( openssl_decrypt( $license->data, $license->cipher, $license->key, 0, urldecode( $license->iv ) ) ); } return $this->data = $data; }
php
{ "resource": "" }
q2237
License.deactivate
train
public function deactivate() { if ( ! $this->isValid() && Configs::get( 'licenseActivate' ) ) { delete_site_transient( $this->getKey() ); deactivate_plugins( Configs::get( 'file' ) ); } }
php
{ "resource": "" }
q2238
License.getRemoteLicense
train
private function getRemoteLicense() { $call = new Api\Call( Configs::get( 'api' ) . '/api/plugin/getLicense?v=' . $this->apiVersion ); if ( ! $response = $call->getError() ) { $response = $call->getResponse()->result->data; } return $response; }
php
{ "resource": "" }
q2239
License.initLicense
train
public function initLicense() { $this->license = $this->setLicense(); if ( is_object( $this->getLicense() ) ) { $this->data = $this->setData(); $this->setTransient( $this->getData() ); $licenseData = array( 'licenseData' => $this->getData() ); Configs::set( $licenseData, Configs::get() ); } }
php
{ "resource": "" }
q2240
License.isPremium
train
public function isPremium( $product ) { $isPremium = isset( $this->getData()->$product ); $this->licenseString = $isPremium ? __( 'Premium', 'boldgrid-connect' ) : __( 'Free', 'boldgrid-library' ); return $isPremium; }
php
{ "resource": "" }
q2241
License.isVersionValid
train
public function isVersionValid( $license ) { return ( ! empty( $license->version ) && ! empty( $license->iv ) && 16 === strlen( urldecode( $license->iv ) ) && $this->apiVersion === $license->version ); }
php
{ "resource": "" }
q2242
SessionController.applyUserLocale
train
protected function applyUserLocale(UserInterface $user) { // Set the current language according to locale preference $locale = $user->getLocale(); if (null === $lang = LangQuery::create()->findOneByLocale($locale)) { $lang = Lang::getDefaultLanguage(); } $this->getSession()->setLang($lang); }
php
{ "resource": "" }
q2243
DatabaseConfigurationSource.addConnection
train
protected function addConnection($name, array $parameters = [], array $envParameters = []) { $connectionParameterBag = new ParameterBag($envParameters); $connectionParameterBag->add($parameters); $connectionParameterBag->resolve(); $this->connections[$name] = $connectionParameterBag; }
php
{ "resource": "" }
q2244
ShadowTranslateBehavior.setupFieldAssociations
train
public function setupFieldAssociations($fields, $table, $fieldConditions, $strategy) { $config = $this->getConfig(); $this->_table->hasMany($config['translationTable'], [ 'className' => $config['translationTable'], 'foreignKey' => 'id', 'strategy' => $strategy, 'propertyName' => '_i18n', 'dependent' => true, ]); }
php
{ "resource": "" }
q2245
ShadowTranslateBehavior._addFieldsToQuery
train
protected function _addFieldsToQuery(Query $query, array $config) { if ($query->isAutoFieldsEnabled()) { return true; } $select = array_filter($query->clause('select'), function ($field) { return is_string($field); }); if (!$select) { return true; } $alias = $config['mainTableAlias']; $joinRequired = false; foreach ($this->_translationFields() as $field) { if (array_intersect($select, [$field, "$alias.$field"])) { $joinRequired = true; $query->select($query->aliasField($field, $config['hasOneAlias'])); } } if ($joinRequired) { $query->select($query->aliasField('locale', $config['hasOneAlias'])); } return $joinRequired; }
php
{ "resource": "" }
q2246
ShadowTranslateBehavior._iterateClause
train
protected function _iterateClause(Query $query, $name = '', $config = []) { $clause = $query->clause($name); if (!$clause || !$clause->count()) { return false; } $alias = $config['hasOneAlias']; $fields = $this->_translationFields(); $mainTableAlias = $config['mainTableAlias']; $mainTableFields = $this->_mainFields(); $joinRequired = false; $clause->iterateParts(function ($c, &$field) use ($fields, $alias, $mainTableAlias, $mainTableFields, &$joinRequired) { if (!is_string($field) || strpos($field, '.')) { return $c; } if (in_array($field, $fields)) { $joinRequired = true; $field = "$alias.$field"; } elseif (in_array($field, $mainTableFields)) { $field = "$mainTableAlias.$field"; } return $c; }); return $joinRequired; }
php
{ "resource": "" }
q2247
ShadowTranslateBehavior._traverseClause
train
protected function _traverseClause(Query $query, $name = '', $config = []) { $clause = $query->clause($name); if (!$clause || !$clause->count()) { return false; } $alias = $config['hasOneAlias']; $fields = $this->_translationFields(); $mainTableAlias = $config['mainTableAlias']; $mainTableFields = $this->_mainFields(); $joinRequired = false; $clause->traverse(function ($expression) use ($fields, $alias, $mainTableAlias, $mainTableFields, &$joinRequired) { if (!($expression instanceof FieldInterface)) { return; } $field = $expression->getField(); if (!is_string($field) || strpos($field, '.')) { return; } if (in_array($field, $fields)) { $joinRequired = true; $expression->setField("$alias.$field"); return; } if (in_array($field, $mainTableFields)) { $expression->setField("$mainTableAlias.$field"); } }); return $joinRequired; }
php
{ "resource": "" }
q2248
ShadowTranslateBehavior._mainFields
train
protected function _mainFields() { $fields = $this->getConfig('mainTableFields'); if ($fields) { return $fields; } $table = $this->_table; $fields = $table->getSchema()->columns(); $this->setConfig('mainTableFields', $fields); return $fields; }
php
{ "resource": "" }
q2249
ShadowTranslateBehavior._translationFields
train
protected function _translationFields() { $fields = $this->getConfig('fields'); if ($fields) { return $fields; } $table = $this->_translationTable(); $fields = $table->getSchema()->columns(); $fields = array_values(array_diff($fields, ['id', 'locale'])); $this->setConfig('fields', $fields); return $fields; }
php
{ "resource": "" }
q2250
ModelCriteriaTools.getI18n
train
public static function getI18n( $backendContext, $requestedLangId, ModelCriteria &$search, $currentLocale, $columns, $foreignTable, $foreignKey, $forceReturn = false, $localeAlias = null ) { // If a lang has been requested, find the related Lang object, and get the locale if ($requestedLangId !== null) { $localeSearch = LangQuery::create()->findByIdOrLocale($requestedLangId); if ($localeSearch === null) { throw new \InvalidArgumentException( sprintf( 'Incorrect lang argument given : lang %s not found', $requestedLangId ) ); } $locale = $localeSearch->getLocale(); } else { // Use the currently defined locale $locale = $currentLocale; } // Call the proper method depending on the context: front or back if ($backendContext) { self::getBackEndI18n($search, $locale, $columns, $foreignTable, $foreignKey, $localeAlias); } else { self::getFrontEndI18n($search, $locale, $columns, $foreignTable, $foreignKey, $forceReturn, $localeAlias); } return $locale; }
php
{ "resource": "" }
q2251
AnalysisTrait.provideFilesToCheck
train
public function provideFilesToCheck() { $iterator = new AppendIterator(); foreach ($this->getPaths() as $path) { $iterator->append(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path))); } $files = new CallbackFilterIterator($iterator, function ($file) { return $file->getFilename()[0] !== '.' && !$file->isDir(); }); return array_map(function ($file) { return [(string) $file]; }, iterator_to_array($files)); }
php
{ "resource": "" }
q2252
Connect.isConnectScreen
train
public function isConnectScreen( $screen ) { $base = ! empty( $screen->base ) ? $screen->base : null; return 'settings_page_boldgrid-connect' === $base; }
php
{ "resource": "" }
q2253
Connect.addScripts
train
public function addScripts() { if ( $this->isConnectScreen( get_current_screen() ) ) { // Enqueue bglib-connect js. $handle = 'bglib-connect'; wp_register_script( $handle, Configs::get( 'libraryUrl' ) . 'src/assets/js/connect.js' , array( 'jquery' ), date( 'Ymd' ), false ); $translation = array( 'settingsSaved' => __( 'Settings saved.', 'boldgrid-library' ), 'unknownError' => __( 'Unknown error.', 'boldgrid-library' ), 'ajaxError' => __( 'Could not reach the AJAX URL address. HTTP error: ', 'boldgrid-library' ), ); wp_localize_script( $handle, 'BoldGridLibraryConnect', $translation ); wp_enqueue_script( $handle ); // Enqueue jquery-toggles js. wp_enqueue_script( 'jquery-toggles', Configs::get( 'libraryUrl' ) . 'build/toggles.min.js', array( 'jquery' ), date( 'Ymd' ), true ); // Enqueue jquery-toggles css. wp_enqueue_style( 'jquery-toggles-full', Configs::get( 'libraryUrl' ) . 'build/toggles-full.css', array(), date( 'Ymd' ) ); /** * Add additional scripts to Connect page. * * @since 2.4.0 */ do_action( 'Boldgrid\Library\Library\Page\Connect\addScripts' ); } }
php
{ "resource": "" }
q2254
Connect.saveSettings
train
public function saveSettings() { // Check user permissions. if ( ! current_user_can( 'update_plugins' ) ) { wp_send_json_error( array( 'error' => __( 'User access violation!', 'boldgrid-library' ), ) ); } // Check security nonce and referer. if ( ! check_admin_referer( 'boldgrid_library_connect_settings_save' ) ) { wp_send_json_error( array( 'error' => __( 'Security violation! Please try again.', 'boldgrid-library' ), ) ); } // Read settings form POST request, sanitize, and merge settings with saved. $boldgridSettings = array_merge( get_option( 'boldgrid_settings' ), self::sanitizeSettings( array( 'autoupdate' => ! empty( $_POST['autoupdate'] ) ? (array) $_POST['autoupdate'] : array(), 'release_channel' => ! empty( $_POST['plugin_release_channel'] ) ? sanitize_key( $_POST['plugin_release_channel'] ) : 'stable', 'theme_release_channel' => ! empty( $_POST['theme_release_channel'] ) ? sanitize_key( $_POST['theme_release_channel'] ) : 'stable', ) ) ); // If new auto-update settings were passed, then remove deprecated settings. if ( ! empty( $_POST['autoupdate'] ) ) { unset( $boldgridSettings['plugin_autoupdate'], $boldgridSettings['theme_autoupdate'] ); } update_option( 'boldgrid_settings', $boldgridSettings ); wp_send_json_success(); }
php
{ "resource": "" }
q2255
Connect.sanitizeSettings
train
public static function sanitizeSettings( array $settings ) { $result = array(); if ( ! empty( $settings['autoupdate'] ) && is_array( $settings['autoupdate'] ) ) { foreach ( $settings['autoupdate'] as $category => $itemSetting ) { $category = sanitize_key( $category ); foreach ( $itemSetting as $id => $val ) { $id = sanitize_text_field( $id ); $result['autoupdate'][ $category ][ $id ] = (bool) $val; } } } // Validate release channel settings. $channels = array( 'stable', 'edge', 'candidate', ); if ( empty( $settings['release_channel'] ) || ! in_array( $settings['release_channel'], $channels, true ) ) { $result['release_channel'] = 'stable'; } else { $result['release_channel'] = $settings['release_channel']; } if ( empty( $settings['theme_release_channel'] ) || ! in_array( $settings['theme_release_channel'], $channels, true ) ) { $result['theme_release_channel'] = 'stable'; } else { $result['theme_release_channel'] = $settings['theme_release_channel']; } return $result; }
php
{ "resource": "" }
q2256
HookHelper.trans
train
protected function trans($context, $key) { $message = ""; if (array_key_exists($context, $this->messages)) { if (array_key_exists($key, $this->messages[$context])) { $message = $this->messages[$context][$key]; } } return $message; }
php
{ "resource": "" }
q2257
CategoryQuery.getPathToCategory
train
public static function getPathToCategory($categoryId) { $path = []; $category = (new CategoryQuery)->findPk($categoryId); if ($category !== null) { $path[] = $category; if ($category->getParent() !== 0) { $path = array_merge(self::getPathToCategory($category->getParent()), $path); } } return $path; }
php
{ "resource": "" }
q2258
Request.getPathInfo
train
public function getPathInfo() { $pathInfo = parent::getPathInfo(); $pathLength = \strlen($pathInfo); if ($pathInfo !== '/' && $pathInfo[$pathLength - 1] === '/' && (bool) ConfigQuery::read('allow_slash_ended_uri', false) ) { if (null === $this->resolvedPathInfo) { $this->resolvedPathInfo = substr($pathInfo, 0, $pathLength - 1); // Remove the slash } $pathInfo = $this->resolvedPathInfo; } return $pathInfo; }
php
{ "resource": "" }
q2259
Registration.preUpgradePlugin
train
public function preUpgradePlugin( $options ) { $plugin = ! empty( $options['hook_extra']['plugin'] ) ? $options['hook_extra']['plugin'] : null; $isBoldgridPlugin = \Boldgrid\Library\Library\Util\Plugin::isBoldgridPlugin( $plugin ); if( $isBoldgridPlugin ) { /* * Before this plugin is upgraded, remove it from the list of * registered libraries. * * We need to remove it because this plugin may be upgraded * (or downgraded) to a version of the plugin where it does not * contain the library. * * Reregistration of this plugin will take place in the constructor * the next time this class is instantiated. */ $utilPlugin = new \Boldgrid\Library\Util\Registration\Plugin( $plugin ); $utilPlugin->deregister(); } return $options; }
php
{ "resource": "" }
q2260
PingdomApi.getDomains
train
public function getDomains() { $domains = array(); $checks = $this->getChecks(); foreach ($checks as $check) { $domains[$check->id] = $check->hostname; } return $domains; }
php
{ "resource": "" }
q2261
PingdomApi.getChecks
train
public function getChecks($limit = NULL, $offset = NULL) { $parameters = array(); if (!empty($limit)) { $parameters['limit'] = $limit; if (!empty($offset)) { $parameters['offset'] = $offset; } } $data = $this->request('GET', 'checks', $parameters); return $data->checks; }
php
{ "resource": "" }
q2262
PingdomApi.getCheck
train
public function getCheck($check_id) { $this->ensureParameters(array('check_id' => $check_id), __METHOD__); $data = $this->request('GET', "checks/${check_id}"); return $data->check; }
php
{ "resource": "" }
q2263
PingdomApi.addCheck
train
public function addCheck($check, $defaults = array()) { $this->ensureParameters(array( 'name' => $check['name'], 'host' => $check['host'], 'url' => $check['url'], ), __METHOD__); $check += $defaults; $data = $this->request('POST', 'checks', $check); return sprintf('Created check %s for %s at http://%s%s', $data->check->id, $check['name'], $check['host'], $check['url']); }
php
{ "resource": "" }
q2264
PingdomApi.pauseCheck
train
public function pauseCheck($check_id) { $this->ensureParameters(array('check_id' => $check_id), __METHOD__); $check = array( 'paused' => TRUE, ); return $this->modifyCheck($check_id, $check); }
php
{ "resource": "" }
q2265
PingdomApi.unpauseCheck
train
public function unpauseCheck($check_id) { $this->ensureParameters(array('check_id' => $check_id), __METHOD__); $check = array( 'paused' => FALSE, ); return $this->modifyCheck($check_id, $check); }
php
{ "resource": "" }
q2266
PingdomApi.pauseChecks
train
public function pauseChecks($check_ids) { $this->ensureParameters(array('check_ids' => $check_ids), __METHOD__); $parameters = array( 'paused' => TRUE, ); return $this->modifyChecks($check_ids, $parameters); }
php
{ "resource": "" }
q2267
PingdomApi.unpauseChecks
train
public function unpauseChecks($check_ids) { $this->ensureParameters(array('check_ids' => $check_ids), __METHOD__); $parameters = array( 'paused' => FALSE, ); return $this->modifyChecks($check_ids, $parameters); }
php
{ "resource": "" }
q2268
PingdomApi.modifyCheck
train
public function modifyCheck($check_id, $parameters) { $this->ensureParameters(array( 'check_id' => $check_id, 'parameters' => $parameters, ), __METHOD__); $data = $this->request('PUT', "checks/${check_id}", $parameters); return $data->message; }
php
{ "resource": "" }
q2269
PingdomApi.modifyChecks
train
public function modifyChecks($check_ids, $parameters) { $this->ensureParameters(array( 'check_ids' => $check_ids, 'parameters' => $parameters, ), __METHOD__); $parameters['checkids'] = implode(',', $check_ids); $data = $this->request('PUT', 'checks', $parameters); return $data->message; }
php
{ "resource": "" }
q2270
PingdomApi.modifyAllChecks
train
public function modifyAllChecks($parameters) { $this->ensureParameters(array('parameters' => $parameters), __METHOD__); $data = $this->request('PUT', 'checks', $parameters); return $data->message; }
php
{ "resource": "" }
q2271
PingdomApi.removeCheck
train
public function removeCheck($check_id) { $this->ensureParameters(array('check_id' => $check_id), __METHOD__); $data = $this->request('DELETE', "checks/${check_id}"); return $data->message; }
php
{ "resource": "" }
q2272
PingdomApi.getContacts
train
public function getContacts($limit = NULL, $offset = NULL) { $parameters = array(); if (!empty($limit)) { $parameters['limit'] = $limit; if (!empty($offset)) { $parameters['offset'] = $offset; } } $data = $this->request('GET', 'contacts', $parameters); return $data->contacts; }
php
{ "resource": "" }
q2273
PingdomApi.getAnalysis
train
public function getAnalysis($check_id, $parameters = array()) { $this->ensureParameters(array('check_id' => $check_id), __METHOD__); $data = $this->request('GET', "analysis/${check_id}", $parameters); return $data->analysis; }
php
{ "resource": "" }
q2274
PingdomApi.getRawAnalysis
train
public function getRawAnalysis($check_id, $analysis_id, $parameters = array()) { $this->ensureParameters(array( 'check_id' => $check_id, 'analysis_id' => $analysis_id, ), __METHOD__); $data = $this->request('GET', "analysis/{$check_id}/{$analysis_id}", $parameters); return $data; }
php
{ "resource": "" }
q2275
PingdomApi.ensureParameters
train
public function ensureParameters($parameters = array(), $method) { if (empty($parameters) || empty($method)) { throw new MissingParameterException(sprintf('%s called without required parameters.', __METHOD__)); } foreach ($parameters as $parameter => $value) { if (!isset($value)) { throw new MissingParameterException(sprintf('Missing required %s parameter in %s', $parameter, $method)); } } }
php
{ "resource": "" }
q2276
PingdomApi.request
train
public function request($method, $resource, $parameters = array(), $headers = array(), $body = NULL) { $handle = curl_init(); $headers[] = 'Content-Type: application/json; charset=utf-8'; $headers[] = 'App-Key: ' . $this->api_key; if (!empty($this->account_email)) { $headers[] = 'Account-Email: '.$this->account_email; } if (!empty($body)) { if (!is_string($body)) { $body = json_encode($body); } curl_setopt($handle, CURLOPT_POSTFIELDS, $body); $headers[] = 'Content-Length: ' . strlen($body); } if (!empty($headers)) { curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); } curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($handle, CURLOPT_URL, $this->buildRequestUrl($resource, $parameters)); curl_setopt($handle, CURLOPT_USERPWD, $this->getAuth()); curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($handle, CURLOPT_MAXREDIRS, 10); curl_setopt($handle, CURLOPT_USERAGENT, 'PingdomApi/1.0'); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($handle, CURLOPT_TIMEOUT, 10); $gzip = !empty($this->gzip) ? 'gzip' : ''; curl_setopt($handle, CURLOPT_ENCODING, $gzip); $response = curl_exec($handle); if (curl_errno($handle) > 0) { $curl_error = sprintf('Curl error: %s', curl_error($handle)); curl_close($handle); throw new CurlErrorException($curl_error, $curl_errno); } $data = json_decode($response); $status = curl_getinfo($handle, CURLINFO_HTTP_CODE); curl_close($handle); $status_class = (int) floor($status / 100); if ($status_class === 4 || $status_class === 5) { $message = $this->getError($data, $status); switch ($status_class) { case 4: throw new ClientErrorException(sprintf('Client error: %s', $message), $status); case 5: throw new ServerErrorException(sprintf('Server error: %s', $message), $status); } } return $data; }
php
{ "resource": "" }
q2277
PingdomApi.buildRequestUrl
train
public function buildRequestUrl($resource, $parameters = array()) { foreach ($parameters as $property => $value) { if (is_bool($value)) { $parameters[$property] = $value ? 'true' : 'false'; } } $query = empty($parameters) ? '' : '?' . http_build_query($parameters, NULL, '&'); return sprintf('%s/%s%s', self::ENDPOINT, $resource, $query); }
php
{ "resource": "" }
q2278
PingdomApi.getError
train
protected function getError($response_data, $status) { if (!empty($response_data->error)) { $error = $response_data->error; $message = sprintf('%s %s: %s', $error->statuscode, $error->statusdesc, $error->errormessage); } else { $message = sprintf('Error code: %s. No reason was given by Pingdom for the error.', $status); } return $message; }
php
{ "resource": "" }
q2279
Coupon.getArgDefinitions
train
protected function getArgDefinitions() { return new ArgumentCollection( Argument::createIntListTypeArgument('id'), Argument::createBooleanOrBothTypeArgument('is_enabled'), Argument::createBooleanTypeArgument('in_use'), Argument::createAnyListTypeArgument('code'), new Argument( 'order', new TypeCollection( new EnumListType( array( 'id', 'id-reverse', 'code', 'code-reverse', 'title', 'title-reverse', 'enabled', 'enabled-reverse', 'start-date', 'start-date-reverse', 'expiration-date', 'expiration-date-reverse', 'days-left', 'days-left-reverse', 'usages-left', 'usages-left-reverse' ) ) ), 'code' ) ); }
php
{ "resource": "" }
q2280
Database.prepareSql
train
protected function prepareSql($sql) { $sql = str_replace(";',", "-CODE-", $sql); $sql = trim($sql); preg_match_all('#DELIMITER (.+?)\n(.+?)DELIMITER ;#s', $sql, $m); foreach ($m[0] as $k => $v) { if ($m[1][$k] == '|') { throw new \RuntimeException('You can not use "|" as delimiter: '.$v); } $stored = str_replace(';', '|', $m[2][$k]); $stored = str_replace($m[1][$k], ";\n", $stored); $sql = str_replace($v, $stored, $sql); } $query = array(); $tab = explode(";\n", $sql); $size = \count($tab); for ($i = 0; $i < $size; $i++) { $queryTemp = str_replace("-CODE-", ";',", $tab[$i]); $queryTemp = str_replace("|", ";", $queryTemp); $query[] = $queryTemp; } return $query; }
php
{ "resource": "" }
q2281
Database.backupDb
train
public function backupDb($filename, $tables = '*') { $data = []; // get all of the tables if ($tables == '*') { $tables = array(); $result = $this->connection->prepare('SHOW TABLES'); $result->execute(); while ($row = $result->fetch(PDO::FETCH_NUM)) { $tables[] = $row[0]; } } else { $tables = \is_array($tables) ? $tables : explode(',', $tables); } $data[] = "\n"; $data[] = 'SET foreign_key_checks=0;'; $data[] = "\n\n"; foreach ($tables as $table) { if (!preg_match("/^[\w_\-]+$/", $table)) { Tlog::getInstance()->alert( sprintf( "Attempt to backup the db with this invalid table name: '%s'", $table ) ); continue; } $result = $this->execute('SELECT * FROM `' . $table . '`'); $fieldCount = $result->columnCount(); $data[] = 'DROP TABLE `' . $table . '`;'; $resultStruct = $this->execute('SHOW CREATE TABLE `' . $table . '`'); $rowStruct = $resultStruct->fetch(PDO::FETCH_NUM); $data[] = "\n\n"; $data[] = $rowStruct[1]; $data[] = ";\n\n"; for ($i = 0; $i < $fieldCount; $i++) { while ($row = $result->fetch(PDO::FETCH_NUM)) { $data[] = 'INSERT INTO `' . $table . '` VALUES('; for ($j = 0; $j < $fieldCount; $j++) { $row[$j] = addslashes($row[$j]); $row[$j] = str_replace("\n", "\\n", $row[$j]); if (isset($row[$j])) { $data[] = '"' . $row[$j] . '"'; } else { $data[] = '""'; } if ($j < ($fieldCount - 1)) { $data[] = ','; } } $data[] = ");\n"; } } $data[] = "\n\n\n"; } $data[] = 'SET foreign_key_checks=1;'; //save filename $this->writeFilename($filename, $data); }
php
{ "resource": "" }
q2282
Database.writeFilename
train
private function writeFilename($filename, $data) { $f = fopen($filename, "w+"); fwrite($f, implode('', $data)); fclose($f); }
php
{ "resource": "" }
q2283
Country.toggleVisibility
train
public function toggleVisibility(CountryToggleVisibilityEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $country = $event->getCountry(); $country ->setDispatcher($dispatcher) ->setVisible(!$country->getVisible()) ->save(); $event->setCountry($country); }
php
{ "resource": "" }
q2284
Cart.addItem
train
public function addItem(CartEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $cart = $event->getCart(); $newness = $event->getNewness(); $append = $event->getAppend(); $quantity = $event->getQuantity(); $currency = $cart->getCurrency(); $customer = $cart->getCustomer(); $discount = 0; if ($cart->isNew()) { $persistEvent = new CartPersistEvent($cart); $dispatcher->dispatch(TheliaEvents::CART_PERSIST, $persistEvent); } if (null !== $customer && $customer->getDiscount() > 0) { $discount = $customer->getDiscount(); } $productSaleElementsId = $event->getProductSaleElementsId(); $productId = $event->getProduct(); // Search for an identical item in the cart $findItemEvent = clone $event; $dispatcher->dispatch(TheliaEvents::CART_FINDITEM, $findItemEvent); $cartItem = $findItemEvent->getCartItem(); if ($cartItem === null || $newness) { $productSaleElements = ProductSaleElementsQuery::create()->findPk($productSaleElementsId); if (null !== $productSaleElements) { $productPrices = $productSaleElements->getPricesByCurrency($currency, $discount); $cartItem = $this->doAddItem($dispatcher, $cart, $productId, $productSaleElements, $quantity, $productPrices); } } elseif ($append && $cartItem !== null) { $cartItem->addQuantity($quantity)->save(); } $event->setCartItem($cartItem); }
php
{ "resource": "" }
q2285
Cart.updateQuantity
train
protected function updateQuantity(EventDispatcherInterface $dispatcher, CartItem $cartItem, $quantity) { $cartItem->setDisptacher($dispatcher); $cartItem->updateQuantity($quantity) ->save(); return $cartItem; }
php
{ "resource": "" }
q2286
Cart.doAddItem
train
protected function doAddItem( EventDispatcherInterface $dispatcher, CartModel $cart, $productId, ProductSaleElements $productSaleElements, $quantity, ProductPriceTools $productPrices ) { $cartItem = new CartItem(); $cartItem->setDisptacher($dispatcher); $cartItem ->setCart($cart) ->setProductId($productId) ->setProductSaleElementsId($productSaleElements->getId()) ->setQuantity($quantity) ->setPrice($productPrices->getPrice()) ->setPromoPrice($productPrices->getPromoPrice()) ->setPromo($productSaleElements->getPromo()) ->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30)) ->save(); return $cartItem; }
php
{ "resource": "" }
q2287
Cart.findItem
train
protected function findItem($cartId, $productId, $productSaleElementsId) { return CartItemQuery::create() ->filterByCartId($cartId) ->filterByProductId($productId) ->filterByProductSaleElementsId($productSaleElementsId) ->findOne(); }
php
{ "resource": "" }
q2288
Cart.findCartItem
train
public function findCartItem(CartEvent $event) { // Do not try to find a cartItem if one exists in the event, as previous event handlers // mays have put it in th event. if (null === $event->getCartItem() && null !== $foundItem = CartItemQuery::create() ->filterByCartId($event->getCart()->getId()) ->filterByProductId($event->getProduct()) ->filterByProductSaleElementsId($event->getProductSaleElementsId()) ->findOne()) { $event->setCartItem($foundItem); } }
php
{ "resource": "" }
q2289
Cart.restoreCurrentCart
train
public function restoreCurrentCart(CartRestoreEvent $cartRestoreEvent, $eventName, EventDispatcherInterface $dispatcher) { $cookieName = ConfigQuery::read("cart.cookie_name", 'thelia_cart'); $persistentCookie = ConfigQuery::read("cart.use_persistent_cookie", 1); $cart = null; if ($this->requestStack->getCurrentRequest()->cookies->has($cookieName) && $persistentCookie) { $cart = $this->managePersistentCart($cartRestoreEvent, $cookieName, $dispatcher); } elseif (!$persistentCookie) { $cart = $this->manageNonPersistentCookie($cartRestoreEvent, $dispatcher); } // Still no cart ? Create a new one. if (null === $cart) { $cart = $this->dispatchNewCart($dispatcher); } $cartRestoreEvent->setCart($cart); }
php
{ "resource": "" }
q2290
Cart.manageNonPersistentCookie
train
protected function manageNonPersistentCookie(CartRestoreEvent $cartRestoreEvent, EventDispatcherInterface $dispatcher) { $cart = $cartRestoreEvent->getCart(); if (null === $cart) { $cart = $this->dispatchNewCart($dispatcher); } else { $cart = $this->manageCartDuplicationAtCustomerLogin($cart, $dispatcher); } return $cart; }
php
{ "resource": "" }
q2291
Cart.createEmptyCart
train
public function createEmptyCart(CartCreateEvent $cartCreateEvent) { $cart = new CartModel(); $cart->setCurrency($this->getSession()->getCurrency(true)); /** @var CustomerModel $customer */ if (null !== $customer = $this->getSession()->getCustomerUser()) { $cart->setCustomer(CustomerQuery::create()->findPk($customer->getId())); } $this->getSession()->setSessionCart($cart); if (ConfigQuery::read("cart.use_persistent_cookie", 1) == 1) { // set cart_use_cookie to "" to remove the cart cookie // see Thelia\Core\EventListener\ResponseListener $this->getSession()->set("cart_use_cookie", ""); } $cartCreateEvent->setCart($cart); }
php
{ "resource": "" }
q2292
Cart.duplicateCart
train
protected function duplicateCart(EventDispatcherInterface $dispatcher, CartModel $cart, CustomerModel $customer = null) { $newCart = $cart->duplicate( $this->generateCartCookieIdentifier(), $customer, $this->getSession()->getCurrency(), $dispatcher ); $cartEvent = new CartDuplicationEvent($newCart, $cart); $dispatcher->dispatch(TheliaEvents::CART_DUPLICATE, $cartEvent); return $cartEvent->getDuplicatedCart(); }
php
{ "resource": "" }
q2293
Cart.generateCartCookieIdentifier
train
protected function generateCartCookieIdentifier() { $id = null; if (ConfigQuery::read("cart.use_persistent_cookie", 1) == 1) { $id = $this->tokenProvider->getToken(); $this->getSession()->set('cart_use_cookie', $id); } return $id; }
php
{ "resource": "" }
q2294
Content.addCriteriaToPositionQuery
train
protected function addCriteriaToPositionQuery($query) { $contents = ContentFolderQuery::create() ->filterByFolderId($this->getDefaultFolderId()) ->filterByDefaultFolder(true) ->select('content_id') ->find(); // Filtrer la requete sur ces produits if ($contents != null) { $query->filterById($contents, Criteria::IN); } }
php
{ "resource": "" }
q2295
Update.getDatabasePDO
train
protected function getDatabasePDO() { $configPath = THELIA_CONF_DIR . "database.yml"; if (!file_exists($configPath)) { throw new UpdateException("Thelia is not installed yet"); } $definePropel = new DatabaseConfigurationSource( Yaml::parse(file_get_contents($configPath)), $this->getEnvParameters() ); return $definePropel->getTheliaConnectionPDO(); }
php
{ "resource": "" }
q2296
Update.getDataBaseSize
train
public function getDataBaseSize() { $stmt = $this->connection->query( "SELECT sum(data_length) / 1024 / 1024 'size' FROM information_schema.TABLES WHERE table_schema = DATABASE() GROUP BY table_schema" ); if ($stmt->rowCount()) { return \floatval($stmt->fetch(PDO::FETCH_OBJ)->size); } throw new \Exception('Impossible to calculate the database size'); }
php
{ "resource": "" }
q2297
Update.checkBackupIsPossible
train
public function checkBackupIsPossible() { $size = 0; if (preg_match('/^(\d+)(.)$/', ini_get('memory_limit'), $matches)) { switch (strtolower($matches[2])) { case 'k': $size = $matches[1] / 1024; break; case 'm': $size = $matches[1]; break; case 'g': $size = $matches[1] * 1024; break; } } if ($this->getDataBaseSize() > ($size - 64) / 8) { return false; } return true; }
php
{ "resource": "" }
q2298
Update.addPostInstructions
train
protected function addPostInstructions($version, $instructions) { if (!isset($this->postInstructions[$version])) { $this->postInstructions[$version] = []; } $this->postInstructions[$version][] = $instructions; }
php
{ "resource": "" }
q2299
Update.getPostInstructions
train
public function getPostInstructions($format = 'plain') { $content = []; if (\count($this->postInstructions) == 0) { return null; } ksort($this->postInstructions); foreach ($this->postInstructions as $version => $instructions) { $content[] = sprintf("## %s", $version); foreach ($instructions as $instruction) { $content[] = sprintf("%s", $instruction); } } $content = implode("\n\n", $content); if ($format === 'html') { $content = Markdown::defaultTransform($content); } return $content; }
php
{ "resource": "" }