_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q2000
BaseHook.getView
train
protected function getView() { $ret = ""; if (null !== $this->getRequest()) { $ret = $this->getRequest()->attributes->get("_view", ""); } return $ret; }
php
{ "resource": "" }
q2001
BaseHook.getCart
train
protected function getCart() { if (null === $this->cart) { $this->cart = $this->getSession() ? $this->getSession()->getSessionCart($this->dispatcher) : null; } return $this->cart; }
php
{ "resource": "" }
q2002
BaseHook.getOrder
train
protected function getOrder() { if (null === $this->order) { $this->order = $this->getSession() ? $this->getSession()->getOrder() : null; } return $this->order; }
php
{ "resource": "" }
q2003
BaseHook.getCurrency
train
protected function getCurrency() { if (null === $this->currency) { $this->currency = $this->getSession() ? $this->getSession()->getCurrency(true) : Currency::getDefaultCurrency(); } return $this->currency; }
php
{ "resource": "" }
q2004
BaseHook.getCustomer
train
protected function getCustomer() { if (null === $this->customer) { $this->customer = $this->getSession() ? $this->getSession()->getCustomerUser() : null; } return $this->customer; }
php
{ "resource": "" }
q2005
BaseHook.getLang
train
protected function getLang() { if (null === $this->lang) { $this->lang = $this->getSession() ? $this->getSession()->getLang(true) : $this->lang = Lang::getDefaultLanguage(); } return $this->lang; }
php
{ "resource": "" }
q2006
BaseHook.addTemplate
train
public function addTemplate($hookCode, $value) { if (array_key_exists($hookCode, $this->templates)) { throw new \InvalidArgumentException(sprintf("The hook '%s' is already used in this class.", $hookCode)); } $this->templates[$hookCode] = $value; }
php
{ "resource": "" }
q2007
RegisterHookListenersPass.addHooksMethodCall
train
protected function addHooksMethodCall(ContainerBuilder $container, Definition $definition) { $moduleHooks = ModuleHookQuery::create() ->orderByHookId() ->orderByPosition() ->orderById() ->find(); $modulePosition = 0; $hookId = 0; /** @var ModuleHook $moduleHook */ foreach ($moduleHooks as $moduleHook) { // check if class and method exists if (!$container->hasDefinition($moduleHook->getClassname())) { continue; } $hook = $moduleHook->getHook(); if (!$this->isValidHookMethod( $container->getDefinition($moduleHook->getClassname())->getClass(), $moduleHook->getMethod(), $hook->getBlock(), true ) ) { $moduleHook->delete(); continue; } // manage module hook position for new hook if ($hookId !== $moduleHook->getHookId()) { $hookId = $moduleHook->getHookId(); $modulePosition = 1; } else { $modulePosition++; } if ($moduleHook->getPosition() === ModuleHook::MAX_POSITION) { // new module hook, we set it at the end of the queue for this event $moduleHook->setPosition($modulePosition)->save(); } else { $modulePosition = $moduleHook->getPosition(); } // Add the the new listener for active hooks, we have to reverse the priority and the position if ($moduleHook->getActive() && $moduleHook->getModuleActive() && $moduleHook->getHookActive()) { $eventName = sprintf('hook.%s.%s', $hook->getType(), $hook->getCode()); // we a register an event which is relative to a specific module if ($hook->getByModule()) { $eventName .= '.' . $moduleHook->getModuleId(); } $definition->addMethodCall( 'addListenerService', array( $eventName, array($moduleHook->getClassname(), $moduleHook->getMethod()), ModuleHook::MAX_POSITION - $moduleHook->getPosition() ) ); if ($moduleHook->getTemplates()) { if ($container->hasDefinition($moduleHook->getClassname())) { $moduleHookEventName = 'hook.' . $hook->getType() . '.' . $hook->getCode(); if (true === $moduleHook->getHook()->getByModule()) { $moduleHookEventName .= '.' . $moduleHook->getModuleId(); } $container ->getDefinition($moduleHook->getClassname()) ->addMethodCall( 'addTemplate', array( $moduleHookEventName, $moduleHook->getTemplates() ) ) ; } } } } }
php
{ "resource": "" }
q2008
RegisterHookListenersPass.getHookType
train
protected function getHookType($name) { $type = TemplateDefinition::FRONT_OFFICE; if (null !== $name && \is_string($name)) { $name = preg_replace("[^a-z]", "", strtolower(trim($name))); if (\in_array($name, array('bo', 'back', 'backoffice'))) { $type = TemplateDefinition::BACK_OFFICE; } elseif (\in_array($name, array('email'))) { $type = TemplateDefinition::EMAIL; } elseif (\in_array($name, array('pdf'))) { $type = TemplateDefinition::PDF; } } return $type; }
php
{ "resource": "" }
q2009
RegisterHookListenersPass.isValidHookMethod
train
protected function isValidHookMethod($className, $methodName, $block, $failSafe = false) { try { $method = new ReflectionMethod($className, $methodName); $parameters = $method->getParameters(); $eventType = ($block) ? HookDefinition::RENDER_BLOCK_EVENT : HookDefinition::RENDER_FUNCTION_EVENT; if (!($parameters[0]->getClass()->getName() == $eventType || is_subclass_of($parameters[0]->getClass()->getName(), $eventType))) { $this->logAlertMessage(sprintf("Method %s should use an event of type %s. found: %s", $methodName, $eventType, $parameters[0]->getClass()->getName())); return false; } } catch (ReflectionException $ex) { $this->logAlertMessage( sprintf("Method %s does not exist in %s : %s", $methodName, $className, $ex), $failSafe ); return false; } return true; }
php
{ "resource": "" }
q2010
BaseAction.genericUpdatePosition
train
protected function genericUpdatePosition(ModelCriteria $query, UpdatePositionEvent $event, EventDispatcherInterface $dispatcher = null) { if (null !== $object = $query->findPk($event->getObjectId())) { if (!isset(class_uses($object)['Thelia\Model\Tools\PositionManagementTrait'])) { throw new \InvalidArgumentException("Your model does not implement the PositionManagementTrait trait"); } $object->setDispatcher($dispatcher !== null ? $dispatcher : $event->getDispatcher()); $mode = $event->getMode(); if ($mode == UpdatePositionEvent::POSITION_ABSOLUTE) { $object->changeAbsolutePosition($event->getPosition()); } elseif ($mode == UpdatePositionEvent::POSITION_UP) { $object->movePositionUp(); } elseif ($mode == UpdatePositionEvent::POSITION_DOWN) { $object->movePositionDown(); } } }
php
{ "resource": "" }
q2011
BaseAction.genericUpdateSeo
train
protected function genericUpdateSeo(ModelCriteria $query, UpdateSeoEvent $event, EventDispatcherInterface $dispatcher = null) { if (null !== $object = $query->findPk($event->getObjectId())) { $object //for backward compatibility ->setDispatcher($dispatcher !== null ? $dispatcher : $event->getDispatcher()) ->setLocale($event->getLocale()) ->setMetaTitle($event->getMetaTitle()) ->setMetaDescription($event->getMetaDescription()) ->setMetaKeywords($event->getMetaKeywords()) ->save() ; // Update the rewritten URL, if required try { $object->setRewrittenUrl($event->getLocale(), $event->getUrl()); } catch (UrlRewritingException $e) { throw new FormValidationException($e->getMessage(), $e->getCode()); } $event->setObject($object); } return $object; }
php
{ "resource": "" }
q2012
BaseAction.genericToggleVisibility
train
public function genericToggleVisibility(ModelCriteria $query, ToggleVisibilityEvent $event, EventDispatcherInterface $dispatcher = null) { if (null !== $object = $query->findPk($event->getObjectId())) { $newVisibility = !$object->getVisible(); $object //for backward compatibility ->setDispatcher($dispatcher !== null ? $dispatcher : $event->getDispatcher()) ->setVisible($newVisibility) ->save() ; $event->setObject($object); } return $object; }
php
{ "resource": "" }
q2013
TemplateDescriptorValidator.schemaValidate
train
protected function schemaValidate(\DOMDocument $dom, \SplFileInfo $xsdFile) { $errorMessages = []; try { libxml_use_internal_errors(true); if (!$dom->schemaValidate($xsdFile->getRealPath())) { $errors = libxml_get_errors(); foreach ($errors as $error) { $errorMessages[] = sprintf( 'XML error "%s" [%d] (Code %d) in %s on line %d column %d' . "\n", $error->message, $error->level, $error->code, $error->file, $error->line, $error->column ); } libxml_clear_errors(); } libxml_use_internal_errors(false); } catch (\Exception $ex) { libxml_use_internal_errors(false); } return $errorMessages; }
php
{ "resource": "" }
q2014
ViewListener.onKernelView
train
public function onKernelView(GetResponseForControllerResultEvent $event) { $parser = $this->container->get('thelia.parser'); $templateHelper = $this->container->get('thelia.template_helper'); $parser->setTemplateDefinition($templateHelper->getActiveFrontTemplate(), true); $request = $this->container->get('request_stack')->getCurrentRequest(); $response = null; try { $view = $request->attributes->get('_view'); $viewId = $request->attributes->get($view . '_id'); $this->eventDispatcher->dispatch(TheliaEvents::VIEW_CHECK, new ViewCheckEvent($view, $viewId)); $content = $parser->render($view . '.html'); if ($content instanceof Response) { $response = $content; } else { $response = new Response($content, $parser->getStatus() ?: 200); } } catch (ResourceNotFoundException $e) { throw new NotFoundHttpException(); } catch (OrderException $e) { switch ($e->getCode()) { case OrderException::CART_EMPTY: // Redirect to the cart template $response = RedirectResponse::create($this->container->get('router.chainRequest')->generate($e->cartRoute, $e->arguments, Router::ABSOLUTE_URL)); break; case OrderException::UNDEFINED_DELIVERY: // Redirect to the delivery choice template $response = RedirectResponse::create($this->container->get('router.chainRequest')->generate($e->orderDeliveryRoute, $e->arguments, Router::ABSOLUTE_URL)); break; } if (null === $response) { throw $e; } } $event->setResponse($response); }
php
{ "resource": "" }
q2015
NameVisitor.enterNode
train
public function enterNode(Node $node) { if ($node instanceof ConstFetch || $node instanceof FuncCall) { $node->name = null; } if ($node instanceof FullyQualified) { $this->names[] = $node->toString(); } return $node; }
php
{ "resource": "" }
q2016
SingleInheritanceNode.getMethodNames
train
public function getMethodNames() { return array_map(function (ClassMethodNode $node) { return $node->getName()->getText(); }, $this->getMethods()->toArray()); }
php
{ "resource": "" }
q2017
SingleInheritanceNode.getProperty
train
public function getProperty($name) { $name = ltrim($name, '$'); $properties = $this ->getProperties() ->filter(function (ClassMemberNode $property) use ($name) { return ltrim($property->getName(), '$') === $name; }); return $properties->isEmpty() ? NULL : $properties[0]; }
php
{ "resource": "" }
q2018
SingleInheritanceNode.createProperty
train
public function createProperty($name, ExpressionNode $value = NULL, $visibility = 'public') { return $this->appendProperty(ClassMemberNode::create($name, $value, $visibility)); }
php
{ "resource": "" }
q2019
SingleInheritanceNode.appendProperty
train
public function appendProperty($property) { if (is_string($property)) { $property = ClassMemberListNode::create($property); } $properties = $this->statements->children(Filter::isInstanceOf('\Pharborist\ClassMemberListNode')); if ($properties->count() === 0) { $this->statements->firstChild()->after($property); } else { $properties->last()->after($property); } FormatterFactory::format($this); return $this; }
php
{ "resource": "" }
q2020
DocCommentNode.create
train
public static function create($comment) { $comment = trim($comment); $lines = array_map('trim', explode("\n", $comment)); $text = "/**\n"; foreach ($lines as $i => $line) { $text .= ' * ' . $line . "\n"; } $text .= ' */'; return new DocCommentNode(T_DOC_COMMENT, $text); }
php
{ "resource": "" }
q2021
DocCommentNode.setIndent
train
public function setIndent($indent) { $lines = explode("\n", $this->text); if (count($lines) === 1) { return $this; } $comment = ''; $last_index = count($lines) - 1; foreach ($lines as $i => $line) { if ($i === 0) { $comment .= trim($line) . "\n"; } elseif ($i === $last_index) { $comment .= $indent . ' ' . trim($line); } else { $comment .= $indent . ' ' . trim($line) . "\n"; } } $this->setText($comment); return $this; }
php
{ "resource": "" }
q2022
DocCommentNode.getDocBlock
train
public function getDocBlock() { if ($this->docBlock === NULL) { $namespace = '\\'; $aliases = array(); /** @var NamespaceNode $namespace_node */ $namespace_node = $this->closest(Filter::isInstanceOf('\Pharborist\Namespaces\NamespaceNode')); if ($namespace_node !== NULL) { $namespace = $namespace_node->getName() ? $namespace_node->getName()->getAbsolutePath() : ''; $aliases = $namespace_node->getClassAliases(); } else { /** @var RootNode $root_node */ $root_node = $this->closest(Filter::isInstanceOf('\Pharborist\RootNode')); if ($root_node !== NULL) { $aliases = $root_node->getClassAliases(); } } $context = new DocBlock\Context($namespace, $aliases); $this->docBlock = new DocBlock($this->text, $context); } return $this->docBlock; }
php
{ "resource": "" }
q2023
DocCommentNode.getParametersByName
train
public function getParametersByName() { $param_tags = $this->getDocBlock()->getTagsByName('param'); $parameters = array(); /** @var \phpDocumentor\Reflection\DocBlock\Tag\ParamTag $param_tag */ foreach ($param_tags as $param_tag) { $name = ltrim($param_tag->getVariableName(), '$'); $parameters[$name] = $param_tag; } return $parameters; }
php
{ "resource": "" }
q2024
DocCommentNode.getParameter
train
public function getParameter($parameterName) { $parameterName = ltrim($parameterName, '$'); $param_tags = $this->getDocBlock()->getTagsByName('param'); /** @var \phpDocumentor\Reflection\DocBlock\Tag\ParamTag $param_tag */ foreach ($param_tags as $param_tag) { if (ltrim($param_tag->getVariableName(), '$') === $parameterName) { return $param_tag; } } return NULL; }
php
{ "resource": "" }
q2025
PagerdutyFactory.make
train
public function make(array $config) { Arr::requires($config, ['token']); $client = new Client(); return new PagerdutyGateway($client, $config); }
php
{ "resource": "" }
q2026
LessHelper.fetch
train
public function fetch(array $options = [], array $modifyVars = []) { if (empty($options['overwrite'])) { $options['overwrite'] = true; } $overwrite = $options['overwrite']; unset($options['overwrite']); $matches = $css = $less = []; preg_match_all('@(<link[^>]+>)@', $this->_View->fetch('css'), $matches); if (empty($matches)) { return null; } $matches = array_shift($matches); foreach ($matches as $stylesheet) { if (strpos($stylesheet, 'rel="stylesheet/less"') !== false) { $match = []; preg_match('@href="([^"]+)"@', $stylesheet, $match); $file = rtrim(array_pop($match), '?'); array_push($less, $this->less($file, $options, $modifyVars)); continue; } array_push($css, $stylesheet); } if ($overwrite) { $this->_View->Blocks->set('css', join($css)); } return join($less); }
php
{ "resource": "" }
q2027
LessHelper.less
train
public function less($less = 'styles.less', array $options = [], array $modifyVars = []) { $options = $this->setOptions($options); $less = (array)$less; if ($options['js']['env'] == 'development') { return $this->jsBlock($less, $options); } try { $css = $this->compile($less, $options['cache'], $options['parser'], $modifyVars); if (isset($options['tag']) && !$options['tag']) { return $css; } if (!$options['cache']) { return $this->Html->formatTemplate('style', ['content' => $css]); } return $this->Html->css($css); } catch (\Exception $e) { // env must be development in order to see errors on-screen if (Configure::read('debug')) { $options['js']['env'] = 'development'; } $this->error = $e->getMessage(); Log::write('error', "Error compiling less file: " . $this->error); return $this->jsBlock($less, $options); } }
php
{ "resource": "" }
q2028
LessHelper.jsBlock
train
protected function jsBlock($less, array $options = []) { $return = ''; $less = (array)$less; // Append the user less files foreach ($less as $les) { $return .= $this->Html->meta('link', null, [ 'link' => $les, 'rel' => 'stylesheet/less' ]); } // Less.js configuration $return .= $this->Html->scriptBlock(sprintf('less = %s;', json_encode($options['js'], JSON_UNESCAPED_SLASHES))); // <script> tag for less.js file $return .= $this->Html->script($options['less']); return $return; }
php
{ "resource": "" }
q2029
LessHelper.compile
train
protected function compile(array $input, $cache, array $options = [], array $modifyVars = []) { $parse = $this->prepareInputFilesForParsing($input); if ($cache) { $options += ['cache_dir' => $this->cssPath]; return \Less_Cache::Get($parse, $options, $modifyVars); } $lessc = new \Less_Parser($options); foreach ($parse as $file => $path) { $lessc->parseFile($file, $path); } // ModifyVars must be called at the bottom of the parsing, // this way we're ensuring they override their default values. // http://lesscss.org/usage/#command-line-usage-modify-variable $lessc->ModifyVars($modifyVars); return $lessc->getCss(); }
php
{ "resource": "" }
q2030
LessHelper.prepareInputFilesForParsing
train
protected function prepareInputFilesForParsing(array $input = []) { $parse = []; foreach ($input as $in) { $less = realpath(WWW_ROOT . $in); // If we have plugin notation (Plugin.less/file.less) // ensure to properly load the files list($plugin, $basefile) = $this->_View->pluginSplit($in, false); if (!empty($plugin)) { $less = realpath(Plugin::path($plugin) . 'webroot' . DS . $basefile); if ($less !== false) { $parse[$less] = $this->assetBaseUrl($plugin, $basefile); continue; } } if ($less !== false) { $parse[$less] = ''; continue; } // Plugins without plugin notation (/plugin/less/file.less) list($plugin, $basefile) = $this->assetSplit($in); if ($file = $this->pluginAssetFile([$plugin, $basefile])) { $parse[$file] = $this->assetBaseUrl($plugin, $basefile); continue; } // Will probably throw a not found error $parse[$in] = ''; } return $parse; }
php
{ "resource": "" }
q2031
LessHelper.setOptions
train
protected function setOptions(array $options) { // @codeCoverageIgnoreStart $this->parserDefaults = array_merge($this->parserDefaults, [ // The import callback ensures that if a file is not found in the // app's webroot, it will search for that file in its plugin's // webroot path 'import_callback' => function ($lessTree) { if ($pathAndUri = $lessTree->PathAndUri()) { return $pathAndUri; } $file = $lessTree->getPath(); list($plugin, $basefile) = $this->assetSplit($file); $file = $this->pluginAssetFile([$plugin, $basefile]); if ($file) { return [ $file, $this->assetBaseUrl($plugin, $basefile) ]; } return null; } ]); // @codeCoverageIgnoreEnd if (empty($options['parser'])) { $options['parser'] = []; } if (Configure::read('debug') && !isset($options['parser']['sourceMap'])) { $options['parser']['sourceMap'] = true; } $options['parser'] = array_merge($this->parserDefaults, $options['parser']); if (empty($options['js'])) { $options['js'] = []; } $options['js'] = array_merge($this->lessjsDefaults, $options['js']); if (empty($options['less'])) { $options['less'] = 'Less.less.min'; } if (!isset($options['cache'])) { $options['cache'] = true; } return $options; }
php
{ "resource": "" }
q2032
LessHelper.assetBaseUrl
train
protected function assetBaseUrl($plugin, $asset) { $dir = dirname($asset); $path = !empty($dir) && $dir != '.' ? "/$dir" : null; return $this->Url->assetUrl($plugin . $path); }
php
{ "resource": "" }
q2033
LessHelper.pluginAssetFile
train
protected function pluginAssetFile(array $url) { list($plugin, $basefile) = $url; if ($plugin && Plugin::loaded($plugin)) { return realpath(Plugin::path($plugin) . 'webroot' . DS . $basefile); } return false; }
php
{ "resource": "" }
q2034
LessHelper.assetSplit
train
protected function assetSplit($url) { $basefile = ltrim(ltrim($url, '.'), '/'); $exploded = explode('/', $basefile); $plugin = Inflector::camelize(array_shift($exploded)); $basefile = implode(DS, $exploded); return [ $plugin, $basefile ]; }
php
{ "resource": "" }
q2035
PushoverFactory.make
train
public function make(array $config) { Arr::requires($config, ['token']); $client = new Client(); return new PushoverGateway($client, $config); }
php
{ "resource": "" }
q2036
LoopResult.finalizeRows
train
public function finalizeRows() { // Fix rows LOOP_TOTAL if parseResults() did not added all resultsCollection items to the collection array // see https://github.com/thelia/thelia/issues/2337 if (true === $this->countable && $this->getResultDataCollectionCount() !== $realCount = $this->getCount()) { foreach ($this->collection as &$item) { $item->set('LOOP_TOTAL', $realCount); } } }
php
{ "resource": "" }
q2037
MYR.parse
train
public static function parse(string $amount) { $parser = new DecimalMoneyParser(new ISOCurrencies()); return static::given( $parser->parse($amount, new Currency('MYR'))->getAmount() ); }
php
{ "resource": "" }
q2038
AreaDeliveryModuleQuery.findByCountryAndModule
train
public function findByCountryAndModule(Country $country, Module $module, State $state = null) { $response = null; $countryInAreaList = CountryAreaQuery::findByCountryAndState($country, $state); /** @var CountryArea $countryInArea */ foreach ($countryInAreaList as $countryInArea) { $response = self::create()->filterByAreaId($countryInArea->getAreaId()) ->filterByModule($module) ->findOne() ; if ($response !== null) { break; } } return $response; }
php
{ "resource": "" }
q2039
PageEditionController.renderPagetabEditionAction
train
public function renderPagetabEditionAction() { $idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', '')); $melisKey = $this->params()->fromRoute('melisKey', ''); /** * Clearing the session data of the page in every open in page edition */ $container = new Container('meliscms'); if (!empty($container['content-pages'])) if (!empty($container['content-pages'][$idPage])) $container['content-pages'][$idPage] = array(); $melisCoreConf = $this->getServiceLocator()->get('MelisConfig'); $resizeConfig = $melisCoreConf->getItem('meliscms/conf')['pluginResizable'] ?? null; $melisPage = $this->getServiceLocator()->get('MelisEnginePage'); $datasPage = $melisPage->getDatasPage($idPage, 'saved'); if($datasPage) { $datasPageTree = $datasPage->getMelisPageTree(); $datasTemplate = $datasPage->getMelisTemplate(); } $this->loadPageContentPluginsInSession($idPage); $view = new ViewModel(); $view->idPage = $idPage; $view->melisKey = $melisKey; $view->resizablePlugin = $resizeConfig; if (empty($datasPageTree->page_tpl_id) || $datasPageTree->page_tpl_id == -1) $view->noTemplate = true; else $view->noTemplate = false; if(!empty($datasTemplate)) $view->namespace = $datasTemplate->tpl_zf2_website_folder; else $view->namespace = ''; return $view; }
php
{ "resource": "" }
q2040
PageEditionController.savePageSessionPluginAction
train
public function savePageSessionPluginAction() { $idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', '')); $translator = $this->serviceLocator->get('translator'); $postValues = array(); $request = $this->getRequest(); if (!empty($idPage) && $request->isPost()) { // Get values posted and set them in form $postValues = get_object_vars($request->getPost()); // Send the event and let listeners do their job to catch and format their plugins values $eventDatas = array('idPage' => $idPage, 'postValues' => $postValues); $this->getEventManager()->trigger('meliscms_page_savesession_plugin_start', $this, $eventDatas); $result = array( 'success' => 1, 'errors' => array() ); } else { $result = array( 'success' => 0, 'errors' => array(array('empty' => $translator->translate('tr_meliscms_form_common_errors_Empty datas'))) ); } return new JsonModel($result); }
php
{ "resource": "" }
q2041
PageEditionController.removePageSessionPluginAction
train
public function removePageSessionPluginAction() { $module = $this->getRequest()->getQuery('module', null); $pluginName = $this->getRequest()->getQuery('pluginName', ''); $pageId = $this->getRequest()->getQuery('pageId', null); $pluginId = $this->getRequest()->getQuery('pluginId', null); $pluginTag = $this->getRequest()->getQuery('pluginTag', null); $parameters = array( 'module' => $module, 'pluginName' => $pluginName, 'pageId' => $pageId, 'pluginId' => $pluginId, 'pluginTag' => $pluginTag, ); $translator = $this->serviceLocator->get('translator'); if (empty($module) || empty($pluginName) || empty($pageId) || empty($pluginId)) { $result = array( 'success' => 0, 'errors' => array(array('empty' => $translator->translate('tr_meliscms_form_common_errors_Empty datas'))) ); } else { $this->getEventManager()->trigger('meliscms_page_removesession_plugin_start', null, $parameters); // removing plugin from session $container = new Container('meliscms'); if (!empty($container['content-pages'][$pageId][$pluginTag][$pluginId])) unset($container['content-pages'][$pageId][$pluginTag][$pluginId]); $this->getEventManager()->trigger('meliscms_page_removesession_plugin_end', null, $parameters); $result = array( 'success' => 1, 'errors' => array() ); } return new JsonModel($result); }
php
{ "resource": "" }
q2042
PageEditionController.getEditionLogOfPageEditionById
train
public function getEditionLogOfPageEditionById($pageId) { $data = array(); $pageEdition = $this->getServiceLocator()->get('MelisEnginePage'); $dataLogs = $pageEdition->getEditionLogsOfPage($pageId); $data = $dataLogs; return $data; }
php
{ "resource": "" }
q2043
PageEditionController.saveEditionAction
train
public function saveEditionAction() { $idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', '')); $translator = $this->serviceLocator->get('translator'); $eventDatas = array('idPage' => $idPage); $this->getEventManager()->trigger('meliscms_page_saveedition_start', null, $eventDatas); $container = new Container('meliscms'); if (empty($idPage)) { $result = array( 'success' => 0, 'errors' => array(array('empty' => $translator->translate('tr_meliscms_form_common_errors_Empty datas'))) ); } else { // Resave XML of the page if (!empty($container['content-pages'][$idPage])) { // Create the new XML $newXmlContent = '<?xml version="1.0" encoding="UTF-8"?>' . "\n"; $newXmlContent .= '<document type="MelisCMS" author="MelisTechnology" version="2.0">' . "\n"; foreach ($container['content-pages'][$idPage] as $namePlugin => $pluginEntries) { if($namePlugin != 'private:melisPluginSettings') { foreach ($pluginEntries as $idEntry => $valueEntry) { $newXmlContent .= "\t" . $valueEntry . "\n"; } } } $newXmlContent .= '</document>'; // Save the result $melisPageSavedTable = $this->getServiceLocator()->get('MelisEngineTablePageSaved'); $melisPageSavedTable->save(array('page_content' => $newXmlContent), $idPage); } $result = array( 'success' => 1, 'errors' => array(), ); } $this->getEventManager()->trigger('meliscms_page_saveedition_end', null, $result); return new JsonModel($result); }
php
{ "resource": "" }
q2044
PageEditionController.getTinyTemplatesAction
train
public function getTinyTemplatesAction() { $idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', '')); $success = 1; $tinyTemplates = array(); // No pageId, return empty array if (!empty($idPage)) { // Get datas from page $melisPage = $this->getServiceLocator()->get('MelisEnginePage'); $datasPage = $melisPage->getDatasPage($idPage, 'saved'); $datasTemplate = $datasPage->getMelisTemplate(); // No template, return empty array if (!empty($datasTemplate)) { // Get the path of mini-templates to this website $folderSite = $datasTemplate->tpl_zf2_website_folder; $folderSite .= '/public/' . self::MINI_TEMPLATES_FOLDER; $folderSite = $_SERVER['DOCUMENT_ROOT'] . '/../module/MelisSites/' . $folderSite; // List the mini-templates from the folder if (is_dir($folderSite)) { if ($handle = opendir($folderSite)) { while (false !== ($entry = readdir($handle))) { if (is_dir($folderSite . '/' . $entry) || $entry == '.' || $entry == '..') continue; array_push($tinyTemplates, array( 'title' => $entry, 'url' => "/" . $datasTemplate->tpl_zf2_website_folder . '/' . self::MINI_TEMPLATES_FOLDER . '/' . $entry )); } closedir($handle); } } } } return new JsonModel($tinyTemplates); }
php
{ "resource": "" }
q2045
ObjectMethodCallNode.create
train
public static function create(Node $object, $method_name) { /** @var ObjectMethodCallNode $node */ $node = new static(); $node->addChild($object, 'object'); $node->addChild(Token::objectOperator(), 'operator'); $node->addChild(Token::identifier($method_name), 'methodName'); $node->addChild(Token::openParen(), 'openParen'); $node->addChild(new CommaListNode(), 'arguments'); $node->addChild(Token::closeParen(), 'closeParen'); return $node; }
php
{ "resource": "" }
q2046
XmlFileLoader.parseFilters
train
protected function parseFilters(SimpleXMLElement $xml) { if (false === $filters = $xml->xpath('//config:filters/config:filter')) { return; } try { $filterConfig = $this->container->getParameter("Thelia.parser.filters"); } catch (ParameterNotFoundException $e) { $filterConfig = array(); } foreach ($filters as $filter) { $filterConfig[$this->getAttributeAsPhp($filter, "name")] = $this->getAttributeAsPhp($filter, "class"); } $this->container->setParameter("Thelia.parser.filters", $filterConfig); }
php
{ "resource": "" }
q2047
XmlFileLoader.parseTemplateDirectives
train
protected function parseTemplateDirectives(SimpleXMLElement $xml) { if (false === $baseParams = $xml->xpath('//config:templateDirectives/config:templateDirective')) { return; } try { $baseParamConfig = $this->container->getParameter("Thelia.parser.templateDirectives"); } catch (ParameterNotFoundException $e) { $baseParamConfig = array(); } foreach ($baseParams as $baseParam) { $baseParamConfig[$this->getAttributeAsPhp($baseParam, "name")] = $this->getAttributeAsPhp($baseParam, "class"); } $this->container->setParameter("Thelia.parser.templateDirectives", $baseParamConfig); }
php
{ "resource": "" }
q2048
XmlFileLoader.parseService
train
protected function parseService($id, $service, $file) { if ((string) $service['alias']) { $public = true; if (isset($service['public'])) { $public = $this->getAttributeAsPhp($service, 'public'); } $this->container->setAlias($id, new Alias((string) $service['alias'], $public)); return; } if (isset($service['parent'])) { $definition = new DefinitionDecorator((string) $service['parent']); } else { $definition = new Definition(); } foreach (array('class', 'scope', 'public', 'factory-class', 'factory-method', 'factory-service', 'synthetic', 'abstract') as $key) { if (isset($service[$key])) { $method = 'set'.str_replace('-', '', $key); $definition->$method((string) $this->getAttributeAsPhp($service, $key)); } } if ($service->file) { $definition->setFile((string) $service->file); } $definition->setArguments($this->getArgumentsAsPhp($service, 'argument')); $definition->setProperties($this->getArgumentsAsPhp($service, 'property')); if (isset($service->configurator)) { if (isset($service->configurator['function'])) { $definition->setConfigurator((string) $service->configurator['function']); } else { if (isset($service->configurator['service'])) { $class = new Reference((string) $service->configurator['service'], ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false); } else { $class = (string) $service->configurator['class']; } $definition->setConfigurator(array($class, (string) $service->configurator['method'])); } } foreach ($service->call as $call) { $definition->addMethodCall((string) $call['method'], $this->getArgumentsAsPhp($call, 'argument')); } foreach ($service->tag as $tag) { $parameters = array(); foreach ($tag->attributes() as $name => $value) { if ('name' === $name) { continue; } $parameters[$name] = XmlUtils::phpize($value); } $definition->addTag((string) $tag['name'], $parameters); } return $definition; }
php
{ "resource": "" }
q2049
XmlFileLoader.getArgumentsAsPhp
train
private function getArgumentsAsPhp(SimpleXMLElement $xml, $name, $lowercase = true) { $arguments = array(); foreach ($xml->$name as $arg) { if (isset($arg['name'])) { $arg['key'] = (string) $arg['name']; } $key = isset($arg['key']) ? (string) $arg['key'] : (!$arguments ? 0 : max(array_keys($arguments)) + 1); // parameter keys are case insensitive if ('parameter' == $name && $lowercase) { $key = strtolower($key); } // this is used by DefinitionDecorator to overwrite a specific // argument of the parent definition if (isset($arg['index'])) { $key = 'index_'.$arg['index']; } switch ($arg['type']) { case 'service': $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE; if (isset($arg['on-invalid']) && 'ignore' == $arg['on-invalid']) { $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE; } elseif (isset($arg['on-invalid']) && 'null' == $arg['on-invalid']) { $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE; } if (isset($arg['strict'])) { $strict = XmlUtils::phpize($arg['strict']); } else { $strict = true; } $arguments[$key] = new Reference((string) $arg['id'], $invalidBehavior, $strict); break; case 'expression': $arguments[$key] = new Expression((string) $arg); break; case 'collection': $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, false); break; case 'string': $arguments[$key] = (string) $arg; break; case 'constant': $arguments[$key] = constant((string) $arg); break; default: $arguments[$key] = XmlUtils::phpize($arg); } } return $arguments; }
php
{ "resource": "" }
q2050
Product.create
train
public function create(ProductCreateEvent $event) { $defaultTaxRuleId = null; if (null !== $defaultTaxRule = TaxRuleQuery::create()->findOneByIsDefault(true)) { $defaultTaxRuleId = $defaultTaxRule->getId(); } $product = new ProductModel(); $product ->setDispatcher($this->eventDispatcher) ->setRef($event->getRef()) ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setVisible($event->getVisible() ? 1 : 0) ->setVirtual($event->getVirtual() ? 1 : 0) ->setTemplateId($event->getTemplateId()) ->create( $event->getDefaultCategory(), $event->getBasePrice(), $event->getCurrencyId(), // Set the default tax rule if not defined $event->getTaxRuleId() ?: $defaultTaxRuleId, $event->getBaseWeight(), $event->getBaseQuantity() ) ; $event->setProduct($product); }
php
{ "resource": "" }
q2051
Product.update
train
public function update(ProductUpdateEvent $event) { if (null !== $product = ProductQuery::create()->findPk($event->getProductId())) { $con = Propel::getWriteConnection(ProductTableMap::DATABASE_NAME); $con->beginTransaction(); try { $prevRef = $product->getRef(); $product ->setDispatcher($this->eventDispatcher) ->setRef($event->getRef()) ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setDescription($event->getDescription()) ->setChapo($event->getChapo()) ->setPostscriptum($event->getPostscriptum()) ->setVisible($event->getVisible() ? 1 : 0) ->setVirtual($event->getVirtual() ? 1 : 0) ->setBrandId($event->getBrandId() <= 0 ? null : $event->getBrandId()) ->save($con) ; // Update default PSE (if product has no attributes and the product's ref change) $defaultPseRefChange = $prevRef !== $product->getRef() && 0 === $product->getDefaultSaleElements()->countAttributeCombinations(); if ($defaultPseRefChange) { $defaultPse = $product->getDefaultSaleElements(); $defaultPse->setRef($product->getRef())->save(); } // Update default category (if required) $product->setDefaultCategory($event->getDefaultCategory()); $event->setProduct($product); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } } }
php
{ "resource": "" }
q2052
Product.delete
train
public function delete(ProductDeleteEvent $event) { if (null !== $product = ProductQuery::create()->findPk($event->getProductId())) { $con = Propel::getWriteConnection(ProductTableMap::DATABASE_NAME); $con->beginTransaction(); try { $fileList = ['images' => [], 'documentList' => []]; // Get product's files to delete after product deletion $fileList['images']['list'] = ProductImageQuery::create() ->findByProductId($event->getProductId()); $fileList['images']['type'] = TheliaEvents::IMAGE_DELETE; $fileList['documentList']['list'] = ProductDocumentQuery::create() ->findByProductId($event->getProductId()); $fileList['documentList']['type'] = TheliaEvents::DOCUMENT_DELETE; // Delete product $product ->setDispatcher($this->eventDispatcher) ->delete($con) ; $event->setProduct($product); // Dispatch delete product's files event foreach ($fileList as $fileTypeList) { foreach ($fileTypeList['list'] as $fileToDelete) { $fileDeleteEvent = new FileDeleteEvent($fileToDelete); $this->eventDispatcher->dispatch($fileTypeList['type'], $fileDeleteEvent); } } $con->commit(); } catch (\Exception $e) { $con->rollBack(); throw $e; } } }
php
{ "resource": "" }
q2053
Product.toggleVisibility
train
public function toggleVisibility(ProductToggleVisibilityEvent $event) { $product = $event->getProduct(); $product ->setDispatcher($this->eventDispatcher) ->setVisible($product->getVisible() ? false : true) ->save() ; $event->setProduct($product); }
php
{ "resource": "" }
q2054
Product.updateAccessoryPosition
train
public function updateAccessoryPosition(UpdatePositionEvent $event, $eventName, EventDispatcherInterface $dispatcher) { return $this->genericUpdatePosition(AccessoryQuery::create(), $event, $dispatcher); }
php
{ "resource": "" }
q2055
Product.deleteFeatureProductValue
train
public function deleteFeatureProductValue(FeatureProductDeleteEvent $event) { FeatureProductQuery::create() ->filterByProductId($event->getProductId()) ->filterByFeatureId($event->getFeatureId()) ->delete() ; }
php
{ "resource": "" }
q2056
Product.deleteTemplateFeature
train
public function deleteTemplateFeature(TemplateDeleteFeatureEvent $event, $eventName, EventDispatcherInterface $dispatcher) { // Detete the removed feature in all products which are using this template $products = ProductQuery::create() ->filterByTemplateId($event->getTemplate()->getId()) ->find() ; foreach ($products as $product) { $dispatcher->dispatch( TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, new FeatureProductDeleteEvent($product->getId(), $event->getFeatureId()) ); } }
php
{ "resource": "" }
q2057
Product.deleteTemplateAttribute
train
public function deleteTemplateAttribute(TemplateDeleteAttributeEvent $event, $eventName, EventDispatcherInterface $dispatcher) { // Detete the removed attribute in all products which are using this template $pseToDelete = ProductSaleElementsQuery::create() ->useProductQuery() ->filterByTemplateId($event->getTemplate()->getId()) ->endUse() ->useAttributeCombinationQuery() ->filterByAttributeId($event->getAttributeId()) ->endUse() ->select([ ProductSaleElementsTableMap::COL_ID ]) ->find(); $currencyId = CurrencyModel::getDefaultCurrency()->getId(); foreach ($pseToDelete->getData() as $pseId) { $dispatcher->dispatch( TheliaEvents::PRODUCT_DELETE_PRODUCT_SALE_ELEMENT, new ProductSaleElementDeleteEvent( $pseId, $currencyId ) ); } }
php
{ "resource": "" }
q2058
Product.viewCheck
train
public function viewCheck(ViewCheckEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if ($event->getView() == 'product') { $product = ProductQuery::create() ->filterById($event->getViewId()) ->filterByVisible(1) ->count(); if ($product == 0) { $dispatcher->dispatch(TheliaEvents::VIEW_PRODUCT_ID_NOT_VISIBLE, $event); } } }
php
{ "resource": "" }
q2059
CouponCreationForm.checkDuplicateCouponCode
train
public function checkDuplicateCouponCode($value, ExecutionContextInterface $context) { $exists = CouponQuery::create()->filterByCode($value)->count() > 0; if ($exists) { $context->addViolation( Translator::getInstance()->trans( "The coupon code '%code' already exists. Please choose another coupon code", ['%code' => $value] ) ); } }
php
{ "resource": "" }
q2060
CouponCreationForm.checkLocalizedDate
train
public function checkLocalizedDate($value, ExecutionContextInterface $context) { $format = LangQuery::create()->findOneByByDefault(true)->getDatetimeFormat(); if (false === \DateTime::createFromFormat($format, $value)) { $context->addViolation( Translator::getInstance()->trans( "Date '%date' is invalid, please enter a valid date using %fmt format", [ '%fmt' => $format, '%date' => $value ] ) ); } }
php
{ "resource": "" }
q2061
ModuleValidator.getModulesDependOf
train
public function getModulesDependOf($active = true) { $code = $this->getModuleDefinition()->getCode(); $query = ModuleQuery::create(); $dependantModules = []; if (true === $active) { $query->findByActivate(1); } elseif (false === $active) { $query->findByActivate(0); } $modules = $query->find(); /** @var Module $module */ foreach ($modules as $module) { try { $validator = new ModuleValidator($module->getAbsoluteBaseDir()); $definition = $validator->getModuleDefinition(); $dependencies = $definition->getDependencies(); if (\count($dependencies) > 0) { foreach ($dependencies as $dependency) { if ($dependency[0] == $code) { $dependantModules[] = [ 'code' => $definition->getCode(), 'version' => $dependency[1] ]; break; } } } } catch (\Exception $ex) { ; } } return $dependantModules; }
php
{ "resource": "" }
q2062
ModuleValidator.getCurrentModuleDependencies
train
public function getCurrentModuleDependencies($recursive = false) { if (empty($this->moduleDescriptor->required)) { return []; } $dependencies = []; foreach ($this->moduleDescriptor->required->module as $dependency) { $dependencyArray = [ "code" => (string)$dependency, "version" => (string)$dependency['version'], ]; if (!\in_array($dependencyArray, $dependencies)) { $dependencies[] = $dependencyArray; } if ($recursive) { $recursiveModuleValidator = new ModuleValidator(THELIA_MODULE_DIR . '/' . (string)$dependency); array_merge( $dependencies, $recursiveModuleValidator->getCurrentModuleDependencies(true) ); } } return $dependencies; }
php
{ "resource": "" }
q2063
Node.sortKey
train
public function sortKey() { if ($this instanceof RootNode) { return spl_object_hash($this); } if (!$this->parent) { return '~/' . spl_object_hash($this); } $path = $this->parent->sortKey() . '/'; $position = 0; $previous = $this->previous; while ($previous) { $position++; $previous = $previous->previous; } $path .= $position; return $path; }
php
{ "resource": "" }
q2064
Node.is
train
public function is($test) { if (is_callable($test)) { return (boolean) $test($this); } elseif (is_string($test)) { return $this->is(Filter::isInstanceOf($test)); } else { throw new \InvalidArgumentException(); } }
php
{ "resource": "" }
q2065
Node.isAnyOf
train
public function isAnyOf(array $tests) { foreach ($tests as $test) { if ($this->is($test)) { return TRUE; } } return FALSE; }
php
{ "resource": "" }
q2066
Node.isAllOf
train
public function isAllOf(array $tests) { foreach ($tests as $test) { if (! $this->is($test)) { return FALSE; } } return TRUE; }
php
{ "resource": "" }
q2067
Node.fromValue
train
public static function fromValue($value) { if (is_array($value)) { $elements = []; foreach ($value as $k => $v) { $elements[] = ArrayPairNode::create(static::fromValue($k), static::fromValue($v)); } return ArrayNode::create($elements); } elseif (is_string($value)) { return StringNode::create(var_export($value, TRUE)); } elseif (is_integer($value)) { return new IntegerNode(T_LNUMBER, $value); } elseif (is_float($value)) { return new FloatNode(T_DNUMBER, $value); } elseif (is_bool($value)) { return BooleanNode::create($value); } elseif (is_null($value)) { return NullNode::create('NULL'); } else { throw new \InvalidArgumentException(); } }
php
{ "resource": "" }
q2068
Tlog.init
train
protected function init() { $this->setLevel(ConfigQuery::read(self::VAR_LEVEL, self::DEFAULT_LEVEL)); $this->dir_destinations = array( __DIR__.DS.'Destination', THELIA_LOCAL_DIR.'tlog'.DS.'destinations' ); $this->setPrefix(ConfigQuery::read(self::VAR_PREFIXE, self::DEFAUT_PREFIXE)); $this->setFiles(ConfigQuery::read(self::VAR_FILES, self::DEFAUT_FILES)); $this->setIp(ConfigQuery::read(self::VAR_IP, self::DEFAUT_IP)); $this->setDestinations(ConfigQuery::read(self::VAR_DESTINATIONS, self::DEFAUT_DESTINATIONS)); $this->setShowRedirect(ConfigQuery::read(self::VAR_SHOW_REDIRECT, self::DEFAUT_SHOW_REDIRECT)); // Au cas ou il y aurait un exit() quelque part dans le code. register_shutdown_function(array($this, 'writeOnExit')); }
php
{ "resource": "" }
q2069
ExportCommand.listExport
train
protected function listExport(OutputInterface $output) { $table = new Table($output); foreach ((new ExportQuery)->find() as $export) { $table->addRow([ $export->getRef(), $export->getTitle(), $export->getDescription() ]); } $table ->setHeaders([ 'Reference', 'Title', 'Description' ]) ->render() ; }
php
{ "resource": "" }
q2070
ExportCommand.listSerializer
train
protected function listSerializer(OutputInterface $output) { $table = new Table($output); /** @var SerializerManager $serializerManager */ $serializerManager = $this->getContainer()->get(RegisterSerializerPass::MANAGER_SERVICE_ID); /** @var SerializerInterface $serializer */ foreach ($serializerManager->getSerializers() as $serializer) { $table->addRow([ $serializer->getId(), $serializer->getName(), $serializer->getExtension(), $serializer->getMimeType() ]); } $table ->setHeaders([ 'Id', 'Name', 'Extension', 'MIME type' ]) ->render() ; }
php
{ "resource": "" }
q2071
ExportCommand.listArchiver
train
protected function listArchiver(OutputInterface $output) { $table = new Table($output); /** @var ArchiverManager $archiverManager */ $archiverManager = $this->getContainer()->get(RegisterArchiverPass::MANAGER_SERVICE_ID); /** @var ArchiverInterface $archiver */ foreach ($archiverManager->getArchivers(true) as $archiver) { $table->addRow([ $archiver->getId(), $archiver->getName(), $archiver->getExtension(), $archiver->getMimeType() ]); } $table ->setHeaders([ 'Id', 'Name', 'Extension', 'MIME type' ]) ->render() ; }
php
{ "resource": "" }
q2072
Session.getCurrency
train
public function getCurrency($forceDefault = true) { $currency = $this->get("thelia.current.currency"); if (null === $currency && $forceDefault) { $currency = Currency::getDefaultCurrency(); } return $currency; }
php
{ "resource": "" }
q2073
Session.setSessionCart
train
public function setSessionCart(Cart $cart = null) { if (null === $cart || $cart->isNew()) { self::$transientCart = $cart; $this->remove("thelia.cart_id"); } else { self::$transientCart = null; $this->set("thelia.cart_id", $cart->getId()); } return $this; }
php
{ "resource": "" }
q2074
Session.getSessionCart
train
public function getSessionCart(EventDispatcherInterface $dispatcher = null) { $cart_id = $this->get("thelia.cart_id", null); if (null !== $cart_id) { $cart = CartQuery::create()->findPk($cart_id); } else { $cart = self::$transientCart; } // If we do not have a cart, or if the current cart is nor valid // restore it from the cart cookie, or create a new one if (null === $cart || ! $this->isValidCart($cart)) { // A dispatcher is required here. If we do not have it, throw an exception // This is a temporary workaround to ensure backward compatibility with getCart(), // When genCart() will be removed, this check should be removed, and $dispatcher should become // a required parameter. if (null == $dispatcher) { throw new \InvalidArgumentException( "In this context (no cart in session), an EventDispatcher should be provided to Session::getSessionCart()." ); } $cartEvent = new CartRestoreEvent(); if (null !== $cart) { $cartEvent->setCart($cart); } $dispatcher->dispatch(TheliaEvents::CART_RESTORE_CURRENT, $cartEvent); if (null === $cart = $cartEvent->getCart()) { throw new \LogicException( "Unable to get a Cart." ); } // Store the cart. $this->setSessionCart($cart); } return $cart; }
php
{ "resource": "" }
q2075
Session.clearSessionCart
train
public function clearSessionCart(EventDispatcherInterface $dispatcher) { $event = new CartCreateEvent(); $dispatcher->dispatch(TheliaEvents::CART_CREATE_NEW, $event); if (null === $cart = $event->getCart()) { throw new \LogicException( "Unable to get a new empty Cart." ); } // Store the cart $this->setSessionCart($cart); }
php
{ "resource": "" }
q2076
Session.isValidCart
train
protected function isValidCart(Cart $cart) { $customer = $this->getCustomerUser(); return (null !== $customer && $cart->getCustomerId() == $customer->getId()) || (null === $customer && $cart->getCustomerId() === null); }
php
{ "resource": "" }
q2077
Coupon.create
train
public function create(CouponCreateOrUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $coupon = new CouponModel(); $this->createOrUpdate($coupon, $event, $dispatcher); }
php
{ "resource": "" }
q2078
Coupon.update
train
public function update(CouponCreateOrUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $coupon = $event->getCouponModel(); $this->createOrUpdate($coupon, $event, $dispatcher); }
php
{ "resource": "" }
q2079
Coupon.updateCondition
train
public function updateCondition(CouponCreateOrUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $modelCoupon = $event->getCouponModel(); $this->createOrUpdateCondition($modelCoupon, $event, $dispatcher); }
php
{ "resource": "" }
q2080
Coupon.clearAllCoupons
train
public function clearAllCoupons(Event $event, $eventName, EventDispatcherInterface $dispatcher) { // Tell coupons to clear any data they may have stored $this->couponManager->clear(); $this->getSession()->setConsumedCoupons(array()); $this->updateOrderDiscount($event, $eventName, $dispatcher); }
php
{ "resource": "" }
q2081
Coupon.consume
train
public function consume(CouponConsumeEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $totalDiscount = 0; $isValid = false; /** @var CouponInterface $coupon */ $coupon = $this->couponFactory->buildCouponFromCode($event->getCode()); if ($coupon) { $isValid = $coupon->isMatching(); if ($isValid) { $this->couponManager->pushCouponInSession($event->getCode()); $totalDiscount = $this->couponManager->getDiscount(); $this->getSession() ->getSessionCart($dispatcher) ->setDiscount($totalDiscount) ->save(); $this->getSession() ->getOrder() ->setDiscount($totalDiscount) ; } } $event->setIsValid($isValid); $event->setDiscount($totalDiscount); }
php
{ "resource": "" }
q2082
Coupon.orderStatusChange
train
public function orderStatusChange(OrderEvent $event, $eventName, EventDispatcherInterface $dispatcher) { // The order has been canceled or refunded ? if ($event->getOrder()->isCancelled() || $event->getOrder()->isRefunded()) { // Cancel usage of all coupons for this order $usedCoupons = OrderCouponQuery::create() ->filterByUsageCanceled(false) ->findByOrderId($event->getOrder()->getId()); $customerId = $event->getOrder()->getCustomerId(); /** @var OrderCoupon $usedCoupon */ foreach ($usedCoupons as $usedCoupon) { if (null !== $couponModel = CouponQuery::create()->findOneByCode($usedCoupon->getCode())) { // If the coupon still exists, restore one usage to the usage count. $this->couponManager->incrementQuantity($couponModel, $customerId); } // Mark coupon usage as canceled in the OrderCoupon table $usedCoupon->setUsageCanceled(true)->save(); } } else { // Mark canceled coupons for this order as used again $usedCoupons = OrderCouponQuery::create() ->filterByUsageCanceled(true) ->findByOrderId($event->getOrder()->getId()); $customerId = $event->getOrder()->getCustomerId(); /** @var OrderCoupon $usedCoupon */ foreach ($usedCoupons as $usedCoupon) { if (null !== $couponModel = CouponQuery::create()->findOneByCode($usedCoupon->getCode())) { // If the coupon still exists, mark the coupon as used $this->couponManager->decrementQuantity($couponModel, $customerId); } // The coupon is no longer canceled $usedCoupon->setUsageCanceled(false)->save(); } } }
php
{ "resource": "" }
q2083
Sale.updateProductSaleElementsPrices
train
protected function updateProductSaleElementsPrices($pseList, $promoStatus, $offsetType, Calculator $taxCalculator, $saleOffsetByCurrency, ConnectionInterface $con) { /** @var ProductSaleElements $pse */ foreach ($pseList as $pse) { if ($pse->getPromo()!= $promoStatus) { $pse ->setPromo($promoStatus) ->save($con) ; } /** @var SaleOffsetCurrency $offsetByCurrency */ foreach ($saleOffsetByCurrency as $currencyId => $offset) { $productPrice = ProductPriceQuery::create() ->filterByProductSaleElementsId($pse->getId()) ->filterByCurrencyId($currencyId) ->findOne($con); if (null !== $productPrice) { // Get the taxed price $priceWithTax = $taxCalculator->getTaxedPrice($productPrice->getPrice()); // Remove the price offset to get the taxed promo price switch ($offsetType) { case SaleModel::OFFSET_TYPE_AMOUNT: $promoPrice = max(0, $priceWithTax - $offset); break; case SaleModel::OFFSET_TYPE_PERCENTAGE: $promoPrice = $priceWithTax * (1 - $offset / 100); break; default: $promoPrice = $priceWithTax; } // and then get the untaxed promo price. $promoPrice = $taxCalculator->getUntaxedPrice($promoPrice); $productPrice ->setPromoPrice($promoPrice) ->save($con) ; } } } }
php
{ "resource": "" }
q2084
Sale.updateProductsSaleStatus
train
public function updateProductsSaleStatus(ProductSaleStatusUpdateEvent $event) { $taxCalculator = new Calculator(); $sale = $event->getSale(); // Get all selected product sale elements for this sale if (null !== $saleProducts = SaleProductQuery::create()->filterBySale($sale)->orderByProductId()) { $saleOffsetByCurrency = $sale->getPriceOffsets(); $offsetType = $sale->getPriceOffsetType(); $con = Propel::getWriteConnection(SaleTableMap::DATABASE_NAME); $con->beginTransaction(); try { /** @var SaleProduct $saleProduct */ foreach ($saleProducts as $saleProduct) { // Reset all sale status on product's PSE ProductSaleElementsQuery::create() ->filterByProductId($saleProduct->getProductId()) ->update([ 'Promo' => false], $con) ; $taxCalculator->load( $saleProduct->getProduct($con), CountryModel::getShopLocation() ); $attributeAvId = $saleProduct->getAttributeAvId(); $pseRequest = ProductSaleElementsQuery::create() ->filterByProductId($saleProduct->getProductId()) ; // If no attribute AV id is defined, consider ALL product combinations if (! \is_null($attributeAvId)) { // Find PSE attached to combination containing this attribute av : // SELECT * from product_sale_elements pse // left join attribute_combination ac on ac.product_sale_elements_id = pse.id // where pse.product_id=363 // and ac.attribute_av_id = 7 // group by pse.id $pseRequest ->useAttributeCombinationQuery(null, Criteria::LEFT_JOIN) ->filterByAttributeAvId($attributeAvId) ->endUse() ; } $pseList = $pseRequest->find(); if (null !== $pseList) { $this->updateProductSaleElementsPrices( $pseList, $sale->getActive(), $offsetType, $taxCalculator, $saleOffsetByCurrency, $con ); } } $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } } }
php
{ "resource": "" }
q2085
Sale.create
train
public function create(SaleCreateEvent $event) { $sale = new SaleModel(); $sale ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setSaleLabel($event->getSaleLabel()) ->save() ; $event->setSale($sale); }
php
{ "resource": "" }
q2086
Sale.update
train
public function update(SaleUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $sale = SaleQuery::create()->findPk($event->getSaleId())) { $sale->setDispatcher($dispatcher); $con = Propel::getWriteConnection(SaleTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Disable all promo flag on sale's currently selected products, // to reset promo status of the products that may have been removed from the selection. $sale->setActive(false); $dispatcher->dispatch( TheliaEvents::UPDATE_PRODUCT_SALE_STATUS, new ProductSaleStatusUpdateEvent($sale) ); $sale ->setActive($event->getActive()) ->setStartDate($event->getStartDate()) ->setEndDate($event->getEndDate()) ->setPriceOffsetType($event->getPriceOffsetType()) ->setDisplayInitialPrice($event->getDisplayInitialPrice()) ->setLocale($event->getLocale()) ->setSaleLabel($event->getSaleLabel()) ->setTitle($event->getTitle()) ->setDescription($event->getDescription()) ->setChapo($event->getChapo()) ->setPostscriptum($event->getPostscriptum()) ->save($con) ; $event->setSale($sale); // Update price offsets SaleOffsetCurrencyQuery::create()->filterBySaleId($sale->getId())->delete($con); foreach ($event->getPriceOffsets() as $currencyId => $priceOffset) { $saleOffset = new SaleOffsetCurrency(); $saleOffset ->setCurrencyId($currencyId) ->setSaleId($sale->getId()) ->setPriceOffsetValue($priceOffset) ->save($con) ; } // Update products SaleProductQuery::create()->filterBySaleId($sale->getId())->delete($con); $productAttributesArray = $event->getProductAttributes(); foreach ($event->getProducts() as $productId) { if (isset($productAttributesArray[$productId])) { foreach ($productAttributesArray[$productId] as $attributeId) { $saleProduct = new SaleProduct(); $saleProduct ->setSaleId($sale->getId()) ->setProductId($productId) ->setAttributeAvId($attributeId) ->save($con) ; } } else { $saleProduct = new SaleProduct(); $saleProduct ->setSaleId($sale->getId()) ->setProductId($productId) ->setAttributeAvId(null) ->save($con) ; } } // Update related products sale status if the Sale is active. This is not required if the sale is // not active, as we de-activated promotion for this sale at the beginning ofd this method if ($sale->getActive()) { $dispatcher->dispatch( TheliaEvents::UPDATE_PRODUCT_SALE_STATUS, new ProductSaleStatusUpdateEvent($sale) ); } $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } } }
php
{ "resource": "" }
q2087
Sale.toggleActivity
train
public function toggleActivity(SaleToggleActivityEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $sale = $event->getSale(); $con = Propel::getWriteConnection(SaleTableMap::DATABASE_NAME); $con->beginTransaction(); try { $sale ->setDispatcher($dispatcher) ->setActive(!$sale->getActive()) ->save($con); // Update related products sale status $dispatcher->dispatch( TheliaEvents::UPDATE_PRODUCT_SALE_STATUS, new ProductSaleStatusUpdateEvent($sale) ); $event->setSale($sale); $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } }
php
{ "resource": "" }
q2088
Sale.delete
train
public function delete(SaleDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $sale = SaleQuery::create()->findPk($event->getSaleId())) { $con = Propel::getWriteConnection(SaleTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Update related products sale status, if required if ($sale->getActive()) { $sale->setActive(false); // Update related products sale status $dispatcher->dispatch( TheliaEvents::UPDATE_PRODUCT_SALE_STATUS, new ProductSaleStatusUpdateEvent($sale) ); } $sale->setDispatcher($dispatcher)->delete($con); $event->setSale($sale); $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } } }
php
{ "resource": "" }
q2089
Sale.clearStatus
train
public function clearStatus(/** @noinspection PhpUnusedParameterInspection */ SaleClearStatusEvent $event) { $con = Propel::getWriteConnection(SaleTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Set the active status of all Sales to false SaleQuery::create() ->filterByActive(true) ->update([ 'Active' => false ], $con) ; // Reset all sale status on PSE ProductSaleElementsQuery::create() ->filterByPromo(true) ->update([ 'Promo' => false], $con) ; $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } }
php
{ "resource": "" }
q2090
Sale.checkSaleActivation
train
public function checkSaleActivation(SaleActiveStatusCheckEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $con = Propel::getWriteConnection(SaleTableMap::DATABASE_NAME); $con->beginTransaction(); try { $now = time(); // Disable expired sales if (null !== $salesToDisable = SaleQuery::create() ->filterByActive(true) ->filterByEndDate($now, Criteria::LESS_THAN) ->find()) { /** @var SaleModel $sale */ foreach ($salesToDisable as $sale) { $sale->setActive(false)->save(); // Update related products sale status $dispatcher->dispatch( TheliaEvents::UPDATE_PRODUCT_SALE_STATUS, new ProductSaleStatusUpdateEvent($sale) ); } } // Enable sales that should be enabled. if (null !== $salesToEnable = SaleQuery::create() ->filterByActive(false) ->filterByStartDate($now, Criteria::LESS_EQUAL) ->filterByEndDate($now, Criteria::GREATER_EQUAL) ->find()) { /** @var SaleModel $sale */ foreach ($salesToEnable as $sale) { $sale->setActive(true)->save(); // Update related products sale status $dispatcher->dispatch( TheliaEvents::UPDATE_PRODUCT_SALE_STATUS, new ProductSaleStatusUpdateEvent($sale) ); } } $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } }
php
{ "resource": "" }
q2091
SchemaCombiner.combine
train
public function combine(array $schemaDocuments = [], array $externalSchemaDocuments = []) { $globalDatabaseElements = []; // merge schema documents, per database foreach ($schemaDocuments as $sourceSchemaDocument) { if (!$sourceSchemaDocument instanceof \DOMDocument) { throw new \InvalidArgumentException('Schema file is not a \DOMDocument'); } // work on document clones since we are going to edit them $sourceSchemaDocument = clone $sourceSchemaDocument; // process all <database> elements in the document /** @var \DOMElement $sourceDatabaseElement */ foreach ($sourceSchemaDocument->getElementsByTagName('database') as $sourceDatabaseElement) { // pre-process the element $this->filterExternalSchemaElements($sourceDatabaseElement); $this->inheritDatabaseAttributes($sourceDatabaseElement); $this->applyDatabaseTablePrefix($sourceDatabaseElement); // append the element $this->mergeDatabaseElement($sourceDatabaseElement); } } // include external schema documents, per database foreach ($externalSchemaDocuments as $externalSchemaDocument) { if (!$externalSchemaDocument instanceof \DOMDocument) { throw new \InvalidArgumentException('Schema file is not a \DOMDocument'); } // process all <database> elements in the document /** @var \DOMElement $externalSchemaDatabaseElement */ foreach ($externalSchemaDocument->getElementsByTagName('database') as $externalSchemaDatabaseElement) { // include the document $this->includeExternalSchema($externalSchemaDatabaseElement); } } // return the documents, not the database elements $globalSchemaDocuments = []; /** * @var string $database * @var \DOMElement $globalDatabaseElement */ foreach ($globalDatabaseElements as $database => $globalDatabaseElement) { $globalSchemaDocuments[$database] = $globalDatabaseElement->ownerDocument; } return $globalSchemaDocuments; }
php
{ "resource": "" }
q2092
SchemaCombiner.inheritDatabaseAttributes
train
protected function inheritDatabaseAttributes(\DOMElement $databaseElement) { $attributesToInherit = []; foreach (static::$DATABASE_INHERITABLE_ATTRIBUTES as $databaseAttribute => $tableAttribute) { if (!$databaseElement->hasAttribute($databaseAttribute)) { continue; } $attributesToInherit[$tableAttribute] = $databaseElement->getAttribute($databaseAttribute); } /** @var \DOMElement $tableElement */ foreach ($databaseElement->getElementsByTagName('table') as $tableElement) { foreach (static::$DATABASE_INHERITABLE_ATTRIBUTES as $databaseAttribute => $tableAttribute) { if (!isset($attributesToInherit[$tableAttribute])) { continue; } if ($tableElement->hasAttribute($tableAttribute)) { // do not inherit the attribute if the table defines its own continue; } // add an inheritance notice $databaseAttributeInheritanceNoticeComment = $tableElement->ownerDocument->createComment( "Attribute '{$tableAttribute}'" . " inherited from parent database attribute '{$databaseAttribute}'" ); $tableElement->insertBefore( $databaseAttributeInheritanceNoticeComment, $tableElement->firstChild ); $tableElement->setAttribute($tableAttribute, $attributesToInherit[$tableAttribute]); } } }
php
{ "resource": "" }
q2093
SchemaCombiner.applyDatabaseTablePrefix
train
protected function applyDatabaseTablePrefix(\DOMElement $databaseElement) { if (!$databaseElement->hasAttribute('tablePrefix')) { return; } $tablePrefix = $databaseElement->getAttribute('tablePrefix'); /** @var \DOMElement $tableElement */ foreach ($databaseElement->getElementsByTagName('table') as $tableElement) { if (!$tableElement->hasAttribute('name')) { // this is probably wrong, but not our problem here - we do not validate the schema continue; } // add a prefixing notice $tablePrefixingNoticeComment = $tableElement->ownerDocument->createComment( "Table name prefixed with parent database 'tablePrefix'" ); $tableElement->appendChild($tablePrefixingNoticeComment); $table = $tableElement->getAttribute('name'); $tableElement->setAttribute('name', $tablePrefix . $table); } }
php
{ "resource": "" }
q2094
SchemaCombiner.getDatabaseFromDatabaseElement
train
protected function getDatabaseFromDatabaseElement(\DOMElement $databaseElement) { $database = $databaseElement->getAttribute('name'); if (empty($database)) { throw new \LogicException('Unnamed database node.'); } return $database; }
php
{ "resource": "" }
q2095
SchemaCombiner.initGlobalDatabaseElement
train
protected function initGlobalDatabaseElement($database) { if (\in_array($database, $this->databases)) { return; } $databaseDocument = new \DOMDocument(static::$GLOBAL_SCHEMA_XML_VERSION, static::$GLOBAL_SCHEMA_XML_ENCODING); $databaseElement = $databaseDocument->createElement('database'); $databaseElement->setAttribute('name', $database); $identifierQuotingNoticeComment = $databaseElement->ownerDocument->createComment( "Attribute 'identifierQuoting' generated" ); $databaseElement->appendChild($identifierQuotingNoticeComment); $databaseElement->setAttribute('identifierQuoting', 'true'); $databaseDocument->appendChild($databaseElement); $this->databases[] = $database; $this->globalDatabaseElements[$database] = $databaseElement; $this->sourceDatabaseElements[$database] = []; $this->externalSchemaDatabaseElements[$database] = []; }
php
{ "resource": "" }
q2096
SchemaCombiner.mergeDatabaseElement
train
protected function mergeDatabaseElement(\DOMElement $sourceDatabaseElement) { $database = $this->getDatabaseFromDatabaseElement($sourceDatabaseElement); $this->initGlobalDatabaseElement($database); $globalDatabaseElement = $this->globalDatabaseElements[$database]; // add a source schema start marker $fileStartMarkerComment = $globalDatabaseElement->ownerDocument->createComment( "Start of schema from '{$sourceDatabaseElement->ownerDocument->baseURI}'" ); $globalDatabaseElement->appendChild($fileStartMarkerComment); // merge the element foreach ($sourceDatabaseElement->childNodes as $childNode) { $importedNode = $globalDatabaseElement->ownerDocument->importNode($childNode, true); $globalDatabaseElement->appendChild($importedNode); } // and a source schema end marker $fileEndMarkerComment = $globalDatabaseElement->ownerDocument->createComment( "End of schema from '{$sourceDatabaseElement->ownerDocument->baseURI}'" ); $globalDatabaseElement->appendChild($fileEndMarkerComment); $this->sourceDatabaseElements[$database][] = $sourceDatabaseElement; }
php
{ "resource": "" }
q2097
SchemaCombiner.includeExternalSchema
train
protected function includeExternalSchema(\DOMElement $externalDatabaseElement) { $database = $this->getDatabaseFromDatabaseElement($externalDatabaseElement); $this->initGlobalDatabaseElement($database); $globalDatabaseElement = $this->globalDatabaseElements[$database]; // add an inclusion notice $externalSchemaIncludeComment = $globalDatabaseElement->ownerDocument->createComment( "External schema included in the combining process" ); $globalDatabaseElement->appendChild($externalSchemaIncludeComment); // include the external schema $externalSchemaInclude = $globalDatabaseElement->ownerDocument->createElement( 'external-schema', $externalDatabaseElement->ownerDocument->baseURI ); $globalDatabaseElement->appendChild($externalSchemaInclude); $this->externalSchemaDatabaseElements[$database][] = $externalDatabaseElement; }
php
{ "resource": "" }
q2098
ImportHandler.getImport
train
public function getImport($importId, $dispatchException = false) { $import = (new ImportQuery)->findPk($importId); if ($import === null && $dispatchException) { throw new \ErrorException( Translator::getInstance()->trans( 'There is no id "%id" in the imports', [ '%id' => $importId ] ) ); } return $import; }
php
{ "resource": "" }
q2099
ImportHandler.getImportByRef
train
public function getImportByRef($importRef, $dispatchException = false) { $import = (new ImportQuery)->findOneByRef($importRef); if ($import === null && $dispatchException) { throw new \ErrorException( Translator::getInstance()->trans( 'There is no id "%ref" in the imports', [ '%ref' => $importRef ] ) ); } return $import; }
php
{ "resource": "" }