_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 33
8k
| 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())
|
php
|
{
"resource": ""
}
|
q1501
|
Config.setValue
|
train
|
public function setValue(ConfigUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== $config = ConfigQuery::create()->findPk($event->getConfigId())) {
|
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())
|
php
|
{
"resource": ""
}
|
q1503
|
Config.delete
|
train
|
public function delete(ConfigDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== ($config = ConfigQuery::create()->findPk($event->getConfigId()))) {
|
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',
|
php
|
{
"resource": ""
}
|
q1505
|
XMLSerializer.setDataNodeName
|
train
|
public function setDataNodeName($dataNodeName)
{
$this->dataNodeName = $dataNodeName;
|
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();
}
|
php
|
{
"resource": ""
}
|
q1507
|
WebhookFactory.make
|
train
|
public function make(array $config)
{
Arr::requires($config, ['endpoint']);
$client = new Client();
|
php
|
{
"resource": ""
}
|
q1508
|
TrueNode.create
|
train
|
public static function create($boolean = TRUE) {
$is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper');
$node = new TrueNode();
|
php
|
{
"resource": ""
}
|
q1509
|
NullNode.create
|
train
|
public static function create($name = 'null') {
$is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper');
$node = new NullNode();
|
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()) {
|
php
|
{
"resource": ""
}
|
q1511
|
AbstractPresenter.addBreadcrumbLink
|
train
|
public function addBreadcrumbLink(string $name, string $link = null, array $arguments = []): Link
{
|
php
|
{
"resource": ""
}
|
q1512
|
AbstractPresenter.viewMobileMenu
|
train
|
public function viewMobileMenu(bool $view = true): void
|
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
|
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) {
|
php
|
{
"resource": ""
}
|
q1515
|
AsseticAssetManager.getStamp
|
train
|
protected function getStamp($directory)
{
$stamp = '';
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::LEAVES_ONLY
|
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);
}
|
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)) {
|
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) {
|
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()
)
|
php
|
{
"resource": ""
}
|
q1520
|
BladeRenderer.render
|
train
|
public function render(string $template, array $data = []): string
{
$data
|
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.
|
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();
|
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
|
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) {
|
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;
|
php
|
{
"resource": ""
}
|
q1526
|
NumberFormat.formatStandardNumber
|
train
|
public function formatStandardNumber($number, $decimals = null)
{
$lang = $this->request->getSession()->getLang();
if ($decimals === null) {
|
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();
|
php
|
{
"resource": ""
}
|
q1528
|
Plugin.isBoldgridPlugin
|
train
|
public static function isBoldgridPlugin( $plugin ) {
if( empty( $plugin ) ) {
return false;
}
$pluginChecker = new \Boldgrid\Library\Library\Plugin\Checker();
$plugins
|
php
|
{
"resource": ""
}
|
q1529
|
LanguageController.getTranslationsList
|
train
|
public function getTranslationsList()
{
$data = "";
$melisCmsAuth = $this->getServiceLocator()->get('MelisCoreAuth');
$melisCmsRights
|
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'
|
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) {
|
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()
|
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,
|
php
|
{
"resource": ""
}
|
q1534
|
Product.countSaleElements
|
train
|
public function countSaleElements($con = null)
{
|
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
|
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
|
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)
|
php
|
{
"resource": ""
}
|
q1538
|
Product.addCriteriaToPositionQuery
|
train
|
protected function addCriteriaToPositionQuery($query)
{
// Find products in the same category
$products = ProductCategoryQuery::create()
->filterByCategoryId($this->getDefaultCategoryId())
->filterByDefaultCategory(true)
|
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');
|
php
|
{
"resource": ""
}
|
q1540
|
Validate.setHash
|
train
|
public function setHash( $key = null ) {
$key = $key ? $this->sanitizeKey( $key ) : $this->getKey();
|
php
|
{
"resource": ""
}
|
q1541
|
Validate.sanitizeKey
|
train
|
public function sanitizeKey( $key ) {
$key = trim( strtolower( preg_replace( '/-/', '', $key ) ) );
$key
|
php
|
{
"resource": ""
}
|
q1542
|
Validate.isValid
|
train
|
public function isValid( $key = null ) {
$key = $key ? $this->sanitizeKey( $key )
|
php
|
{
"resource": ""
}
|
q1543
|
PageSeoController.getSeoKeywordsByPageId
|
train
|
public function getSeoKeywordsByPageId($pageId)
{
$pageId = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', ''));
$data = array();
|
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);
|
php
|
{
"resource": ""
}
|
q1545
|
Reseller.getAttribute
|
train
|
public function getAttribute( $attribute ) {
$data = $this->getData();
|
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/';
|
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' ),
|
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;
}
|
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;
}
|
php
|
{
"resource": ""
}
|
q1550
|
BasePresenter.ajaxRedirect
|
train
|
public function ajaxRedirect(string $destination, array $args = []):
|
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'
|
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(
|
php
|
{
"resource": ""
}
|
q1553
|
ConditionFactory.build
|
train
|
public function build($conditionServiceId, array $operators, array $values)
{
if (!$this->container->has($conditionServiceId)) {
return false;
|
php
|
{
"resource": ""
}
|
q1554
|
ConditionFactory.getInputsFromServiceId
|
train
|
public function getInputsFromServiceId($conditionServiceId)
{
if (!$this->container->has($conditionServiceId)) {
return false;
|
php
|
{
"resource": ""
}
|
q1555
|
ModuleConfigQuery.getConfigValue
|
train
|
public function getConfigValue($moduleId, $variableName, $defaultValue = null, $valueLocale = null)
{
$value = null;
$configValue = self::create()
->filterByModuleId($moduleId)
->filterByName($variableName)
|
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)
|
php
|
{
"resource": ""
}
|
q1557
|
ModuleConfigQuery.deleteConfigValue
|
train
|
public function deleteConfigValue($moduleId, $variableName)
{
if (null !== $moduleConfig = self::create()
->filterByModuleId($moduleId)
->filterByName($variableName)
|
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(
|
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(
|
php
|
{
"resource": ""
}
|
q1560
|
RootNode.create
|
train
|
public static function create($ns = NULL) {
$node = new RootNode();
$node->addChild(Token::openTag());
|
php
|
{
"resource": ""
}
|
q1561
|
RootNode.getNamespace
|
train
|
public function getNamespace($ns) {
$namespaces = $this
->getNamespaces()
->filter(function(NamespaceNode $node) use ($ns) {
|
php
|
{
"resource": ""
}
|
q1562
|
RootNode.getNamespaceNames
|
train
|
public function getNamespaceNames($absolute = FALSE) {
$iterator = function(NamespaceNode $ns) use ($absolute) {
$name = $ns->getName();
return $absolute ? $name->getAbsolutePath() :
|
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;
}
|
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(
|
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' =>
|
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);
|
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(' ',
|
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)
|
php
|
{
"resource": ""
}
|
q1569
|
FunctionTrait.getReturnTypes
|
train
|
public function getReturnTypes() {
$types = ['void'];
$doc_comment = $this->getDocComment();
if (!$doc_comment) {
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)
|
php
|
{
"resource": ""
}
|
q1571
|
UrlRewritingTrait.getUrl
|
train
|
public function getUrl($locale = null)
{
if (null === $locale) {
$locale = $this->getLocale();
}
|
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;
|
php
|
{
"resource": ""
}
|
q1573
|
UrlRewritingTrait.getRewrittenUrl
|
train
|
public function getRewrittenUrl($locale)
{
$rewritingUrl = RewritingUrlQuery::create()
->filterByViewLocale($locale)
->filterByView($this->getRewrittenUrlViewName())
->filterByViewId($this->getId())
->filterByRedirected(null)
|
php
|
{
"resource": ""
}
|
q1574
|
UrlRewritingTrait.markRewrittenUrlObsolete
|
train
|
public function markRewrittenUrlObsolete()
{
RewritingUrlQuery::create()
->filterByView($this->getRewrittenUrlViewName())
->filterByViewId($this->getId())
|
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 */
|
php
|
{
"resource": ""
}
|
q1576
|
ClassMemberNode.create
|
train
|
public static function create($name, ExpressionNode $value = NULL, $visibility = 'public') {
$code = $visibility . ' $' . ltrim($name, '$');
if ($value instanceof ExpressionNode) {
|
php
|
{
"resource": ""
}
|
q1577
|
Render.adminBarNode
|
train
|
public static function adminBarNode( $wpAdminBar, $configs ) {
$wpAdminBar->add_node( $configs['topLevel'] );
|
php
|
{
"resource": ""
}
|
q1578
|
MetaDataQuery.setVal
|
train
|
public static function setVal($metaKey, $elementKey, $elementId, $value)
{
$data = self::create()
->filterByMetaKey($metaKey)
->filterByElementKey($elementKey)
->filterByElementId($elementId)
|
php
|
{
"resource": ""
}
|
q1579
|
IdentifierNameTrait.setName
|
train
|
public function setName($name) {
/** @var TokenNode $identifier */
$identifier = $this->name->firstChild();
|
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;
}
|
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 =
|
php
|
{
"resource": ""
}
|
q1582
|
InfoPresenter.renderPhp
|
train
|
public function renderPhp(): void
{
$this->addBreadcrumbLink('dockbar.info.php');
|
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;
|
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')))
|
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;
|
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);
|
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);
}
|
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) {
|
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[];
}
|
php
|
{
"resource": ""
}
|
q1590
|
TokenProvider.generateToken
|
train
|
public static function generateToken()
{
$raw = self::getOpenSSLRandom();
if (false === $raw) {
|
php
|
{
"resource": ""
}
|
q1591
|
ImportController.indexAction
|
train
|
public function indexAction($_view = 'import')
{
$authResponse = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::VIEW]);
if ($authResponse !== null) {
return $authResponse;
|
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;
|
php
|
{
"resource": ""
}
|
q1593
|
ImportController.matchPositionMode
|
train
|
protected function matchPositionMode($mode)
{
if ($mode === 'up') {
return UpdatePositionEvent::POSITION_UP;
}
if ($mode === 'down') {
return
|
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();
|
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 :<br />%errors',
[
'%errors' => implode('<br />', $importEvent->getErrors())
]
)
);
}
$this->getSession()->getFlashBag()->add(
'thelia.import.success',
$this->getTranslator()->trans(
|
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 {
|
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':
|
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)) {
|
php
|
{
"resource": ""
}
|
q1599
|
CommaListNode.prependItem
|
train
|
public function prependItem(Node $item) {
if ($this->getItems()->isEmpty()) {
$this->append($item);
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.