_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2100 | ImportHandler.getCategory | train | public function getCategory($importCategoryId, $dispatchException = false)
{
$category = (new ImportCategoryQuery)->findPk($importCategoryId);
if ($category === null && $dispatchException) {
throw new \ErrorException(
Translator::getInstance()->trans(
'There is no id "%id" in the import categories',
[
'%id' => $importCategoryId
]
)
);
}
return $category;
} | php | {
"resource": ""
} |
q2101 | ImportHandler.matchArchiverByExtension | train | public function matchArchiverByExtension($fileName)
{
/** @var \Thelia\Core\Archiver\AbstractArchiver $archiver */
foreach ($this->archiverManager->getArchivers(true) as $archiver) {
if (stripos($fileName, '.' . $archiver->getExtension()) !== false) {
return $archiver;
}
}
return null;
} | php | {
"resource": ""
} |
q2102 | ImportHandler.matchSerializerByExtension | train | public function matchSerializerByExtension($fileName)
{
/** @var \Thelia\Core\Serializer\AbstractSerializer $serializer */
foreach ($this->serializerManager->getSerializers() as $serializer) {
if (stripos($fileName, '.' . $serializer->getExtension()) !== false) {
return $serializer;
}
}
return null;
} | php | {
"resource": ""
} |
q2103 | HookRenderEvent.dump | train | public function dump($glue = '', $before = '', $after = '')
{
$ret = '';
if (0 !== \count($this->fragments)) {
$ret = $before . implode($glue, $this->fragments) . $after;
}
return $ret;
} | php | {
"resource": ""
} |
q2104 | DatabaseConfiguration.buildConnectionNode | train | public function buildConnectionNode($rootName, $isArray)
{
$treeBuilder = new TreeBuilder();
$connectionNode = $treeBuilder->root($rootName);
if ($isArray) {
/** @var ArrayNodeDefinition $connectionNodePrototype */
$connectionNodePrototype = $connectionNode->prototype('array');
$connectionNodeBuilder = $connectionNodePrototype->children();
} else {
$connectionNodeBuilder = $connectionNode->children();
}
$connectionNodeBuilder->scalarNode('driver')
->defaultValue('mysql');
$connectionNodeBuilder->scalarNode('user')
->defaultValue('root');
$connectionNodeBuilder->scalarNode('password')
->defaultValue('');
$connectionNodeBuilder->scalarNode('dsn')
->cannotBeEmpty();
$connectionNodeBuilder->scalarNode('classname')
->defaultValue('\Propel\Runtime\Connection\ConnectionWrapper');
return $connectionNode;
} | php | {
"resource": ""
} |
q2105 | StatementBlockNode.getUseDeclarations | train | public function getUseDeclarations() {
$declarations = [];
/** @var \Pharborist\Namespaces\UseDeclarationBlockNode[] $use_blocks */
$use_blocks = $this->children(Filter::isInstanceOf('\Pharborist\Namespaces\UseDeclarationBlockNode'));
foreach ($use_blocks as $use_block) {
foreach ($use_block->getDeclarationStatements() as $use_statement) {
$declarations = array_merge($declarations, $use_statement->getDeclarations()->toArray());
}
}
return new NodeCollection($declarations, FALSE);
} | php | {
"resource": ""
} |
q2106 | StatementBlockNode.getClassAliases | train | public function getClassAliases() {
$mappings = array();
foreach ($this->getUseDeclarations() as $use_declaration) {
if ($use_declaration->isClass()) {
$mappings[$use_declaration->getBoundedName()] = $use_declaration->getName()->getAbsolutePath();
}
}
return $mappings;
} | php | {
"resource": ""
} |
q2107 | StatementBlockNode.appendStatement | train | public function appendStatement(StatementNode $statementNode) {
if (!$this->isEmpty() && $this->firstToken()->getType() === '{') {
$this->lastChild()->before($statementNode);
}
else {
$this->appendChild($statementNode);
}
return $this;
} | php | {
"resource": ""
} |
q2108 | SlackFactory.make | train | public function make(array $config)
{
Arr::requires($config, ['token']);
$client = new Client();
return new SlackGateway($client, $config);
} | php | {
"resource": ""
} |
q2109 | Configs.get | train | public static function get( $key = null ) {
$configs = self::$configs;
if ( $key ) {
$configs = ! empty( self::$configs[ $key ] ) ? self::$configs[ $key ] : null;
} else {
$configs = self::$configs;
}
return $configs;
} | php | {
"resource": ""
} |
q2110 | Filter.any | train | public static function any($filters) {
return function ($node) use ($filters) {
foreach ($filters as $filter) {
if ($filter($node)) {
return TRUE;
}
}
return FALSE;
};
} | php | {
"resource": ""
} |
q2111 | Filter.all | train | public static function all($filters) {
return function ($node) use ($filters) {
foreach ($filters as $filter) {
if (!$filter($node)) {
return FALSE;
}
}
return TRUE;
};
} | php | {
"resource": ""
} |
q2112 | Filter.isInstanceOf | train | public static function isInstanceOf($class_name) {
$classes = func_get_args();
return function ($node) use ($classes) {
foreach ($classes as $class) {
if ($node instanceof $class) {
return TRUE;
}
}
return FALSE;
};
} | php | {
"resource": ""
} |
q2113 | Filter.isFunction | train | public static function isFunction($function_name) {
$function_names = func_get_args();
return function ($node) use ($function_names) {
if ($node instanceof FunctionDeclarationNode) {
return in_array($node->getName()->getText(), $function_names, TRUE);
}
return FALSE;
};
} | php | {
"resource": ""
} |
q2114 | Filter.isFunctionCall | train | public static function isFunctionCall($function_name) {
$function_names = func_get_args();
return function ($node) use ($function_names) {
if ($node instanceof FunctionCallNode) {
return in_array($node->getName()->getText(), $function_names, TRUE);
}
return FALSE;
};
} | php | {
"resource": ""
} |
q2115 | Filter.isClass | train | public static function isClass($class_name) {
$class_names = func_get_args();
return function ($node) use ($class_names) {
if ($node instanceof ClassNode) {
return in_array($node->getName()->getText(), $class_names, TRUE);
}
return FALSE;
};
} | php | {
"resource": ""
} |
q2116 | Filter.isClassMethodCall | train | public static function isClassMethodCall($class_name, $method_name) {
return function ($node) use ($class_name, $method_name) {
if ($node instanceof ClassMethodCallNode) {
$call_class_name_node = $node->getClassName();
$call_class_name = $call_class_name_node instanceof NameNode ? $call_class_name_node->getAbsolutePath() : $call_class_name_node->getText();
$class_matches = $call_class_name === $class_name;
$method_matches = $node->getMethodName()->getText() === $method_name;
return $class_matches && $method_matches;
}
return FALSE;
};
} | php | {
"resource": ""
} |
q2117 | Filter.isComment | train | public static function isComment($include_doc_comment = TRUE) {
if ($include_doc_comment) {
return function ($node) {
if ($node instanceof LineCommentBlockNode) {
return TRUE;
}
elseif ($node instanceof CommentNode) {
return !($node->parent() instanceof LineCommentBlockNode);
}
else {
return FALSE;
}
};
}
else {
return function ($node) {
if ($node instanceof LineCommentBlockNode) {
return TRUE;
}
elseif ($node instanceof DocCommentNode) {
return FALSE;
}
elseif ($node instanceof CommentNode) {
return !($node->parent() instanceof LineCommentBlockNode);
}
else {
return FALSE;
}
};
}
} | php | {
"resource": ""
} |
q2118 | Filter.isTokenType | train | public static function isTokenType($type) {
$types = func_get_args();
return function ($node) use ($types) {
return $node instanceof TokenNode && in_array($node->getType(), $types);
};
} | php | {
"resource": ""
} |
q2119 | Filter.isNewline | train | public static function isNewline() {
static $callback = NULL;
if (!$callback) {
$callback = function (Node $node) {
return $node instanceof WhitespaceNode && $node->getNewlineCount() > 0;
};
}
return $callback;
} | php | {
"resource": ""
} |
q2120 | DocVisitor.create | train | public static function create(string $contents)
{
$contextInst = new ContextFactory();
$context = function (string $namespace) use ($contents, $contextInst) {
return $contextInst->createForNamespace($namespace, $contents);
};
$phpdocInst = DocBlockFactory::createInstance();
$phpdoc = function (string $doc, Context $context) use ($phpdocInst) {
return $phpdocInst->create($doc, $context);
};
return new self($context, $phpdoc);
} | php | {
"resource": ""
} |
q2121 | DocVisitor.enterNode | train | public function enterNode(Node $node)
{
if ($node instanceof Namespace_) {
$this->resetContext($node->name);
}
$this->recordDoc($node->getAttribute('comments', []));
return $node;
} | php | {
"resource": ""
} |
q2122 | DocVisitor.recordDoc | train | protected function recordDoc(array $comments)
{
$callable = $this->phpdocFactory;
foreach ($comments as $comment) {
if ($comment instanceof Doc) {
$this->doc[] = $callable($comment->getText(), $this->context);
}
}
} | php | {
"resource": ""
} |
q2123 | NodeCollection.sortUnique | train | protected static function sortUnique($nodes) {
$sort = [];
$detached = [];
foreach ($nodes as $node) {
$key = $node->sortKey();
if ($key[0] === '~') {
$detached[] = $node;
}
else {
$sort[$key] = $node;
}
}
ksort($sort, SORT_NATURAL);
return array_merge(array_values($sort), $detached);
} | php | {
"resource": ""
} |
q2124 | NodeCollection.slice | train | public function slice($start_index, $end_index = NULL) {
if ($start_index < 0) {
$start_index = $this->count() + $start_index;
}
if ($end_index < 0) {
$end_index = $this->count() + $end_index;
}
$last_index = $this->count() - 1;
if ($start_index > $last_index) {
$start_index = $last_index;
}
if ($end_index !== NULL) {
if ($end_index > $last_index) {
$end_index = $last_index;
}
if ($start_index > $end_index) {
$start_index = $end_index;
}
$length = $end_index - $start_index;
}
else {
$length = $this->count() - $start_index;
}
return new NodeCollection(array_slice($this->nodes, $start_index, $length));
} | php | {
"resource": ""
} |
q2125 | NodeCollection.indexOf | train | public function indexOf(callable $callback) {
foreach ($this->nodes as $i => $node) {
if ($callback($node)) {
return $i;
}
}
return -1;
} | php | {
"resource": ""
} |
q2126 | NodeCollection.is | train | public function is(callable $callback) {
foreach ($this->nodes as $node) {
if ($callback($node)) {
return TRUE;
}
}
return FALSE;
} | php | {
"resource": ""
} |
q2127 | NodeCollection.closest | train | public function closest(callable $callback) {
$matches = [];
foreach ($this->nodes as $node) {
if ($match = $node->closest($callback)) {
$matches[] = $match;
}
}
return new NodeCollection($matches);
} | php | {
"resource": ""
} |
q2128 | NodeCollection.children | train | public function children(callable $callback = NULL) {
$matches = [];
foreach ($this->nodes as $node) {
if ($node instanceof ParentNode) {
$matches = array_merge($matches, $node->children($callback)->nodes);
}
}
return new NodeCollection($matches);
} | php | {
"resource": ""
} |
q2129 | NodeCollection.clear | train | public function clear() {
foreach ($this->nodes as $node) {
if ($node instanceof ParentNode) {
$node->clear();
}
}
return $this;
} | php | {
"resource": ""
} |
q2130 | NodeCollection.previous | train | public function previous(callable $callback = NULL) {
$matches = [];
foreach ($this->nodes as $node) {
if ($match = $node->previous($callback)) {
$matches[] = $match;
}
}
return new NodeCollection($matches);
} | php | {
"resource": ""
} |
q2131 | NodeCollection.previousAll | train | public function previousAll(callable $callback = NULL) {
$matches = [];
foreach ($this->nodes as $node) {
$matches = array_merge($matches, $node->previousAll($callback)->nodes);
}
return new NodeCollection($matches);
} | php | {
"resource": ""
} |
q2132 | NodeCollection.previousUntil | train | public function previousUntil(callable $callback, $inclusive = FALSE) {
$matches = [];
foreach ($this->nodes as $node) {
$matches = array_merge($matches, $node->previousUntil($callback, $inclusive)->nodes);
}
return new NodeCollection($matches);
} | php | {
"resource": ""
} |
q2133 | NodeCollection.find | train | public function find(callable $callback) {
$matches = [];
foreach ($this->nodes as $node) {
if ($node instanceof ParentNode) {
$matches = array_merge($matches, $node->find($callback)->nodes);
}
}
return new NodeCollection($matches);
} | php | {
"resource": ""
} |
q2134 | NodeCollection.filter | train | public function filter(callable $callback) {
$matches = [];
foreach ($this->nodes as $index => $node) {
if ($callback($node, $index)) {
$matches[] = $node;
}
}
return new NodeCollection($matches, FALSE);
} | php | {
"resource": ""
} |
q2135 | NodeCollection.has | train | public function has(callable $callback) {
$matches = [];
foreach ($this->nodes as $node) {
if ($node instanceof ParentNode && $node->has($callback)) {
$matches[] = $node;
}
}
return new NodeCollection($matches, FALSE);
} | php | {
"resource": ""
} |
q2136 | NodeCollection.first | train | public function first() {
$matches = [];
if (!empty($this->nodes)) {
$matches[] = $this->nodes[0];
}
return new NodeCollection($matches, FALSE);
} | php | {
"resource": ""
} |
q2137 | NodeCollection.last | train | public function last() {
$matches = [];
if (!empty($this->nodes)) {
$matches[] = $this->nodes[count($this->nodes) - 1];
}
return new NodeCollection($matches, FALSE);
} | php | {
"resource": ""
} |
q2138 | NodeCollection.insertBefore | train | public function insertBefore($targets) {
foreach ($this->nodes as $node) {
$node->insertBefore($targets);
}
return $this;
} | php | {
"resource": ""
} |
q2139 | NodeCollection.before | train | public function before($nodes) {
foreach ($this->nodes as $i => $node) {
$node->before($i === 0 ? $nodes : clone $nodes);
}
return $this;
} | php | {
"resource": ""
} |
q2140 | NodeCollection.insertAfter | train | public function insertAfter($targets) {
foreach ($this->nodes as $node) {
$node->insertAfter($targets);
}
return $this;
} | php | {
"resource": ""
} |
q2141 | NodeCollection.after | train | public function after($nodes) {
foreach ($this->nodes as $i => $node) {
$node->after($i === 0 ? $nodes : clone $nodes);
}
return $this;
} | php | {
"resource": ""
} |
q2142 | NodeCollection.replaceWith | train | public function replaceWith($nodes) {
$first = TRUE;
foreach ($this->nodes as $node) {
if (!$first) {
if (is_array($nodes)) {
$nodes = new NodeCollection($nodes, FALSE);
}
$nodes = clone $nodes;
}
$node->replaceWith($nodes);
$first = FALSE;
}
return $this;
} | php | {
"resource": ""
} |
q2143 | NodeCollection.replaceAll | train | public function replaceAll($targets) {
if ($targets instanceof Node) {
$targets->replaceWith($this->nodes);
}
elseif ($targets instanceof NodeCollection || is_array($targets)) {
$first = TRUE;
/** @var Node $target */
foreach ($targets as $target) {
$target->replaceWith($first ? $this->nodes : clone $this);
$first = FALSE;
}
}
return $this;
} | php | {
"resource": ""
} |
q2144 | NodeCollection.add | train | public function add($nodes) {
if ($nodes instanceof Node) {
$this->nodes[] = $nodes;
}
elseif ($nodes instanceof NodeCollection) {
$this->nodes = array_merge($this->nodes, $nodes->nodes);
}
elseif (is_array($nodes)) {
$this->nodes = array_merge($this->nodes, $nodes);
}
else {
throw new \InvalidArgumentException();
}
$this->nodes = static::sortUnique($this->nodes);
return $this;
} | php | {
"resource": ""
} |
q2145 | ImportVisitor.enterNode | train | public function enterNode(Node $node)
{
if ($node instanceof UseUse) {
$this->imports[] = $node->name->toString();
}
return $node;
} | php | {
"resource": ""
} |
q2146 | HookCleanCommand.deleteHooks | train | protected function deleteHooks($module)
{
$query = ModuleHookQuery::create();
if (null !== $module) {
$query
->filterByModule($module)
->delete();
} else {
$query->deleteAll();
}
$query = IgnoredModuleHookQuery::create();
if (null !== $module) {
$query
->filterByModule($module)
->delete();
} else {
$query->deleteAll();
}
} | php | {
"resource": ""
} |
q2147 | BaseForm.getFormDefinedUrl | train | public function getFormDefinedUrl($parameterName, $default = null)
{
$formDefinedUrl = $this->form->get($parameterName)->getData();
if (empty($formDefinedUrl)) {
if ($default === null) {
$default = ConfigQuery::read('base_url', '/');
}
$formDefinedUrl = $default;
}
return URL::getInstance()->absoluteUrl($formDefinedUrl);
} | php | {
"resource": ""
} |
q2148 | Image.findNextPrev | train | private function findNextPrev(LoopResultRow $loopResultRow, $imageId, $imageType, $currentPosition)
{
if ($imageType == 'product') {
$imageRow = ProductImageQuery::create()
->filterById($imageId)
->findOne();
if ($imageRow != null) {
$previousQuery = ProductImageQuery::create()
->filterByProductId($imageRow->getProductId())
->filterByPosition($currentPosition, Criteria::LESS_THAN);
$nextQuery = ProductImageQuery::create()
->filterByProductId($imageRow->getProductId())
->filterByPosition($currentPosition, Criteria::GREATER_THAN);
if (!$this->getBackendContext()) {
$previousQuery->useProductQuery()
->filterByVisible(true)
->endUse();
$previousQuery->useProductQuery()
->filterByVisible(true)
->endUse();
}
$previous = $previousQuery
->orderByPosition(Criteria::DESC)
->findOne();
$next = $nextQuery
->orderByPosition(Criteria::ASC)
->findOne();
$loopResultRow
->set("HAS_PREVIOUS", $previous != null ? 1 : 0)
->set("HAS_NEXT", $next != null ? 1 : 0)
->set("PREVIOUS", $previous != null ? $previous->getId() : -1)
->set("NEXT", $next != null ? $next->getId() : -1);
return;
}
}
$loopResultRow
->set("HAS_PREVIOUS", 0)
->set("HAS_NEXT", 0);
} | php | {
"resource": ""
} |
q2149 | Brand.update | train | public function update(BrandUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== $brand = BrandQuery::create()->findPk($event->getBrandId())) {
$brand->setDispatcher($dispatcher);
$brand
->setVisible($event->getVisible())
->setLogoImageId(\intval($event->getLogoImageId()) == 0 ? null : $event->getLogoImageId())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->setDescription($event->getDescription())
->setChapo($event->getChapo())
->setPostscriptum($event->getPostscriptum())
->save()
;
$event->setBrand($brand);
}
} | php | {
"resource": ""
} |
q2150 | Brand.toggleVisibility | train | public function toggleVisibility(BrandToggleVisibilityEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$brand = $event->getBrand();
$brand
->setDispatcher($dispatcher)
->setVisible(!$brand->getVisible())
->save();
$event->setBrand($brand);
} | php | {
"resource": ""
} |
q2151 | Brand.viewCheck | train | public function viewCheck(ViewCheckEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if ($event->getView() == 'brand') {
$brand = BrandQuery::create()
->filterById($event->getViewId())
->filterByVisible(1)
->count();
if ($brand == 0) {
$dispatcher->dispatch(TheliaEvents::VIEW_BRAND_ID_NOT_VISIBLE, $event);
}
}
} | php | {
"resource": ""
} |
q2152 | Dockbar.addLeftLink | train | public function addLeftLink(string $name, string $link = null, bool $ajax = false): Item
{
return $this->leftItems[] = new Item($name, [
'link' => $link ?? '#',
'ajax' => $ajax
]);
} | php | {
"resource": ""
} |
q2153 | Dockbar.addRightLink | train | public function addRightLink(string $name, string $link = null, bool $ajax = false): Item
{
return $this->rightItems[] = new Item($name, [
'link' => $link ?? '#',
'ajax' => $ajax
]);
} | php | {
"resource": ""
} |
q2154 | Dockbar.isLinkAllowed | train | public function isLinkAllowed(string $link): bool
{
if (isset($this->allowedLinks[$link])) {
return true;
} else {
$pos = strrpos($link, ':');
$link = substr($link, 0, ($pos + 1));
return isset($this->allowedLinks[$link]);
}
} | php | {
"resource": ""
} |
q2155 | Dockbar.checkHandlerPermission | train | private function checkHandlerPermission(bool $ajax = true): void
{
if (!isset($this->allowedHandler[$this->presenter->getSignal()[1]])) {
$this->presenter->terminate();
}
if ($ajax && !$this->presenter->isAjax()) {
$this->presenter->terminate();
}
} | php | {
"resource": ""
} |
q2156 | AbstractDeliveryModule.getAreaForCountry | train | public function getAreaForCountry(Country $country)
{
$area = null;
if (null !== $areaDeliveryModule = AreaDeliveryModuleQuery::create()->findByCountryAndModule(
$country,
$this->getModuleModel()
)) {
$area = $areaDeliveryModule->getArea();
}
return $area;
} | php | {
"resource": ""
} |
q2157 | AnonymousFunctionNode.createLexicalVariables | train | protected function createLexicalVariables() {
if (!$this->hasLexicalVariables()) {
$this->lexicalUse = Token::_use();
$this->lexicalOpenParen = Token::openParen();
$this->lexicalVariables = new CommaListNode();
$this->lexicalCloseParen = Token::closeParen();
$this->closeParen->after([
Token::space(),
$this->lexicalUse,
Token::space(),
$this->lexicalOpenParen,
$this->lexicalVariables,
$this->lexicalCloseParen,
]);
}
} | php | {
"resource": ""
} |
q2158 | ProductController.loadRelatedAjaxTabAction | train | public function loadRelatedAjaxTabAction()
{
return $this->render(
'ajax/product-related-tab',
array(
'product_id' => $this->getRequest()->get('product_id', 0),
'folder_id' => $this->getRequest()->get('folder_id', 0),
'accessory_category_id' => $this->getRequest()->get('accessory_category_id', 0)
)
);
} | php | {
"resource": ""
} |
q2159 | ProductController.getVirtualDocumentListAjaxAction | train | public function getVirtualDocumentListAjaxAction($productId, $pseId)
{
$this->checkAuth(AdminResources::PRODUCT, array(), AccessManager::VIEW);
$this->checkXmlHttpRequest();
$selectedId = \intval(MetaDataQuery::getVal('virtual', MetaData::PSE_KEY, $pseId));
$documents = ProductDocumentQuery::create()
->filterByProductId($productId)
->filterByVisible(0)
->orderByPosition()
->find()
;
$results = [];
if (null !== $documents) {
/** @var ProductDocument $document */
foreach ($documents as $document) {
$results[] = [
'id' => $document->getId(),
'title' => $document->getTitle(),
'file' => $document->getFile(),
'selected' => ($document->getId() == $selectedId)
];
}
}
return $this->jsonResponse(json_encode($results));
} | php | {
"resource": ""
} |
q2160 | ProductController.updateAccessoryPositionAction | train | public function updateAccessoryPositionAction()
{
$accessory = AccessoryQuery::create()->findPk($this->getRequest()->get('accessory_id', null));
return $this->genericUpdatePositionAction(
$accessory,
TheliaEvents::PRODUCT_UPDATE_ACCESSORY_POSITION
);
} | php | {
"resource": ""
} |
q2161 | ProductController.updateContentPositionAction | train | public function updateContentPositionAction()
{
$content = ProductAssociatedContentQuery::create()->findPk($this->getRequest()->get('content_id', null));
return $this->genericUpdatePositionAction(
$content,
TheliaEvents::PRODUCT_UPDATE_CONTENT_POSITION
);
} | php | {
"resource": ""
} |
q2162 | ProductController.setProductTemplateAction | train | public function setProductTemplateAction($productId)
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$product = ProductQuery::create()->findPk($productId);
if ($product != null) {
$template_id = \intval($this->getRequest()->get('template_id', 0));
$this->dispatch(
TheliaEvents::PRODUCT_SET_TEMPLATE,
new ProductSetTemplateEvent($product, $template_id, $this->getCurrentEditionCurrency()->getId())
);
}
return $this->redirectToEditionTemplate();
} | php | {
"resource": ""
} |
q2163 | ProductController.updateAttributesAndFeaturesAction | train | public function updateAttributesAndFeaturesAction($productId)
{
$product = ProductQuery::create()->findPk($productId);
if ($product != null) {
$featureTemplate = FeatureTemplateQuery::create()->filterByTemplateId($product->getTemplateId())->find();
if ($featureTemplate !== null) {
// Get all features for the template attached to this product
$allFeatures = FeatureQuery::create()
->filterByFeatureTemplate($featureTemplate)
->find();
$updatedFeatures = array();
// Update all features values, starting with feature av. values
$featureValues = $this->getRequest()->get('feature_value', array());
foreach ($featureValues as $featureId => $featureValueList) {
// Delete all features av. for this feature.
$event = new FeatureProductDeleteEvent($productId, $featureId);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, $event);
// Add then all selected values
foreach ($featureValueList as $featureValue) {
$event = new FeatureProductUpdateEvent($productId, $featureId, $featureValue);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE, $event);
}
$updatedFeatures[] = $featureId;
}
// Update then features text values
$featureTextValues = $this->getRequest()->get('feature_text_value', array());
foreach ($featureTextValues as $featureId => $featureValue) {
// Check if a FeatureProduct exists for this product and this feature (for another lang)
$freeTextFeatureProduct = FeatureProductQuery::create()
->filterByProductId($productId)
->filterByIsFreeText(true)
->findOneByFeatureId($featureId);
// If no corresponding FeatureProduct exists AND if the feature_text_value is empty, do nothing
if (\is_null($freeTextFeatureProduct) && empty($featureValue)) {
continue;
}
$event = new FeatureProductUpdateEvent($productId, $featureId, $featureValue, true);
$event->setLocale($this->getCurrentEditionLocale());
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE, $event);
$updatedFeatures[] = $featureId;
}
// Delete features which don't have any values
/** @var Feature $feature */
foreach ($allFeatures as $feature) {
if (! \in_array($feature->getId(), $updatedFeatures)) {
$event = new FeatureProductDeleteEvent($productId, $feature->getId());
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, $event);
}
}
}
}
// If we have to stay on the same page, do not redirect to the successUrl,
// just redirect to the edit page again.
if ($this->getRequest()->get('save_mode') == 'stay') {
return $this->redirectToEditionTemplate();
}
// Redirect to the category/product list
return $this->redirectToListTemplate();
} | php | {
"resource": ""
} |
q2164 | ProductController.processSingleProductSaleElementUpdate | train | protected function processSingleProductSaleElementUpdate($data)
{
$event = new ProductSaleElementUpdateEvent(
$this->getExistingObject(),
$data['product_sale_element_id']
);
$event
->setReference($data['reference'])
->setPrice($data['price'])
->setCurrencyId($data['currency'])
->setWeight($data['weight'])
->setQuantity($data['quantity'])
->setSalePrice($data['sale_price'])
->setOnsale($data['onsale'])
->setIsnew($data['isnew'])
->setIsdefault($data['isdefault'])
->setEanCode($data['ean_code'])
->setTaxRuleId($data['tax_rule'])
->setFromDefaultCurrency($data['use_exchange_rate'])
;
$this->dispatch(TheliaEvents::PRODUCT_UPDATE_PRODUCT_SALE_ELEMENT, $event);
// Log object modification
if (null !== $changedObject = $event->getProductSaleElement()) {
$this->adminLogAppend(
$this->resourceCode,
AccessManager::UPDATE,
sprintf(
"Product Sale Element (ID %s) for product reference %s modified",
$changedObject->getId(),
$event->getProduct()->getRef()
),
$changedObject->getId()
);
}
} | php | {
"resource": ""
} |
q2165 | ProductController.processProductSaleElementUpdate | train | protected function processProductSaleElementUpdate($changeForm)
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
if (\is_array($data['product_sale_element_id'])) {
// Common fields
$tmp_data = array(
'tax_rule' => $data['tax_rule'],
'currency' => $data['currency'],
'use_exchange_rate' => $data['use_exchange_rate'],
);
$count = \count($data['product_sale_element_id']);
for ($idx = 0; $idx < $count; $idx++) {
$tmp_data['product_sale_element_id'] = $pse_id = $data['product_sale_element_id'][$idx];
$tmp_data['reference'] = $data['reference'][$idx];
$tmp_data['price'] = $data['price'][$idx];
$tmp_data['weight'] = $data['weight'][$idx];
$tmp_data['quantity'] = $data['quantity'][$idx];
$tmp_data['sale_price'] = $data['sale_price'][$idx];
$tmp_data['onsale'] = isset($data['onsale'][$idx]) ? 1 : 0;
$tmp_data['isnew'] = isset($data['isnew'][$idx]) ? 1 : 0;
$tmp_data['isdefault'] = $data['default_pse'] == $pse_id;
$tmp_data['ean_code'] = $data['ean_code'][$idx];
$this->processSingleProductSaleElementUpdate($tmp_data);
}
} else {
// No need to preprocess data
$this->processSingleProductSaleElementUpdate($data);
}
// If we have to stay on the same page, do not redirect to the successUrl, just redirect to the edit page again.
if ($this->getRequest()->get('save_mode') == 'stay') {
return $this->redirectToEditionTemplate();
}
// Redirect to the success URL
return $this->generateSuccessRedirect($changeForm);
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
$this->setupFormErrorContext(
$this->getTranslator()->trans("ProductSaleElement modification"),
$error_msg,
$changeForm,
$ex
);
// At this point, the form has errors, and should be redisplayed.
return $this->renderEditionTemplate();
} | php | {
"resource": ""
} |
q2166 | ProductController.buildCombinationsAction | train | public function buildCombinationsAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$changeForm = $this->createForm(AdminForm::PRODUCT_COMBINATION_GENERATION);
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
// Rework attributes_av array, to build an array which contains all combinations,
// in the form combination[] = array of combination attributes av IDs
//
// First, create an array of attributes_av ID in the form $attributes_av_list[$attribute_id] = array of attributes_av ID
// from the list of attribute_id:attributes_av ID from the form.
$combinations = $attributes_av_list = $tmp = array();
foreach ($data['attribute_av'] as $item) {
list($attribute_id, $attribute_av_id) = explode(':', $item);
if (! isset($attributes_av_list[$attribute_id])) {
$attributes_av_list[$attribute_id] = array();
}
$attributes_av_list[$attribute_id][] = $attribute_av_id;
}
// Next, recursively combine array
$this->combine($attributes_av_list, $combinations, $tmp);
// Create event
$event = new ProductCombinationGenerationEvent(
$this->getExistingObject(),
$data['currency'],
$combinations
);
$event
->setReference($data['reference'] == null ? '' : $data['reference'])
->setPrice($data['price'] == null ? 0 : $data['price'])
->setWeight($data['weight'] == null ? 0 : $data['weight'])
->setQuantity($data['quantity'] == null ? 0 : $data['quantity'])
->setSalePrice($data['sale_price'] == null ? 0 : $data['sale_price'])
->setOnsale($data['onsale'] == null ? false : $data['onsale'])
->setIsnew($data['isnew'] == null ? false : $data['isnew'])
->setEanCode($data['ean_code'] == null ? '' : $data['ean_code'])
;
$this->dispatch(TheliaEvents::PRODUCT_COMBINATION_GENERATION, $event);
// Log object modification
$this->adminLogAppend(
$this->resourceCode,
AccessManager::CREATE,
sprintf(
"Combination generation for product reference %s",
$event->getProduct()->getRef()
),
$event->getProduct()->getId()
);
// Redirect to the success URL
return $this->generateSuccessRedirect($changeForm);
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
$this->setupFormErrorContext(
$this->getTranslator()->trans("Combination builder"),
$error_msg,
$changeForm,
$ex
);
// At this point, the form has errors, and should be redisplayed.
return $this->renderEditionTemplate();
} | php | {
"resource": ""
} |
q2167 | ProductController.priceCalculator | train | public function priceCalculator()
{
$return_price = 0;
$price = \floatval($this->getRequest()->query->get('price', 0));
$product_id = \intval($this->getRequest()->query->get('product_id', 0));
$action = $this->getRequest()->query->get('action', ''); // With ot without tax
$convert = \intval($this->getRequest()->query->get('convert_from_default_currency', 0));
if (null !== $product = ProductQuery::create()->findPk($product_id)) {
if ($action == 'to_tax') {
$return_price = $this->computePrice($price, 'without_tax', $product);
} elseif ($action == 'from_tax') {
$return_price = $this->computePrice($price, 'with_tax', $product);
} else {
$return_price = $price;
}
if ($convert != 0) {
$return_price = $price * Currency::getDefaultCurrency()->getRate();
}
}
return new JsonResponse(array('result' => $this->formatPrice($return_price)));
} | php | {
"resource": ""
} |
q2168 | ProductController.loadConvertedPrices | train | public function loadConvertedPrices()
{
$product_sale_element_id = \intval($this->getRequest()->get('product_sale_element_id', 0));
$currency_id = \intval($this->getRequest()->get('currency_id', 0));
$price_with_tax = $price_without_tax = $sale_price_with_tax = $sale_price_without_tax = 0;
if (null !== $pse = ProductSaleElementsQuery::create()->findPk($product_sale_element_id)) {
if ($currency_id > 0
&&
$currency_id != Currency::getDefaultCurrency()->getId()
&&
null !== $currency = CurrencyQuery::create()->findPk($currency_id)) {
// Get the default currency price
$productPrice = ProductPriceQuery::create()
->filterByCurrency(Currency::getDefaultCurrency())
->filterByProductSaleElementsId($product_sale_element_id)
->findOne()
;
// Calculate the converted price
if (null !== $productPrice) {
$price_without_tax = $productPrice->getPrice() * $currency->getRate();
$sale_price_without_tax = $productPrice->getPromoPrice() * $currency->getRate();
}
}
if (null !== $product = $pse->getProduct()) {
$price_with_tax = $this->computePrice($price_without_tax, 'with_tax', $product);
$sale_price_with_tax = $this->computePrice($sale_price_without_tax, 'with_tax', $product);
}
}
return new JsonResponse(array(
'price_with_tax' => $this->formatPrice($price_with_tax),
'price_without_tax' => $this->formatPrice($price_without_tax),
'sale_price_with_tax' => $this->formatPrice($sale_price_with_tax),
'sale_price_without_tax' => $this->formatPrice($sale_price_without_tax)
));
} | php | {
"resource": ""
} |
q2169 | ExpressionParser.parse | train | public function parse($nodes, $filename = NULL) {
$this->nodes = $nodes;
$this->filename = $filename;
$this->position = 0;
$this->length = count($nodes);
$this->operators = [$this->sentinel];
$this->operands = [];
$this->E();
if ($this->next()) {
$next = $this->next();
throw new ParserException(
$this->filename,
$next->getLineNumber(),
$next->getColumnNumber(),
"invalid expression");
}
return self::arrayLast($this->operands);
} | php | {
"resource": ""
} |
q2170 | ConfigController.changeValuesAction | train | public function changeValuesAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$variables = $this->getRequest()->get('variable', array());
// Process all changed variables
foreach ($variables as $id => $value) {
$event = new ConfigUpdateEvent($id);
$event->setValue($value);
$this->dispatch(TheliaEvents::CONFIG_SETVALUE, $event);
}
return $this->generateRedirectFromRoute('admin.configuration.variables.default');
} | php | {
"resource": ""
} |
q2171 | CouponAbstract.isExpired | train | public function isExpired()
{
$ret = true;
$now = new \DateTime();
if ($this->expirationDate > $now) {
$ret = false;
}
return $ret;
} | php | {
"resource": ""
} |
q2172 | CouponAbstract.drawBackOfficeInputs | train | public function drawBackOfficeInputs()
{
return $this->facade->getParser()->render('coupon/type-fragments/remove-x.html', [
'label' => $this->getInputName(),
'fieldId' => self::AMOUNT_FIELD_NAME,
'fieldName' => $this->makeCouponFieldName(self::AMOUNT_FIELD_NAME),
'value' => $this->amount
]);
} | php | {
"resource": ""
} |
q2173 | CouponAbstract.getCouponFieldValue | train | protected function getCouponFieldValue($fieldName, $data, $defaultValue = null)
{
if (isset($data[self::COUPON_DATASET_NAME][$fieldName])) {
return $this->checkCouponFieldValue(
$fieldName,
$data[self::COUPON_DATASET_NAME][$fieldName]
);
} elseif (null !== $defaultValue) {
return $defaultValue;
} else {
throw new \InvalidArgumentException(sprintf("The coupon field name %s was not found in the coupon form", $fieldName));
}
} | php | {
"resource": ""
} |
q2174 | CouponAbstract.getEffects | train | public function getEffects($data)
{
$effects = [];
foreach ($this->getFieldList() as $fieldName) {
$effects[$fieldName] = $this->getCouponFieldValue($fieldName, $data);
}
return $effects;
} | php | {
"resource": ""
} |
q2175 | CustomerLogin.verifyAccount | train | public function verifyAccount($value, ExecutionContextInterface $context)
{
if ($value == 1) {
$data = $context->getRoot()->getData();
if (false === $data['password'] || (empty($data['password']) && '0' != $data['password'])) {
$context->getViolations()->add(new ConstraintViolation(
Translator::getInstance()->trans('This value should not be blank.'),
'account_password',
array(),
$context->getRoot(),
'children[password].data',
'propertyPath'
));
}
}
} | php | {
"resource": ""
} |
q2176 | CustomerLogin.verifyExistingEmail | train | public function verifyExistingEmail($value, ExecutionContextInterface $context)
{
$data = $context->getRoot()->getData();
if ($data["account"] == 0) {
$customer = CustomerQuery::create()->findOneByEmail($value);
if ($customer) {
$context->addViolation(Translator::getInstance()->trans("A user already exists with this email address. Please login or if you've forgotten your password, go to Reset Your Password."));
}
}
} | php | {
"resource": ""
} |
q2177 | Export.exportChangePosition | train | public function exportChangePosition(UpdatePositionEvent $updatePositionEvent, $eventName, EventDispatcherInterface $dispatcher)
{
$this->handler->getExport($updatePositionEvent->getObjectId(), true);
$this->genericUpdatePosition(new ExportQuery, $updatePositionEvent, $dispatcher);
} | php | {
"resource": ""
} |
q2178 | Export.exportCategoryChangePosition | train | public function exportCategoryChangePosition(UpdatePositionEvent $updatePositionEvent, $eventName, EventDispatcherInterface $dispatcher)
{
$this->handler->getCategory($updatePositionEvent->getObjectId(), true);
$this->genericUpdatePosition(new ExportCategoryQuery, $updatePositionEvent, $dispatcher);
} | php | {
"resource": ""
} |
q2179 | ProductSaleElements.getPricesByCurrency | train | public function getPricesByCurrency(Currency $currency, $discount = 0)
{
$defaultCurrency = Currency::getDefaultCurrency();
$productPrice = ProductPriceQuery::create()
->filterByProductSaleElementsId($this->getId())
->filterByCurrencyId($currency->getId())
->findOne();
if (null === $productPrice || $productPrice->getFromDefaultCurrency()) {
// need to calculate the prices based on the product prices for the default currency
$productPrice = ProductPriceQuery::create()
->filterByProductSaleElementsId($this->getId())
->filterByCurrencyId($defaultCurrency->getId())
->findOne();
if (null !== $productPrice) {
$price = $productPrice->getPrice() * $currency->getRate() / $defaultCurrency->getRate();
$promoPrice = $productPrice->getPromoPrice() * $currency->getRate() / $defaultCurrency->getRate();
} else {
throw new \RuntimeException('Cannot find product prices for currency id: `' . $currency->getId() . '`');
}
} else {
$price = $productPrice->getPrice();
$promoPrice = $productPrice->getPromoPrice();
}
if ($discount > 0) {
$price = $price * (1-($discount/100));
$promoPrice = $promoPrice * (1-($discount/100));
}
$productPriceTools = new ProductPriceTools($price, $promoPrice);
return $productPriceTools;
} | php | {
"resource": ""
} |
q2180 | Lint.getAllFiles | train | public function getAllFiles($sources)
{
$files = array();
foreach ($sources as $source) {
if (!is_dir($source)) {
$files[] = $source;
continue;
}
$recursiveFiles = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source)
);
foreach ($recursiveFiles as $file) {
if ($file->isDir()) {
continue;
}
$path = $file->getPathname();
$info = pathinfo(basename($path));
if (array_key_exists('extension', $info) && $info['extension'] == 'php') {
$files[] = $path;
}
}
}
return $files;
} | php | {
"resource": ""
} |
q2181 | Thelia.addStandardModuleTemplatesToParserEnvironment | train | protected function addStandardModuleTemplatesToParserEnvironment($parser, $module)
{
$stdTpls = TemplateDefinition::getStandardTemplatesSubdirsIterator();
foreach ($stdTpls as $templateType => $templateSubdirName) {
$this->addModuleTemplateToParserEnvironment($parser, $module, $templateType, $templateSubdirName);
}
} | php | {
"resource": ""
} |
q2182 | Thelia.addModuleTemplateToParserEnvironment | train | protected function addModuleTemplateToParserEnvironment($parser, $module, $templateType, $templateSubdirName)
{
// Get template path
$templateDirectory = $module->getAbsoluteTemplateDirectoryPath($templateSubdirName);
try {
$templateDirBrowser = new \DirectoryIterator($templateDirectory);
$code = ucfirst($module->getCode());
/* browse the directory */
foreach ($templateDirBrowser as $templateDirContent) {
/* is it a directory which is not . or .. ? */
if ($templateDirContent->isDir() && ! $templateDirContent->isDot()) {
$parser->addMethodCall(
'addTemplateDirectory',
array(
$templateType,
$templateDirContent->getFilename(),
$templateDirContent->getPathName(),
$code
)
);
}
}
} catch (\UnexpectedValueException $ex) {
// The directory does not exists, ignore it.
}
} | php | {
"resource": ""
} |
q2183 | Folder.viewCheck | train | public function viewCheck(ViewCheckEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if ($event->getView() == 'folder') {
$folder = FolderQuery::create()
->filterById($event->getViewId())
->filterByVisible(1)
->count();
if ($folder == 0) {
$dispatcher->dispatch(TheliaEvents::VIEW_FOLDER_ID_NOT_VISIBLE, $event);
}
}
} | php | {
"resource": ""
} |
q2184 | LocaleService.setDefault | train | protected function setDefault(int $localeId): void
{
$this->orm->locales->getById($localeId)->setDefault();
} | php | {
"resource": ""
} |
q2185 | LocaleService.setAllowed | train | protected function setAllowed(array $allowed): void
{
$locales = $this->orm->locales->findAll();
foreach ($locales as $locale) {
/* @var $locale Locale */
if (in_array($locale->id, $allowed)) {
$locale->allowed = true;
} else {
$locale->allowed = false;
}
$this->orm->persist($locale);
}
$this->orm->flush();
} | php | {
"resource": ""
} |
q2186 | TranslationsController.checkWritableI18nDirectory | train | public function checkWritableI18nDirectory($dir)
{
if (file_exists($dir)) {
return is_writable($dir);
}
$parentDir = dirname($dir);
return file_exists($parentDir) && is_writable($parentDir);
} | php | {
"resource": ""
} |
q2187 | HipchatFactory.make | train | public function make(array $config)
{
Arr::requires($config, ['token']);
$client = new Client();
return new HipchatGateway($client, $config);
} | php | {
"resource": ""
} |
q2188 | BallouGateway.parse | train | protected function parse($body)
{
$disableEntities = libxml_disable_entity_loader(true);
$internalErrors = libxml_use_internal_errors(true);
try {
$xml = new SimpleXMLElement((string) $body ?: '<root />', LIBXML_NONET);
return json_decode(json_encode($xml), true);
} catch (Exception $e) {
//
} catch (Throwable $e) {
//
} finally {
libxml_disable_entity_loader($disableEntities);
libxml_use_internal_errors($internalErrors);
}
} | php | {
"resource": ""
} |
q2189 | Country.getZipCodeRE | train | public function getZipCodeRE()
{
$zipCodeFormat = $this->getZipCodeFormat();
if (empty($zipCodeFormat)) {
return null;
}
$zipCodeRE = preg_replace("/\\s+/", ' ', $zipCodeFormat);
$trans = [
"N" => "\\d",
"L" => "[a-zA-Z]",
"C" => ".+",
" " => " +"
];
$zipCodeRE = "#^" . strtr($zipCodeRE, $trans) . "$#";
return $zipCodeRE;
} | php | {
"resource": ""
} |
q2190 | Country.getAreaId | train | public function getAreaId()
{
$firstAreaCountry = CountryAreaQuery::create()->findOneByCountryId($this->getId());
if (null !== $firstAreaCountry) {
return $firstAreaCountry->getAreaId();
}
return null;
} | php | {
"resource": ""
} |
q2191 | Country.getDefaultCountry | train | public static function getDefaultCountry()
{
if (null === self::$defaultCountry) {
self::$defaultCountry = CountryQuery::create()->findOneByByDefault(true);
if (null === self::$defaultCountry) {
throw new \LogicException(Translator::getInstance()->trans("Cannot find a default country. Please define one."));
}
}
return self::$defaultCountry;
} | php | {
"resource": ""
} |
q2192 | Country.getShopLocation | train | public static function getShopLocation()
{
$countryId = ConfigQuery::getStoreCountry();
// return the default country if no shop country defined
if (empty($countryId)) {
return self::getDefaultCountry();
}
$shopCountry = CountryQuery::create()->findPk($countryId);
if ($shopCountry === null) {
throw new \LogicException(Translator::getInstance()->trans("Cannot find the shop country. Please select a shop country."));
}
return $shopCountry;
} | php | {
"resource": ""
} |
q2193 | AbstractTags.getAliasColumn | train | protected function getAliasColumn()
{
$strColNameAlias = $this->get('tag_alias');
if ($this->isTreePicker() || !$strColNameAlias) {
$strColNameAlias = $this->getIdColumn();
}
return $strColNameAlias;
} | php | {
"resource": ""
} |
q2194 | AbstractTags.setDataForItem | train | private function setDataForItem($itemId, $tags, $thisExisting)
{
if ($tags === null) {
$tagIds = [];
} else {
$tagIds = \array_keys($tags);
}
// First pass, delete all not mentioned anymore.
$valuesToRemove = \array_diff($thisExisting, $tagIds);
if ($valuesToRemove) {
$this->connection
->createQueryBuilder()
->delete('tl_metamodel_tag_relation')
->where('att_id=:attId')
->andWhere('item_id=:itemId')
->andWhere('value_id IN (:valueIds)')
->setParameter('attId', $this->get('id'))
->setParameter('itemId', $itemId)
->setParameter('valueIds', $valuesToRemove, Connection::PARAM_STR_ARRAY)
->execute();
}
// Second pass, add all new values in a row.
$valuesToAdd = \array_diff($tagIds, $thisExisting);
$insertValues = [];
if ($valuesToAdd) {
foreach ($valuesToAdd as $valueId) {
$insertValues[] = [
'attId' => $this->get('id'),
'itemId' => $itemId,
'sorting' => (int) $tags[$valueId]['tag_value_sorting'],
'valueId' => $valueId
];
}
}
// Third pass, update all sorting values.
$valuesToUpdate = \array_diff($tagIds, $valuesToAdd);
if ($valuesToUpdate) {
$query = $this->connection
->createQueryBuilder()
->update('tl_metamodel_tag_relation')
->set('value_sorting', ':sorting')
->where('att_id=:attId')
->andWhere('item_id=:itemId')
->andWhere('value_id=:valueId')
->setParameter('attId', $this->get('id'))
->setParameter('itemId', $itemId);
foreach ($valuesToUpdate as $valueId) {
if (!array_key_exists('tag_value_sorting', $tags[$valueId])) {
continue;
}
$query
->setParameter('sorting', (int) $tags[$valueId]['tag_value_sorting'])
->setParameter('valueId', $valueId)
->execute();
}
}
return $insertValues;
} | php | {
"resource": ""
} |
q2195 | ReleaseChannel.updateChannel | train | public function updateChannel( $old, $new, $option ) {
$old['release_channel'] = ! empty( $old['release_channel'] ) ?
$old['release_channel'] : null;
$new['release_channel'] = ! empty( $new['release_channel'] ) ?
$new['release_channel'] : 'stable';
$old['theme_release_channel'] = ! empty( $old['theme_release_channel'] ) ?
$old['theme_release_channel'] : null;
$new['theme_release_channel'] = ! empty( $new['theme_release_channel'] ) ?
$new['theme_release_channel'] : 'stable';
// Plugin checks.
if ( $old['release_channel'] !== $new['release_channel'] ) {
Util\Option::deletePluginTransients();
wp_update_plugins();
}
// Theme checks.
if ( $old['theme_release_channel'] !== $new['theme_release_channel'] ) {
/**
* Action to take when theme release channel has changed.
*
* @since 1.1
*
* @param string $old Old theme release channel.
* @param string $new New theme release channel.
*/
do_action( 'Boldgrid\Library\Library\ReleaseChannel\theme_channel_updated', $old['theme_release_channel'], $new['theme_release_channel'] );
delete_site_transient( 'boldgrid_api_data' );
delete_site_transient( 'update_themes' );
wp_update_themes();
}
return $new;
} | php | {
"resource": ""
} |
q2196 | TemplateDefinition.getParentList | train | public function getParentList()
{
if (null === $this->parentList) {
$this->parentList = [];
$parent = $this->getDescriptor()->getParent();
for ($index = 1; null !== $parent; $index++) {
$this->parentList[$parent->getName() . '-'] = $parent;
$parent = $parent->getDescriptor()->getParent();
}
}
return $this->parentList;
} | php | {
"resource": ""
} |
q2197 | TemplateDefinition.getTemplateFilePath | train | public function getTemplateFilePath($templateName)
{
$templateList = array_merge(
[ $this ],
$this->getParentList()
);
/** @var TemplateDefinition $templateDefinition */
foreach ($templateList as $templateDefinition) {
$templateFilePath = sprintf(
'%s%s/%s',
THELIA_TEMPLATE_DIR,
$templateDefinition->getPath(),
$templateName
);
if (file_exists($templateFilePath)) {
return $templateFilePath;
}
}
throw new TemplateException("Template file not found: $templateName");
} | php | {
"resource": ""
} |
q2198 | Currency.create | train | public function create(CurrencyCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$currency = new CurrencyModel();
$isDefault = CurrencyQuery::create()->count() === 0;
$currency
->setDispatcher($dispatcher)
->setLocale($event->getLocale())
->setName($event->getCurrencyName())
->setSymbol($event->getSymbol())
->setFormat($event->getFormat())
->setRate($event->getRate())
->setCode(strtoupper($event->getCode()))
->setByDefault($isDefault)
->save()
;
$event->setCurrency($currency);
} | php | {
"resource": ""
} |
q2199 | Currency.update | train | public function update(CurrencyUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== $currency = CurrencyQuery::create()->findPk($event->getCurrencyId())) {
$currency
->setDispatcher($dispatcher)
->setLocale($event->getLocale())
->setName($event->getCurrencyName())
->setSymbol($event->getSymbol())
->setFormat($event->getFormat())
->setRate($event->getRate())
->setCode(strtoupper($event->getCode()))
->save();
$event->setCurrency($currency);
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.