_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q1500
Config.create
train
public function create(ConfigCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $config = new ConfigModel(); $config->setDispatcher($dispatcher) ->setName($event->getEventName()) ->setValue($event->getValue()) ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setHidden($event->getHidden()) ->setSecured($event->getSecured()) ->save(); $event->setConfig($config); }
php
{ "resource": "" }
q1501
Config.setValue
train
public function setValue(ConfigUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $config = ConfigQuery::create()->findPk($event->getConfigId())) { if ($event->getValue() !== $config->getValue()) { $config->setDispatcher($dispatcher)->setValue($event->getValue())->save(); $event->setConfig($config); } } }
php
{ "resource": "" }
q1502
Config.modify
train
public function modify(ConfigUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $config = ConfigQuery::create()->findPk($event->getConfigId())) { $config->setDispatcher($dispatcher) ->setName($event->getEventName()) ->setValue($event->getValue()) ->setHidden($event->getHidden()) ->setSecured($event->getSecured()) ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setDescription($event->getDescription()) ->setChapo($event->getChapo()) ->setPostscriptum($event->getPostscriptum()) ->save(); $event->setConfig($config); } }
php
{ "resource": "" }
q1503
Config.delete
train
public function delete(ConfigDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== ($config = ConfigQuery::create()->findPk($event->getConfigId()))) { if (!$config->getSecured()) { $config->setDispatcher($dispatcher)->delete(); $event->setConfig($config); } } }
php
{ "resource": "" }
q1504
StandardDescriptionFieldsTrait.addStandardDescFields
train
protected function addStandardDescFields($exclude = array()) { if (! \in_array('locale', $exclude)) { $this->formBuilder->add( 'locale', 'hidden', [ 'constraints' => [ new NotBlank() ], 'required' => true, ] ); } if (! \in_array('title', $exclude)) { $this->formBuilder->add( 'title', 'text', [ 'constraints' => [ new NotBlank() ], 'required' => true, 'label' => Translator::getInstance()->trans('Title'), 'label_attr' => [ 'for' => 'title_field', ], 'attr' => [ 'placeholder' => Translator::getInstance()->trans('A descriptive title'), ] ] ); } if (! \in_array('chapo', $exclude)) { $this->formBuilder->add( 'chapo', 'textarea', [ 'constraints' => [ ], 'required' => false, 'label' => Translator::getInstance()->trans('Summary'), 'label_attr' => [ 'for' => 'summary_field', 'help' => Translator::getInstance()->trans('A short description, used when a summary or an introduction is required'), ], 'attr' => [ 'rows' => 3, 'placeholder' => Translator::getInstance()->trans('Short description text'), ] ] ); } if (! \in_array('description', $exclude)) { $this->formBuilder->add( 'description', 'textarea', [ 'constraints' => [ ], 'required' => false, 'label' => Translator::getInstance()->trans('Detailed description'), 'label_attr' => [ 'for' => 'detailed_description_field', 'help' => Translator::getInstance()->trans('The detailed description.'), ], 'attr' => [ 'rows' => 10, ] ] ); } if (! \in_array('postscriptum', $exclude)) { $this->formBuilder->add( 'postscriptum', 'textarea', [ 'constraints' => [ ], 'required' => false, 'label' => Translator::getInstance()->trans('Conclusion'), 'label_attr' => [ 'for' => 'conclusion_field', 'help' => Translator::getInstance()->trans('A short text, used when an additional or supplemental information is required.'), ], 'attr' => [ 'placeholder' => Translator::getInstance()->trans('Short additional text'), 'rows' => 3, ] ] ); } }
php
{ "resource": "" }
q1505
XMLSerializer.setDataNodeName
train
public function setDataNodeName($dataNodeName) { $this->dataNodeName = $dataNodeName; $this->xmlEncoder->setRootNodeName($this->dataNodeName); return $this; }
php
{ "resource": "" }
q1506
RequestListener.registerPreviousUrl
train
public function registerPreviousUrl(PostResponseEvent $event) { $request = $event->getRequest(); if (!$request->isXmlHttpRequest() && $event->getResponse()->isSuccessful()) { $referrer = $request->attributes->get('_previous_url', null); $catalogViews = ['category', 'product']; $view = $request->attributes->get('_view', null); if (null !== $referrer) { // A previous URL (or the keyword 'dont-save') has been specified. if ('dont-save' == $referrer) { // We should not save the current URL as the previous URL $referrer = null; } } else { // The current URL will become the previous URL $referrer = $request->getUri(); } // Set previous URL, if defined if (null !== $referrer) { /** @var Session $session */ $session = $request->getSession(); if (ConfigQuery::isMultiDomainActivated()) { $components = parse_url($referrer); $lang = LangQuery::create() ->filterByUrl(sprintf("%s://%s", $components["scheme"], $components["host"]), ModelCriteria::LIKE) ->findOne(); if (null !== $lang) { $session->setReturnToUrl($referrer); if (\in_array($view, $catalogViews)) { $session->setReturnToCatalogLastUrl($referrer); } } } else { if (false !== strpos($referrer, $request->getSchemeAndHttpHost())) { $session->setReturnToUrl($referrer); if (\in_array($view, $catalogViews)) { $session->setReturnToCatalogLastUrl($referrer); } } } } } }
php
{ "resource": "" }
q1507
WebhookFactory.make
train
public function make(array $config) { Arr::requires($config, ['endpoint']); $client = new Client(); return new WebhookGateway($client, $config); }
php
{ "resource": "" }
q1508
TrueNode.create
train
public static function create($boolean = TRUE) { $is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper'); $node = new TrueNode(); $node->addChild(NameNode::create($is_upper ? 'TRUE' : 'true'), 'constantName'); return $node; }
php
{ "resource": "" }
q1509
NullNode.create
train
public static function create($name = 'null') { $is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper'); $node = new NullNode(); $node->addChild(NameNode::create($is_upper ? 'NULL' : 'null'), 'constantName'); return $node; }
php
{ "resource": "" }
q1510
Delivery.getPostage
train
public function getPostage(DeliveryPostageEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $module = $event->getModule(); // dispatch event to target specific module $dispatcher->dispatch( TheliaEvents::getModuleEvent( TheliaEvents::MODULE_DELIVERY_GET_POSTAGE, $module->getCode() ), $event ); if ($event->isPropagationStopped()) { return; } // call legacy module method $event->setValidModule($module->isValidDelivery($event->getCountry())); if ($event->isValidModule()) { $event->setPostage($module->getPostage($event->getCountry())); } }
php
{ "resource": "" }
q1511
AbstractPresenter.addBreadcrumbLink
train
public function addBreadcrumbLink(string $name, string $link = null, array $arguments = []): Link { return $this['breadcrumb']->addLink($name, $link, $arguments); }
php
{ "resource": "" }
q1512
AbstractPresenter.viewMobileMenu
train
public function viewMobileMenu(bool $view = true): void { $this->template->shifted = $view; $this['dockbar']->setShifted($view); }
php
{ "resource": "" }
q1513
AreaController.addCountry
train
public function addCountry() { // Check current user authorization if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) { return $response; } $areaCountryForm = $this->createForm(AdminForm::AREA_COUNTRY); $error_msg = null; try { $form = $this->validateForm($areaCountryForm); $event = new AreaAddCountryEvent($form->get('area_id')->getData(), $form->get('country_id')->getData()); $this->dispatch(TheliaEvents::AREA_ADD_COUNTRY, $event); if (! $this->eventContainsObject($event)) { throw new \LogicException( $this->getTranslator()->trans("No %obj was updated.", array('%obj', $this->objectName)) ); } // Log object modification if (null !== $changedObject = $this->getObjectFromEvent($event)) { $this->adminLogAppend( $this->resourceCode, AccessManager::UPDATE, sprintf( "%s %s (ID %s) modified, new country added", ucfirst($this->objectName), $this->getObjectLabel($changedObject), $this->getObjectId($changedObject) ), $this->getObjectId($changedObject) ); } // Redirect to the success URL return $this->generateSuccessRedirect($areaCountryForm); } 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("%obj modification", array('%obj' => $this->objectName)), $error_msg, $areaCountryForm ); // At this point, the form has errors, and should be redisplayed. return $this->renderEditionTemplate(); }
php
{ "resource": "" }
q1514
AreaController.removeCountries
train
public function removeCountries() { // Check current user authorization if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) { return $response; } $areaDeleteCountriesForm = $this->createForm(AdminForm::AREA_DELETE_COUNTRY); try { $form = $this->validateForm($areaDeleteCountriesForm); $data = $form->getData(); foreach ($data['country_id'] as $countryId) { $country = explode('-', $countryId); $this->removeOneCountryFromArea($data['area_id'], $country[0], $country[1]); } // Redirect to the success URL return $this->generateSuccessRedirect($areaDeleteCountriesForm); } 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("Failed to delete selected countries"), $error_msg, $areaDeleteCountriesForm ); // At this point, the form has errors, and should be redisplayed. return $this->renderEditionTemplate(); }
php
{ "resource": "" }
q1515
AsseticAssetManager.getStamp
train
protected function getStamp($directory) { $stamp = ''; $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($iterator as $file) { $stamp .= $file->getMTime(); } return md5($stamp); }
php
{ "resource": "" }
q1516
AsseticAssetManager.copyAssets
train
protected function copyAssets(Filesystem $fs, $from_directory, $to_directory) { Tlog::getInstance()->addDebug("Copying assets from $from_directory to $to_directory"); $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($from_directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); $fs->mkdir($to_directory, 0777); /** @var \RecursiveDirectoryIterator $iterator */ foreach ($iterator as $item) { if ($item->isDir()) { $dest_dir = $to_directory . DS . $iterator->getSubPathName(); if (! is_dir($dest_dir)) { if ($fs->exists($dest_dir)) { $fs->remove($dest_dir); } $fs->mkdir($dest_dir, 0777); } } elseif (! $this->isSourceFile($item)) { // We don't copy source files $dest_file = $to_directory . DS . $iterator->getSubPathName(); if ($fs->exists($dest_file)) { $fs->remove($dest_file); } $fs->copy($item, $dest_file); } } }
php
{ "resource": "" }
q1517
AsseticAssetManager.prepareAssets
train
public function prepareAssets($sourceAssetsDirectory, $webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey) { // Compute the absolute path of the output directory $to_directory = $this->getDestinationDirectory($webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey); // Get a path to the stamp file $stamp_file_path = $to_directory . DS . '.source-stamp'; // Get the last stamp of source assets directory $prev_stamp = @file_get_contents($stamp_file_path); // Get the current stamp of the source directory $curr_stamp = $this->getStamp($sourceAssetsDirectory); if ($prev_stamp !== $curr_stamp) { $fs = new Filesystem(); $tmp_dir = "$to_directory.tmp"; $fs->remove($tmp_dir); // Copy the whole source dir in a temp directory $this->copyAssets($fs, $sourceAssetsDirectory, $tmp_dir); // Remove existing directory if ($fs->exists($to_directory)) { $fs->remove($to_directory); } // Put in place the new directory $fs->rename($tmp_dir, $to_directory); if (false === @file_put_contents($stamp_file_path, $curr_stamp)) { throw new \RuntimeException( "Failed to create asset stamp file $stamp_file_path. Please check that your web server has the proper access rights to do that." ); } } }
php
{ "resource": "" }
q1518
AsseticAssetManager.decodeAsseticFilters
train
protected function decodeAsseticFilters(FilterManager $filterManager, $filters) { if (! empty($filters)) { $filter_list = \is_array($filters) ? $filters : explode(',', $filters); foreach ($filter_list as $filter_name) { $filter_name = trim($filter_name); foreach ($this->assetFilters as $filterIdentifier => $filterInstance) { if ($filterIdentifier == $filter_name) { $filterManager->set($filterIdentifier, $filterInstance); // No, goto is not evil. goto filterFound; } } throw new \InvalidArgumentException("Unsupported Assetic filter: '$filter_name'"); break; filterFound: } } else { $filter_list = array(); } return $filter_list; }
php
{ "resource": "" }
q1519
SaleController.toggleActivity
train
public function toggleActivity() { if (null !== $response = $this->checkAuth(AdminResources::SALES, [], AccessManager::UPDATE)) { return $response; } try { $this->dispatch( TheliaEvents::SALE_TOGGLE_ACTIVITY, new SaleToggleActivityEvent( $this->getExistingObject() ) ); } catch (\Exception $ex) { // Any error return $this->errorPage($ex); } return $this->nullResponse(); }
php
{ "resource": "" }
q1520
BladeRenderer.render
train
public function render(string $template, array $data = []): string { $data = array_merge($this->data, $data); return $this->getRenderer()->make($template, $data)->render(); }
php
{ "resource": "" }
q1521
FreeProduct.getRelatedCartItem
train
protected function getRelatedCartItem($product) { $cartItemIdList = $this->facade->getRequest()->getSession()->get( $this->getSessionVarName(), array() ); if (isset($cartItemIdList[$product->getId()])) { $cartItemId = $cartItemIdList[$product->getId()]; if ($cartItemId == self::ADD_TO_CART_IN_PROCESS) { return self::ADD_TO_CART_IN_PROCESS; } elseif (null !== $cartItem = CartItemQuery::create()->findPk($cartItemId)) { return $cartItem; } } else { // Maybe the product we're offering is already in the cart ? Search it. $cartItems = $this->facade->getCart()->getCartItems(); /** @var CartItem $cartItem */ foreach ($cartItems as $cartItem) { if ($cartItem->getProduct()->getId() == $this->offeredProductId) { // We found the product. Store its cart item as the free product container. $this->setRelatedCartItem($product, $cartItem->getId()); return $cartItem; } } } return false; }
php
{ "resource": "" }
q1522
FreeProduct.setRelatedCartItem
train
protected function setRelatedCartItem($product, $cartItemId) { $cartItemIdList = $this->facade->getRequest()->getSession()->get( $this->getSessionVarName(), array() ); if (! \is_array($cartItemIdList)) { $cartItemIdList = array(); } $cartItemIdList[$product->getId()] = $cartItemId; $this->facade->getRequest()->getSession()->set( $this->getSessionVarName(), $cartItemIdList ); }
php
{ "resource": "" }
q1523
LineCommentBlockNode.create
train
public static function create($comment) { $block_comment = new LineCommentBlockNode(); $comment = trim($comment); $lines = array_map('rtrim', explode("\n", $comment)); foreach ($lines as $line) { $comment_node = new CommentNode(T_COMMENT, '// ' . $line . "\n"); $block_comment->addChild($comment_node); } return $block_comment; }
php
{ "resource": "" }
q1524
LineCommentBlockNode.addIndent
train
public function addIndent($whitespace) { $has_indent = $this->children(function (Node $node) { return !($node instanceof CommentNode); })->count() > 0; if ($has_indent) { $this->children(Filter::isInstanceOf('\Pharborist\WhitespaceNode'))->each(function (WhitespaceNode $ws_node) use ($whitespace) { $ws_node->setText($ws_node->getText() . $whitespace); }); } else { $this->children()->before(Token::whitespace($whitespace)); } return $this; }
php
{ "resource": "" }
q1525
SimpleEvent.setAttribute
train
public function setAttribute($name, $value = null) { if (is_array($name)) { foreach ($name as $k => $v) { $this->attributes[$k] = $v; } } else { $this->attributes[$name] = $value; } }
php
{ "resource": "" }
q1526
NumberFormat.formatStandardNumber
train
public function formatStandardNumber($number, $decimals = null) { $lang = $this->request->getSession()->getLang(); if ($decimals === null) { $decimals = $lang->getDecimals(); } return number_format($number, $decimals, '.', ''); }
php
{ "resource": "" }
q1527
Plugin.getFiltered
train
public static function getFiltered( $pattern = '' ) { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $plugins = get_plugins(); if ( empty( $pattern ) ) { return $plugins; } $filtered = array(); foreach ( $plugins as $slug => $data ) { if ( preg_match( '#' . $pattern . '#', $slug ) ) { $filtered[ $slug ] = $data; } } return $filtered; }
php
{ "resource": "" }
q1528
Plugin.isBoldgridPlugin
train
public static function isBoldgridPlugin( $plugin ) { if( empty( $plugin ) ) { return false; } $pluginChecker = new \Boldgrid\Library\Library\Plugin\Checker(); $plugins = \Boldgrid\Library\Library\Util\Plugin::getFiltered( $pluginChecker->getPluginPattern() ); return array_key_exists( $plugin, $plugins ); }
php
{ "resource": "" }
q1529
LanguageController.getTranslationsList
train
public function getTranslationsList() { $data = ""; $melisCmsAuth = $this->getServiceLocator()->get('MelisCoreAuth'); $melisCmsRights = $this->getServiceLocator()->get('MelisCoreRights'); return $data; }
php
{ "resource": "" }
q1530
LanguageController.getDataTableTranslationsAction
train
public function getDataTableTranslationsAction() { // Get the current language $container = new Container('meliscms'); $locale = $container['melis-lang-locale']; $translator = $this->getServiceLocator()->get('translator'); $transData = array( 'sEmptyTable' => $translator->translate('tr_meliscms_dt_sEmptyTable'), 'sInfo' => $translator->translate('tr_meliscms_dt_sInfo'), 'sInfoEmpty' => $translator->translate('tr_meliscms_dt_sInfoEmpty'), 'sInfoFiltered' => $translator->translate('tr_meliscms_dt_sInfoFiltered'), 'sInfoPostFix' => $translator->translate('tr_meliscms_dt_sInfoPostFix'), 'sInfoThousands' => $translator->translate('tr_meliscms_dt_sInfoThousands'), 'sLengthMenu' => $translator->translate('tr_meliscms_dt_sLengthMenu'), 'sLoadingRecords' => $translator->translate('tr_meliscms_dt_sLoadingRecords'), 'sProcessing' => $translator->translate('tr_meliscms_dt_sProcessing'), 'sSearch' => $translator->translate('tr_meliscms_dt_sSearch'), 'sZeroRecords' => $translator->translate('tr_meliscms_dt_sZeroRecords'), 'oPaginate' => array( 'sFirst' => $translator->translate('tr_meliscms_dt_sFirst'), 'sLast' => $translator->translate('tr_meliscms_dt_sLast'), 'sNext' => $translator->translate('tr_meliscms_dt_sNext'), 'sPrevious' => $translator->translate('tr_meliscms_dt_sPrevious'), ), 'oAria' => array( 'sSortAscending' => $translator->translate('tr_meliscms_dt_sSortAscending'), 'sSortDescending' => $translator->translate('tr_meliscms_dt_sSortDescending'), ), ); return new JsonModel($transData); }
php
{ "resource": "" }
q1531
TaxRule.getArrayFromJson22Compat
train
protected function getArrayFromJson22Compat($obj) { $obj = $this->getArrayFromJson($obj); if (isset($obj[0]) && ! \is_array($obj[0])) { $objEx = []; foreach ($obj as $item) { $objEx[] = [$item, 0]; } return $objEx; } return $obj; }
php
{ "resource": "" }
q1532
ExampleController.handleAction
train
private function handleAction(Request $request, &$data) { // Keyword Search if ($this->isAction($request, "searchByKeyword")) { $preparedKeywords = htmlspecialchars($data["keywords"]); $data["listings"] = $this->listingController($data) ->setSortBy($data["sortBy"])->setReverseSort($data["reverseSort"]) ->searchByKeyword($preparedKeywords); } // Advanced Search else if ($this->isAction($request, "search")) { $data["listings"] = $this->listingController($data) ->setSortBy($data["sortBy"])->setReverseSort($data["reverseSort"]) ->search($data["keywords"], $data["extra"], $data["maxPrice"], $data["minPrice"], $data["beds"], $data["baths"], $data["includeResidential"], $data["includeLand"], $data["includeCommercial"]); } // Return Listings by DMQL else if ($this->isAction($request, "getListingsByDMQL")) { $results = GetRETS::getRETSListing() ->setSortBy($data["sortBy"])->setReverseSort($data["reverseSort"]) ->getListingsByDMQL($data["dmql"], ExampleController::EXAMPLE_SOURCE, "Residential"); if (!empty($results)) { if ($results->success && !empty($results->data)) { $data["listings"] = $results->data; } } } // Return raw DMQL results else if ($this->isAction($request, "executeDMQL")) { $data["rawData"] = GetRETS::getRETSListing()->executeDMQL($data["dmql"], ExampleController::EXAMPLE_SOURCE, "Residential"); } }
php
{ "resource": "" }
q1533
ExampleController.getPageData
train
private function getPageData(Request $request) { $publicDMQL = '(L_UpdateDate=' . date('Y-m-d', (strtotime('-1 day', time()))) . '-' . date('Y-m-d') . ')'; $data = [ "isPublic" => ExampleController::IS_PUBLIC, "disableCache" => !empty($request->disableCache), "keywords" => $request->keywords ? : ExampleController::EXAMPLE_ADDRESS, "extra" => $request->extra, "maxPrice" => $request->maxPrice, "minPrice" => $request->minPrice, "beds" => $request->beds, "baths" => $request->baths, "includeResidential" => $request->includeResidential, "includeLand" => $request->includeLand, "includeCommercial" => $request->includeCommercial, "sortBy" => $request->sortBy ? : "rawListPrice", "reverseSort" => !empty($request->reverseSort), // Only let the public search the last days worth of modified residential listings (to prevent abusive queries) "dmql" => (!empty($request->dmql) && !$data["isPublic"]) ? $request->dmql : $publicDMQL, "listings" => null, "detail" => null, "rawData" => null, "allInput" => $request->all(), ]; if ($request->isMethod('POST')) { $this->handleAction($request, $data); } // Listing Details if ($request->has("source") && $request->has("type") && $request->has("id")) { $data["detail"] = $this->listingController($data)->details($request->source, $request->type, $request->id); } return $data; }
php
{ "resource": "" }
q1534
Product.countSaleElements
train
public function countSaleElements($con = null) { return ProductSaleElementsQuery::create()->filterByProductId($this->id)->count($con); }
php
{ "resource": "" }
q1535
Product.setDefaultCategory
train
public function setDefaultCategory($defaultCategoryId) { // Allow uncategorized products (NULL instead of 0, to bypass delete cascade constraint) if ($defaultCategoryId <= 0) { $defaultCategoryId = null; } /** @var ProductCategory $productCategory */ $productCategory = ProductCategoryQuery::create() ->filterByProductId($this->getId()) ->filterByDefaultCategory(true) ->findOne() ; if ($productCategory !== null && (int) $productCategory->getCategoryId() === (int) $defaultCategoryId) { return $this; } if ($productCategory !== null) { $productCategory->delete(); } // checks if the product is already associated with the category and but not default if (null !== $productCategory = ProductCategoryQuery::create()->filterByProduct($this)->filterByCategoryId($defaultCategoryId)->findOne()) { $productCategory->setDefaultCategory(true)->save(); } else { $position = (new ProductCategory())->setCategoryId($defaultCategoryId)->getNextPosition(); (new ProductCategory()) ->setProduct($this) ->setCategoryId($defaultCategoryId) ->setDefaultCategory(true) ->setPosition($position) ->save(); $this->setPosition($position); } return $this; }
php
{ "resource": "" }
q1536
Product.create
train
public function create($defaultCategoryId, $basePrice, $priceCurrencyId, $taxRuleId, $baseWeight, $baseQuantity = 0) { $con = Propel::getWriteConnection(ProductTableMap::DATABASE_NAME); $con->beginTransaction(); $this->dispatchEvent(TheliaEvents::BEFORE_CREATEPRODUCT, new ProductEvent($this)); try { // Create the product $this->save($con); // Add the default category $this->setDefaultCategory($defaultCategoryId)->save($con); $this->setTaxRuleId($taxRuleId); // Create the default product sale element of this product $this->createProductSaleElement($con, $baseWeight, $basePrice, $basePrice, $priceCurrencyId, true, false, false, $baseQuantity); // Store all the stuff ! $con->commit(); $this->dispatchEvent(TheliaEvents::AFTER_CREATEPRODUCT, new ProductEvent($this)); } catch (\Exception $ex) { $con->rollback(); throw $ex; } }
php
{ "resource": "" }
q1537
Product.createProductSaleElement
train
public function createProductSaleElement(ConnectionInterface $con, $weight, $basePrice, $salePrice, $currencyId, $isDefault, $isPromo = false, $isNew = false, $quantity = 0, $eanCode = '', $ref = false) { // Create an empty product sale element $saleElements = new ProductSaleElements(); $saleElements ->setProduct($this) ->setRef($ref == false ? $this->getRef() : $ref) ->setPromo($isPromo) ->setNewness($isNew) ->setWeight($weight) ->setIsDefault($isDefault) ->setEanCode($eanCode) ->setQuantity($quantity) ->save($con) ; // Create an empty product price in the provided currency $productPrice = new ProductPrice(); $productPrice ->setProductSaleElements($saleElements) ->setPromoPrice($salePrice) ->setPrice($basePrice) ->setCurrencyId($currencyId) ->setFromDefaultCurrency(false) ->save($con) ; return $saleElements; }
php
{ "resource": "" }
q1538
Product.addCriteriaToPositionQuery
train
protected function addCriteriaToPositionQuery($query) { // Find products in the same category $products = ProductCategoryQuery::create() ->filterByCategoryId($this->getDefaultCategoryId()) ->filterByDefaultCategory(true) ->select('product_id') ->find(); if ($products != null) { $query->filterById($products, Criteria::IN); } }
php
{ "resource": "" }
q1539
MelisCmsPageGetterService.getPageContent
train
public function getPageContent($pageId) { // Retrieve cache version if front mode to avoid multiple calls $melisEngineCacheSystem = $this->getServiceLocator()->get('MelisEngineCacheSystem'); $pageContent = $melisEngineCacheSystem->getCacheByKey($this->cachekey.$pageId, $this->cacheConfig, true); return $pageContent; }
php
{ "resource": "" }
q1540
Validate.setHash
train
public function setHash( $key = null ) { $key = $key ? $this->sanitizeKey( $key ) : $this->getKey(); return $this->hash = $this->hashKey( $key ); }
php
{ "resource": "" }
q1541
Validate.sanitizeKey
train
public function sanitizeKey( $key ) { $key = trim( strtolower( preg_replace( '/-/', '', $key ) ) ); $key = implode( '-', str_split( $key, 8 ) ); return sanitize_key( $key ); }
php
{ "resource": "" }
q1542
Validate.isValid
train
public function isValid( $key = null ) { $key = $key ? $this->sanitizeKey( $key ) : $this->getKey(); return strlen( $key ) === 35; }
php
{ "resource": "" }
q1543
PageSeoController.getSeoKeywordsByPageId
train
public function getSeoKeywordsByPageId($pageId) { $pageId = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', '')); $data = array(); $seoKeywords = $pageId->getSeoKeywords($pageId); $data = $seoKeywords; return $data; }
php
{ "resource": "" }
q1544
PageSeoController.cleanURL
train
private function cleanURL(string $url = '') { $url = str_replace(' ', '-', $url); // Replaces all spaces with hyphens $url = preg_replace('/[^A-Za-z0-9\/\-]+/', '-', $url); // Replaces special characters with hyphens // remove "/" prefix on generated URL if (substr($url, 0, 1) == '/') { return preg_replace('/\//', '', $url, 1); } return $url; }
php
{ "resource": "" }
q1545
Reseller.getAttribute
train
public function getAttribute( $attribute ) { $data = $this->getData(); return ! empty ( $data[$attribute] ) ? $data[$attribute] : ''; }
php
{ "resource": "" }
q1546
Reseller.getData
train
public function getData() { $data = $this->resellerOption; $data['reseller_identifier'] = ! empty( $data['reseller_identifier'] ) ? strtolower( $data['reseller_identifier'] ) : null; $data['reseller_website_url'] = ! empty( $data['reseller_website_url'] ) ? esc_url( $data['reseller_website_url'] ) : 'https://www.boldgrid.com/'; $data['reseller_title'] = ! empty( $data['reseller_title'] ) ? esc_html( $data['reseller_title'] ) : esc_html( 'BoldGrid.com' ); $data['reseller_support_url'] = ! empty( $data['reseller_support_url'] ) ? esc_url( $data['reseller_support_url'] ) : 'https://www.boldgrid.com/documentation'; $data['reseller_amp_url'] = ! empty( $data['reseller_amp_url'] ) ? esc_url( $data['reseller_amp_url'] ) : 'https://www.boldgrid.com/central'; return $data; }
php
{ "resource": "" }
q1547
Reseller.getMenuItems
train
protected function getMenuItems() { $data = $this->getData(); return array( 'topLevel' => array( 'id' => 'reseller-adminbar-icon', 'title' => '<span aria-hidden="true" class="' . $data['reseller_identifier'] . '-icon ab-icon"></span>', 'href' => $data['reseller_website_url'], 'meta' => array( 'class' => 'reseller-node-icon', ), ), 'items' => array( array( 'id' => 'reseller-site-url', 'parent' => 'reseller-adminbar-icon', 'title' => $data['reseller_title'], 'href' => $data['reseller_website_url'], 'meta' => array( 'class' => 'reseller-dropdown', 'target' => '_blank', 'title' => $data['reseller_title'], ), ), array( 'id' => 'reseller-support-center', 'parent' => 'reseller-adminbar-icon', 'title' => esc_html__( 'Support Center', 'boldgrid-library' ), 'href' => $data['reseller_support_url'], 'meta' => array( 'class' => 'reseller-dropdown', 'target' => '_blank', 'title' => __( 'Support Center', 'boldgrid-library' ), ), ), array( 'id' => 'reseller-amp-login', 'parent' => 'reseller-adminbar-icon', 'title' => esc_html__( 'AMP Login', 'boldgrid-library' ), 'href' => $data['reseller_amp_url'], 'meta' => array( 'class' => 'reseller-dropdown', 'target' => '_blank', 'title' => __( 'Account Management', 'boldgrid-library' ), ), ), ), ); }
php
{ "resource": "" }
q1548
FeatureController.addRemoveFromAllTemplates
train
protected function addRemoveFromAllTemplates($eventType) { // Check current user authorization if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) { return $response; } try { if (null !== $object = $this->getExistingObject()) { $event = new FeatureEvent($object); $this->dispatch($eventType, $event); } } catch (\Exception $ex) { // Any error return $this->errorPage($ex); } return $this->redirectToListTemplate(); }
php
{ "resource": "" }
q1549
TreePickerManipulatingListener.manipulateTreePrickerForSortOrder
train
public function manipulateTreePrickerForSortOrder(ManipulateWidgetEvent $event) { $widget = $event->getWidget(); if (!($widget instanceof TreePicker)) { return; } $options = (array) $widget->options; if (0 === \count($options)) { return; } $model = $event->getModel(); if (!($model instanceof Model)) { return; } $attribute = $model->getItem()->getAttribute($widget->strField); if (!($attribute instanceof AbstractTags)) { return; } $widget->orderField = $widget->orderField . '__ordered'; $ordered = \array_flip(\array_merge([], (array) $model->getProperty($widget->strField))); foreach ($options as $option) { $ordered[$option['value']] = $option['value']; } $widget->{$widget->orderField} = $ordered; }
php
{ "resource": "" }
q1550
BasePresenter.ajaxRedirect
train
public function ajaxRedirect(string $destination, array $args = []): void { $this->payload->forceRedirect = $this->link($destination, $args); $this->sendPayload(); }
php
{ "resource": "" }
q1551
ConditionFactory.serializeConditionCollection
train
public function serializeConditionCollection(ConditionCollection $collection) { if ($collection->count() == 0) { /** @var ConditionInterface $conditionNone */ $conditionNone = $this->container->get( 'thelia.condition.match_for_everyone' ); $collection[] = $conditionNone; } $serializableConditions = []; /** @var $condition ConditionInterface */ foreach ($collection as $condition) { $serializableConditions[] = $condition->getSerializableCondition(); } return base64_encode(json_encode($serializableConditions)); }
php
{ "resource": "" }
q1552
ConditionFactory.unserializeConditionCollection
train
public function unserializeConditionCollection($serializedConditions) { $unserializedConditions = json_decode(base64_decode($serializedConditions)); $collection = new ConditionCollection(); if (!empty($unserializedConditions)) { /** @var SerializableCondition $condition */ foreach ($unserializedConditions as $condition) { if ($this->container->has($condition->conditionServiceId)) { /** @var ConditionInterface $conditionManager */ $conditionManager = $this->build( $condition->conditionServiceId, (array) $condition->operators, (array) $condition->values ); $collection[] = clone $conditionManager; } } } return $collection; }
php
{ "resource": "" }
q1553
ConditionFactory.build
train
public function build($conditionServiceId, array $operators, array $values) { if (!$this->container->has($conditionServiceId)) { return false; } /** @var ConditionInterface $condition */ $condition = $this->container->get($conditionServiceId); $condition->setValidatorsFromForm($operators, $values); return clone $condition; }
php
{ "resource": "" }
q1554
ConditionFactory.getInputsFromServiceId
train
public function getInputsFromServiceId($conditionServiceId) { if (!$this->container->has($conditionServiceId)) { return false; } /** @var ConditionInterface $condition */ $condition = $this->container->get($conditionServiceId); return $this->getInputsFromConditionInterface($condition); }
php
{ "resource": "" }
q1555
ModuleConfigQuery.getConfigValue
train
public function getConfigValue($moduleId, $variableName, $defaultValue = null, $valueLocale = null) { $value = null; $configValue = self::create() ->filterByModuleId($moduleId) ->filterByName($variableName) ->findOne(); ; if (null !== $configValue) { if (null !== $valueLocale) { $configValue->setLocale($valueLocale); } $value = $configValue->getValue(); } return $value === null ? $defaultValue : $value; }
php
{ "resource": "" }
q1556
ModuleConfigQuery.setConfigValue
train
public function setConfigValue($moduleId, $variableName, $variableValue, $valueLocale = null, $createIfNotExists = true) { $configValue = self::create() ->filterByModuleId($moduleId) ->filterByName($variableName) ->findOne(); ; if (null === $configValue) { if (true === $createIfNotExists) { $configValue = new ModuleConfig(); $configValue ->setModuleId($moduleId) ->setName($variableName) ; } else { throw new \LogicException("Module configuration variable $variableName does not exists. Create it first."); } } if (null !== $valueLocale) { $configValue->setLocale($valueLocale); } $configValue ->setValue($variableValue) ->save(); ; return $this; }
php
{ "resource": "" }
q1557
ModuleConfigQuery.deleteConfigValue
train
public function deleteConfigValue($moduleId, $variableName) { if (null !== $moduleConfig = self::create() ->filterByModuleId($moduleId) ->filterByName($variableName) ->findOne() ) { $moduleConfig->delete(); }; return $this; }
php
{ "resource": "" }
q1558
Update.auto_update_plugin
train
public function auto_update_plugin( $update, $item ) { if ( ! apply_filters( 'Boldgrid\Library\Update\isEnalbed', false ) ) { return $update; } // Old settings. $pluginAutoupdate = \Boldgrid\Library\Util\Option::get( 'plugin_autoupdate' ); // Update if global setting is on, individual settings is on, or not set and default is on. if ( ! empty( $pluginAutoupdate ) || ! empty( $this->settings['plugins'][ $item->plugin ] ) || ( ! isset( $this->settings['plugins'][ $item->plugin ] ) && ! empty( $this->settings['plugins']['default'] ) ) ) { $update = true; } return $update; }
php
{ "resource": "" }
q1559
Update.auto_update_theme
train
public function auto_update_theme( $update, $item ) { if ( ! apply_filters( 'Boldgrid\Library\Update\isEnalbed', false ) ) { return $update; } // Old settings. $themeAutoupdate = \Boldgrid\Library\Util\Option::get( 'theme_autoupdate' ); // Update if global setting is on, individual settings is on, or not set and default is on. if ( ! empty( $themeAutoupdate ) || ! empty( $this->settings['themes'][ $item->theme ] ) || ( ! isset( $this->settings['themes'][ $item->theme ] ) && ! empty( $this->settings['themes']['default'] ) ) ) { $update = true; } return $update; }
php
{ "resource": "" }
q1560
RootNode.create
train
public static function create($ns = NULL) { $node = new RootNode(); $node->addChild(Token::openTag()); if (is_string($ns) && $ns) { NamespaceNode::create($ns)->appendTo($node)->after(Token::newline()); } return $node; }
php
{ "resource": "" }
q1561
RootNode.getNamespace
train
public function getNamespace($ns) { $namespaces = $this ->getNamespaces() ->filter(function(NamespaceNode $node) use ($ns) { return $node->getName()->getPath() === $ns; }); return $namespaces->isEmpty() ? NULL : $namespaces[0]; }
php
{ "resource": "" }
q1562
RootNode.getNamespaceNames
train
public function getNamespaceNames($absolute = FALSE) { $iterator = function(NamespaceNode $ns) use ($absolute) { $name = $ns->getName(); return $absolute ? $name->getAbsolutePath() : $name->getPath(); }; return array_map($iterator, $this->getNamespaces()->toArray()); }
php
{ "resource": "" }
q1563
MelisCmsSiteService.getSitePages
train
public function getSitePages($siteId) { $results = array(); // Event parameters prepare $arrayParameters = $this->makeArrayFromParameters(__METHOD__, func_get_args()); // Sending service start event $arrayParameters = $this->sendEvent('meliscmssite_service_get_site_pages_start', $arrayParameters); // Service implementation start $siteTable = $this->getServiceLocator()->get('MelisEngineTableSite'); $site = $siteTable->getEntryById($arrayParameters['siteId'])->current(); if (!empty($site)) { $pages = $siteTable->getSiteSavedPagesById($site->site_id)->toArray(); if (!empty($pages)) { $site->pages = $pages; } $results = $site; } // Service implementation end // Adding results to parameters for events treatment if needed $arrayParameters['results'] = $results; // Sending service end event $arrayParameters = $this->sendEvent('meliscmssite_service_get_site_pages_start', $arrayParameters); return $arrayParameters['results']; }
php
{ "resource": "" }
q1564
MelisCmsSiteService.createSitePage
train
private function createSitePage($siteName, $fatherId, $siteLangId, $pageType, $pageId, $templateId, $platformId) { // Event parameters prepare $arrayParameters = $this->makeArrayFromParameters(__METHOD__, func_get_args()); // Sending service start event $arrayParameters = $this->sendEvent('meliscmssite_service_save_site_page_start', $arrayParameters); // Service implementation start $pageTreeTable = $this->getServiceLocator()->get('MelisEngineTablePageTree'); $pageLangTable = $this->getServiceLocator()->get('MelisEngineTablePageLang'); $pageSavedTable = $this->getServiceLocator()->get('MelisEngineTablePageSaved'); $cmsPlatformTable = $this->getServiceLocator()->get('MelisEngineTablePlatformIds'); /** * Retrieving the Current Page tree * with Father Id of -1 "root node of the page tree" * to get the Order of the new entry */ $treePageOrder = $pageTreeTable->getTotalData('tree_father_page_id', $fatherId); // Saving Site page on Page tree $pageTreeTable->save(array( 'tree_page_id' => $arrayParameters['pageId'], 'tree_father_page_id' => $fatherId, 'tree_page_order' => $treePageOrder + 1, )); // Saving Site page Language $pageLangTable->save(array( 'plang_page_id' => $arrayParameters['pageId'], 'plang_lang_id' => $arrayParameters['siteLangId'], 'plang_page_id_initial' => $arrayParameters['pageId'] )); // Saving Site page in Save Version as new page entry $pageSavedTable->save(array( 'page_id' => $arrayParameters['pageId'], 'page_type' => $arrayParameters['pageType'], 'page_status' => 1, 'page_menu' => 'LINK', 'page_name' => $arrayParameters['siteName'], 'page_tpl_id' => $arrayParameters['templateId'], 'page_content' => '<?xml version="1.0" encoding="UTF-8"?><document type="MelisCMS" author="MelisTechnology" version="2.0"></document>', 'page_taxonomy' => '', 'page_creation_date' => date('Y-m-d H:i:s') )); // Updating platform ids after site pages creation $platform = array( 'pids_page_id_current' => ++$arrayParameters['pageId'] ); $cmsPlatformTable->save($platform, $arrayParameters['platformId']); // Service implementation end // Adding results to parameters for events treatment if needed $arrayParameters['results'] = $arrayParameters['pageId']; // Sending service end event $arrayParameters = $this->sendEvent('meliscmssite_service_save_site_page_end', $arrayParameters); return $arrayParameters['results']; }
php
{ "resource": "" }
q1565
MelisCmsSiteService.createSitePageTemplate
train
private function createSitePageTemplate($tplId, $siteId, $siteName, $tempName, $controler, $action, $platformId) { $cmsTemplateTbl = $this->getServiceLocator()->get('MelisEngineTableTemplate'); $cmsPlatformTable = $this->getServiceLocator()->get('MelisEngineTablePlatformIds'); // Template data $template = array( 'tpl_id' => $tplId, 'tpl_site_id' => $siteId, 'tpl_name' => $tempName, 'tpl_type' => 'ZF2', 'tpl_zf2_website_folder' => $siteName, 'tpl_zf2_layout' => 'defaultLayout', 'tpl_zf2_controller' => $controler, 'tpl_zf2_action' => $action, 'tpl_php_path' => '', 'tpl_creation_date' => date('Y-m-d H:i:s'), ); // Saving template $templateId = $cmsTemplateTbl->save($template); // Updating platform ids after site pages creation $platform = array( 'pids_tpl_id_current' => ++$tplId ); $cmsPlatformTable->save($platform, $platformId); return $templateId; }
php
{ "resource": "" }
q1566
MelisCmsSiteService.mapDirectory
train
private function mapDirectory($dir, $targetModuleName, $newModuleName) { $result = array(); $cdir = scandir($dir); $fileName = ''; foreach ($cdir as $key => $value) { if (!in_array($value,array(".",".."))) { if (is_dir($dir . '/' . $value)) { if ($value == $targetModuleName) { rename($dir . '/' . $value, $dir . '/' . $newModuleName); $value = $newModuleName; } elseif ($value == $this->moduleNameToViewName($targetModuleName)) { $newModuleNameSnakeCase = $this->moduleNameToViewName($newModuleName); rename($dir . '/' . $value, $dir . '/' . $newModuleNameSnakeCase); $value = $newModuleNameSnakeCase; } $result[$dir . '/' .$value] = $this->mapDirectory($dir . '/' . $value, $targetModuleName, $newModuleName); } else { $newFileName = str_replace($targetModuleName, $newModuleName, $value); if ($value != $newFileName) { rename($dir . '/' . $value, $dir . '/' . $newFileName); $value = $newFileName; } $result[$dir . '/' .$value] = $value; $fileName = $dir . '/' .$value; $this->replaceFileTextContent($fileName, $fileName, $targetModuleName, $newModuleName); } } } return $result; }
php
{ "resource": "" }
q1567
MelisCmsSiteService.generateModuleNameCase
train
private function generateModuleNameCase($str) { $i = array("-","_"); $str = preg_replace('/([a-z])([A-Z])/', "$1 $2", $str); $str = str_replace($i, ' ', $str); $str = str_replace(' ', '', ucwords(strtolower($str))); $str = strtolower(substr($str,0,1)).substr($str,1); $str = ucfirst($str); return $str; }
php
{ "resource": "" }
q1568
FunctionTrait.hasReturnTypes
train
public function hasReturnTypes() { $doc_comment = $this->getDocComment(); if (!$doc_comment) { return FALSE; } $return_tag = $doc_comment->getReturn(); if (!$return_tag) { return FALSE; } $types = $return_tag->getTypes(); return !empty($types); }
php
{ "resource": "" }
q1569
FunctionTrait.getReturnTypes
train
public function getReturnTypes() { $types = ['void']; $doc_comment = $this->getDocComment(); if (!$doc_comment) { return $types; } $return_tag = $doc_comment->getReturn(); if (!$return_tag) { return $types; } $types = Types::normalize($return_tag->getTypes()); if (empty($types)) { $types[] = 'void'; } return $types; }
php
{ "resource": "" }
q1570
Application.setDefaultTimezone
train
protected function setDefaultTimezone() { $timezone = 'UTC'; if (is_link('/etc/localtime')) { // Mac OS X (and older Linuxes) // /etc/localtime is a symlink to the timezone in /usr/share/zoneinfo. $filename = readlink('/etc/localtime'); if (strpos($filename, '/usr/share/zoneinfo/') === 0) { $timezone = substr($filename, 20); } } elseif (file_exists('/etc/timezone')) { // Ubuntu / Debian. $data = file_get_contents('/etc/timezone'); if ($data) { $timezone = trim($data); } } elseif (file_exists('/etc/sysconfig/clock')) { // RHEL/CentOS $data = parse_ini_file('/etc/sysconfig/clock'); if (!empty($data['ZONE'])) { $timezone = trim($data['ZONE']); } } date_default_timezone_set($timezone); }
php
{ "resource": "" }
q1571
UrlRewritingTrait.getUrl
train
public function getUrl($locale = null) { if (null === $locale) { $locale = $this->getLocale(); } return URL::getInstance()->retrieve($this->getRewrittenUrlViewName(), $this->getId(), $locale)->toString(); }
php
{ "resource": "" }
q1572
UrlRewritingTrait.generateRewrittenUrl
train
public function generateRewrittenUrl($locale) { if ($this->isNew()) { throw new \RuntimeException(sprintf('Object %s must be saved before generating url', $this->getRewrittenUrlViewName())); } // Borrowed from http://stackoverflow.com/questions/2668854/sanitizing-strings-to-make-them-url-and-filename-safe $this->setLocale($locale); $generateEvent = new GenerateRewrittenUrlEvent($this, $locale); $this->dispatchEvent(TheliaEvents::GENERATE_REWRITTENURL, $generateEvent); if ($generateEvent->isRewritten()) { return $generateEvent->getUrl(); } $title = $this->getTitle(); if (null == $title) { throw new \RuntimeException('Impossible to create an url if title is null'); } // Replace all weird characters with dashes $string = preg_replace('/[^\w\-~_\.]+/u', '-', $title); // Only allow one dash separator at a time (and make string lowercase) $cleanString = mb_strtolower(preg_replace('/--+/u', '-', $string), 'UTF-8'); $urlFilePart = rtrim($cleanString, '.-~_') . ".html"; try { $i=0; while (URL::getInstance()->resolve($urlFilePart)) { $i++; $urlFilePart = sprintf("%s-%d.html", $cleanString, $i); } } catch (UrlRewritingException $e) { $rewritingUrl = new RewritingUrl(); $rewritingUrl->setUrl($urlFilePart) ->setView($this->getRewrittenUrlViewName()) ->setViewId($this->getId()) ->setViewLocale($locale) ->save() ; } return $urlFilePart; }
php
{ "resource": "" }
q1573
UrlRewritingTrait.getRewrittenUrl
train
public function getRewrittenUrl($locale) { $rewritingUrl = RewritingUrlQuery::create() ->filterByViewLocale($locale) ->filterByView($this->getRewrittenUrlViewName()) ->filterByViewId($this->getId()) ->filterByRedirected(null) ->findOne() ; if ($rewritingUrl) { $url = $rewritingUrl->getUrl(); } else { $url = null; } return $url; }
php
{ "resource": "" }
q1574
UrlRewritingTrait.markRewrittenUrlObsolete
train
public function markRewrittenUrlObsolete() { RewritingUrlQuery::create() ->filterByView($this->getRewrittenUrlViewName()) ->filterByViewId($this->getId()) ->update(array( "View" => ConfigQuery::getObsoleteRewrittenUrlView() )); }
php
{ "resource": "" }
q1575
UrlRewritingTrait.setRewrittenUrl
train
public function setRewrittenUrl($locale, $url) { $currentUrl = $this->getRewrittenUrl($locale); if ($currentUrl == $url || null === $url) { /* no url update */ return $this; } try { $resolver = new RewritingResolver($url); /* we can reassign old url */ if (null === $resolver->redirectedToUrl) { /* else ... */ if ($resolver->view == $this->getRewrittenUrlViewName() && $resolver->viewId == $this->getId()) { /* it's an url related to the current object */ if ($resolver->locale != $locale) { /* it is an url related to this product for another locale */ throw new UrlRewritingException(Translator::getInstance()->trans('URL_ALREADY_EXISTS'), UrlRewritingException::URL_ALREADY_EXISTS); } if (\count($resolver->otherParameters) > 0) { /* it is an url related to this product but with more arguments */ throw new UrlRewritingException(Translator::getInstance()->trans('URL_ALREADY_EXISTS'), UrlRewritingException::URL_ALREADY_EXISTS); } /* here it must be a deprecated url */ } else { /* already related to another object */ throw new UrlRewritingException(Translator::getInstance()->trans('URL_ALREADY_EXISTS'), UrlRewritingException::URL_ALREADY_EXISTS); } } } catch (UrlRewritingException $e) { /* It's all good if URL is not found */ if ($e->getCode() !== UrlRewritingException::URL_NOT_FOUND) { throw $e; } } /* set the new URL */ if (isset($resolver)) { /* erase the old one */ $rewritingUrl = RewritingUrlQuery::create()->findOneByUrl($url); $rewritingUrl->setView($this->getRewrittenUrlViewName()) ->setViewId($this->getId()) ->setViewLocale($locale) ->setRedirected(null) ->save() ; /* erase additional arguments if any : only happens in case it erases a deprecated url */ RewritingArgumentQuery::create()->filterByRewritingUrl($rewritingUrl)->deleteAll(); } else { /* just create it */ $rewritingUrl = new RewritingUrl(); $rewritingUrl->setUrl($url) ->setView($this->getRewrittenUrlViewName()) ->setViewId($this->getId()) ->setViewLocale($locale) ->save() ; } /* deprecate the old one if needed */ if (null !== $oldRewritingUrl = RewritingUrlQuery::create()->findOneByUrl($currentUrl)) { $oldRewritingUrl->setRedirected($rewritingUrl->getId())->save(); } return $this; }
php
{ "resource": "" }
q1576
ClassMemberNode.create
train
public static function create($name, ExpressionNode $value = NULL, $visibility = 'public') { $code = $visibility . ' $' . ltrim($name, '$'); if ($value instanceof ExpressionNode) { $code .= ' = ' . $value->getText(); } /** @var ClassNode $class_node */ $class_node = Parser::parseSnippet('class Foo { ' . $code . '; }'); return $class_node->getStatements()[0]->remove(); }
php
{ "resource": "" }
q1577
Render.adminBarNode
train
public static function adminBarNode( $wpAdminBar, $configs ) { $wpAdminBar->add_node( $configs['topLevel'] ); foreach ( $configs['items'] as $item ) { $wpAdminBar->add_menu( $item ); } }
php
{ "resource": "" }
q1578
MetaDataQuery.setVal
train
public static function setVal($metaKey, $elementKey, $elementId, $value) { $data = self::create() ->filterByMetaKey($metaKey) ->filterByElementKey($elementKey) ->filterByElementId($elementId) ->findOne() ; if (null === $data) { $data = new MetaData(); $data->setMetaKey($metaKey); $data->setElementKey($elementKey); $data->setElementId($elementId); } $data->setValue($value); $data->save(); }
php
{ "resource": "" }
q1579
IdentifierNameTrait.setName
train
public function setName($name) { /** @var TokenNode $identifier */ $identifier = $this->name->firstChild(); $identifier->setText($name); return $this; }
php
{ "resource": "" }
q1580
IdentifierNameTrait.inNamespace
train
public function inNamespace($ns) { if (is_string($ns)) { $namespace_node = $this->name->getNamespace(); $namespace = $namespace_node === NULL ? '' : $namespace_node->getName()->getAbsolutePath(); return $ns === $namespace; } elseif ($ns instanceof NamespaceNode) { return $this->name->getNamespace() === $ns; } else { throw new \InvalidArgumentException(); } }
php
{ "resource": "" }
q1581
InfoPresenter.renderServer
train
public function renderServer(): void { $this->addBreadcrumbLink('dockbar.info.server'); $this->template->refresh = $this->refresh; $this->template->system = $this->app->info->system; $this->template->fileSystem = $this->app->info->fileSystem; $this->template->hardware = $this->app->info->hardware; $this->template->memory = $this->app->info->memory; $this->template->network = $this->app->info->network; }
php
{ "resource": "" }
q1582
InfoPresenter.renderPhp
train
public function renderPhp(): void { $this->addBreadcrumbLink('dockbar.info.php'); $this->template->php = $this->app->info->phpInfo; }
php
{ "resource": "" }
q1583
UsersPresenter.setState
train
public function setState(int $id, bool $value): void { if ($this->isAjax()) { $user = $this->orm->users->getById($id); $user->active = $value; $this->orm->persistAndFlush($user); $this['userList']->redrawItem($id); } else { $this->terminate(); } }
php
{ "resource": "" }
q1584
UsersPresenter.createComponentAddForm
train
protected function createComponentAddForm(): Form { $form = $this->formFactory->create(); $form->addProtection(); $form->addText('username', 'cms.user.username') ->setRequired(); $form->addText('firstName', 'cms.user.firstName'); $form->addText('surname', 'cms.user.surname'); $form->addText('email', 'cms.user.email') ->setRequired() ->addRule(Form::EMAIL); $form->addPhone('phone', 'cms.user.phone'); $form->addSelectUntranslated('language', 'cms.user.language', $this->localeService->allowed, 'form.none'); $form->addMultiSelectUntranslated('roles', 'cms.permissions.roles', $this->orm->aclRoles->fetchPairs($this->user->isAllowed('dockbar.settings.permissions.superadmin', 'view'))) ->setRequired(); if ($this->configurator->sendNewUserPassword) { $form->addCheckbox('generatePassword', 'cms.user.generatePassword') ->addCondition($form::EQUAL, false) ->toggle('password') ->toggle('passwordVerify'); } else { $form->addHidden('generatePassword', false); } $form->addPassword('password', 'cms.user.newPassword') ->setOption('id', 'password') ->addConditionOn($form['generatePassword'], Form::EQUAL, false) ->setRequired() ->addRule(Form::MIN_LENGTH, null, $this->minPasswordLength) ->endCondition(); $form->addPassword('passwordVerify', 'cms.user.passwordVerify') ->setOption('id', 'passwordVerify') ->addConditionOn($form['generatePassword'], Form::EQUAL, false) ->setRequired() ->addRule(Form::EQUAL, null, $form['password']) ->endCondition(); $form->addSubmit('save', 'form.save'); $form->addLink('back', 'form.back', $this->getBacklink()); $form->onSuccess[] = [$this, 'addFormSucceeded']; return $form; }
php
{ "resource": "" }
q1585
UsersPresenter.addFormSucceeded
train
public function addFormSucceeded(Form $form, ArrayHash $values): void { if ($values->generatePassword) { $password = Random::generate($this->minPasswordLength, $this->passwordChars); } else { $password = $values->password; } $user = new User; $this->orm->users->attach($user); try { $user->setUsername($values->username); } catch (UniqueConstraintViolationException $ex) { $form->addError('cms.user.duplicityUsername'); return; } catch (InvalidArgumentException $ex) { $form->addError('cms.user.invalidUsername'); return; } try { $user->setEmail($values->email); } catch (UniqueConstraintViolationException $ex) { $form->addError('cms.user.duplicityEmail'); return; } catch (InvalidArgumentException $ex) { $form->addError('cms.user.invalidUsername'); return; } try { $user->setPhone($values->phone ?: null); } catch (InvalidArgumentException $ex) { $form->addError('cms.user.invalidPhone'); return; } $user->firstName = $values->firstName; $user->surname = $values->surname; $language = $this->localeService->getById($values->language); $user->language = $language === null ? null : $language->name; $user->roles->set($values->roles); $user->setPassword($password); $this->orm->persistAndFlush($user); if ($this->configurator->sendNewUserPassword) { $this->mailer->sendNewUser($user->email, $user->username, $password); } $this->flashNotifier->success('cms.user.dataSaved'); $this->restoreBacklink(); }
php
{ "resource": "" }
q1586
UsersPresenter.createComponentEditForm
train
protected function createComponentEditForm(): Form { $form = $this->formFactory->create(); $form->addProtection(); $form->addText('username', 'cms.user.username') ->setDefaultValue($this->currentUser->username) ->setRequired(); $form->addText('firstName', 'cms.user.firstName') ->setDefaultValue($this->currentUser->firstName); $form->addText('surname', 'cms.user.surname') ->setDefaultValue($this->currentUser->surname); $form->addText('email', 'cms.user.email') ->setDefaultValue($this->currentUser->email) ->setRequired() ->addRule(Form::EMAIL); $form->addPhone('phone', 'cms.user.phone') ->setDefaultValue($this->currentUser->phone); $language = $form->addSelectUntranslated('language', 'cms.user.language', $this->localeService->allowed, 'form.none'); if (!empty($this->currentUser->language)) { $locale = $this->localeService->get($this->currentUser->language); if ($locale) { $language->setDefaultValue($locale->id); } } $roles = $form->addMultiSelectUntranslated('roles', 'cms.permissions.roles', $this->orm->aclRoles->fetchPairs($this->user->isAllowed('dockbar.settings.permissions.superadmin', 'view'))) ->setRequired(); try { $roles->setDefaultValue($this->currentUser->roles->getRawValue()); } catch (InvalidArgumentException $ex) { } $form->addSubmit('save', 'form.save'); $form->addLink('back', 'form.back', $this->getBacklink()); $form->onSuccess[] = [$this, 'editFormSucceeded']; return $form; }
php
{ "resource": "" }
q1587
UsersPresenter.editFormSucceeded
train
public function editFormSucceeded(Form $form, ArrayHash $values): void { try { $this->currentUser->setUsername($values->username); } catch (UniqueConstraintViolationException $ex) { $form->addError('cms.user.duplicityUsername'); return; } catch (InvalidArgumentException $ex) { $form->addError('cms.user.invalidUsername'); return; } try { $this->currentUser->setEmail($values->email); } catch (UniqueConstraintViolationException $ex) { $form->addError('cms.user.duplicityEmail'); return; } catch (InvalidArgumentException $ex) { $form->addError('cms.user.invalidUsername'); return; } try { $this->currentUser->setPhone($values->phone ?: null); } catch (InvalidArgumentException $ex) { $form->addError('cms.user.invalidPhone'); return; } $this->currentUser->firstName = $values->firstName; $this->currentUser->surname = $values->surname; $this->currentUser->roles->set($values->roles); $language = $this->localeService->getById($values->language); $this->currentUser->language = $language === null ? null : $language->name; $this->orm->persistAndFlush($this->currentUser); $this->flashNotifier->success('cms.user.dataSaved'); $this->restoreBacklink(); }
php
{ "resource": "" }
q1588
UsersPresenter.passwordFormSucceeded
train
public function passwordFormSucceeded(Form $form, ArrayHash $values): void { if ($values->generatePassword) { $password = Random::generate($this->minPasswordLength, $this->passwordChars); } else { $password = $values->password; } $this->currentUser->setPassword($password); $this->orm->persistAndFlush($this->currentUser); if ($this->configurator->sendChangePassword) { $this->mailer->sendNewPassword($this->currentUser->email, $this->currentUser->username, $password); } $this->flashNotifier->success('cms.user.passwordChanged'); $this->restoreBacklink(); }
php
{ "resource": "" }
q1589
FolderQuery.findAllChild
train
public static function findAllChild($folderId, $depth = 0, $currentPosition = 0) { $result = array(); if (\is_array($folderId)) { foreach ($folderId as $folderSingleId) { $result = array_merge($result, (array) self::findAllChild($folderSingleId, $depth, $currentPosition)); } } else { $currentPosition++; if ($depth == $currentPosition && $depth != 0) { return[]; } $categories = self::create() ->filterByParent($folderId) ->find(); foreach ($categories as $folder) { array_push($result, $folder); $result = array_merge($result, (array) self::findAllChild($folder->getId(), $depth, $currentPosition)); } } return $result; }
php
{ "resource": "" }
q1590
TokenProvider.generateToken
train
public static function generateToken() { $raw = self::getOpenSSLRandom(); if (false === $raw) { $raw = self::getComplexRandom(); } return md5($raw); }
php
{ "resource": "" }
q1591
ImportController.indexAction
train
public function indexAction($_view = 'import') { $authResponse = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::VIEW]); if ($authResponse !== null) { return $authResponse; } $this->getParserContext() ->set('category_order', $this->getRequest()->query->get('category_order', 'manual')) ->set('import_order', $this->getRequest()->query->get('import_order', 'manual')) ; return $this->render($_view); }
php
{ "resource": "" }
q1592
ImportController.changeImportPositionAction
train
public function changeImportPositionAction() { $authResponse = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::UPDATE]); if ($authResponse !== null) { return $authResponse; } $query = $this->getRequest()->query; $this->dispatch( TheliaEvents::IMPORT_CHANGE_POSITION, new UpdatePositionEvent( $query->get('id'), $this->matchPositionMode($query->get('mode')), $query->get('value') ) ); return $this->generateRedirectFromRoute('import.list'); }
php
{ "resource": "" }
q1593
ImportController.matchPositionMode
train
protected function matchPositionMode($mode) { if ($mode === 'up') { return UpdatePositionEvent::POSITION_UP; } if ($mode === 'down') { return UpdatePositionEvent::POSITION_DOWN; } return UpdatePositionEvent::POSITION_ABSOLUTE; }
php
{ "resource": "" }
q1594
ImportController.configureAction
train
public function configureAction($id) { /** @var \Thelia\Handler\ImportHandler $importHandler */ $importHandler = $this->container->get('thelia.import.handler'); $import = $importHandler->getImport($id); if ($import === null) { return $this->pageNotFound(); } $extensions = []; $mimeTypes = []; /** @var \Thelia\Core\Serializer\AbstractSerializer $serializer */ foreach ($this->container->get(RegisterSerializerPass::MANAGER_SERVICE_ID)->getSerializers() as $serializer) { $extensions[] = $serializer->getExtension(); $mimeTypes[] = $serializer->getMimeType(); } /** @var \Thelia\Core\Archiver\AbstractArchiver $archiver */ foreach ($this->container->get(RegisterArchiverPass::MANAGER_SERVICE_ID)->getArchivers(true) as $archiver) { $extensions[] = $archiver->getExtension(); $mimeTypes[] = $archiver->getMimeType(); } // Render standard view or ajax one $templateName = 'import-page'; if ($this->getRequest()->isXmlHttpRequest()) { $templateName = 'ajax/import-modal'; } return $this->render( $templateName, [ 'importId' => $id, 'ALLOWED_MIME_TYPES' => implode(', ', $mimeTypes), 'ALLOWED_EXTENSIONS' => implode(', ', $extensions), ] ); }
php
{ "resource": "" }
q1595
ImportController.importAction
train
public function importAction($id) { /** @var \Thelia\Handler\Importhandler $importHandler */ $importHandler = $this->container->get('thelia.import.handler'); $import = $importHandler->getImport($id); if ($import === null) { return $this->pageNotFound(); } $form = $this->createForm(AdminForm::IMPORT); try { $validatedForm = $this->validateForm($form); /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */ $file = $validatedForm->get('file_upload')->getData(); $file = $file->move( THELIA_CACHE_DIR . 'import' . DS . (new\DateTime)->format('Ymd'), uniqid() . '-' . $file->getClientOriginalName() ); $lang = (new LangQuery)->findPk($validatedForm->get('language')->getData()); $importEvent = $importHandler->import($import, $file, $lang); if (\count($importEvent->getErrors()) > 0) { $this->getSession()->getFlashBag()->add( 'thelia.import.error', $this->getTranslator()->trans( 'Error(s) in import&nbsp;:<br />%errors', [ '%errors' => implode('<br />', $importEvent->getErrors()) ] ) ); } $this->getSession()->getFlashBag()->add( 'thelia.import.success', $this->getTranslator()->trans( 'Import successfully done, %count row(s) have been changed', [ '%count' => $importEvent->getImport()->getImportedRows() ] ) ); return $this->generateRedirectFromRoute('import.view', [], ['id' => $id]); } catch (FormValidationException $e) { $form->setErrorMessage($this->createStandardFormValidationErrorMessage($e)); } catch (\Exception $e) { $this->getParserContext()->setGeneralError($e->getMessage()); } $this->getParserContext() ->addForm($form) ; return $this->configureAction($id); }
php
{ "resource": "" }
q1596
Cache.getMeter
train
public function getMeter($meterIdentifier) { // create cache key $item_key = $this->getCacheKey($meterIdentifier); // if not cached, go get it if (!($meter = $this->cacheService->retrieve($item_key))) { try { // find specific meter for company and login $meter = $this->meterStorage->getMeter($meterIdentifier); } catch (\Exception $e) { $meter = array(); } // cache meter $this->cacheService->store($item_key, $meter, $this->cacheExpires); } return $meter; }
php
{ "resource": "" }
q1597
Types.normalize
train
public static function normalize($types) { $normalized_types = []; foreach ($types as $type) { switch ($type) { case 'boolean': $normalized_types[] = 'bool'; break; case 'integer': $normalized_types[] = 'int'; break; case 'double': $normalized_types[] = 'float'; break; case 'callback': $normalized_types[] = 'callable'; break; case 'scalar': $normalized_types[] = 'bool'; $normalized_types[] = 'int'; $normalized_types[] = 'float'; $normalized_types[] = 'string'; break; default: $normalized_types[] = $type; break; } } return $normalized_types; }
php
{ "resource": "" }
q1598
ClassMemberListNode.getTypes
train
public function getTypes() { // No type specified means type is mixed. $types = ['mixed']; // Use types from the doc comment if available. $doc_comment = $this->getDocComment(); if (!$doc_comment) { return $types; } $doc_block = $doc_comment->getDocBlock(); $var_tags = $doc_block->getTagsByName('var'); if (empty($var_tags)) { return $types; } /** @var \phpDocumentor\Reflection\DocBlock\Tag\VarTag $var_tag */ $var_tag = reset($var_tags); return Types::normalize($var_tag->getTypes()); }
php
{ "resource": "" }
q1599
CommaListNode.prependItem
train
public function prependItem(Node $item) { if ($this->getItems()->isEmpty()) { $this->append($item); } else { $this->prepend([ $item, Token::comma(), Token::space(), ]); } return $this; }
php
{ "resource": "" }