repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
verbb/super-table
src/elements/db/SuperTableBlockQuery.php
SuperTableBlockQuery.ownerSiteId
public function ownerSiteId($value) { $this->ownerSiteId = $value; if ($value && strtolower($value) !== ':empty:') { // A block will never exist in a site that is different than its ownerSiteId, // so let's set the siteId param here too. $this->siteId = (int)$value; } return $this; }
php
public function ownerSiteId($value) { $this->ownerSiteId = $value; if ($value && strtolower($value) !== ':empty:') { // A block will never exist in a site that is different than its ownerSiteId, // so let's set the siteId param here too. $this->siteId = (int)$value; } return $this; }
[ "public", "function", "ownerSiteId", "(", "$", "value", ")", "{", "$", "this", "->", "ownerSiteId", "=", "$", "value", ";", "if", "(", "$", "value", "&&", "strtolower", "(", "$", "value", ")", "!==", "':empty:'", ")", "{", "// A block will never exist in a...
Sets the [[ownerSiteId]] and [[siteId]] properties. @param int|string|null $value The property value @return static self reference
[ "Sets", "the", "[[", "ownerSiteId", "]]", "and", "[[", "siteId", "]]", "properties", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/elements/db/SuperTableBlockQuery.php#L138-L149
verbb/super-table
src/elements/db/SuperTableBlockQuery.php
SuperTableBlockQuery.ownerLocale
public function ownerLocale($value) { Craft::$app->getDeprecator()->log('ElementQuery::ownerLocale()', 'The “ownerLocale” SuperTable block query param has been deprecated. Use “site” or “siteId” instead.'); $this->ownerSite($value); return $this; }
php
public function ownerLocale($value) { Craft::$app->getDeprecator()->log('ElementQuery::ownerLocale()', 'The “ownerLocale” SuperTable block query param has been deprecated. Use “site” or “siteId” instead.'); $this->ownerSite($value); return $this; }
[ "public", "function", "ownerLocale", "(", "$", "value", ")", "{", "Craft", "::", "$", "app", "->", "getDeprecator", "(", ")", "->", "log", "(", "'ElementQuery::ownerLocale()'", ",", "'The “ownerLocale” SuperTable block query param has been deprecated. Use “site” or “siteId”...
Sets the [[ownerLocale]] property. @param string|string[] $value The property value @return static self reference @deprecated in 3.0. Use [[ownerSiteId()]] instead.
[ "Sets", "the", "[[", "ownerLocale", "]]", "property", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/elements/db/SuperTableBlockQuery.php#L184-L190
verbb/super-table
src/elements/db/SuperTableBlockQuery.php
SuperTableBlockQuery.type
public function type($value) { if ($value instanceof SuperTableBlockType) { $this->typeId = $value->id; } else if ($value !== null) { $this->typeId = (new Query()) ->select(['id']) ->from(['{{%supertableblocktypes}}']) ->where(Db::parseParam('id', $value)) ->column(); } else { $this->typeId = null; } return $this; }
php
public function type($value) { if ($value instanceof SuperTableBlockType) { $this->typeId = $value->id; } else if ($value !== null) { $this->typeId = (new Query()) ->select(['id']) ->from(['{{%supertableblocktypes}}']) ->where(Db::parseParam('id', $value)) ->column(); } else { $this->typeId = null; } return $this; }
[ "public", "function", "type", "(", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "SuperTableBlockType", ")", "{", "$", "this", "->", "typeId", "=", "$", "value", "->", "id", ";", "}", "else", "if", "(", "$", "value", "!==", "null", ...
Sets the [[typeId]] property based on a given block type(s)’s id(s). @param string|string[]|SuperTableBlockType|null $value The property value @return static self reference
[ "Sets", "the", "[[", "typeId", "]]", "property", "based", "on", "a", "given", "block", "type", "(", "s", ")", "’s", "id", "(", "s", ")", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/elements/db/SuperTableBlockQuery.php#L215-L230
verbb/super-table
src/fields/SuperTableField.php
SuperTableField.getBlockTypes
public function getBlockTypes(): array { if ($this->_blockTypes !== null) { return $this->_blockTypes; } if ($this->getIsNew()) { return []; } return $this->_blockTypes = SuperTable::$plugin->getService()->getBlockTypesByFieldId($this->id); }
php
public function getBlockTypes(): array { if ($this->_blockTypes !== null) { return $this->_blockTypes; } if ($this->getIsNew()) { return []; } return $this->_blockTypes = SuperTable::$plugin->getService()->getBlockTypesByFieldId($this->id); }
[ "public", "function", "getBlockTypes", "(", ")", ":", "array", "{", "if", "(", "$", "this", "->", "_blockTypes", "!==", "null", ")", "{", "return", "$", "this", "->", "_blockTypes", ";", "}", "if", "(", "$", "this", "->", "getIsNew", "(", ")", ")", ...
Returns the block types. @return SuperTableBlockType[]
[ "Returns", "the", "block", "types", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/fields/SuperTableField.php#L129-L140
verbb/super-table
src/fields/SuperTableField.php
SuperTableField.getBlockTypeFields
public function getBlockTypeFields(): array { if ($this->_blockTypeFields !== null) { return $this->_blockTypeFields; } if (empty($blockTypes = $this->getBlockTypes())) { return $this->_blockTypeFields = []; } // Get the fields & layout IDs $contexts = []; $layoutIds = []; foreach ($blockTypes as $blockType) { $contexts[] = 'superTableBlockType:' . $blockType->uid; $layoutIds[] = $blockType->fieldLayoutId; } /** @var Field[] $fieldsById */ $fieldsById = ArrayHelper::index(Craft::$app->getFields()->getAllFields($contexts), 'id'); // Get all the field IDs grouped by layout ID $fieldIdsByLayoutId = Craft::$app->getFields()->getFieldIdsByLayoutIds($layoutIds); // Assemble the fields $this->_blockTypeFields = []; foreach ($blockTypes as $blockType) { if (isset($fieldIdsByLayoutId[$blockType->fieldLayoutId])) { $fieldColumnPrefix = 'field_'; foreach ($fieldIdsByLayoutId[$blockType->fieldLayoutId] as $fieldId) { if (isset($fieldsById[$fieldId])) { $fieldsById[$fieldId]->columnPrefix = $fieldColumnPrefix; $this->_blockTypeFields[] = $fieldsById[$fieldId]; } } } } return $this->_blockTypeFields; }
php
public function getBlockTypeFields(): array { if ($this->_blockTypeFields !== null) { return $this->_blockTypeFields; } if (empty($blockTypes = $this->getBlockTypes())) { return $this->_blockTypeFields = []; } // Get the fields & layout IDs $contexts = []; $layoutIds = []; foreach ($blockTypes as $blockType) { $contexts[] = 'superTableBlockType:' . $blockType->uid; $layoutIds[] = $blockType->fieldLayoutId; } /** @var Field[] $fieldsById */ $fieldsById = ArrayHelper::index(Craft::$app->getFields()->getAllFields($contexts), 'id'); // Get all the field IDs grouped by layout ID $fieldIdsByLayoutId = Craft::$app->getFields()->getFieldIdsByLayoutIds($layoutIds); // Assemble the fields $this->_blockTypeFields = []; foreach ($blockTypes as $blockType) { if (isset($fieldIdsByLayoutId[$blockType->fieldLayoutId])) { $fieldColumnPrefix = 'field_'; foreach ($fieldIdsByLayoutId[$blockType->fieldLayoutId] as $fieldId) { if (isset($fieldsById[$fieldId])) { $fieldsById[$fieldId]->columnPrefix = $fieldColumnPrefix; $this->_blockTypeFields[] = $fieldsById[$fieldId]; } } } } return $this->_blockTypeFields; }
[ "public", "function", "getBlockTypeFields", "(", ")", ":", "array", "{", "if", "(", "$", "this", "->", "_blockTypeFields", "!==", "null", ")", "{", "return", "$", "this", "->", "_blockTypeFields", ";", "}", "if", "(", "empty", "(", "$", "blockTypes", "="...
Returns all of the block types' fields. @return FieldInterface[]
[ "Returns", "all", "of", "the", "block", "types", "fields", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/fields/SuperTableField.php#L147-L188
verbb/super-table
src/fields/SuperTableField.php
SuperTableField.setBlockTypes
public function setBlockTypes($blockTypes) { $this->_blockTypes = []; $defaultFieldConfig = [ 'type' => null, 'instructions' => null, 'required' => false, 'translationMethod' => Field::TRANSLATION_METHOD_NONE, 'translationKeyFormat' => null, 'typesettings' => null, ]; foreach ($blockTypes as $key => $config) { if ($config instanceof SuperTableBlockTypeModel) { $this->_blockTypes[] = $config; } else { $blockType = new SuperTableBlockTypeModel(); $blockType->fieldId = $this->id; // Existing block type? if (is_numeric($key)) { $info = (new Query()) ->select(['uid', 'fieldLayoutId']) ->from(['{{%supertableblocktypes}}']) ->where(['id'=> $key]) ->one(); if ($info) { $blockType->id = $key; $blockType->uid = $info['uid']; $blockType->fieldLayoutId = $info['fieldLayoutId']; } } $fields = []; if (!empty($config['fields'])) { foreach ($config['fields'] as $fieldId => $fieldConfig) { /** @noinspection SlowArrayOperationsInLoopInspection */ $fieldConfig = array_merge($defaultFieldConfig, $fieldConfig); $fields[] = Craft::$app->getFields()->createField([ 'type' => $fieldConfig['type'], 'id' => is_numeric($fieldId) ? $fieldId : null, 'name' => $fieldConfig['name'], 'handle' => $fieldConfig['handle'], 'instructions' => $fieldConfig['instructions'], 'required' => (bool)$fieldConfig['required'], 'translationMethod' => $fieldConfig['translationMethod'], 'translationKeyFormat' => $fieldConfig['translationKeyFormat'], 'settings' => $fieldConfig['typesettings'], ]); } } $blockType->setFields($fields); $this->_blockTypes[] = $blockType; } } }
php
public function setBlockTypes($blockTypes) { $this->_blockTypes = []; $defaultFieldConfig = [ 'type' => null, 'instructions' => null, 'required' => false, 'translationMethod' => Field::TRANSLATION_METHOD_NONE, 'translationKeyFormat' => null, 'typesettings' => null, ]; foreach ($blockTypes as $key => $config) { if ($config instanceof SuperTableBlockTypeModel) { $this->_blockTypes[] = $config; } else { $blockType = new SuperTableBlockTypeModel(); $blockType->fieldId = $this->id; // Existing block type? if (is_numeric($key)) { $info = (new Query()) ->select(['uid', 'fieldLayoutId']) ->from(['{{%supertableblocktypes}}']) ->where(['id'=> $key]) ->one(); if ($info) { $blockType->id = $key; $blockType->uid = $info['uid']; $blockType->fieldLayoutId = $info['fieldLayoutId']; } } $fields = []; if (!empty($config['fields'])) { foreach ($config['fields'] as $fieldId => $fieldConfig) { /** @noinspection SlowArrayOperationsInLoopInspection */ $fieldConfig = array_merge($defaultFieldConfig, $fieldConfig); $fields[] = Craft::$app->getFields()->createField([ 'type' => $fieldConfig['type'], 'id' => is_numeric($fieldId) ? $fieldId : null, 'name' => $fieldConfig['name'], 'handle' => $fieldConfig['handle'], 'instructions' => $fieldConfig['instructions'], 'required' => (bool)$fieldConfig['required'], 'translationMethod' => $fieldConfig['translationMethod'], 'translationKeyFormat' => $fieldConfig['translationKeyFormat'], 'settings' => $fieldConfig['typesettings'], ]); } } $blockType->setFields($fields); $this->_blockTypes[] = $blockType; } } }
[ "public", "function", "setBlockTypes", "(", "$", "blockTypes", ")", "{", "$", "this", "->", "_blockTypes", "=", "[", "]", ";", "$", "defaultFieldConfig", "=", "[", "'type'", "=>", "null", ",", "'instructions'", "=>", "null", ",", "'required'", "=>", "false...
Sets the block types. @param SuperTableBlockType|array $blockTypes The block type settings or actual SuperTableBlockType model instances
[ "Sets", "the", "block", "types", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/fields/SuperTableField.php#L195-L254
verbb/super-table
src/fields/SuperTableField.php
SuperTableField.validateBlocks
public function validateBlocks(ElementInterface $element) { /** @var Element $element */ /** @var SuperTableBlockQuery $value */ $value = $element->getFieldValue($this->handle); foreach ($value->all() as $i => $block) { /** @var SuperTableBlock $block */ if ($element->getScenario() === Element::SCENARIO_LIVE) { $block->setScenario(Element::SCENARIO_LIVE); } if (!$block->validate()) { foreach ($block->getErrors() as $attribute => $errors) { $element->addErrors([ "{$this->handle}[{$i}].{$attribute}" => $errors, ]); } } } }
php
public function validateBlocks(ElementInterface $element) { /** @var Element $element */ /** @var SuperTableBlockQuery $value */ $value = $element->getFieldValue($this->handle); foreach ($value->all() as $i => $block) { /** @var SuperTableBlock $block */ if ($element->getScenario() === Element::SCENARIO_LIVE) { $block->setScenario(Element::SCENARIO_LIVE); } if (!$block->validate()) { foreach ($block->getErrors() as $attribute => $errors) { $element->addErrors([ "{$this->handle}[{$i}].{$attribute}" => $errors, ]); } } } }
[ "public", "function", "validateBlocks", "(", "ElementInterface", "$", "element", ")", "{", "/** @var Element $element */", "/** @var SuperTableBlockQuery $value */", "$", "value", "=", "$", "element", "->", "getFieldValue", "(", "$", "this", "->", "handle", ")", ";", ...
Validates an owner element’s Super Table blocks. @param ElementInterface $element
[ "Validates", "an", "owner", "element’s", "Super", "Table", "blocks", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/fields/SuperTableField.php#L572-L592
verbb/super-table
src/fields/SuperTableField.php
SuperTableField._getFieldOptionsForConfigurator
private function _getFieldOptionsForConfigurator(): array { $fieldTypes = []; // Set a temporary namespace for these $originalNamespace = Craft::$app->getView()->getNamespace(); $namespace = Craft::$app->getView()->namespaceInputName('blockTypes[__BLOCK_TYPE_ST__][fields][__FIELD_ST__][typesettings]', $originalNamespace); Craft::$app->getView()->setNamespace($namespace); foreach (Craft::$app->getFields()->getAllFieldTypes() as $class) { /** @var Field|string $class */ // No SuperTable-Inception, sorry buddy. if ($class === self::class) { continue; } Craft::$app->getView()->startJsBuffer(); /** @var FieldInterface $field */ $field = new $class(); // A Matrix field will fetch all available fields, grabbing their Settings HTML. Then Super Table will do the same, // causing an infinite loop - extract some methods from MatrixFieldType if ($class === Matrix::class) { $settingsBodyHtml = Craft::$app->getView()->namespaceInputs((string)SuperTable::$plugin->matrixService->getMatrixSettingsHtml($field)); } else { $settingsBodyHtml = Craft::$app->getView()->namespaceInputs((string)$field->getSettingsHtml()); } $settingsFootHtml = Craft::$app->getView()->clearJsBuffer(); $fieldTypes[] = [ 'type' => $class, 'name' => $class::displayName(), 'settingsBodyHtml' => $settingsBodyHtml, 'settingsFootHtml' => $settingsFootHtml, ]; } // Sort them by name ArrayHelper::multisort($fieldTypes, 'name'); Craft::$app->getView()->setNamespace($originalNamespace); return $fieldTypes; }
php
private function _getFieldOptionsForConfigurator(): array { $fieldTypes = []; // Set a temporary namespace for these $originalNamespace = Craft::$app->getView()->getNamespace(); $namespace = Craft::$app->getView()->namespaceInputName('blockTypes[__BLOCK_TYPE_ST__][fields][__FIELD_ST__][typesettings]', $originalNamespace); Craft::$app->getView()->setNamespace($namespace); foreach (Craft::$app->getFields()->getAllFieldTypes() as $class) { /** @var Field|string $class */ // No SuperTable-Inception, sorry buddy. if ($class === self::class) { continue; } Craft::$app->getView()->startJsBuffer(); /** @var FieldInterface $field */ $field = new $class(); // A Matrix field will fetch all available fields, grabbing their Settings HTML. Then Super Table will do the same, // causing an infinite loop - extract some methods from MatrixFieldType if ($class === Matrix::class) { $settingsBodyHtml = Craft::$app->getView()->namespaceInputs((string)SuperTable::$plugin->matrixService->getMatrixSettingsHtml($field)); } else { $settingsBodyHtml = Craft::$app->getView()->namespaceInputs((string)$field->getSettingsHtml()); } $settingsFootHtml = Craft::$app->getView()->clearJsBuffer(); $fieldTypes[] = [ 'type' => $class, 'name' => $class::displayName(), 'settingsBodyHtml' => $settingsBodyHtml, 'settingsFootHtml' => $settingsFootHtml, ]; } // Sort them by name ArrayHelper::multisort($fieldTypes, 'name'); Craft::$app->getView()->setNamespace($originalNamespace); return $fieldTypes; }
[ "private", "function", "_getFieldOptionsForConfigurator", "(", ")", ":", "array", "{", "$", "fieldTypes", "=", "[", "]", ";", "// Set a temporary namespace for these", "$", "originalNamespace", "=", "Craft", "::", "$", "app", "->", "getView", "(", ")", "->", "ge...
Returns info about each field type for the configurator. @return array
[ "Returns", "info", "about", "each", "field", "type", "for", "the", "configurator", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/fields/SuperTableField.php#L824-L869
verbb/super-table
src/fields/SuperTableField.php
SuperTableField._getBlockTypeInfoForInput
private function _getBlockTypeInfoForInput(ElementInterface $element = null): array { $settings = $this->getSettings(); $blockTypes = []; // Set a temporary namespace for these $originalNamespace = Craft::$app->getView()->getNamespace(); $namespace = Craft::$app->getView()->namespaceInputName($this->handle . '[__BLOCK_ST__][fields]', $originalNamespace); Craft::$app->getView()->setNamespace($namespace); foreach ($this->getBlockTypes() as $blockType) { // Create a fake SuperTableBlock so the field types have a way to get at the owner element, if there is one $block = new SuperTableBlockElement(); $block->fieldId = $this->id; $block->typeId = $blockType->id; if ($element) { $block->setOwner($element); $block->siteId = $element->siteId; } $fieldLayoutFields = $blockType->getFieldLayout()->getFields(); foreach ($fieldLayoutFields as $field) { $field->setIsFresh(true); } Craft::$app->getView()->startJsBuffer(); $bodyHtml = Craft::$app->getView()->namespaceInputs(Craft::$app->getView()->renderTemplate('super-table/fields', [ 'namespace' => null, 'fields' => $fieldLayoutFields, 'element' => $block, 'settings' => $settings, 'staticField' => $this->staticField, ])); // Reset $_isFresh's foreach ($fieldLayoutFields as $field) { $field->setIsFresh(null); } $footHtml = Craft::$app->getView()->clearJsBuffer(); $blockTypes[] = [ 'type' => $blockType->id, 'bodyHtml' => $bodyHtml, 'footHtml' => $footHtml, ]; } Craft::$app->getView()->setNamespace($originalNamespace); return $blockTypes; }
php
private function _getBlockTypeInfoForInput(ElementInterface $element = null): array { $settings = $this->getSettings(); $blockTypes = []; // Set a temporary namespace for these $originalNamespace = Craft::$app->getView()->getNamespace(); $namespace = Craft::$app->getView()->namespaceInputName($this->handle . '[__BLOCK_ST__][fields]', $originalNamespace); Craft::$app->getView()->setNamespace($namespace); foreach ($this->getBlockTypes() as $blockType) { // Create a fake SuperTableBlock so the field types have a way to get at the owner element, if there is one $block = new SuperTableBlockElement(); $block->fieldId = $this->id; $block->typeId = $blockType->id; if ($element) { $block->setOwner($element); $block->siteId = $element->siteId; } $fieldLayoutFields = $blockType->getFieldLayout()->getFields(); foreach ($fieldLayoutFields as $field) { $field->setIsFresh(true); } Craft::$app->getView()->startJsBuffer(); $bodyHtml = Craft::$app->getView()->namespaceInputs(Craft::$app->getView()->renderTemplate('super-table/fields', [ 'namespace' => null, 'fields' => $fieldLayoutFields, 'element' => $block, 'settings' => $settings, 'staticField' => $this->staticField, ])); // Reset $_isFresh's foreach ($fieldLayoutFields as $field) { $field->setIsFresh(null); } $footHtml = Craft::$app->getView()->clearJsBuffer(); $blockTypes[] = [ 'type' => $blockType->id, 'bodyHtml' => $bodyHtml, 'footHtml' => $footHtml, ]; } Craft::$app->getView()->setNamespace($originalNamespace); return $blockTypes; }
[ "private", "function", "_getBlockTypeInfoForInput", "(", "ElementInterface", "$", "element", "=", "null", ")", ":", "array", "{", "$", "settings", "=", "$", "this", "->", "getSettings", "(", ")", ";", "$", "blockTypes", "=", "[", "]", ";", "// Set a temporar...
Returns info about each block type and their field types for the Super Table field input. @param ElementInterface|null $element @return array
[ "Returns", "info", "about", "each", "block", "type", "and", "their", "field", "types", "for", "the", "Super", "Table", "field", "input", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/fields/SuperTableField.php#L878-L933
verbb/super-table
src/fields/SuperTableField.php
SuperTableField._createBlocksFromSerializedData
private function _createBlocksFromSerializedData($value, ElementInterface $element = null): array { if (!is_array($value)) { return []; } /** @var Element $element */ // Get the possible block types for this field /** @var SuperTableBlockType[] $blockTypes */ $blockTypes = ArrayHelper::index(SuperTable::$plugin->getService()->getBlockTypesByFieldId($this->id), 'id'); $oldBlocksById = []; // Get the old blocks that are still around if ($element && $element->id) { $ownerId = $element->id; $ids = []; foreach (array_keys($value) as $blockId) { if (is_numeric($blockId) && $blockId != 0) { $ids[] = $blockId; // If that block was duplicated earlier in this request, check for that as well. if (isset(Elements::$duplicatedElementIds[$blockId])) { $ids[] = Elements::$duplicatedElementIds[$blockId]; } } } if (!empty($ids)) { $oldBlocksQuery = SuperTableBlockElement::find(); $oldBlocksQuery->fieldId($this->id); $oldBlocksQuery->ownerId($ownerId); $oldBlocksQuery->id($ids); $oldBlocksQuery->anyStatus(); $oldBlocksQuery->siteId($element->siteId); $oldBlocksQuery->indexBy('id'); $oldBlocksById = $oldBlocksQuery->all(); } } else { $ownerId = null; } $isLivePreview = Craft::$app->getRequest()->getIsLivePreview(); $blocks = []; $sortOrder = 0; $prevBlock = null; foreach ($value as $blockId => $blockData) { if (!isset($blockData['type']) || !isset($blockTypes[$blockData['type']])) { continue; } $blockType = $blockTypes[$blockData['type']]; // If this is a preexisting block but we don't have a record of it, // check to see if it was recently duplicated. if ( strpos($blockId, 'new') !== 0 && !isset($oldBlocksById[$blockId]) && isset(Elements::$duplicatedElementIds[$blockId]) ) { $blockId = Elements::$duplicatedElementIds[$blockId]; } // Is this new? (Or has it been deleted?) if (strpos($blockId, 'new') === 0 || !isset($oldBlocksById[$blockId])) { $block = new SuperTableBlockElement(); $block->fieldId = $this->id; $block->typeId = $blockType->id; $block->ownerId = $ownerId; $block->siteId = $element->siteId; } else { $block = $oldBlocksById[$blockId]; } $block->setOwner($element); // Set the content post location on the block if we can $fieldNamespace = $element->getFieldParamNamespace(); if ($fieldNamespace !== null) { $blockFieldNamespace = ($fieldNamespace ? $fieldNamespace . '.' : '') . $this->handle . '.' . $blockId . '.fields'; $block->setFieldParamNamespace($blockFieldNamespace); } if (isset($blockData['fields'])) { foreach ($blockData['fields'] as $fieldHandle => $fieldValue) { try { $block->setFieldValue($fieldHandle, $fieldValue); } catch (UnknownPropertyException $e) { // the field was probably deleted } } } $sortOrder++; $block->sortOrder = $sortOrder; // Set the prev/next blocks if ($prevBlock) { /** @var ElementInterface $prevBlock */ $prevBlock->setNext($block); /** @var ElementInterface $block */ $block->setPrev($prevBlock); } $prevBlock = $block; $blocks[] = $block; } return $blocks; }
php
private function _createBlocksFromSerializedData($value, ElementInterface $element = null): array { if (!is_array($value)) { return []; } /** @var Element $element */ // Get the possible block types for this field /** @var SuperTableBlockType[] $blockTypes */ $blockTypes = ArrayHelper::index(SuperTable::$plugin->getService()->getBlockTypesByFieldId($this->id), 'id'); $oldBlocksById = []; // Get the old blocks that are still around if ($element && $element->id) { $ownerId = $element->id; $ids = []; foreach (array_keys($value) as $blockId) { if (is_numeric($blockId) && $blockId != 0) { $ids[] = $blockId; // If that block was duplicated earlier in this request, check for that as well. if (isset(Elements::$duplicatedElementIds[$blockId])) { $ids[] = Elements::$duplicatedElementIds[$blockId]; } } } if (!empty($ids)) { $oldBlocksQuery = SuperTableBlockElement::find(); $oldBlocksQuery->fieldId($this->id); $oldBlocksQuery->ownerId($ownerId); $oldBlocksQuery->id($ids); $oldBlocksQuery->anyStatus(); $oldBlocksQuery->siteId($element->siteId); $oldBlocksQuery->indexBy('id'); $oldBlocksById = $oldBlocksQuery->all(); } } else { $ownerId = null; } $isLivePreview = Craft::$app->getRequest()->getIsLivePreview(); $blocks = []; $sortOrder = 0; $prevBlock = null; foreach ($value as $blockId => $blockData) { if (!isset($blockData['type']) || !isset($blockTypes[$blockData['type']])) { continue; } $blockType = $blockTypes[$blockData['type']]; // If this is a preexisting block but we don't have a record of it, // check to see if it was recently duplicated. if ( strpos($blockId, 'new') !== 0 && !isset($oldBlocksById[$blockId]) && isset(Elements::$duplicatedElementIds[$blockId]) ) { $blockId = Elements::$duplicatedElementIds[$blockId]; } // Is this new? (Or has it been deleted?) if (strpos($blockId, 'new') === 0 || !isset($oldBlocksById[$blockId])) { $block = new SuperTableBlockElement(); $block->fieldId = $this->id; $block->typeId = $blockType->id; $block->ownerId = $ownerId; $block->siteId = $element->siteId; } else { $block = $oldBlocksById[$blockId]; } $block->setOwner($element); // Set the content post location on the block if we can $fieldNamespace = $element->getFieldParamNamespace(); if ($fieldNamespace !== null) { $blockFieldNamespace = ($fieldNamespace ? $fieldNamespace . '.' : '') . $this->handle . '.' . $blockId . '.fields'; $block->setFieldParamNamespace($blockFieldNamespace); } if (isset($blockData['fields'])) { foreach ($blockData['fields'] as $fieldHandle => $fieldValue) { try { $block->setFieldValue($fieldHandle, $fieldValue); } catch (UnknownPropertyException $e) { // the field was probably deleted } } } $sortOrder++; $block->sortOrder = $sortOrder; // Set the prev/next blocks if ($prevBlock) { /** @var ElementInterface $prevBlock */ $prevBlock->setNext($block); /** @var ElementInterface $block */ $block->setPrev($prevBlock); } $prevBlock = $block; $blocks[] = $block; } return $blocks; }
[ "private", "function", "_createBlocksFromSerializedData", "(", "$", "value", ",", "ElementInterface", "$", "element", "=", "null", ")", ":", "array", "{", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "return", "[", "]", ";", "}", "/** @v...
Creates an array of blocks based on the given serialized data. @param array|string $value The raw field value @param ElementInterface|null $element The element the field is associated with, if there is one @return SuperTableBlock[]
[ "Creates", "an", "array", "of", "blocks", "based", "on", "the", "given", "serialized", "data", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/fields/SuperTableField.php#L943-L1056
verbb/super-table
src/services/SuperTableService.php
SuperTableService.getBlockTypesByFieldId
public function getBlockTypesByFieldId(int $fieldId): array { if (!empty($this->_fetchedAllBlockTypesForFieldId[$fieldId])) { return $this->_blockTypesByFieldId[$fieldId]; } $this->_blockTypesByFieldId[$fieldId] = []; $results = $this->_createBlockTypeQuery() ->where(['fieldId' => $fieldId]) ->all(); foreach ($results as $result) { $blockType = new SuperTableBlockTypeModel($result); $this->_blockTypesById[$blockType->id] = $blockType; $this->_blockTypesByFieldId[$fieldId][] = $blockType; } $this->_fetchedAllBlockTypesForFieldId[$fieldId] = true; return $this->_blockTypesByFieldId[$fieldId]; }
php
public function getBlockTypesByFieldId(int $fieldId): array { if (!empty($this->_fetchedAllBlockTypesForFieldId[$fieldId])) { return $this->_blockTypesByFieldId[$fieldId]; } $this->_blockTypesByFieldId[$fieldId] = []; $results = $this->_createBlockTypeQuery() ->where(['fieldId' => $fieldId]) ->all(); foreach ($results as $result) { $blockType = new SuperTableBlockTypeModel($result); $this->_blockTypesById[$blockType->id] = $blockType; $this->_blockTypesByFieldId[$fieldId][] = $blockType; } $this->_fetchedAllBlockTypesForFieldId[$fieldId] = true; return $this->_blockTypesByFieldId[$fieldId]; }
[ "public", "function", "getBlockTypesByFieldId", "(", "int", "$", "fieldId", ")", ":", "array", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "_fetchedAllBlockTypesForFieldId", "[", "$", "fieldId", "]", ")", ")", "{", "return", "$", "this", "->", ...
Returns the block types for a given Super Table field. @param int $fieldId The Super Table field ID. @return SuperTableBlockType[] An array of block types.
[ "Returns", "the", "block", "types", "for", "a", "given", "Super", "Table", "field", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L90-L111
verbb/super-table
src/services/SuperTableService.php
SuperTableService.getBlockTypeById
public function getBlockTypeById(int $blockTypeId) { if ($this->_blockTypesById !== null && array_key_exists($blockTypeId, $this->_blockTypesById)) { return $this->_blockTypesById[$blockTypeId]; } $result = $this->_createBlockTypeQuery() ->where(['id' => $blockTypeId]) ->one(); return $this->_blockTypesById[$blockTypeId] = $result ? new SuperTableBlockTypeModel($result) : null; }
php
public function getBlockTypeById(int $blockTypeId) { if ($this->_blockTypesById !== null && array_key_exists($blockTypeId, $this->_blockTypesById)) { return $this->_blockTypesById[$blockTypeId]; } $result = $this->_createBlockTypeQuery() ->where(['id' => $blockTypeId]) ->one(); return $this->_blockTypesById[$blockTypeId] = $result ? new SuperTableBlockTypeModel($result) : null; }
[ "public", "function", "getBlockTypeById", "(", "int", "$", "blockTypeId", ")", "{", "if", "(", "$", "this", "->", "_blockTypesById", "!==", "null", "&&", "array_key_exists", "(", "$", "blockTypeId", ",", "$", "this", "->", "_blockTypesById", ")", ")", "{", ...
Returns a block type by its ID. @param int $blockTypeId The block type ID. @return SuperTableBlockTypeModel|null The block type, or `null` if it didn’t exist.
[ "Returns", "a", "block", "type", "by", "its", "ID", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L120-L131
verbb/super-table
src/services/SuperTableService.php
SuperTableService.validateBlockType
public function validateBlockType(SuperTableBlockTypeModel $blockType, bool $validateUniques = true): bool { $validates = true; $reservedHandles = ['type']; $blockTypeRecord = $this->_getBlockTypeRecord($blockType); $blockTypeRecord->fieldId = $blockType->fieldId; if (!$blockTypeRecord->validate()) { $validates = false; $blockType->addErrors($blockTypeRecord->getErrors()); } // Reset this each time - normal Super Table fields won't be an issue, but when validation is called multiple times // its because its being embedded in another field (Matrix). Thus, we need to reset unique field handles, because they // can be different across multiple parent fields. $this->_uniqueFieldHandles = []; // Can't validate multiple new rows at once so we'll need to give these temporary context to avoid false unique // handle validation errors, and just validate those manually. Also apply the future fieldColumnPrefix so that // field handle validation takes its length into account. $contentService = Craft::$app->getContent(); $originalFieldContext = $contentService->fieldContext; $originalFieldColumnPrefix = $contentService->fieldColumnPrefix; $contentService->fieldContext = StringHelper::randomString(10); $contentService->fieldColumnPrefix = 'field_'; foreach ($blockType->getFields() as $field) { $field->validate(); if ($field->handle) { if (in_array($field->handle, $this->_uniqueFieldHandles, true)) { // This error *might* not be entirely accurate, but it's such an edge case that it's probably better // for the error to be worded for the common problem (two duplicate handles within the same block // type). $error = Craft::t('app', '{attribute} "{value}" has already been taken.', [ 'attribute' => Craft::t('app', 'Handle'), 'value' => $field->handle ]); $field->addError('handle', $error); } else { $this->_uniqueFieldHandles[] = $field->handle; } } if ($field->hasErrors()) { $blockType->hasFieldErrors = true; $validates = false; $blockType->addErrors($field->getErrors()); } // `type` is a restricted handle if (in_array($field->handle, $reservedHandles)) { $blockType->hasFieldErrors = true; $validates = false; $field->addErrors(['handle' => Craft::t('app', '"{handle}" is a reserved word.', ['handle' => $field->handle])]); } // Special-case for validating child Matrix fields if (get_class($field) == 'craft\fields\Matrix') { $matrixBlockTypes = $field->getBlockTypes(); foreach ($matrixBlockTypes as $matrixBlockType) { if ($matrixBlockType->hasFieldErrors) { $blockType->hasFieldErrors = true; $validates = false; // Store a generic error for our parent Super Table field to show a nested error exists $field->addErrors(['field' => 'general']); } } } } $contentService->fieldContext = $originalFieldContext; $contentService->fieldColumnPrefix = $originalFieldColumnPrefix; return $validates; }
php
public function validateBlockType(SuperTableBlockTypeModel $blockType, bool $validateUniques = true): bool { $validates = true; $reservedHandles = ['type']; $blockTypeRecord = $this->_getBlockTypeRecord($blockType); $blockTypeRecord->fieldId = $blockType->fieldId; if (!$blockTypeRecord->validate()) { $validates = false; $blockType->addErrors($blockTypeRecord->getErrors()); } // Reset this each time - normal Super Table fields won't be an issue, but when validation is called multiple times // its because its being embedded in another field (Matrix). Thus, we need to reset unique field handles, because they // can be different across multiple parent fields. $this->_uniqueFieldHandles = []; // Can't validate multiple new rows at once so we'll need to give these temporary context to avoid false unique // handle validation errors, and just validate those manually. Also apply the future fieldColumnPrefix so that // field handle validation takes its length into account. $contentService = Craft::$app->getContent(); $originalFieldContext = $contentService->fieldContext; $originalFieldColumnPrefix = $contentService->fieldColumnPrefix; $contentService->fieldContext = StringHelper::randomString(10); $contentService->fieldColumnPrefix = 'field_'; foreach ($blockType->getFields() as $field) { $field->validate(); if ($field->handle) { if (in_array($field->handle, $this->_uniqueFieldHandles, true)) { // This error *might* not be entirely accurate, but it's such an edge case that it's probably better // for the error to be worded for the common problem (two duplicate handles within the same block // type). $error = Craft::t('app', '{attribute} "{value}" has already been taken.', [ 'attribute' => Craft::t('app', 'Handle'), 'value' => $field->handle ]); $field->addError('handle', $error); } else { $this->_uniqueFieldHandles[] = $field->handle; } } if ($field->hasErrors()) { $blockType->hasFieldErrors = true; $validates = false; $blockType->addErrors($field->getErrors()); } // `type` is a restricted handle if (in_array($field->handle, $reservedHandles)) { $blockType->hasFieldErrors = true; $validates = false; $field->addErrors(['handle' => Craft::t('app', '"{handle}" is a reserved word.', ['handle' => $field->handle])]); } // Special-case for validating child Matrix fields if (get_class($field) == 'craft\fields\Matrix') { $matrixBlockTypes = $field->getBlockTypes(); foreach ($matrixBlockTypes as $matrixBlockType) { if ($matrixBlockType->hasFieldErrors) { $blockType->hasFieldErrors = true; $validates = false; // Store a generic error for our parent Super Table field to show a nested error exists $field->addErrors(['field' => 'general']); } } } } $contentService->fieldContext = $originalFieldContext; $contentService->fieldColumnPrefix = $originalFieldColumnPrefix; return $validates; }
[ "public", "function", "validateBlockType", "(", "SuperTableBlockTypeModel", "$", "blockType", ",", "bool", "$", "validateUniques", "=", "true", ")", ":", "bool", "{", "$", "validates", "=", "true", ";", "$", "reservedHandles", "=", "[", "'type'", "]", ";", "...
Validates a block type. If the block type doesn’t validate, any validation errors will be stored on the block type. @param SuperTableBlockTypeModel $blockType The block type. @param bool $validateUniques Whether the Name and Handle attributes should be validated to ensure they’re unique. Defaults to `true`. @return bool Whether the block type validated.
[ "Validates", "a", "block", "type", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L144-L227
verbb/super-table
src/services/SuperTableService.php
SuperTableService.saveBlockType
public function saveBlockType(SuperTableBlockTypeModel $blockType, bool $runValidation = true): bool { if ($runValidation && !$blockType->validate()) { return false; } $fieldsService = Craft::$app->getFields(); /** @var Field $parentField */ $parentField = $fieldsService->getFieldById($blockType->fieldId); $isNewBlockType = $blockType->getIsNew(); $projectConfig = Craft::$app->getProjectConfig(); $configData = [ 'field' => $parentField->uid, ]; // Now, take care of the field layout for this block type // ------------------------------------------------------------- $fieldLayoutFields = []; $sortOrder = 0; $configData['fields'] = []; foreach ($blockType->getFields() as $field) { $configData['fields'][$field->uid] = $fieldsService->createFieldConfig($field); $field->sortOrder = ++$sortOrder; $fieldLayoutFields[] = $field; } $fieldLayoutTab = new FieldLayoutTab(); $fieldLayoutTab->name = 'Content'; $fieldLayoutTab->sortOrder = 1; $fieldLayoutTab->setFields($fieldLayoutFields); $fieldLayout = $blockType->getFieldLayout(); if ($fieldLayout->uid) { $layoutUid = $fieldLayout->uid; } else { $layoutUid = StringHelper::UUID(); $fieldLayout->uid = $layoutUid; } $fieldLayout->setTabs([$fieldLayoutTab]); $fieldLayout->setFields($fieldLayoutFields); $fieldLayoutConfig = $fieldLayout->getConfig(); $configData['fieldLayouts'] = [ $layoutUid => $fieldLayoutConfig ]; $configPath = self::CONFIG_BLOCKTYPE_KEY . '.' . $blockType->uid; $projectConfig->set($configPath, $configData); if ($isNewBlockType) { $blockType->id = Db::idByUid('{{%supertableblocktypes}}', $blockType->uid); } return true; }
php
public function saveBlockType(SuperTableBlockTypeModel $blockType, bool $runValidation = true): bool { if ($runValidation && !$blockType->validate()) { return false; } $fieldsService = Craft::$app->getFields(); /** @var Field $parentField */ $parentField = $fieldsService->getFieldById($blockType->fieldId); $isNewBlockType = $blockType->getIsNew(); $projectConfig = Craft::$app->getProjectConfig(); $configData = [ 'field' => $parentField->uid, ]; // Now, take care of the field layout for this block type // ------------------------------------------------------------- $fieldLayoutFields = []; $sortOrder = 0; $configData['fields'] = []; foreach ($blockType->getFields() as $field) { $configData['fields'][$field->uid] = $fieldsService->createFieldConfig($field); $field->sortOrder = ++$sortOrder; $fieldLayoutFields[] = $field; } $fieldLayoutTab = new FieldLayoutTab(); $fieldLayoutTab->name = 'Content'; $fieldLayoutTab->sortOrder = 1; $fieldLayoutTab->setFields($fieldLayoutFields); $fieldLayout = $blockType->getFieldLayout(); if ($fieldLayout->uid) { $layoutUid = $fieldLayout->uid; } else { $layoutUid = StringHelper::UUID(); $fieldLayout->uid = $layoutUid; } $fieldLayout->setTabs([$fieldLayoutTab]); $fieldLayout->setFields($fieldLayoutFields); $fieldLayoutConfig = $fieldLayout->getConfig(); $configData['fieldLayouts'] = [ $layoutUid => $fieldLayoutConfig ]; $configPath = self::CONFIG_BLOCKTYPE_KEY . '.' . $blockType->uid; $projectConfig->set($configPath, $configData); if ($isNewBlockType) { $blockType->id = Db::idByUid('{{%supertableblocktypes}}', $blockType->uid); } return true; }
[ "public", "function", "saveBlockType", "(", "SuperTableBlockTypeModel", "$", "blockType", ",", "bool", "$", "runValidation", "=", "true", ")", ":", "bool", "{", "if", "(", "$", "runValidation", "&&", "!", "$", "blockType", "->", "validate", "(", ")", ")", ...
Saves a block type. @param SuperTableBlockTypeModel $blockType The block type to be saved. @param bool $validate Whether the block type should be validated before being saved. Defaults to `true`. @return bool @throws Exception if an error occurs when saving the block type @throws \Throwable if reasons
[ "Saves", "a", "block", "type", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L240-L303
verbb/super-table
src/services/SuperTableService.php
SuperTableService.handleChangedBlockType
public function handleChangedBlockType(ConfigEvent $event) { if ($this->ignoreProjectConfigChanges) { return; } $blockTypeUid = $event->tokenMatches[0]; $data = $event->newValue; $previousData = $event->oldValue; // Make sure the field has been synced $fieldId = Db::idByUid(Table::FIELDS, $data['field']); if ($fieldId === null) { Craft::$app->getProjectConfig()->defer($event, [$this, __FUNCTION__]); return; } $fieldsService = Craft::$app->getFields(); $contentService = Craft::$app->getContent(); $transaction = Craft::$app->getDb()->beginTransaction(); try { // Store the current contexts. $originalContentTable = $contentService->contentTable; $originalFieldContext = $contentService->fieldContext; $originalFieldColumnPrefix = $contentService->fieldColumnPrefix; $originalOldFieldColumnPrefix = $fieldsService->oldFieldColumnPrefix; // Get the block type record $blockTypeRecord = $this->_getBlockTypeRecord($blockTypeUid); // Set the basic info on the new block type record $blockTypeRecord->fieldId = $fieldId; $blockTypeRecord->uid = $blockTypeUid; // Make sure that alterations, if any, occur in the correct context. $contentService->fieldContext = 'superTableBlockType:' . $blockTypeUid; $contentService->fieldColumnPrefix = 'field_'; /** @var SuperTableField $superTableField */ $superTableField = $fieldsService->getFieldById($blockTypeRecord->fieldId); $contentService->contentTable = $superTableField->contentTable; $fieldsService->oldFieldColumnPrefix = 'field_'; $oldFields = $previousData['fields'] ?? []; $newFields = $data['fields'] ?? []; // Remove fields that this block type no longer has foreach ($oldFields as $fieldUid => $fieldData) { if (!array_key_exists($fieldUid, $newFields)) { $fieldsService->applyFieldDelete($fieldUid); } } // (Re)save all the fields that now exist for this block. foreach ($newFields as $fieldUid => $fieldData) { $fieldsService->applyFieldSave($fieldUid, $fieldData, 'superTableBlockType:' . $blockTypeUid); } // Refresh the schema cache Craft::$app->getDb()->getSchema()->refresh(); $contentService->fieldContext = $originalFieldContext; $contentService->fieldColumnPrefix = $originalFieldColumnPrefix; $contentService->contentTable = $originalContentTable; $fieldsService->oldFieldColumnPrefix = $originalOldFieldColumnPrefix; if (!empty($data['fieldLayouts'])) { // Save the field layout $layout = FieldLayout::createFromConfig(reset($data['fieldLayouts'])); $layout->id = $blockTypeRecord->fieldLayoutId; $layout->type = SuperTableBlockElement::class; $layout->uid = key($data['fieldLayouts']); $fieldsService->saveLayout($layout); $blockTypeRecord->fieldLayoutId = $layout->id; } else if ($blockTypeRecord->fieldLayoutId) { // Delete the field layout $fieldsService->deleteLayoutById($blockTypeRecord->fieldLayoutId); $blockTypeRecord->fieldLayoutId = null; } // Save it $blockTypeRecord->save(false); $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } // Clear caches unset( $this->_blockTypesById[$blockTypeRecord->id], $this->_blockTypesByFieldId[$blockTypeRecord->fieldId] ); $this->_fetchedAllBlockTypesForFieldId[$blockTypeRecord->fieldId] = false; }
php
public function handleChangedBlockType(ConfigEvent $event) { if ($this->ignoreProjectConfigChanges) { return; } $blockTypeUid = $event->tokenMatches[0]; $data = $event->newValue; $previousData = $event->oldValue; // Make sure the field has been synced $fieldId = Db::idByUid(Table::FIELDS, $data['field']); if ($fieldId === null) { Craft::$app->getProjectConfig()->defer($event, [$this, __FUNCTION__]); return; } $fieldsService = Craft::$app->getFields(); $contentService = Craft::$app->getContent(); $transaction = Craft::$app->getDb()->beginTransaction(); try { // Store the current contexts. $originalContentTable = $contentService->contentTable; $originalFieldContext = $contentService->fieldContext; $originalFieldColumnPrefix = $contentService->fieldColumnPrefix; $originalOldFieldColumnPrefix = $fieldsService->oldFieldColumnPrefix; // Get the block type record $blockTypeRecord = $this->_getBlockTypeRecord($blockTypeUid); // Set the basic info on the new block type record $blockTypeRecord->fieldId = $fieldId; $blockTypeRecord->uid = $blockTypeUid; // Make sure that alterations, if any, occur in the correct context. $contentService->fieldContext = 'superTableBlockType:' . $blockTypeUid; $contentService->fieldColumnPrefix = 'field_'; /** @var SuperTableField $superTableField */ $superTableField = $fieldsService->getFieldById($blockTypeRecord->fieldId); $contentService->contentTable = $superTableField->contentTable; $fieldsService->oldFieldColumnPrefix = 'field_'; $oldFields = $previousData['fields'] ?? []; $newFields = $data['fields'] ?? []; // Remove fields that this block type no longer has foreach ($oldFields as $fieldUid => $fieldData) { if (!array_key_exists($fieldUid, $newFields)) { $fieldsService->applyFieldDelete($fieldUid); } } // (Re)save all the fields that now exist for this block. foreach ($newFields as $fieldUid => $fieldData) { $fieldsService->applyFieldSave($fieldUid, $fieldData, 'superTableBlockType:' . $blockTypeUid); } // Refresh the schema cache Craft::$app->getDb()->getSchema()->refresh(); $contentService->fieldContext = $originalFieldContext; $contentService->fieldColumnPrefix = $originalFieldColumnPrefix; $contentService->contentTable = $originalContentTable; $fieldsService->oldFieldColumnPrefix = $originalOldFieldColumnPrefix; if (!empty($data['fieldLayouts'])) { // Save the field layout $layout = FieldLayout::createFromConfig(reset($data['fieldLayouts'])); $layout->id = $blockTypeRecord->fieldLayoutId; $layout->type = SuperTableBlockElement::class; $layout->uid = key($data['fieldLayouts']); $fieldsService->saveLayout($layout); $blockTypeRecord->fieldLayoutId = $layout->id; } else if ($blockTypeRecord->fieldLayoutId) { // Delete the field layout $fieldsService->deleteLayoutById($blockTypeRecord->fieldLayoutId); $blockTypeRecord->fieldLayoutId = null; } // Save it $blockTypeRecord->save(false); $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } // Clear caches unset( $this->_blockTypesById[$blockTypeRecord->id], $this->_blockTypesByFieldId[$blockTypeRecord->fieldId] ); $this->_fetchedAllBlockTypesForFieldId[$blockTypeRecord->fieldId] = false; }
[ "public", "function", "handleChangedBlockType", "(", "ConfigEvent", "$", "event", ")", "{", "if", "(", "$", "this", "->", "ignoreProjectConfigChanges", ")", "{", "return", ";", "}", "$", "blockTypeUid", "=", "$", "event", "->", "tokenMatches", "[", "0", "]",...
Handle block type change @param ConfigEvent $event
[ "Handle", "block", "type", "change" ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L310-L407
verbb/super-table
src/services/SuperTableService.php
SuperTableService.deleteBlockType
public function deleteBlockType(SuperTableBlockTypeModel $blockType): bool { Craft::$app->getProjectConfig()->remove(self::CONFIG_BLOCKTYPE_KEY . '.' . $blockType->uid); return true; }
php
public function deleteBlockType(SuperTableBlockTypeModel $blockType): bool { Craft::$app->getProjectConfig()->remove(self::CONFIG_BLOCKTYPE_KEY . '.' . $blockType->uid); return true; }
[ "public", "function", "deleteBlockType", "(", "SuperTableBlockTypeModel", "$", "blockType", ")", ":", "bool", "{", "Craft", "::", "$", "app", "->", "getProjectConfig", "(", ")", "->", "remove", "(", "self", "::", "CONFIG_BLOCKTYPE_KEY", ".", "'.'", ".", "$", ...
Deletes a block type. @param SuperTableBlockTypeModel $blockType The block type. @return bool Whether the block type was deleted successfully.
[ "Deletes", "a", "block", "type", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L415-L420
verbb/super-table
src/services/SuperTableService.php
SuperTableService.handleDeletedBlockType
public function handleDeletedBlockType(ConfigEvent $event) { if ($this->ignoreProjectConfigChanges) { return; } $blockTypeUid = $event->tokenMatches[0]; $blockTypeRecord = $this->_getBlockTypeRecord($blockTypeUid); if (!$blockTypeRecord->id) { return; } $db = Craft::$app->getDb(); $transaction = $db->beginTransaction(); try { $blockType = $this->getBlockTypeById($blockTypeRecord->id); if (!$blockType) { return; } // First delete the blocks of this type foreach (Craft::$app->getSites()->getAllSiteIds() as $siteId) { $blocks = SuperTableBlockElement::find() ->siteId($siteId) ->typeId($blockType->id) ->all(); foreach ($blocks as $block) { Craft::$app->getElements()->deleteElement($block); } } // Set the new contentTable $contentService = Craft::$app->getContent(); $fieldsService = Craft::$app->getFields(); $originalContentTable = $contentService->contentTable; /** @var SuperTableField $superTableField */ $superTableField = $fieldsService->getFieldById($blockType->fieldId); $contentService->contentTable = $superTableField->contentTable; // Set the new fieldColumnPrefix $originalFieldColumnPrefix = Craft::$app->getContent()->fieldColumnPrefix; Craft::$app->getContent()->fieldColumnPrefix = 'field_'; // Now delete the block type fields foreach ($blockType->getFields() as $field) { Craft::$app->getFields()->deleteField($field); } // Restore the contentTable and the fieldColumnPrefix to original values. Craft::$app->getContent()->fieldColumnPrefix = $originalFieldColumnPrefix; $contentService->contentTable = $originalContentTable; // Delete the field layout $fieldLayoutId = (new Query()) ->select(['fieldLayoutId']) ->from(['{{%supertableblocktypes}}']) ->where(['id' => $blockTypeRecord->id]) ->scalar(); // Delete the field layout Craft::$app->getFields()->deleteLayoutById($fieldLayoutId); // Finally delete the actual block type $db->createCommand() ->delete('{{%supertableblocktypes}}', ['id' => $blockTypeRecord->id]) ->execute(); $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } // Clear caches unset( $this->_blockTypesById[$blockTypeRecord->id], $this->_blockTypesByFieldId[$blockTypeRecord->fieldId], $this->_blockTypeRecordsById[$blockTypeRecord->id] ); $this->_fetchedAllBlockTypesForFieldId[$blockTypeRecord->fieldId] = false; }
php
public function handleDeletedBlockType(ConfigEvent $event) { if ($this->ignoreProjectConfigChanges) { return; } $blockTypeUid = $event->tokenMatches[0]; $blockTypeRecord = $this->_getBlockTypeRecord($blockTypeUid); if (!$blockTypeRecord->id) { return; } $db = Craft::$app->getDb(); $transaction = $db->beginTransaction(); try { $blockType = $this->getBlockTypeById($blockTypeRecord->id); if (!$blockType) { return; } // First delete the blocks of this type foreach (Craft::$app->getSites()->getAllSiteIds() as $siteId) { $blocks = SuperTableBlockElement::find() ->siteId($siteId) ->typeId($blockType->id) ->all(); foreach ($blocks as $block) { Craft::$app->getElements()->deleteElement($block); } } // Set the new contentTable $contentService = Craft::$app->getContent(); $fieldsService = Craft::$app->getFields(); $originalContentTable = $contentService->contentTable; /** @var SuperTableField $superTableField */ $superTableField = $fieldsService->getFieldById($blockType->fieldId); $contentService->contentTable = $superTableField->contentTable; // Set the new fieldColumnPrefix $originalFieldColumnPrefix = Craft::$app->getContent()->fieldColumnPrefix; Craft::$app->getContent()->fieldColumnPrefix = 'field_'; // Now delete the block type fields foreach ($blockType->getFields() as $field) { Craft::$app->getFields()->deleteField($field); } // Restore the contentTable and the fieldColumnPrefix to original values. Craft::$app->getContent()->fieldColumnPrefix = $originalFieldColumnPrefix; $contentService->contentTable = $originalContentTable; // Delete the field layout $fieldLayoutId = (new Query()) ->select(['fieldLayoutId']) ->from(['{{%supertableblocktypes}}']) ->where(['id' => $blockTypeRecord->id]) ->scalar(); // Delete the field layout Craft::$app->getFields()->deleteLayoutById($fieldLayoutId); // Finally delete the actual block type $db->createCommand() ->delete('{{%supertableblocktypes}}', ['id' => $blockTypeRecord->id]) ->execute(); $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } // Clear caches unset( $this->_blockTypesById[$blockTypeRecord->id], $this->_blockTypesByFieldId[$blockTypeRecord->fieldId], $this->_blockTypeRecordsById[$blockTypeRecord->id] ); $this->_fetchedAllBlockTypesForFieldId[$blockTypeRecord->fieldId] = false; }
[ "public", "function", "handleDeletedBlockType", "(", "ConfigEvent", "$", "event", ")", "{", "if", "(", "$", "this", "->", "ignoreProjectConfigChanges", ")", "{", "return", ";", "}", "$", "blockTypeUid", "=", "$", "event", "->", "tokenMatches", "[", "0", "]",...
Handle block type change @param ConfigEvent $event @throws \Throwable if reasons
[ "Handle", "block", "type", "change" ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L428-L513
verbb/super-table
src/services/SuperTableService.php
SuperTableService.validateFieldSettings
public function validateFieldSettings(SuperTableField $supertableField): bool { $validates = true; foreach ($supertableField->getBlockTypes() as $blockType) { if (!$this->validateBlockType($blockType, false)) { $validates = false; $blockTypeErrors = $blockType->getErrors(); // Make sure to look at validation for each field if (!$blockTypeErrors) { foreach ($blockType->getFields() as $blockTypeField) { $blockTypeFieldErrors = $blockTypeField->getErrors(); if ($blockTypeFieldErrors) { $blockTypeErrors[] = $blockTypeFieldErrors; } } } // Make sure to add any errors to the actual Super Table field. Really important when its // being nested in a Matrix field, because Matrix checks for the presence of errors - not the result // of this function (which correctly returns false). $supertableField->addErrors([ $blockType->id => $blockTypeErrors ]); } } return $validates; }
php
public function validateFieldSettings(SuperTableField $supertableField): bool { $validates = true; foreach ($supertableField->getBlockTypes() as $blockType) { if (!$this->validateBlockType($blockType, false)) { $validates = false; $blockTypeErrors = $blockType->getErrors(); // Make sure to look at validation for each field if (!$blockTypeErrors) { foreach ($blockType->getFields() as $blockTypeField) { $blockTypeFieldErrors = $blockTypeField->getErrors(); if ($blockTypeFieldErrors) { $blockTypeErrors[] = $blockTypeFieldErrors; } } } // Make sure to add any errors to the actual Super Table field. Really important when its // being nested in a Matrix field, because Matrix checks for the presence of errors - not the result // of this function (which correctly returns false). $supertableField->addErrors([ $blockType->id => $blockTypeErrors ]); } } return $validates; }
[ "public", "function", "validateFieldSettings", "(", "SuperTableField", "$", "supertableField", ")", ":", "bool", "{", "$", "validates", "=", "true", ";", "foreach", "(", "$", "supertableField", "->", "getBlockTypes", "(", ")", "as", "$", "blockType", ")", "{",...
Validates a Super Table field's settings. If the settings don’t validate, any validation errors will be stored on the settings model. @param SuperTableField $supertableField The Super Table field @return bool Whether the settings validated.
[ "Validates", "a", "Super", "Table", "field", "s", "settings", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L524-L553
verbb/super-table
src/services/SuperTableService.php
SuperTableService.saveSettings
public function saveSettings(SuperTableField $supertableField, bool $validate = true): bool { if (!$supertableField->contentTable) { // Silently fail if this is a migration or console request $request = Craft::$app->getRequest(); if ($request->getIsConsoleRequest() || $request->getUrl() == '/actions/update/updateDatabase') { return true; } throw new Exception('Unable to save a Super Table field’s settings without knowing its content table: ' . $supertableField->contentTable); } if ($validate && !$this->validateFieldSettings($supertableField)) { return false; } $db = Craft::$app->getDb(); $transaction = $db->beginTransaction(); try { // Do we need to create/rename the content table? if (!$db->tableExists($supertableField->contentTable)) { $oldContentTable = $supertableField->oldSettings['contentTable'] ?? null; if ($oldContentTable && $db->tableExists($oldContentTable)) { MigrationHelper::renameTable($oldContentTable, $supertableField->contentTable); } else { $this->_createContentTable($supertableField->contentTable); } } if (!Craft::$app->getProjectConfig()->areChangesPending(self::CONFIG_BLOCKTYPE_KEY)) { // Delete the old block types first, in case there's a handle conflict with one of the new ones $oldBlockTypes = $this->getBlockTypesByFieldId($supertableField->id); $oldBlockTypesById = []; foreach ($oldBlockTypes as $blockType) { $oldBlockTypesById[$blockType->id] = $blockType; } foreach ($supertableField->getBlockTypes() as $blockType) { if (!$blockType->getIsNew()) { unset($oldBlockTypesById[$blockType->id]); } } foreach ($oldBlockTypesById as $blockType) { $this->deleteBlockType($blockType); } $originalContentTable = Craft::$app->getContent()->contentTable; Craft::$app->getContent()->contentTable = $supertableField->contentTable; foreach ($supertableField->getBlockTypes() as $blockType) { $blockType->fieldId = $supertableField->id; $this->saveBlockType($blockType, false); } Craft::$app->getContent()->contentTable = $originalContentTable; } $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } // Clear caches unset( $this->_blockTypesByFieldId[$supertableField->id], $this->_fetchedAllBlockTypesForFieldId[$supertableField->id] ); return true; }
php
public function saveSettings(SuperTableField $supertableField, bool $validate = true): bool { if (!$supertableField->contentTable) { // Silently fail if this is a migration or console request $request = Craft::$app->getRequest(); if ($request->getIsConsoleRequest() || $request->getUrl() == '/actions/update/updateDatabase') { return true; } throw new Exception('Unable to save a Super Table field’s settings without knowing its content table: ' . $supertableField->contentTable); } if ($validate && !$this->validateFieldSettings($supertableField)) { return false; } $db = Craft::$app->getDb(); $transaction = $db->beginTransaction(); try { // Do we need to create/rename the content table? if (!$db->tableExists($supertableField->contentTable)) { $oldContentTable = $supertableField->oldSettings['contentTable'] ?? null; if ($oldContentTable && $db->tableExists($oldContentTable)) { MigrationHelper::renameTable($oldContentTable, $supertableField->contentTable); } else { $this->_createContentTable($supertableField->contentTable); } } if (!Craft::$app->getProjectConfig()->areChangesPending(self::CONFIG_BLOCKTYPE_KEY)) { // Delete the old block types first, in case there's a handle conflict with one of the new ones $oldBlockTypes = $this->getBlockTypesByFieldId($supertableField->id); $oldBlockTypesById = []; foreach ($oldBlockTypes as $blockType) { $oldBlockTypesById[$blockType->id] = $blockType; } foreach ($supertableField->getBlockTypes() as $blockType) { if (!$blockType->getIsNew()) { unset($oldBlockTypesById[$blockType->id]); } } foreach ($oldBlockTypesById as $blockType) { $this->deleteBlockType($blockType); } $originalContentTable = Craft::$app->getContent()->contentTable; Craft::$app->getContent()->contentTable = $supertableField->contentTable; foreach ($supertableField->getBlockTypes() as $blockType) { $blockType->fieldId = $supertableField->id; $this->saveBlockType($blockType, false); } Craft::$app->getContent()->contentTable = $originalContentTable; } $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } // Clear caches unset( $this->_blockTypesByFieldId[$supertableField->id], $this->_fetchedAllBlockTypesForFieldId[$supertableField->id] ); return true; }
[ "public", "function", "saveSettings", "(", "SuperTableField", "$", "supertableField", ",", "bool", "$", "validate", "=", "true", ")", ":", "bool", "{", "if", "(", "!", "$", "supertableField", "->", "contentTable", ")", "{", "// Silently fail if this is a migration...
Saves a Super Table field's settings. @param SuperTableField $supertableField The Super Table field @param bool $validate Whether the settings should be validated before being saved. @return bool Whether the settings saved successfully. @throws \Throwable if reasons
[ "Saves", "a", "Super", "Table", "field", "s", "settings", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L564-L640
verbb/super-table
src/services/SuperTableService.php
SuperTableService.deleteSuperTableField
public function deleteSuperTableField(SuperTableField $supertableField): bool { // Clear the schema cache $db = Craft::$app->getDb(); $db->getSchema()->refresh(); $transaction = $db->beginTransaction(); try { $originalContentTable = Craft::$app->getContent()->contentTable; Craft::$app->getContent()->contentTable = $supertableField->contentTable; // Delete the block types $blockTypes = $this->getBlockTypesByFieldId($supertableField->id); foreach ($blockTypes as $blockType) { $this->deleteBlockType($blockType); } // Drop the content table $db->createCommand() ->dropTable($supertableField->contentTable) ->execute(); Craft::$app->getContent()->contentTable = $originalContentTable; $transaction->commit(); return true; } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } }
php
public function deleteSuperTableField(SuperTableField $supertableField): bool { // Clear the schema cache $db = Craft::$app->getDb(); $db->getSchema()->refresh(); $transaction = $db->beginTransaction(); try { $originalContentTable = Craft::$app->getContent()->contentTable; Craft::$app->getContent()->contentTable = $supertableField->contentTable; // Delete the block types $blockTypes = $this->getBlockTypesByFieldId($supertableField->id); foreach ($blockTypes as $blockType) { $this->deleteBlockType($blockType); } // Drop the content table $db->createCommand() ->dropTable($supertableField->contentTable) ->execute(); Craft::$app->getContent()->contentTable = $originalContentTable; $transaction->commit(); return true; } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } }
[ "public", "function", "deleteSuperTableField", "(", "SuperTableField", "$", "supertableField", ")", ":", "bool", "{", "// Clear the schema cache", "$", "db", "=", "Craft", "::", "$", "app", "->", "getDb", "(", ")", ";", "$", "db", "->", "getSchema", "(", ")"...
Deletes a Super Table field. @param SuperTableField $supertableField The Super Table field. @return bool Whether the field was deleted successfully. @throws \Throwable
[ "Deletes", "a", "Super", "Table", "field", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L650-L683
verbb/super-table
src/services/SuperTableService.php
SuperTableService.defineContentTableName
public function defineContentTableName(SuperTableField $field): string { $baseName = 'stc_' . strtolower($field->handle); $db = Craft::$app->getDb(); $i = -1; do { $i++; $parentFieldId = ''; // Check if this field is inside a Matrix - we need to prefix this content table if so. if ($field->context != 'global') { $parentFieldContext = explode(':', $field->context); if ($parentFieldContext[0] == 'matrixBlockType') { $parentFieldUid = $parentFieldContext[1]; $parentFieldId = Db::idByUid('{{%matrixblocktypes}}', $parentFieldUid); } } if ($parentFieldId) { $baseName = 'stc_' . $parentFieldId . '_' . strtolower($field->handle); } $name = '{{%' . $baseName . ($i !== 0 ? '_' . $i : '') . '}}'; } while ($name !== $field->contentTable && $db->tableExists($name)); return $name; }
php
public function defineContentTableName(SuperTableField $field): string { $baseName = 'stc_' . strtolower($field->handle); $db = Craft::$app->getDb(); $i = -1; do { $i++; $parentFieldId = ''; // Check if this field is inside a Matrix - we need to prefix this content table if so. if ($field->context != 'global') { $parentFieldContext = explode(':', $field->context); if ($parentFieldContext[0] == 'matrixBlockType') { $parentFieldUid = $parentFieldContext[1]; $parentFieldId = Db::idByUid('{{%matrixblocktypes}}', $parentFieldUid); } } if ($parentFieldId) { $baseName = 'stc_' . $parentFieldId . '_' . strtolower($field->handle); } $name = '{{%' . $baseName . ($i !== 0 ? '_' . $i : '') . '}}'; } while ($name !== $field->contentTable && $db->tableExists($name)); return $name; }
[ "public", "function", "defineContentTableName", "(", "SuperTableField", "$", "field", ")", ":", "string", "{", "$", "baseName", "=", "'stc_'", ".", "strtolower", "(", "$", "field", "->", "handle", ")", ";", "$", "db", "=", "Craft", "::", "$", "app", "->"...
Defines a new Super Table content table name. @param SuperTableField $field @return string
[ "Defines", "a", "new", "Super", "Table", "content", "table", "name", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L702-L732
verbb/super-table
src/services/SuperTableService.php
SuperTableService.getBlockById
public function getBlockById(int $blockId, int $siteId = null) { /** @var SuperTableBlock|null $block */ $block = Craft::$app->getElements()->getElementById($blockId, SuperTableBlockElement::class, $siteId); return $block; }
php
public function getBlockById(int $blockId, int $siteId = null) { /** @var SuperTableBlock|null $block */ $block = Craft::$app->getElements()->getElementById($blockId, SuperTableBlockElement::class, $siteId); return $block; }
[ "public", "function", "getBlockById", "(", "int", "$", "blockId", ",", "int", "$", "siteId", "=", "null", ")", "{", "/** @var SuperTableBlock|null $block */", "$", "block", "=", "Craft", "::", "$", "app", "->", "getElements", "(", ")", "->", "getElementById", ...
Returns a block by its ID. @param int $blockId The Super Table block’s ID. @param int|null $siteId The site ID to return. Defaults to the current site. @return SuperTableBlock|null The Super Table block, or `null` if it didn’t exist.
[ "Returns", "a", "block", "by", "its", "ID", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L742-L748
verbb/super-table
src/services/SuperTableService.php
SuperTableService.saveField
public function saveField(SuperTableField $field, ElementInterface $owner) { // Is the owner being duplicated? /** @var Element $owner */ if ($owner->duplicateOf !== null) { /** @var SuperTableBlockQuery $query */ $query = $owner->duplicateOf->getFieldValue($field->handle); // If this is the first site the element is being duplicated for, or if the element is set to manage blocks // on a per-site basis, then we need to duplicate them for the new element $duplicateBlocks = !$owner->propagating || $field->localizeBlocks; } else { /** @var SuperTableBlockQuery $query */ $query = $owner->getFieldValue($field->handle); // If the element is brand new and propagating, and the field manages blocks on a per-site basis, // then we will need to duplicate the blocks for this site $duplicateBlocks = !$query->ownerId && $owner->propagating && $field->localizeBlocks; } // Skip if the element is propagating right now, and we don't need to duplicate the blocks if ($owner->propagating && !$duplicateBlocks) { return; } // Fetch the Super Table blocks /** @var SuperTableBlock[] $blocks */ $blocks = $query->getCachedResult() ?? (clone $query)->anyStatus()->all(); $elementsService = Craft::$app->getElements(); $transaction = Craft::$app->getDb()->beginTransaction(); try { // If we're duplicating an element, or the owner was a preexisting element, // make sure that the blocks for this field/owner respect the field's translation setting if ($owner->duplicateOf || $query->ownerId) { $this->_applyFieldTranslationSetting($owner->duplicateOf ?? $owner, $field); } $blockIds = []; // Only propagate the blocks if the owner isn't being propagated $propagate = !$owner->propagating; foreach ($blocks as $block) { if ($duplicateBlocks) { $block = $elementsService->duplicateElement($block, [ 'ownerId' => $owner->id, 'ownerSiteId' => $field->localizeBlocks ? $owner->siteId : null, 'siteId' => $owner->siteId, 'propagating' => false, ]); } else { $block->ownerId = $owner->id; $block->ownerSiteId = ($field->localizeBlocks ? $owner->siteId : null); $block->propagating = $owner->propagating; $elementsService->saveElement($block, false, $propagate); } $blockIds[] = $block->id; } // Delete any blocks that shouldn't be there anymore $deleteBlocksQuery = SuperTableBlockElement::find() ->anyStatus() ->ownerId($owner->id) ->fieldId($field->id) ->where(['not', ['elements.id' => $blockIds]]); if ($field->localizeBlocks) { $deleteBlocksQuery->ownerSiteId($owner->siteId); } else { $deleteBlocksQuery->siteId($owner->siteId); } foreach ($deleteBlocksQuery->all() as $deleteBlock) { $elementsService->deleteElement($deleteBlock); } $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } }
php
public function saveField(SuperTableField $field, ElementInterface $owner) { // Is the owner being duplicated? /** @var Element $owner */ if ($owner->duplicateOf !== null) { /** @var SuperTableBlockQuery $query */ $query = $owner->duplicateOf->getFieldValue($field->handle); // If this is the first site the element is being duplicated for, or if the element is set to manage blocks // on a per-site basis, then we need to duplicate them for the new element $duplicateBlocks = !$owner->propagating || $field->localizeBlocks; } else { /** @var SuperTableBlockQuery $query */ $query = $owner->getFieldValue($field->handle); // If the element is brand new and propagating, and the field manages blocks on a per-site basis, // then we will need to duplicate the blocks for this site $duplicateBlocks = !$query->ownerId && $owner->propagating && $field->localizeBlocks; } // Skip if the element is propagating right now, and we don't need to duplicate the blocks if ($owner->propagating && !$duplicateBlocks) { return; } // Fetch the Super Table blocks /** @var SuperTableBlock[] $blocks */ $blocks = $query->getCachedResult() ?? (clone $query)->anyStatus()->all(); $elementsService = Craft::$app->getElements(); $transaction = Craft::$app->getDb()->beginTransaction(); try { // If we're duplicating an element, or the owner was a preexisting element, // make sure that the blocks for this field/owner respect the field's translation setting if ($owner->duplicateOf || $query->ownerId) { $this->_applyFieldTranslationSetting($owner->duplicateOf ?? $owner, $field); } $blockIds = []; // Only propagate the blocks if the owner isn't being propagated $propagate = !$owner->propagating; foreach ($blocks as $block) { if ($duplicateBlocks) { $block = $elementsService->duplicateElement($block, [ 'ownerId' => $owner->id, 'ownerSiteId' => $field->localizeBlocks ? $owner->siteId : null, 'siteId' => $owner->siteId, 'propagating' => false, ]); } else { $block->ownerId = $owner->id; $block->ownerSiteId = ($field->localizeBlocks ? $owner->siteId : null); $block->propagating = $owner->propagating; $elementsService->saveElement($block, false, $propagate); } $blockIds[] = $block->id; } // Delete any blocks that shouldn't be there anymore $deleteBlocksQuery = SuperTableBlockElement::find() ->anyStatus() ->ownerId($owner->id) ->fieldId($field->id) ->where(['not', ['elements.id' => $blockIds]]); if ($field->localizeBlocks) { $deleteBlocksQuery->ownerSiteId($owner->siteId); } else { $deleteBlocksQuery->siteId($owner->siteId); } foreach ($deleteBlocksQuery->all() as $deleteBlock) { $elementsService->deleteElement($deleteBlock); } $transaction->commit(); } catch (\Throwable $e) { $transaction->rollBack(); throw $e; } }
[ "public", "function", "saveField", "(", "SuperTableField", "$", "field", ",", "ElementInterface", "$", "owner", ")", "{", "// Is the owner being duplicated?", "/** @var Element $owner */", "if", "(", "$", "owner", "->", "duplicateOf", "!==", "null", ")", "{", "/** @...
Saves a Super Table field. @param SuperTableField $field The Super Table field @param ElementInterface $owner The element the field is associated with @throws \Throwable if reasons
[ "Saves", "a", "Super", "Table", "field", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L758-L841
verbb/super-table
src/services/SuperTableService.php
SuperTableService._getBlockTypeRecord
private function _getBlockTypeRecord($blockType): SuperTableBlockTypeRecord { if (is_string($blockType)) { $blockTypeRecord = SuperTableBlockTypeRecord::findOne(['uid' => $blockType]) ?? new SuperTableBlockTypeRecord(); if (!$blockTypeRecord->getIsNewRecord()) { $this->_blockTypeRecordsById[$blockTypeRecord->id] = $blockTypeRecord; } return $blockTypeRecord; } if ($blockType->getIsNew()) { return new SuperTableBlockTypeRecord(); } if (isset($this->_blockTypeRecordsById[$blockType->id])) { return $this->_blockTypeRecordsById[$blockType->id]; } $blockTypeRecord = SuperTableBlockTypeRecord::findOne($blockType->id); if ($blockTypeRecord === null) { throw new SuperTableBlockTypeNotFoundException('Invalid block type ID: ' . $blockType->id); } return $this->_blockTypeRecordsById[$blockType->id] = $blockTypeRecord; }
php
private function _getBlockTypeRecord($blockType): SuperTableBlockTypeRecord { if (is_string($blockType)) { $blockTypeRecord = SuperTableBlockTypeRecord::findOne(['uid' => $blockType]) ?? new SuperTableBlockTypeRecord(); if (!$blockTypeRecord->getIsNewRecord()) { $this->_blockTypeRecordsById[$blockTypeRecord->id] = $blockTypeRecord; } return $blockTypeRecord; } if ($blockType->getIsNew()) { return new SuperTableBlockTypeRecord(); } if (isset($this->_blockTypeRecordsById[$blockType->id])) { return $this->_blockTypeRecordsById[$blockType->id]; } $blockTypeRecord = SuperTableBlockTypeRecord::findOne($blockType->id); if ($blockTypeRecord === null) { throw new SuperTableBlockTypeNotFoundException('Invalid block type ID: ' . $blockType->id); } return $this->_blockTypeRecordsById[$blockType->id] = $blockTypeRecord; }
[ "private", "function", "_getBlockTypeRecord", "(", "$", "blockType", ")", ":", "SuperTableBlockTypeRecord", "{", "if", "(", "is_string", "(", "$", "blockType", ")", ")", "{", "$", "blockTypeRecord", "=", "SuperTableBlockTypeRecord", "::", "findOne", "(", "[", "'...
Returns a block type record by its ID or creates a new one. @param SuperTableBlockTypeModel $blockType @return SuperTableBlockTypeRecord @throws SuperTableBlockTypeNotFoundException if $blockType->id is invalid
[ "Returns", "a", "block", "type", "record", "by", "its", "ID", "or", "creates", "a", "new", "one", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L872-L899
verbb/super-table
src/services/SuperTableService.php
SuperTableService._createContentTable
private function _createContentTable(string $tableName) { $migration = new CreateSuperTableContentTable([ 'tableName' => $tableName ]); ob_start(); $migration->up(); ob_end_clean(); }
php
private function _createContentTable(string $tableName) { $migration = new CreateSuperTableContentTable([ 'tableName' => $tableName ]); ob_start(); $migration->up(); ob_end_clean(); }
[ "private", "function", "_createContentTable", "(", "string", "$", "tableName", ")", "{", "$", "migration", "=", "new", "CreateSuperTableContentTable", "(", "[", "'tableName'", "=>", "$", "tableName", "]", ")", ";", "ob_start", "(", ")", ";", "$", "migration", ...
Creates the content table for a Super Table field. @param string $tableName @return void
[ "Creates", "the", "content", "table", "for", "a", "Super", "Table", "field", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L908-L917
verbb/super-table
src/services/SuperTableService.php
SuperTableService._applyFieldTranslationSetting
private function _applyFieldTranslationSetting(ElementInterface $owner, SuperTableField $field) { // If the field is translatable, see if there are any global blocks that should be localized if ($field->localizeBlocks) { $blockQuery = SuperTableBlockElement::find() ->fieldId($field->id) ->ownerId($owner->id) ->anyStatus() ->siteId($owner->siteId) ->ownerSiteId(':empty:'); $blocks = $blockQuery->all(); if (!empty($blocks)) { // Duplicate the blocks for each of the owner's other sites $elementsService = Craft::$app->getElements(); $siteIds = ArrayHelper::getColumn(ElementHelper::supportedSitesForElement($owner), 'siteId'); foreach ($siteIds as $siteId) { if ($siteId != $owner->siteId) { $blockQuery->siteId = $siteId; $siteBlocks = $blockQuery->all(); foreach ($siteBlocks as $siteBlock) { $elementsService->duplicateElement($siteBlock, [ 'siteId' => (int)$siteId, 'ownerSiteId' => (int)$siteId, ]); } } } // Now resave the blocks for this site foreach ($blocks as $block) { $block->ownerSiteId = $owner->siteId; Craft::$app->getElements()->saveElement($block, false); } } } else { // Otherwise, see if the field has any localized blocks that should be deleted $elementsService = Craft::$app->getElements(); foreach (Craft::$app->getSites()->getAllSiteIds() as $siteId) { if ($siteId != $owner->siteId) { $blocks = SuperTableBlockElement::find() ->fieldId($field->id) ->ownerId($owner->id) ->anyStatus() ->siteId($siteId) ->ownerSiteId($siteId) ->all(); foreach ($blocks as $block) { $elementsService->deleteElement($block); } } } } }
php
private function _applyFieldTranslationSetting(ElementInterface $owner, SuperTableField $field) { // If the field is translatable, see if there are any global blocks that should be localized if ($field->localizeBlocks) { $blockQuery = SuperTableBlockElement::find() ->fieldId($field->id) ->ownerId($owner->id) ->anyStatus() ->siteId($owner->siteId) ->ownerSiteId(':empty:'); $blocks = $blockQuery->all(); if (!empty($blocks)) { // Duplicate the blocks for each of the owner's other sites $elementsService = Craft::$app->getElements(); $siteIds = ArrayHelper::getColumn(ElementHelper::supportedSitesForElement($owner), 'siteId'); foreach ($siteIds as $siteId) { if ($siteId != $owner->siteId) { $blockQuery->siteId = $siteId; $siteBlocks = $blockQuery->all(); foreach ($siteBlocks as $siteBlock) { $elementsService->duplicateElement($siteBlock, [ 'siteId' => (int)$siteId, 'ownerSiteId' => (int)$siteId, ]); } } } // Now resave the blocks for this site foreach ($blocks as $block) { $block->ownerSiteId = $owner->siteId; Craft::$app->getElements()->saveElement($block, false); } } } else { // Otherwise, see if the field has any localized blocks that should be deleted $elementsService = Craft::$app->getElements(); foreach (Craft::$app->getSites()->getAllSiteIds() as $siteId) { if ($siteId != $owner->siteId) { $blocks = SuperTableBlockElement::find() ->fieldId($field->id) ->ownerId($owner->id) ->anyStatus() ->siteId($siteId) ->ownerSiteId($siteId) ->all(); foreach ($blocks as $block) { $elementsService->deleteElement($block); } } } } }
[ "private", "function", "_applyFieldTranslationSetting", "(", "ElementInterface", "$", "owner", ",", "SuperTableField", "$", "field", ")", "{", "// If the field is translatable, see if there are any global blocks that should be localized", "if", "(", "$", "field", "->", "localiz...
Applies the field's translation setting to a set of blocks. @param ElementInterface $owner @param SuperTableField $field
[ "Applies", "the", "field", "s", "translation", "setting", "to", "a", "set", "of", "blocks", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/services/SuperTableService.php#L925-L983
verbb/super-table
src/migrations/CreateSuperTableContentTable.php
CreateSuperTableContentTable.addForeignKeys
public function addForeignKeys() { $this->addForeignKey(null, $this->tableName, ['elementId'], '{{%elements}}', ['id'], 'CASCADE', null); $this->addForeignKey(null, $this->tableName, ['siteId'], '{{%sites}}', ['id'], 'CASCADE', 'CASCADE'); }
php
public function addForeignKeys() { $this->addForeignKey(null, $this->tableName, ['elementId'], '{{%elements}}', ['id'], 'CASCADE', null); $this->addForeignKey(null, $this->tableName, ['siteId'], '{{%sites}}', ['id'], 'CASCADE', 'CASCADE'); }
[ "public", "function", "addForeignKeys", "(", ")", "{", "$", "this", "->", "addForeignKey", "(", "null", ",", "$", "this", "->", "tableName", ",", "[", "'elementId'", "]", ",", "'{{%elements}}'", ",", "[", "'id'", "]", ",", "'CASCADE'", ",", "null", ")", ...
Adds the foreign keys.
[ "Adds", "the", "foreign", "keys", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/migrations/CreateSuperTableContentTable.php#L40-L44
verbb/super-table
src/models/SuperTableBlockTypeModel.php
SuperTableBlockTypeModel.getHandle
public function getHandle() { if (!isset($this->handle) && $this->fieldId) { $field = Craft::$app->fields->getFieldById($this->fieldId); foreach ($field->getBlockTypes() as $index => $blockType) { if ($blockType->id == $this->id) { $this->handle = $field->handle . '-' . $index; break; } } } return $this->handle; }
php
public function getHandle() { if (!isset($this->handle) && $this->fieldId) { $field = Craft::$app->fields->getFieldById($this->fieldId); foreach ($field->getBlockTypes() as $index => $blockType) { if ($blockType->id == $this->id) { $this->handle = $field->handle . '-' . $index; break; } } } return $this->handle; }
[ "public", "function", "getHandle", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "handle", ")", "&&", "$", "this", "->", "fieldId", ")", "{", "$", "field", "=", "Craft", "::", "$", "app", "->", "fields", "->", "getFieldById", "(",...
Fake handle for easier integrations. @return string
[ "Fake", "handle", "for", "easier", "integrations", "." ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/models/SuperTableBlockTypeModel.php#L90-L104
verbb/super-table
src/SuperTable.php
SuperTable.init
public function init() { parent::init(); self::$plugin = $this; $this->_setPluginComponents(); $this->_setLogging(); $this->_registerCpRoutes(); $this->_registerVariables(); $this->_registerFieldTypes(); $this->_registerElementTypes(); $this->_registerIntegrations(); $this->_registerProjectConfigEventListeners(); }
php
public function init() { parent::init(); self::$plugin = $this; $this->_setPluginComponents(); $this->_setLogging(); $this->_registerCpRoutes(); $this->_registerVariables(); $this->_registerFieldTypes(); $this->_registerElementTypes(); $this->_registerIntegrations(); $this->_registerProjectConfigEventListeners(); }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "self", "::", "$", "plugin", "=", "$", "this", ";", "$", "this", "->", "_setPluginComponents", "(", ")", ";", "$", "this", "->", "_setLogging", "(", ")", ";", "$", ...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/SuperTable.php#L48-L62
verbb/super-table
src/helpers/ProjectConfigData.php
ProjectConfigData.rebuildProjectConfig
public static function rebuildProjectConfig(): array { $data = []; $superTableBlockTypes = (new Query()) ->select([ 'bt.fieldId', 'bt.fieldLayoutId', 'bt.uid', 'f.uid AS field', ]) ->from(['{{%supertableblocktypes}} bt']) ->innerJoin('{{%fields}} f', '[[bt.fieldId]] = [[f.id]]') ->all(); $layoutIds = []; $blockTypeData = []; foreach ($superTableBlockTypes as $superTableBlockType) { $fieldId = $superTableBlockType['fieldId']; unset($superTableBlockType['fieldId']); $layoutIds[] = $superTableBlockType['fieldLayoutId']; $blockTypeData[$fieldId][$superTableBlockType['uid']] = $superTableBlockType; } $superTableFieldLayouts = self::_generateFieldLayoutArray($layoutIds); // Fetch the subfields $superTableSubfieldRows = (new Query()) ->select([ 'fields.id', 'fields.name', 'fields.handle', 'fields.instructions', 'fields.searchable', 'fields.translationMethod', 'fields.translationKeyFormat', 'fields.type', 'fields.settings', 'fields.context', 'fields.uid', 'fieldGroups.uid AS fieldGroup', ]) ->from(['{{%fields}} fields']) ->leftJoin('{{%fieldgroups}} fieldGroups', '[[fields.groupId]] = [[fieldGroups.id]]') ->where(['like', 'fields.context', 'superTableBlockType:']) ->all(); $superTableSubFields = []; $fieldService = Craft::$app->getFields(); // Massage the data and index by UID foreach ($superTableSubfieldRows as $superTableSubfieldRow) { $superTableSubfieldRow['settings'] = Json::decodeIfJson($superTableSubfieldRow['settings']); $fieldInstance = $fieldService->getFieldById($superTableSubfieldRow['id']); $superTableSubfieldRow['contentColumnType'] = $fieldInstance->getContentColumnType(); list (, $blockTypeUid) = explode(':', $superTableSubfieldRow['context']); if (empty($superTableSubFields[$blockTypeUid])) { $superTableSubFields[$blockTypeUid] = []; } $fieldUid = $superTableSubfieldRow['uid']; unset($superTableSubfieldRow['uid'], $superTableSubfieldRow['id'], $superTableSubfieldRow['context']); $superTableSubFields[$blockTypeUid][$fieldUid] = $superTableSubfieldRow; } foreach ($blockTypeData as &$blockTypes) { foreach ($blockTypes as &$blockType) { $blockTypeUid = $blockType['uid']; $layout = $superTableFieldLayouts[$blockType['fieldLayoutId']]; unset($blockType['uid'], $blockType['fieldLayoutId']); $blockType['fieldLayouts'] = [$layout['uid'] => ['tabs' => $layout['tabs']]]; $blockType['fields'] = $superTableSubFields[$blockTypeUid] ?? []; $data[$blockTypeUid] = $blockType; } } return ['superTableBlockTypes' => $data]; }
php
public static function rebuildProjectConfig(): array { $data = []; $superTableBlockTypes = (new Query()) ->select([ 'bt.fieldId', 'bt.fieldLayoutId', 'bt.uid', 'f.uid AS field', ]) ->from(['{{%supertableblocktypes}} bt']) ->innerJoin('{{%fields}} f', '[[bt.fieldId]] = [[f.id]]') ->all(); $layoutIds = []; $blockTypeData = []; foreach ($superTableBlockTypes as $superTableBlockType) { $fieldId = $superTableBlockType['fieldId']; unset($superTableBlockType['fieldId']); $layoutIds[] = $superTableBlockType['fieldLayoutId']; $blockTypeData[$fieldId][$superTableBlockType['uid']] = $superTableBlockType; } $superTableFieldLayouts = self::_generateFieldLayoutArray($layoutIds); // Fetch the subfields $superTableSubfieldRows = (new Query()) ->select([ 'fields.id', 'fields.name', 'fields.handle', 'fields.instructions', 'fields.searchable', 'fields.translationMethod', 'fields.translationKeyFormat', 'fields.type', 'fields.settings', 'fields.context', 'fields.uid', 'fieldGroups.uid AS fieldGroup', ]) ->from(['{{%fields}} fields']) ->leftJoin('{{%fieldgroups}} fieldGroups', '[[fields.groupId]] = [[fieldGroups.id]]') ->where(['like', 'fields.context', 'superTableBlockType:']) ->all(); $superTableSubFields = []; $fieldService = Craft::$app->getFields(); // Massage the data and index by UID foreach ($superTableSubfieldRows as $superTableSubfieldRow) { $superTableSubfieldRow['settings'] = Json::decodeIfJson($superTableSubfieldRow['settings']); $fieldInstance = $fieldService->getFieldById($superTableSubfieldRow['id']); $superTableSubfieldRow['contentColumnType'] = $fieldInstance->getContentColumnType(); list (, $blockTypeUid) = explode(':', $superTableSubfieldRow['context']); if (empty($superTableSubFields[$blockTypeUid])) { $superTableSubFields[$blockTypeUid] = []; } $fieldUid = $superTableSubfieldRow['uid']; unset($superTableSubfieldRow['uid'], $superTableSubfieldRow['id'], $superTableSubfieldRow['context']); $superTableSubFields[$blockTypeUid][$fieldUid] = $superTableSubfieldRow; } foreach ($blockTypeData as &$blockTypes) { foreach ($blockTypes as &$blockType) { $blockTypeUid = $blockType['uid']; $layout = $superTableFieldLayouts[$blockType['fieldLayoutId']]; unset($blockType['uid'], $blockType['fieldLayoutId']); $blockType['fieldLayouts'] = [$layout['uid'] => ['tabs' => $layout['tabs']]]; $blockType['fields'] = $superTableSubFields[$blockTypeUid] ?? []; $data[$blockTypeUid] = $blockType; } } return ['superTableBlockTypes' => $data]; }
[ "public", "static", "function", "rebuildProjectConfig", "(", ")", ":", "array", "{", "$", "data", "=", "[", "]", ";", "$", "superTableBlockTypes", "=", "(", "new", "Query", "(", ")", ")", "->", "select", "(", "[", "'bt.fieldId'", ",", "'bt.fieldLayoutId'",...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/helpers/ProjectConfigData.php#L16-L96
verbb/super-table
src/migrations/Install.php
Install.safeUp
public function safeUp() { if (!$this->db->tableExists('{{%supertableblocks}}')) { $this->createTables(); $this->createIndexes(); $this->addForeignKeys(); } return true; }
php
public function safeUp() { if (!$this->db->tableExists('{{%supertableblocks}}')) { $this->createTables(); $this->createIndexes(); $this->addForeignKeys(); } return true; }
[ "public", "function", "safeUp", "(", ")", "{", "if", "(", "!", "$", "this", "->", "db", "->", "tableExists", "(", "'{{%supertableblocks}}'", ")", ")", "{", "$", "this", "->", "createTables", "(", ")", ";", "$", "this", "->", "createIndexes", "(", ")", ...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/migrations/Install.php#L11-L20
verbb/super-table
src/migrations/Install.php
Install.createTables
protected function createTables() { $this->createTable('{{%supertableblocks}}', [ 'id' => $this->integer()->notNull(), 'ownerId' => $this->integer()->notNull(), 'ownerSiteId' => $this->integer(), 'fieldId' => $this->integer()->notNull(), 'typeId' => $this->integer()->notNull(), 'sortOrder' => $this->smallInteger()->unsigned(), 'deletedWithOwner' => $this->boolean()->null(), 'dateCreated' => $this->dateTime()->notNull(), 'dateUpdated' => $this->dateTime()->notNull(), 'uid' => $this->uid(), 'PRIMARY KEY([[id]])', ]); $this->createTable('{{%supertableblocktypes}}', [ 'id' => $this->primaryKey(), 'fieldId' => $this->integer()->notNull(), 'fieldLayoutId' => $this->integer(), 'dateCreated' => $this->dateTime()->notNull(), 'dateUpdated' => $this->dateTime()->notNull(), 'uid' => $this->uid(), ]); }
php
protected function createTables() { $this->createTable('{{%supertableblocks}}', [ 'id' => $this->integer()->notNull(), 'ownerId' => $this->integer()->notNull(), 'ownerSiteId' => $this->integer(), 'fieldId' => $this->integer()->notNull(), 'typeId' => $this->integer()->notNull(), 'sortOrder' => $this->smallInteger()->unsigned(), 'deletedWithOwner' => $this->boolean()->null(), 'dateCreated' => $this->dateTime()->notNull(), 'dateUpdated' => $this->dateTime()->notNull(), 'uid' => $this->uid(), 'PRIMARY KEY([[id]])', ]); $this->createTable('{{%supertableblocktypes}}', [ 'id' => $this->primaryKey(), 'fieldId' => $this->integer()->notNull(), 'fieldLayoutId' => $this->integer(), 'dateCreated' => $this->dateTime()->notNull(), 'dateUpdated' => $this->dateTime()->notNull(), 'uid' => $this->uid(), ]); }
[ "protected", "function", "createTables", "(", ")", "{", "$", "this", "->", "createTable", "(", "'{{%supertableblocks}}'", ",", "[", "'id'", "=>", "$", "this", "->", "integer", "(", ")", "->", "notNull", "(", ")", ",", "'ownerId'", "=>", "$", "this", "->"...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/verbb/super-table/blob/95b05389cc200d674c54401e4a3d8b5fc70c0712/src/migrations/Install.php#L30-L54
liuggio/fastest
src/Process/EnvCommandCreator.php
EnvCommandCreator.execute
public function execute($i, $maxProcesses, $suite, $currentProcessCounter, $isFirstOnItsThread = false) { return array_change_key_case(static::cleanEnvVariables($_SERVER) + $_ENV + [ self::ENV_TEST_CHANNEL => (int) $i, self::ENV_TEST_CHANNEL_READABLE => 'test_'.$i, self::ENV_TEST_CHANNELS_NUMBER => (int) $maxProcesses, self::ENV_TEST_ARGUMENT => (string) $suite, self::ENV_TEST_INCREMENTAL_NUMBER => (int) $currentProcessCounter, self::ENV_TEST_IS_FIRST_ON_CHANNEL => (int) $isFirstOnItsThread, ], CASE_UPPER); }
php
public function execute($i, $maxProcesses, $suite, $currentProcessCounter, $isFirstOnItsThread = false) { return array_change_key_case(static::cleanEnvVariables($_SERVER) + $_ENV + [ self::ENV_TEST_CHANNEL => (int) $i, self::ENV_TEST_CHANNEL_READABLE => 'test_'.$i, self::ENV_TEST_CHANNELS_NUMBER => (int) $maxProcesses, self::ENV_TEST_ARGUMENT => (string) $suite, self::ENV_TEST_INCREMENTAL_NUMBER => (int) $currentProcessCounter, self::ENV_TEST_IS_FIRST_ON_CHANNEL => (int) $isFirstOnItsThread, ], CASE_UPPER); }
[ "public", "function", "execute", "(", "$", "i", ",", "$", "maxProcesses", ",", "$", "suite", ",", "$", "currentProcessCounter", ",", "$", "isFirstOnItsThread", "=", "false", ")", "{", "return", "array_change_key_case", "(", "static", "::", "cleanEnvVariables", ...
create an array of env
[ "create", "an", "array", "of", "env" ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/src/Process/EnvCommandCreator.php#L15-L25
liuggio/fastest
adapters/Doctrine/DBAL/ConnectionFactory.php
ConnectionFactory.createConnection
public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = []) { if (isset($params['dbname'])) { $dbName = $this->getDbNameFromEnv($params['dbname']); } else { $dbName = $this->getDbNameFromEnv($params['master']['dbname']); } if ('pdo_sqlite' === $params['driver']) { if (isset($params['path'])) { $params['path'] = str_replace('__DBNAME__', $dbName, $params['path']); } if (isset($params['master']['path'])) { $params['master']['path'] = str_replace('__DBNAME__', $dbName, $params['master']['path']); } if (!empty($params['slaves'])) { foreach ($params['slaves'] as &$slave) { $slave['path'] = str_replace('__DBNAME__', $dbName, $slave['path']); } } } else { $params['dbname'] = $dbName; } return parent::createConnection($params, $config, $eventManager, $mappingTypes); }
php
public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = []) { if (isset($params['dbname'])) { $dbName = $this->getDbNameFromEnv($params['dbname']); } else { $dbName = $this->getDbNameFromEnv($params['master']['dbname']); } if ('pdo_sqlite' === $params['driver']) { if (isset($params['path'])) { $params['path'] = str_replace('__DBNAME__', $dbName, $params['path']); } if (isset($params['master']['path'])) { $params['master']['path'] = str_replace('__DBNAME__', $dbName, $params['master']['path']); } if (!empty($params['slaves'])) { foreach ($params['slaves'] as &$slave) { $slave['path'] = str_replace('__DBNAME__', $dbName, $slave['path']); } } } else { $params['dbname'] = $dbName; } return parent::createConnection($params, $config, $eventManager, $mappingTypes); }
[ "public", "function", "createConnection", "(", "array", "$", "params", ",", "Configuration", "$", "config", "=", "null", ",", "EventManager", "$", "eventManager", "=", "null", ",", "array", "$", "mappingTypes", "=", "[", "]", ")", "{", "if", "(", "isset", ...
Create a connection by name. @param array $params @param Configuration $config @param EventManager $eventManager @param array $mappingTypes @return \Doctrine\DBAL\Connection
[ "Create", "a", "connection", "by", "name", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Doctrine/DBAL/ConnectionFactory.php#L25-L52
liuggio/fastest
adapters/Behat2/features/bootstrap/Hooks.php
Hooks.rmdirRecursive
private static function rmdirRecursive($path) { $files = scandir($path); array_shift($files); array_shift($files); foreach ($files as $file) { $file = $path.DIRECTORY_SEPARATOR.$file; if (is_dir($file)) { self::rmdirRecursive($file); } else { unlink($file); } } rmdir($path); }
php
private static function rmdirRecursive($path) { $files = scandir($path); array_shift($files); array_shift($files); foreach ($files as $file) { $file = $path.DIRECTORY_SEPARATOR.$file; if (is_dir($file)) { self::rmdirRecursive($file); } else { unlink($file); } } rmdir($path); }
[ "private", "static", "function", "rmdirRecursive", "(", "$", "path", ")", "{", "$", "files", "=", "scandir", "(", "$", "path", ")", ";", "array_shift", "(", "$", "files", ")", ";", "array_shift", "(", "$", "files", ")", ";", "foreach", "(", "$", "fil...
Removes files and folders recursively at provided path. @param string $path
[ "Removes", "files", "and", "folders", "recursively", "at", "provided", "path", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat2/features/bootstrap/Hooks.php#L100-L116
liuggio/fastest
adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php
ListFeaturesProcessor.configure
public function configure(Command $command) { $command->addOption( 'list-features', null, InputOption::VALUE_NONE, 'Output a list of feature files to be executed by Behat' ); $command->addOption( 'list-scenarios', null, InputOption::VALUE_NONE, 'Output a list of individual scenarios to be executed by Behat' ); }
php
public function configure(Command $command) { $command->addOption( 'list-features', null, InputOption::VALUE_NONE, 'Output a list of feature files to be executed by Behat' ); $command->addOption( 'list-scenarios', null, InputOption::VALUE_NONE, 'Output a list of individual scenarios to be executed by Behat' ); }
[ "public", "function", "configure", "(", "Command", "$", "command", ")", "{", "$", "command", "->", "addOption", "(", "'list-features'", ",", "null", ",", "InputOption", "::", "VALUE_NONE", ",", "'Output a list of feature files to be executed by Behat'", ")", ";", "$...
{@inheritdoc}
[ "{" ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php#L45-L59
liuggio/fastest
adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php
ListFeaturesProcessor.execute
public function execute(InputInterface $input, OutputInterface $output) { $listFeatures = $input->getOption('list-features'); $listScenarios = $input->getOption('list-scenarios'); if (!$listFeatures && !$listScenarios) { return; } $results = []; if ($listFeatures) { $results = array_merge($results, $this->getFeatureFiles()); } else { $results = array_merge($results, $this->getScenarios()); } $output->writeln(implode(PHP_EOL, $results)); exit(0); }
php
public function execute(InputInterface $input, OutputInterface $output) { $listFeatures = $input->getOption('list-features'); $listScenarios = $input->getOption('list-scenarios'); if (!$listFeatures && !$listScenarios) { return; } $results = []; if ($listFeatures) { $results = array_merge($results, $this->getFeatureFiles()); } else { $results = array_merge($results, $this->getScenarios()); } $output->writeln(implode(PHP_EOL, $results)); exit(0); }
[ "public", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "listFeatures", "=", "$", "input", "->", "getOption", "(", "'list-features'", ")", ";", "$", "listScenarios", "=", "$", "input", "->",...
{@inheritdoc}
[ "{" ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php#L64-L82
liuggio/fastest
adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php
ListFeaturesProcessor.getScenarios
public function getScenarios() { $scenarios = []; foreach ($this->registry->getSuites() as $suite) { foreach ($this->locator->locateSpecifications($suite, '') as $feature) { foreach ($feature->getScenarios() as $key => $scenario) { $file = $feature->getFile(); $lines = [$scenario->getLine()]; if ($scenario instanceof OutlineNode) { $lines = $scenario->getExampleTable()->getLines(); array_shift($lines); } foreach ($lines as $line) { $scenarios[] = "$file:$line"; } } } } return $scenarios; }
php
public function getScenarios() { $scenarios = []; foreach ($this->registry->getSuites() as $suite) { foreach ($this->locator->locateSpecifications($suite, '') as $feature) { foreach ($feature->getScenarios() as $key => $scenario) { $file = $feature->getFile(); $lines = [$scenario->getLine()]; if ($scenario instanceof OutlineNode) { $lines = $scenario->getExampleTable()->getLines(); array_shift($lines); } foreach ($lines as $line) { $scenarios[] = "$file:$line"; } } } } return $scenarios; }
[ "public", "function", "getScenarios", "(", ")", "{", "$", "scenarios", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "registry", "->", "getSuites", "(", ")", "as", "$", "suite", ")", "{", "foreach", "(", "$", "this", "->", "locator", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php#L87-L110
liuggio/fastest
adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php
ListFeaturesProcessor.getFeatureFiles
private function getFeatureFiles() { $featureFiles = []; foreach ($this->registry->getSuites() as $suite) { foreach ($this->locator->locateSpecifications($suite, '') as $feature) { $featureFiles[] = $feature->getFile(); } } return $featureFiles; }
php
private function getFeatureFiles() { $featureFiles = []; foreach ($this->registry->getSuites() as $suite) { foreach ($this->locator->locateSpecifications($suite, '') as $feature) { $featureFiles[] = $feature->getFile(); } } return $featureFiles; }
[ "private", "function", "getFeatureFiles", "(", ")", "{", "$", "featureFiles", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "registry", "->", "getSuites", "(", ")", "as", "$", "suite", ")", "{", "foreach", "(", "$", "this", "->", "locator", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php#L115-L125
liuggio/fastest
adapters/Behat2/features/bootstrap/FeatureContext.php
FeatureContext.iRunBehat
public function iRunBehat($argumentsString = '') { $argumentsString = strtr($argumentsString, ['\'' => '"']); if ('/' === DIRECTORY_SEPARATOR) { $argumentsString .= ' 2>&1'; } exec($command = sprintf( '%s %s %s --no-time', BEHAT_PHP_BIN_PATH, escapeshellarg(BEHAT_BIN_PATH), $argumentsString ), $output, $return); $this->lastBehatStdOut = trim(implode("\n", $output)); }
php
public function iRunBehat($argumentsString = '') { $argumentsString = strtr($argumentsString, ['\'' => '"']); if ('/' === DIRECTORY_SEPARATOR) { $argumentsString .= ' 2>&1'; } exec($command = sprintf( '%s %s %s --no-time', BEHAT_PHP_BIN_PATH, escapeshellarg(BEHAT_BIN_PATH), $argumentsString ), $output, $return); $this->lastBehatStdOut = trim(implode("\n", $output)); }
[ "public", "function", "iRunBehat", "(", "$", "argumentsString", "=", "''", ")", "{", "$", "argumentsString", "=", "strtr", "(", "$", "argumentsString", ",", "[", "'\\''", "=>", "'\"'", "]", ")", ";", "if", "(", "'/'", "===", "DIRECTORY_SEPARATOR", ")", "...
Runs behat command with provided parameters. Taken from Behat's features/bootstrap/Hooks/FeatureContext::iRunBehat() with some modifications Copyright (c) 2011-2013 Konstantin Kudryashov <ever.zet@gmail.com> @When /^I run "behat(?: ([^"]*))?"$/ @param string $argumentsString
[ "Runs", "behat", "command", "with", "provided", "parameters", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat2/features/bootstrap/FeatureContext.php#L30-L46
liuggio/fastest
src/Command/ParallelCommand.php
ParallelCommand.doExecute
private function doExecute( InputInterface $input, OutputInterface $output, QueueInterface $queue, ProcessesManager $processManager ) { $processes = null; if ($this->isVerbose($output)) { $progressBar = new VerboseRenderer($queue->count(), $this->hasErrorSummary($input), $output); } else { $progressBar = new ProgressBarRenderer($queue->count(), $this->hasErrorSummary($input), $output, new ProgressBar($output)); } $progressBar->renderHeader($queue); while ($processManager->assertNProcessRunning($queue, $processes)) { $progressBar->renderBody($queue, $processes); } /* * @var Processes $processes */ $processes->cleanUP(); //it is not getting called with -p1 after the last process otherwise $processes->wait(function () use ($progressBar, $queue, $processes) { $progressBar->renderBody($queue, $processes); }); $progressBar->renderFooter($queue, $processes); return $processes; }
php
private function doExecute( InputInterface $input, OutputInterface $output, QueueInterface $queue, ProcessesManager $processManager ) { $processes = null; if ($this->isVerbose($output)) { $progressBar = new VerboseRenderer($queue->count(), $this->hasErrorSummary($input), $output); } else { $progressBar = new ProgressBarRenderer($queue->count(), $this->hasErrorSummary($input), $output, new ProgressBar($output)); } $progressBar->renderHeader($queue); while ($processManager->assertNProcessRunning($queue, $processes)) { $progressBar->renderBody($queue, $processes); } /* * @var Processes $processes */ $processes->cleanUP(); //it is not getting called with -p1 after the last process otherwise $processes->wait(function () use ($progressBar, $queue, $processes) { $progressBar->renderBody($queue, $processes); }); $progressBar->renderFooter($queue, $processes); return $processes; }
[ "private", "function", "doExecute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "QueueInterface", "$", "queue", ",", "ProcessesManager", "$", "processManager", ")", "{", "$", "processes", "=", "null", ";", "if", "(", "$", ...
@param InputInterface $input @param OutputInterface $output @param QueueInterface $queue @param ProcessesManager $processManager @return array
[ "@param", "InputInterface", "$input", "@param", "OutputInterface", "$output", "@param", "QueueInterface", "$queue", "@param", "ProcessesManager", "$processManager" ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/src/Command/ParallelCommand.php#L126-L156
liuggio/fastest
src/Command/ParallelCommand.php
ParallelCommand.formatDuration
private function formatDuration($milliseconds) { $hours = floor($milliseconds / 1000 / 3600); $milliseconds -= ($hours * 3600 * 1000); $minutes = floor($milliseconds / 1000 / 60); $milliseconds -= ($minutes * 60 * 1000); $seconds = floor($milliseconds / 1000); $milliseconds -= ($seconds * 1000); $values = [ 'hour' => $hours, 'minute' => $minutes, 'second' => $seconds, 'millisecond' => $milliseconds, ]; $parts = []; foreach ($values as $text => $value) { if ($value > 0) { $parts[] = $value.' '.$text.($value > 1 ? 's' : ''); } } return implode(' ', $parts); }
php
private function formatDuration($milliseconds) { $hours = floor($milliseconds / 1000 / 3600); $milliseconds -= ($hours * 3600 * 1000); $minutes = floor($milliseconds / 1000 / 60); $milliseconds -= ($minutes * 60 * 1000); $seconds = floor($milliseconds / 1000); $milliseconds -= ($seconds * 1000); $values = [ 'hour' => $hours, 'minute' => $minutes, 'second' => $seconds, 'millisecond' => $milliseconds, ]; $parts = []; foreach ($values as $text => $value) { if ($value > 0) { $parts[] = $value.' '.$text.($value > 1 ? 's' : ''); } } return implode(' ', $parts); }
[ "private", "function", "formatDuration", "(", "$", "milliseconds", ")", "{", "$", "hours", "=", "floor", "(", "$", "milliseconds", "/", "1000", "/", "3600", ")", ";", "$", "milliseconds", "-=", "(", "$", "hours", "*", "3600", "*", "1000", ")", ";", "...
Method to format duration to human readable format. @param int $milliseconds @return string
[ "Method", "to", "format", "duration", "to", "human", "readable", "format", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/src/Command/ParallelCommand.php#L196-L223
liuggio/fastest
src/Command/ParallelCommand.php
ParallelCommand.formatMemory
private function formatMemory($bytes) { $units = ['B', 'KiB', 'MiB', 'GiB']; $mod = 1024; $power = ($bytes > 0) ? (int) floor(log($bytes, $mod)) : 0; return sprintf('%01.2f %s', $bytes / pow($mod, $power), $units[$power]); }
php
private function formatMemory($bytes) { $units = ['B', 'KiB', 'MiB', 'GiB']; $mod = 1024; $power = ($bytes > 0) ? (int) floor(log($bytes, $mod)) : 0; return sprintf('%01.2f %s', $bytes / pow($mod, $power), $units[$power]); }
[ "private", "function", "formatMemory", "(", "$", "bytes", ")", "{", "$", "units", "=", "[", "'B'", ",", "'KiB'", ",", "'MiB'", ",", "'GiB'", "]", ";", "$", "mod", "=", "1024", ";", "$", "power", "=", "(", "$", "bytes", ">", "0", ")", "?", "(", ...
Method to format memory usage to human readable format. @param int $bytes @return string
[ "Method", "to", "format", "memory", "usage", "to", "human", "readable", "format", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/src/Command/ParallelCommand.php#L232-L239
liuggio/fastest
src/Process/Processes.php
Processes.wait
public function wait($terminationCallback = null, $addToCompletedQueue = true) { $lastProcessesRunningCount = $currentRunningProcessesCount = $this->countRunning(); while ($currentRunningProcessesCount > 0) { $currentRunningProcessesCount = $this->countRunning(); if ($lastProcessesRunningCount !== $currentRunningProcessesCount) { $lastProcessesRunningCount = $currentRunningProcessesCount; $this->cleanUP($addToCompletedQueue); if (null !== $terminationCallback) { call_user_func($terminationCallback); } } usleep(1000); } return true; }
php
public function wait($terminationCallback = null, $addToCompletedQueue = true) { $lastProcessesRunningCount = $currentRunningProcessesCount = $this->countRunning(); while ($currentRunningProcessesCount > 0) { $currentRunningProcessesCount = $this->countRunning(); if ($lastProcessesRunningCount !== $currentRunningProcessesCount) { $lastProcessesRunningCount = $currentRunningProcessesCount; $this->cleanUP($addToCompletedQueue); if (null !== $terminationCallback) { call_user_func($terminationCallback); } } usleep(1000); } return true; }
[ "public", "function", "wait", "(", "$", "terminationCallback", "=", "null", ",", "$", "addToCompletedQueue", "=", "true", ")", "{", "$", "lastProcessesRunningCount", "=", "$", "currentRunningProcessesCount", "=", "$", "this", "->", "countRunning", "(", ")", ";",...
@param callable $terminationCallback A callback to be called after one of the processes is terminated @param bool $addToCompletedQueue A flag that indicates if this process needs to be added to completedQueue @return bool
[ "@param", "callable", "$terminationCallback", "A", "callback", "to", "be", "called", "after", "one", "of", "the", "processes", "is", "terminated", "@param", "bool", "$addToCompletedQueue", "A", "flag", "that", "indicates", "if", "this", "process", "needs", "to", ...
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/src/Process/Processes.php#L114-L130
liuggio/fastest
adapters/Behat2/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php
ListFeaturesProcessor.process
public function process(InputInterface $input, OutputInterface $output) { $listFeatures = $input->getOption('list-features'); $listScenarios = $input->getOption('list-scenarios'); if (!$listFeatures && !$listScenarios) { return; } $results = []; $featurePaths = $this->container->get('behat.console.command')->getFeaturesPaths(); foreach ($featurePaths as $featurePath) { if ($listFeatures) { $results = array_merge($results, $this->_getFeatureFiles($featurePath)); } else { $results = array_merge($results, $this->_getScenarios($featurePath)); } } $output->writeln(implode(PHP_EOL, $results)); exit(0); }
php
public function process(InputInterface $input, OutputInterface $output) { $listFeatures = $input->getOption('list-features'); $listScenarios = $input->getOption('list-scenarios'); if (!$listFeatures && !$listScenarios) { return; } $results = []; $featurePaths = $this->container->get('behat.console.command')->getFeaturesPaths(); foreach ($featurePaths as $featurePath) { if ($listFeatures) { $results = array_merge($results, $this->_getFeatureFiles($featurePath)); } else { $results = array_merge($results, $this->_getScenarios($featurePath)); } } $output->writeln(implode(PHP_EOL, $results)); exit(0); }
[ "public", "function", "process", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "listFeatures", "=", "$", "input", "->", "getOption", "(", "'list-features'", ")", ";", "$", "listScenarios", "=", "$", "input", "->",...
Processes data from container and console input. @param InputInterface $input @param OutputInterface $output @throws \RuntimeException
[ "Processes", "data", "from", "container", "and", "console", "input", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat2/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php#L60-L81
liuggio/fastest
adapters/Behat2/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php
ListFeaturesProcessor._getScenarios
private function _getScenarios($featurePath) { $scenarios = []; /* @var $featureNodes \Behat\Gherkin\Node\FeatureNode[] */ $featureNodes = $this->container->get('gherkin')->load($featurePath); foreach ($featureNodes as $featureNode) { /* @var $scenario \Behat\Gherkin\Node\ScenarioNode */ foreach ($featureNode->getScenarios() as $scenario) { $file = $scenario->getFile(); $lines = [$scenario->getLine()]; if ($scenario instanceof OutlineNode) { $lines = $scenario->getExamples()->getRowLines(); array_shift($lines); } foreach ($lines as $line) { $scenarios[] = "$file:$line"; } } } return $scenarios; }
php
private function _getScenarios($featurePath) { $scenarios = []; /* @var $featureNodes \Behat\Gherkin\Node\FeatureNode[] */ $featureNodes = $this->container->get('gherkin')->load($featurePath); foreach ($featureNodes as $featureNode) { /* @var $scenario \Behat\Gherkin\Node\ScenarioNode */ foreach ($featureNode->getScenarios() as $scenario) { $file = $scenario->getFile(); $lines = [$scenario->getLine()]; if ($scenario instanceof OutlineNode) { $lines = $scenario->getExamples()->getRowLines(); array_shift($lines); } foreach ($lines as $line) { $scenarios[] = "$file:$line"; } } } return $scenarios; }
[ "private", "function", "_getScenarios", "(", "$", "featurePath", ")", "{", "$", "scenarios", "=", "[", "]", ";", "/* @var $featureNodes \\Behat\\Gherkin\\Node\\FeatureNode[] */", "$", "featureNodes", "=", "$", "this", "->", "container", "->", "get", "(", "'gherkin'"...
Returns an array of absolute feature file paths and scenarios line numbers. The format of the file path: /absolute/path/somefile.feature:XX @param string $featurePath @return array of strings
[ "Returns", "an", "array", "of", "absolute", "feature", "file", "paths", "and", "scenarios", "line", "numbers", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat2/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php#L94-L117
liuggio/fastest
adapters/Behat2/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php
ListFeaturesProcessor._getFeatureFiles
private function _getFeatureFiles($featurePath) { $featureFiles = []; /* @var $featureNodes \Behat\Gherkin\Node\FeatureNode[] */ $featureNodes = $this->container->get('gherkin')->load($featurePath); foreach ($featureNodes as $featureNode) { $featureFiles[] = $featureNode->getFile(); } return $featureFiles; }
php
private function _getFeatureFiles($featurePath) { $featureFiles = []; /* @var $featureNodes \Behat\Gherkin\Node\FeatureNode[] */ $featureNodes = $this->container->get('gherkin')->load($featurePath); foreach ($featureNodes as $featureNode) { $featureFiles[] = $featureNode->getFile(); } return $featureFiles; }
[ "private", "function", "_getFeatureFiles", "(", "$", "featurePath", ")", "{", "$", "featureFiles", "=", "[", "]", ";", "/* @var $featureNodes \\Behat\\Gherkin\\Node\\FeatureNode[] */", "$", "featureNodes", "=", "$", "this", "->", "container", "->", "get", "(", "'ghe...
Returns an array with the absolute paths of the feature files expanded from the $featurePath. @param string $featurePath @return array of strings
[ "Returns", "an", "array", "with", "the", "absolute", "paths", "of", "the", "feature", "files", "expanded", "from", "the", "$featurePath", "." ]
train
https://github.com/liuggio/fastest/blob/90e598ea1ed662b82ffc731a615f146f418c4669/adapters/Behat2/ListFeaturesExtension/Console/Processor/ListFeaturesProcessor.php#L126-L136
kEpEx/laravel-crud-generator
src/Console/Commands/CrudGeneratorCommand.php
CrudGeneratorCommand.handle
public function handle() { $modelname = strtolower($this->argument('model-name')); $prefix = \Config::get('database.connections.mysql.prefix'); $custom_table_name = $this->option('table-name'); $custom_controller = $this->option('custom-controller'); $singular = $this->option('singular'); $tocreate = []; if($modelname == 'all') { $pretables = json_decode(json_encode(DB::select("show tables")), true); $tables = []; foreach($pretables as $p) { list($key) = array_keys($p); $tables[] = $p[$key]; } $this->info("List of tables: ".implode($tables, ",")); foreach ($tables as $t) { // Ignore tables with different prefix if($prefix == '' || str_contains($t, $prefix)) { $t = strtolower(substr($t, strlen($prefix))); $toadd = ['modelname'=> str_singular($t), 'tablename'=>'']; if(str_plural($toadd['modelname']) != $t) { $toadd['tablename'] = $t; } $tocreate[] = $toadd; } } // Remove options not applicabe for multiples tables $custom_table_name = null; $custom_controller = null; $singular = null; } else { $tocreate = [ 'modelname' => $modelname, 'tablename' => '', ]; if($singular) { $tocreate['tablename'] = strtolower($modelname); } else if($custom_table_name) { $tocreate['tablename'] = $custom_table_name; } $tocreate = [$tocreate]; } foreach ($tocreate as $c) { $generator = new \CrudGenerator\CrudGeneratorService(); $generator->output = $this; $generator->appNamespace = Container::getInstance()->getNamespace(); $generator->modelName = ucfirst($c['modelname']); $generator->tableName = $c['tablename']; $generator->prefix = $prefix; $generator->force = $this->option('force'); $generator->layout = $this->option('master-layout'); $generator->controllerName = ucfirst(strtolower($custom_controller)) ?: str_plural($generator->modelName); $generator->Generate(); } }
php
public function handle() { $modelname = strtolower($this->argument('model-name')); $prefix = \Config::get('database.connections.mysql.prefix'); $custom_table_name = $this->option('table-name'); $custom_controller = $this->option('custom-controller'); $singular = $this->option('singular'); $tocreate = []; if($modelname == 'all') { $pretables = json_decode(json_encode(DB::select("show tables")), true); $tables = []; foreach($pretables as $p) { list($key) = array_keys($p); $tables[] = $p[$key]; } $this->info("List of tables: ".implode($tables, ",")); foreach ($tables as $t) { // Ignore tables with different prefix if($prefix == '' || str_contains($t, $prefix)) { $t = strtolower(substr($t, strlen($prefix))); $toadd = ['modelname'=> str_singular($t), 'tablename'=>'']; if(str_plural($toadd['modelname']) != $t) { $toadd['tablename'] = $t; } $tocreate[] = $toadd; } } // Remove options not applicabe for multiples tables $custom_table_name = null; $custom_controller = null; $singular = null; } else { $tocreate = [ 'modelname' => $modelname, 'tablename' => '', ]; if($singular) { $tocreate['tablename'] = strtolower($modelname); } else if($custom_table_name) { $tocreate['tablename'] = $custom_table_name; } $tocreate = [$tocreate]; } foreach ($tocreate as $c) { $generator = new \CrudGenerator\CrudGeneratorService(); $generator->output = $this; $generator->appNamespace = Container::getInstance()->getNamespace(); $generator->modelName = ucfirst($c['modelname']); $generator->tableName = $c['tablename']; $generator->prefix = $prefix; $generator->force = $this->option('force'); $generator->layout = $this->option('master-layout'); $generator->controllerName = ucfirst(strtolower($custom_controller)) ?: str_plural($generator->modelName); $generator->Generate(); } }
[ "public", "function", "handle", "(", ")", "{", "$", "modelname", "=", "strtolower", "(", "$", "this", "->", "argument", "(", "'model-name'", ")", ")", ";", "$", "prefix", "=", "\\", "Config", "::", "get", "(", "'database.connections.mysql.prefix'", ")", ";...
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/kEpEx/laravel-crud-generator/blob/72ded59c2d748b818a4ab44ef579e1d2b75a9ad0/src/Console/Commands/CrudGeneratorCommand.php#L41-L110
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Source/Country.php
Country.toOptionArray
public function toOptionArray() { if (count($this->options) == 0) { $this->options = $this->countryCollectionFactory->create()->toOptionArray(' '); } return $this->options; }
php
public function toOptionArray() { if (count($this->options) == 0) { $this->options = $this->countryCollectionFactory->create()->toOptionArray(' '); } return $this->options; }
[ "public", "function", "toOptionArray", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "options", ")", "==", "0", ")", "{", "$", "this", "->", "options", "=", "$", "this", "->", "countryCollectionFactory", "->", "create", "(", ")", "->", "...
get options as key value pair @return array
[ "get", "options", "as", "key", "value", "pair" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Source/Country.php#L48-L54
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Ajax/Stores.php
Stores.execute
public function execute() { $collection = $this->collectionFactory->create() ->addFieldToFilter('status', StoresModel::STATUS_ENABLED) ->addStoreFilter($this->storeManager->getStore()->getId()) ->getData(); $json = []; foreach ($collection as $stockist) { $json[] = $stockist; } return $this->resultJsonFactory->create()->setData($json); }
php
public function execute() { $collection = $this->collectionFactory->create() ->addFieldToFilter('status', StoresModel::STATUS_ENABLED) ->addStoreFilter($this->storeManager->getStore()->getId()) ->getData(); $json = []; foreach ($collection as $stockist) { $json[] = $stockist; } return $this->resultJsonFactory->create()->setData($json); }
[ "public", "function", "execute", "(", ")", "{", "$", "collection", "=", "$", "this", "->", "collectionFactory", "->", "create", "(", ")", "->", "addFieldToFilter", "(", "'status'", ",", "StoresModel", "::", "STATUS_ENABLED", ")", "->", "addStoreFilter", "(", ...
Load the page defined in view/frontend/layout/stockists_index_index.xml @return \Magento\Framework\Controller\Result\JsonFactory
[ "Load", "the", "page", "defined", "in", "view", "/", "frontend", "/", "layout", "/", "stockists_index_index", ".", "xml" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Ajax/Stores.php#L69-L80
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getStoresForFrontend
public function getStoresForFrontend() { $collection = $this->stockistsCollectionFactory->create() ->addFieldToSelect('*') ->addFieldToFilter('store_id', $this->getStoreId()) ->addFieldToFilter('status', Stores::STATUS_ENABLED) ->setOrder('name', 'ASC'); return $collection; }
php
public function getStoresForFrontend() { $collection = $this->stockistsCollectionFactory->create() ->addFieldToSelect('*') ->addFieldToFilter('store_id', $this->getStoreId()) ->addFieldToFilter('status', Stores::STATUS_ENABLED) ->setOrder('name', 'ASC'); return $collection; }
[ "public", "function", "getStoresForFrontend", "(", ")", "{", "$", "collection", "=", "$", "this", "->", "stockistsCollectionFactory", "->", "create", "(", ")", "->", "addFieldToSelect", "(", "'*'", ")", "->", "addFieldToFilter", "(", "'store_id'", ",", "$", "t...
return stockists collection @return CollectionFactory
[ "return", "stockists", "collection" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L154-L162
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getCountries
public function getCountries(): array { $loadCountries = $this->countryHelper->toOptionArray(); $countries = []; $i = 0; foreach ($loadCountries as $country ) { $i++; if ($i == 1) { //remove first element that is a select continue; } $countries[$country["value"]] = $country["label"]; } return $countries; }
php
public function getCountries(): array { $loadCountries = $this->countryHelper->toOptionArray(); $countries = []; $i = 0; foreach ($loadCountries as $country ) { $i++; if ($i == 1) { //remove first element that is a select continue; } $countries[$country["value"]] = $country["label"]; } return $countries; }
[ "public", "function", "getCountries", "(", ")", ":", "array", "{", "$", "loadCountries", "=", "$", "this", "->", "countryHelper", "->", "toOptionArray", "(", ")", ";", "$", "countries", "=", "[", "]", ";", "$", "i", "=", "0", ";", "foreach", "(", "$"...
get an array of country codes and country names: AF => Afganisthan @return array
[ "get", "an", "array", "of", "country", "codes", "and", "country", "names", ":", "AF", "=", ">", "Afganisthan" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L179-L193
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getLocationSettings
public function getLocationSettings(): int { return (int)$this->_scopeConfig->getValue(self::ASK_LOCATION_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getLocationSettings(): int { return (int)$this->_scopeConfig->getValue(self::ASK_LOCATION_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getLocationSettings", "(", ")", ":", "int", "{", "return", "(", "int", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "ASK_LOCATION_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", "}" ]
get location settings from configuration @return int
[ "get", "location", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L230-L233
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getZoomSettings
public function getZoomSettings(): int { return (int)$this->_scopeConfig->getValue(self::ZOOM_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getZoomSettings(): int { return (int)$this->_scopeConfig->getValue(self::ZOOM_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getZoomSettings", "(", ")", ":", "int", "{", "return", "(", "int", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "ZOOM_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", "}" ]
get zoom settings from configuration @return int
[ "get", "zoom", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L270-L273
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getSliderSettings
public function getSliderSettings(): int { return (int)$this->_scopeConfig->getValue(self::SLIDER_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getSliderSettings(): int { return (int)$this->_scopeConfig->getValue(self::SLIDER_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getSliderSettings", "(", ")", ":", "int", "{", "return", "(", "int", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "SLIDER_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", "}" ]
get slider settings from configuration @return int
[ "get", "slider", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L290-L293
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getOtherStoresSettings
public function getOtherStoresSettings(): int { return (int)$this->_scopeConfig->getValue(self::OTHER_STORES_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getOtherStoresSettings(): int { return (int)$this->_scopeConfig->getValue(self::OTHER_STORES_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getOtherStoresSettings", "(", ")", ":", "int", "{", "return", "(", "int", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "OTHER_STORES_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", "}" ...
get other stores settings from configuration @return int
[ "get", "other", "stores", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L300-L303
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getZoomIndividualSettings
public function getZoomIndividualSettings(): int { return (int)$this->_scopeConfig->getValue(self::ZOOM_INDIVIDUAL_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getZoomIndividualSettings(): int { return (int)$this->_scopeConfig->getValue(self::ZOOM_INDIVIDUAL_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getZoomIndividualSettings", "(", ")", ":", "int", "{", "return", "(", "int", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "ZOOM_INDIVIDUAL_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", ...
get individual zoom settings from configuration for store details page @return int
[ "get", "individual", "zoom", "settings", "from", "configuration", "for", "store", "details", "page" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L310-L313
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getLatitudeSettings
public function getLatitudeSettings(): float { return (float)$this->_scopeConfig->getValue(self::LATITUDE_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getLatitudeSettings(): float { return (float)$this->_scopeConfig->getValue(self::LATITUDE_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getLatitudeSettings", "(", ")", ":", "float", "{", "return", "(", "float", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "LATITUDE_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", "}" ]
get latitude settings from configuration @return float
[ "get", "latitude", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L320-L323
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getLongitudeSettings
public function getLongitudeSettings(): float { return (float)$this->_scopeConfig->getValue(self::LONGITUDE_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getLongitudeSettings(): float { return (float)$this->_scopeConfig->getValue(self::LONGITUDE_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getLongitudeSettings", "(", ")", ":", "float", "{", "return", "(", "float", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "LONGITUDE_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", "}" ]
get longitude settings from configuration @return float
[ "get", "longitude", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L330-L333
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getRadiusSettings
public function getRadiusSettings(): float { return (float)$this->_scopeConfig->getValue(self::RADIUS_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getRadiusSettings(): float { return (float)$this->_scopeConfig->getValue(self::RADIUS_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getRadiusSettings", "(", ")", ":", "float", "{", "return", "(", "float", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "RADIUS_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", "}" ]
get radius settings from configuration @return float
[ "get", "radius", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L340-L343
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getStrokeWeightSettings
public function getStrokeWeightSettings(): float { return (float)$this->_scopeConfig->getValue(self::STROKE_WEIGHT_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getStrokeWeightSettings(): float { return (float)$this->_scopeConfig->getValue(self::STROKE_WEIGHT_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getStrokeWeightSettings", "(", ")", ":", "float", "{", "return", "(", "float", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "STROKE_WEIGHT_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", ...
get stroke weight settings from configuration @return float
[ "get", "stroke", "weight", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L350-L353
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getStrokeOpacitySettings
public function getStrokeOpacitySettings(): float { return (float)$this->_scopeConfig->getValue(self::STROKE_OPACITY_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getStrokeOpacitySettings(): float { return (float)$this->_scopeConfig->getValue(self::STROKE_OPACITY_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getStrokeOpacitySettings", "(", ")", ":", "float", "{", "return", "(", "float", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "STROKE_OPACITY_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";"...
get stroke opacity settings from configuration @return float
[ "get", "stroke", "opacity", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L360-L363
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getFillOpacitySettings
public function getFillOpacitySettings(): float { return (float)$this->_scopeConfig->getValue(self::FILL_OPACITY_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
php
public function getFillOpacitySettings(): float { return (float)$this->_scopeConfig->getValue(self::FILL_OPACITY_CONFIG_PATH, ScopeInterface::SCOPE_STORE); }
[ "public", "function", "getFillOpacitySettings", "(", ")", ":", "float", "{", "return", "(", "float", ")", "$", "this", "->", "_scopeConfig", "->", "getValue", "(", "self", "::", "FILL_OPACITY_CONFIG_PATH", ",", "ScopeInterface", "::", "SCOPE_STORE", ")", ";", ...
get fill opacity settings from configuration @return string
[ "get", "fill", "opacity", "settings", "from", "configuration" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L380-L383
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Stockists.php
Stockists.getBaseImageUrl
public function getBaseImageUrl(): string { return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); }
php
public function getBaseImageUrl(): string { return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); }
[ "public", "function", "getBaseImageUrl", "(", ")", ":", "string", "{", "return", "$", "this", "->", "_storeManager", "->", "getStore", "(", ")", "->", "getBaseUrl", "(", "\\", "Magento", "\\", "Framework", "\\", "UrlInterface", "::", "URL_TYPE_MEDIA", ")", "...
get base image url @return string
[ "get", "base", "image", "url" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Stockists.php#L400-L403
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/Upload.php
Upload.execute
public function execute() { try { $result = $this->uploader->saveFileToTmpDir($this->getFieldName()); $result['cookie'] = [ 'name' => $this->_getSession()->getName(), 'value' => $this->_getSession()->getSessionId(), 'lifetime' => $this->_getSession()->getCookieLifetime(), 'path' => $this->_getSession()->getCookiePath(), 'domain' => $this->_getSession()->getCookieDomain(), ]; } catch (\Exception $e) { $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()]; } return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result); }
php
public function execute() { try { $result = $this->uploader->saveFileToTmpDir($this->getFieldName()); $result['cookie'] = [ 'name' => $this->_getSession()->getName(), 'value' => $this->_getSession()->getSessionId(), 'lifetime' => $this->_getSession()->getCookieLifetime(), 'path' => $this->_getSession()->getCookiePath(), 'domain' => $this->_getSession()->getCookieDomain(), ]; } catch (\Exception $e) { $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()]; } return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result); }
[ "public", "function", "execute", "(", ")", "{", "try", "{", "$", "result", "=", "$", "this", "->", "uploader", "->", "saveFileToTmpDir", "(", "$", "this", "->", "getFieldName", "(", ")", ")", ";", "$", "result", "[", "'cookie'", "]", "=", "[", "'name...
Upload file controller action @return \Magento\Framework\Controller\ResultInterface
[ "Upload", "file", "controller", "action" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/Upload.php#L57-L73
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/View/Index.php
Index.execute
public function execute() { $url = $this->_url->getCurrentUrl(); $moduleUrl = $this->stockistsConfig->getModuleUrlSettings(); preg_match('/'.$moduleUrl.'\/(.*)/', $url, $matches); $details = $this->getStoreDetails($matches[1]); $allStores = $this->getAllStockistStores(); $resultPage = $this->resultPageFactory->create(); $resultPage->getLayout()->getBlock('stockists.stores.individual')->setDetails($details); $resultPage->getLayout()->getBlock('stockists.stores.individual')->setAllStores($allStores ); $resultPage->getConfig()->getTitle()->set( $this->scopeConfig->getValue(self::META_TITLE_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); $resultPage->getConfig()->setDescription( $this->scopeConfig->getValue(self::META_DESCRIPTION_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); $resultPage->getConfig()->setKeywords( $this->scopeConfig->getValue(self::META_KEYWORDS_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); return $resultPage; }
php
public function execute() { $url = $this->_url->getCurrentUrl(); $moduleUrl = $this->stockistsConfig->getModuleUrlSettings(); preg_match('/'.$moduleUrl.'\/(.*)/', $url, $matches); $details = $this->getStoreDetails($matches[1]); $allStores = $this->getAllStockistStores(); $resultPage = $this->resultPageFactory->create(); $resultPage->getLayout()->getBlock('stockists.stores.individual')->setDetails($details); $resultPage->getLayout()->getBlock('stockists.stores.individual')->setAllStores($allStores ); $resultPage->getConfig()->getTitle()->set( $this->scopeConfig->getValue(self::META_TITLE_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); $resultPage->getConfig()->setDescription( $this->scopeConfig->getValue(self::META_DESCRIPTION_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); $resultPage->getConfig()->setKeywords( $this->scopeConfig->getValue(self::META_KEYWORDS_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); return $resultPage; }
[ "public", "function", "execute", "(", ")", "{", "$", "url", "=", "$", "this", "->", "_url", "->", "getCurrentUrl", "(", ")", ";", "$", "moduleUrl", "=", "$", "this", "->", "stockistsConfig", "->", "getModuleUrlSettings", "(", ")", ";", "preg_match", "(",...
Load the page defined in view/frontend/layout/stockists_index_index.xml @return \Magento\Framework\View\Result\Page
[ "Load", "the", "page", "defined", "in", "view", "/", "frontend", "/", "layout", "/", "stockists_index_index", ".", "xml" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/View/Index.php#L104-L130
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/View/Index.php
Index.getStoreDetails
public function getStoreDetails($url) { $collection = $this->getIndividualStore($url); foreach($collection as $stockist){ return $stockist->getData(); } }
php
public function getStoreDetails($url) { $collection = $this->getIndividualStore($url); foreach($collection as $stockist){ return $stockist->getData(); } }
[ "public", "function", "getStoreDetails", "(", "$", "url", ")", "{", "$", "collection", "=", "$", "this", "->", "getIndividualStore", "(", "$", "url", ")", ";", "foreach", "(", "$", "collection", "as", "$", "stockist", ")", "{", "return", "$", "stockist",...
return data from the loaded store details. Only the first store is returned if there are multiple urls @return array
[ "return", "data", "from", "the", "loaded", "store", "details", ".", "Only", "the", "first", "store", "is", "returned", "if", "there", "are", "multiple", "urls" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/View/Index.php#L137-L143
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/View/Index.php
Index.getAllStockistStores
public function getAllStockistStores() { $collection = $this->getAllStoresCollection(); $data = []; foreach($collection as $stockist){ $data[] = $stockist->getData(); } return $data; }
php
public function getAllStockistStores() { $collection = $this->getAllStoresCollection(); $data = []; foreach($collection as $stockist){ $data[] = $stockist->getData(); } return $data; }
[ "public", "function", "getAllStockistStores", "(", ")", "{", "$", "collection", "=", "$", "this", "->", "getAllStoresCollection", "(", ")", ";", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "collection", "as", "$", "stockist", ")", "{", "$", "...
return data from the loaded store details. Only the first store is returned if there are multiple urls @return array
[ "return", "data", "from", "the", "loaded", "store", "details", ".", "Only", "the", "first", "store", "is", "returned", "if", "there", "are", "multiple", "urls" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/View/Index.php#L150-L158
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/View/Index.php
Index.getIndividualStore
public function getIndividualStore($url) { $collection = $this->stockistsCollectionFactory->create() ->addFieldToSelect('*') ->addFieldToFilter('status', Stores::STATUS_ENABLED) ->addFieldToFilter('link', $url) ->addStoreFilter($this->storeManager->getStore()->getId()) ->setOrder('name', 'ASC'); return $collection; }
php
public function getIndividualStore($url) { $collection = $this->stockistsCollectionFactory->create() ->addFieldToSelect('*') ->addFieldToFilter('status', Stores::STATUS_ENABLED) ->addFieldToFilter('link', $url) ->addStoreFilter($this->storeManager->getStore()->getId()) ->setOrder('name', 'ASC'); return $collection; }
[ "public", "function", "getIndividualStore", "(", "$", "url", ")", "{", "$", "collection", "=", "$", "this", "->", "stockistsCollectionFactory", "->", "create", "(", ")", "->", "addFieldToSelect", "(", "'*'", ")", "->", "addFieldToFilter", "(", "'status'", ",",...
return stockists collection filtered by url @return CollectionFactory
[ "return", "stockists", "collection", "filtered", "by", "url" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/View/Index.php#L165-L174
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/ResourceModel/Stores.php
Stores._beforeDelete
public function _beforeDelete(AbstractModel $object) { $condition = ['stockist_id = ?' => (int)$object->getId()]; $this->getConnection()->delete($this->getTable('limesharp_stockists_stores'), $condition); return parent::_beforeDelete($object); }
php
public function _beforeDelete(AbstractModel $object) { $condition = ['stockist_id = ?' => (int)$object->getId()]; $this->getConnection()->delete($this->getTable('limesharp_stockists_stores'), $condition); return parent::_beforeDelete($object); }
[ "public", "function", "_beforeDelete", "(", "AbstractModel", "$", "object", ")", "{", "$", "condition", "=", "[", "'stockist_id = ?'", "=>", "(", "int", ")", "$", "object", "->", "getId", "(", ")", "]", ";", "$", "this", "->", "getConnection", "(", ")", ...
Process stockist data before deleting @param \Magento\Framework\Model\AbstractModel $object @return $this
[ "Process", "stockist", "data", "before", "deleting" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/ResourceModel/Stores.php#L100-L105
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/ResourceModel/Stores.php
Stores._beforeSave
public function _beforeSave(AbstractModel $object) { $object->setUpdatedAt($this->date->gmtDate()); if ($object->isObjectNew()) { $object->setCreatedAt($this->date->gmtDate()); } return parent::_beforeSave($object); }
php
public function _beforeSave(AbstractModel $object) { $object->setUpdatedAt($this->date->gmtDate()); if ($object->isObjectNew()) { $object->setCreatedAt($this->date->gmtDate()); } return parent::_beforeSave($object); }
[ "public", "function", "_beforeSave", "(", "AbstractModel", "$", "object", ")", "{", "$", "object", "->", "setUpdatedAt", "(", "$", "this", "->", "date", "->", "gmtDate", "(", ")", ")", ";", "if", "(", "$", "object", "->", "isObjectNew", "(", ")", ")", ...
before save callback @param AbstractModel|\Limesharp\Stockists\Model\Stores $object @return $this
[ "before", "save", "callback" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/ResourceModel/Stores.php#L113-L123
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Ui/Component/Listing/Column/Store/Options.php
Options.toOptionArray
public function toOptionArray() { if ($this->options !== null) { return $this->options; } $this->currentOptions['All Store Views']['label'] = __('All Store Views'); $this->currentOptions['All Store Views']['value'] = self::ALL_STORE_VIEWS; $this->generateCurrentOptions(); $this->options = array_values($this->currentOptions); return $this->options; }
php
public function toOptionArray() { if ($this->options !== null) { return $this->options; } $this->currentOptions['All Store Views']['label'] = __('All Store Views'); $this->currentOptions['All Store Views']['value'] = self::ALL_STORE_VIEWS; $this->generateCurrentOptions(); $this->options = array_values($this->currentOptions); return $this->options; }
[ "public", "function", "toOptionArray", "(", ")", "{", "if", "(", "$", "this", "->", "options", "!==", "null", ")", "{", "return", "$", "this", "->", "options", ";", "}", "$", "this", "->", "currentOptions", "[", "'All Store Views'", "]", "[", "'label'", ...
Get options @return array
[ "Get", "options" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Ui/Component/Listing/Column/Store/Options.php#L35-L49
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/ResourceModel/Stores/Collection.php
Collection.addStoreFilter
public function addStoreFilter($store, bool $withAdmin = true) { if (!$this->getFlag('store_filter_added')) { if ($store instanceof Store) { $store = [$store->getId()]; } if (!is_array($store)) { $store = [$store]; } if ($withAdmin) { $store[] = Store::DEFAULT_STORE_ID; } $filterParams = []; foreach ($store as $storeId) { $filterParams[]['finset'] = $storeId; } $this->addFilter('store_id', $filterParams, 'public'); } return $this; }
php
public function addStoreFilter($store, bool $withAdmin = true) { if (!$this->getFlag('store_filter_added')) { if ($store instanceof Store) { $store = [$store->getId()]; } if (!is_array($store)) { $store = [$store]; } if ($withAdmin) { $store[] = Store::DEFAULT_STORE_ID; } $filterParams = []; foreach ($store as $storeId) { $filterParams[]['finset'] = $storeId; } $this->addFilter('store_id', $filterParams, 'public'); } return $this; }
[ "public", "function", "addStoreFilter", "(", "$", "store", ",", "bool", "$", "withAdmin", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "getFlag", "(", "'store_filter_added'", ")", ")", "{", "if", "(", "$", "store", "instanceof", "Store", "...
Add filter by store @param int|\Magento\Store\Model\Store $store @param bool $withAdmin @return $this
[ "Add", "filter", "by", "store" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/ResourceModel/Stores/Collection.php#L130-L154
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/ResourceModel/Stores/Grid/ServiceCollection.php
ServiceCollection.loadData
public function loadData($printQuery = false, $logQuery = false) { if (!$this->isLoaded()) { $searchCriteria = $this->getSearchCriteria(); $searchResults = $this->stockistRepository->getList($searchCriteria); $this->_totalRecords = $searchResults->getTotalCount(); /** @var StockistInterface[] $stockists */ $stockists = $searchResults->getItems(); foreach ($stockists as $stockist) { $stockistItem = new DataObject(); $stockistItem->addData( $this->simpleDataObjectConverter->toFlatArray($stockist, StockistInterface::class) ); $this->_addItem($stockistItem); } $this->_setIsLoaded(); } return $this; }
php
public function loadData($printQuery = false, $logQuery = false) { if (!$this->isLoaded()) { $searchCriteria = $this->getSearchCriteria(); $searchResults = $this->stockistRepository->getList($searchCriteria); $this->_totalRecords = $searchResults->getTotalCount(); /** @var StockistInterface[] $stockists */ $stockists = $searchResults->getItems(); foreach ($stockists as $stockist) { $stockistItem = new DataObject(); $stockistItem->addData( $this->simpleDataObjectConverter->toFlatArray($stockist, StockistInterface::class) ); $this->_addItem($stockistItem); } $this->_setIsLoaded(); } return $this; }
[ "public", "function", "loadData", "(", "$", "printQuery", "=", "false", ",", "$", "logQuery", "=", "false", ")", "{", "if", "(", "!", "$", "this", "->", "isLoaded", "(", ")", ")", "{", "$", "searchCriteria", "=", "$", "this", "->", "getSearchCriteria",...
Load customer group collection data from service @param bool $printQuery @param bool $logQuery @return $this @SuppressWarnings(PHPMD.UnusedFormalParameter)
[ "Load", "customer", "group", "collection", "data", "from", "service" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/ResourceModel/Stores/Grid/ServiceCollection.php#L76-L94
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/ImportFile.php
ImportFile.execute
public function execute() { $stockist = null; $data = $this->getRequest()->getPostValue(); $filePath = $data["import"][0]["path"].$data["import"][0]["file"]; $resultRedirect = $this->resultRedirectFactory->create(); if ($data["import"][0]["path"] && $data["import"][0]["file"]) { try { $rawStockistData = $this->csvProcessor->getData($filePath); // first row of file represents headers $fileHeaders = $rawStockistData[0]; $processedStockistData = $this->filterFileData($fileHeaders, $rawStockistData); foreach($processedStockistData as $individualStockist) { $stockistId = !empty($individualStockist['stockist_id']) ? $individualStockist['stockist_id'] : null; if ($stockistId) { $stockist = $this->stockistRepository->getById((int)$stockistId); } else { unset($individualStockist['stockist_id']); $stockist = $this->stockistFactory->create(); } $storeIds = $individualStockist["store_id"] ?? $this->storeManager->getStore()->getId(); $this->dataObjectHelper->populateWithArray($stockist,$individualStockist,StockistInterface::class); $this->stockistRepository->save($stockist); if($individualStockist["link"]){ $this->saveUrlRewrite($individualStockist["link"], $stockist->getId(), $storeIds); } } $this->messageManager->addSuccessMessage(__('Your file has been imported successfully')); $resultRedirect->setPath('stockists/stores'); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/edit'); } catch (\Exception $e) { $this->messageManager->addErrorMessage(__('There was an error importing the file')); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/import'); } } else { $this->messageManager->addError(__('Please upload a file')); } return $resultRedirect; }
php
public function execute() { $stockist = null; $data = $this->getRequest()->getPostValue(); $filePath = $data["import"][0]["path"].$data["import"][0]["file"]; $resultRedirect = $this->resultRedirectFactory->create(); if ($data["import"][0]["path"] && $data["import"][0]["file"]) { try { $rawStockistData = $this->csvProcessor->getData($filePath); // first row of file represents headers $fileHeaders = $rawStockistData[0]; $processedStockistData = $this->filterFileData($fileHeaders, $rawStockistData); foreach($processedStockistData as $individualStockist) { $stockistId = !empty($individualStockist['stockist_id']) ? $individualStockist['stockist_id'] : null; if ($stockistId) { $stockist = $this->stockistRepository->getById((int)$stockistId); } else { unset($individualStockist['stockist_id']); $stockist = $this->stockistFactory->create(); } $storeIds = $individualStockist["store_id"] ?? $this->storeManager->getStore()->getId(); $this->dataObjectHelper->populateWithArray($stockist,$individualStockist,StockistInterface::class); $this->stockistRepository->save($stockist); if($individualStockist["link"]){ $this->saveUrlRewrite($individualStockist["link"], $stockist->getId(), $storeIds); } } $this->messageManager->addSuccessMessage(__('Your file has been imported successfully')); $resultRedirect->setPath('stockists/stores'); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/edit'); } catch (\Exception $e) { $this->messageManager->addErrorMessage(__('There was an error importing the file')); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/import'); } } else { $this->messageManager->addError(__('Please upload a file')); } return $resultRedirect; }
[ "public", "function", "execute", "(", ")", "{", "$", "stockist", "=", "null", ";", "$", "data", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getPostValue", "(", ")", ";", "$", "filePath", "=", "$", "data", "[", "\"import\"", "]", "[", "0"...
run the action @return \Magento\Backend\Model\View\Result\Redirect
[ "run", "the", "action" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/ImportFile.php#L149-L218
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/ImportFile.php
ImportFile.filterFileData
public function filterFileData(array $fileHeaders, array $rawStockistData) { $rowCount=0; $rawDataRows = []; foreach ($rawStockistData as $rowIndex => $dataRow) { // skip headers if ($rowIndex == 0) { continue; } // skip empty rows if (count($dataRow) <= 1) { unset($rawStockistData[$rowIndex]); continue; } /* we take rows from [0] = > value to [website] = base */ if ($rowIndex > 0) { foreach ($dataRow as $rowIndex => $dataRowNew) { $rawDataRows[$rowCount][$fileHeaders[$rowIndex]] = $dataRowNew; } } $rowCount++; } return $rawDataRows; }
php
public function filterFileData(array $fileHeaders, array $rawStockistData) { $rowCount=0; $rawDataRows = []; foreach ($rawStockistData as $rowIndex => $dataRow) { // skip headers if ($rowIndex == 0) { continue; } // skip empty rows if (count($dataRow) <= 1) { unset($rawStockistData[$rowIndex]); continue; } /* we take rows from [0] = > value to [website] = base */ if ($rowIndex > 0) { foreach ($dataRow as $rowIndex => $dataRowNew) { $rawDataRows[$rowCount][$fileHeaders[$rowIndex]] = $dataRowNew; } } $rowCount++; } return $rawDataRows; }
[ "public", "function", "filterFileData", "(", "array", "$", "fileHeaders", ",", "array", "$", "rawStockistData", ")", "{", "$", "rowCount", "=", "0", ";", "$", "rawDataRows", "=", "[", "]", ";", "foreach", "(", "$", "rawStockistData", "as", "$", "rowIndex",...
Filter data so that it will skip empty rows and headers @param array $fileHeaders @param array $rawStockistData @return array
[ "Filter", "data", "so", "that", "it", "will", "skip", "empty", "rows", "and", "headers" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/ImportFile.php#L235-L260
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/ImportFile.php
ImportFile.saveUrlRewrite
public function saveUrlRewrite($link, $id, $storeIds) { $moduleUrl = $this->stockistsConfig->getModuleUrlSettings(); $getCustomUrlRewrite = $moduleUrl . "/" . $link; $stockistId = $moduleUrl . "-" . $id; $storeIds = explode(",", $storeIds); foreach ($storeIds as $storeId){ $filterData = [ UrlRewriteService::STORE_ID => $storeId, UrlRewriteService::REQUEST_PATH => $getCustomUrlRewrite, UrlRewriteService::ENTITY_ID => $id, ]; // check if there is an entity with same url and same id $rewriteFinder = $this->urlFinder->findOneByData($filterData); // if there is then do nothing, otherwise proceed if ($rewriteFinder === null) { // check maybe there is an old url with this target path and delete it $filterDataOldUrl = [ UrlRewriteService::STORE_ID => $storeId, UrlRewriteService::REQUEST_PATH => $getCustomUrlRewrite, ]; $rewriteFinderOldUrl = $this->urlFinder->findOneByData($filterDataOldUrl); if ($rewriteFinderOldUrl !== null) { $this->urlRewrite->load($rewriteFinderOldUrl->getUrlRewriteId())->delete(); } // check maybe there is an old id with different url, in this case load the id and update the url $filterDataOldId = [ UrlRewriteService::STORE_ID => $storeId, UrlRewriteService::ENTITY_TYPE => $stockistId, UrlRewriteService::ENTITY_ID => $id ]; $rewriteFinderOldId = $this->urlFinder->findOneByData($filterDataOldId); if ($rewriteFinderOldId !== null) { $this->urlRewriteFactory->create()->load($rewriteFinderOldId->getUrlRewriteId()) ->setRequestPath($getCustomUrlRewrite) ->save(); continue; } // now we can save $this->urlRewriteFactory->create() ->setStoreId($storeId) ->setIdPath(rand(1, 100000)) ->setRequestPath($getCustomUrlRewrite) ->setTargetPath("stockists/view/index") ->setEntityType($stockistId) ->setEntityId($id) ->setIsAutogenerated(0) ->save(); } } }
php
public function saveUrlRewrite($link, $id, $storeIds) { $moduleUrl = $this->stockistsConfig->getModuleUrlSettings(); $getCustomUrlRewrite = $moduleUrl . "/" . $link; $stockistId = $moduleUrl . "-" . $id; $storeIds = explode(",", $storeIds); foreach ($storeIds as $storeId){ $filterData = [ UrlRewriteService::STORE_ID => $storeId, UrlRewriteService::REQUEST_PATH => $getCustomUrlRewrite, UrlRewriteService::ENTITY_ID => $id, ]; // check if there is an entity with same url and same id $rewriteFinder = $this->urlFinder->findOneByData($filterData); // if there is then do nothing, otherwise proceed if ($rewriteFinder === null) { // check maybe there is an old url with this target path and delete it $filterDataOldUrl = [ UrlRewriteService::STORE_ID => $storeId, UrlRewriteService::REQUEST_PATH => $getCustomUrlRewrite, ]; $rewriteFinderOldUrl = $this->urlFinder->findOneByData($filterDataOldUrl); if ($rewriteFinderOldUrl !== null) { $this->urlRewrite->load($rewriteFinderOldUrl->getUrlRewriteId())->delete(); } // check maybe there is an old id with different url, in this case load the id and update the url $filterDataOldId = [ UrlRewriteService::STORE_ID => $storeId, UrlRewriteService::ENTITY_TYPE => $stockistId, UrlRewriteService::ENTITY_ID => $id ]; $rewriteFinderOldId = $this->urlFinder->findOneByData($filterDataOldId); if ($rewriteFinderOldId !== null) { $this->urlRewriteFactory->create()->load($rewriteFinderOldId->getUrlRewriteId()) ->setRequestPath($getCustomUrlRewrite) ->save(); continue; } // now we can save $this->urlRewriteFactory->create() ->setStoreId($storeId) ->setIdPath(rand(1, 100000)) ->setRequestPath($getCustomUrlRewrite) ->setTargetPath("stockists/view/index") ->setEntityType($stockistId) ->setEntityId($id) ->setIsAutogenerated(0) ->save(); } } }
[ "public", "function", "saveUrlRewrite", "(", "$", "link", ",", "$", "id", ",", "$", "storeIds", ")", "{", "$", "moduleUrl", "=", "$", "this", "->", "stockistsConfig", "->", "getModuleUrlSettings", "(", ")", ";", "$", "getCustomUrlRewrite", "=", "$", "modul...
Saves the url rewrite for that specific store @param $link string @param $id int @param $storeIds string @return void
[ "Saves", "the", "url", "rewrite", "for", "that", "specific", "store" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/ImportFile.php#L280-L341
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/UrlRewrite.php
UrlRewrite.afterSave
public function afterSave() { $storeId = $this->storeManager->getStore()->getId(); if($this->hasDataChanges()){ //different from default $getCustomUrlRewrite = $this->_data["groups"]["stockist_content"]["fields"]["url"]["value"]; foreach ($this->_data as $key => $value) { if($key == "field" && $value == "url"){ $filterData = [ UrlRewriteService::TARGET_PATH => "stockists", UrlRewriteService::STORE_ID => $storeId ]; $rewriteFinder = $this->urlFinder->findOneByData($filterData); // if it was already set, just update it to the new one if($rewriteFinder){ if($getCustomUrlRewrite != "stockists"){ $this->urlRewrite->load($rewriteFinder->getUrlRewriteId()) ->setRequestPath($getCustomUrlRewrite) ->save(); } else { $this->urlRewrite->load($rewriteFinder->getUrlRewriteId())->delete(); } } else { if($getCustomUrlRewrite != "stockists"){ $this->urlRewrite->setStoreId($storeId) ->setIdPath(rand(1, 100000)) ->setRequestPath($getCustomUrlRewrite) ->setTargetPath("stockists") ->setIsSystem(0) ->save(); } } } } } return parent::afterSave(); }
php
public function afterSave() { $storeId = $this->storeManager->getStore()->getId(); if($this->hasDataChanges()){ //different from default $getCustomUrlRewrite = $this->_data["groups"]["stockist_content"]["fields"]["url"]["value"]; foreach ($this->_data as $key => $value) { if($key == "field" && $value == "url"){ $filterData = [ UrlRewriteService::TARGET_PATH => "stockists", UrlRewriteService::STORE_ID => $storeId ]; $rewriteFinder = $this->urlFinder->findOneByData($filterData); // if it was already set, just update it to the new one if($rewriteFinder){ if($getCustomUrlRewrite != "stockists"){ $this->urlRewrite->load($rewriteFinder->getUrlRewriteId()) ->setRequestPath($getCustomUrlRewrite) ->save(); } else { $this->urlRewrite->load($rewriteFinder->getUrlRewriteId())->delete(); } } else { if($getCustomUrlRewrite != "stockists"){ $this->urlRewrite->setStoreId($storeId) ->setIdPath(rand(1, 100000)) ->setRequestPath($getCustomUrlRewrite) ->setTargetPath("stockists") ->setIsSystem(0) ->save(); } } } } } return parent::afterSave(); }
[ "public", "function", "afterSave", "(", ")", "{", "$", "storeId", "=", "$", "this", "->", "storeManager", "->", "getStore", "(", ")", "->", "getId", "(", ")", ";", "if", "(", "$", "this", "->", "hasDataChanges", "(", ")", ")", "{", "//different from de...
after save callback @return $this
[ "after", "save", "callback" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/UrlRewrite.php#L121-L174
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Source/AbstractSource.php
AbstractSource.getOptions
public function getOptions() { $options = []; foreach ($this->toOptionArray() as $values) { $options[$values['value']] = __($values['label']); } return $options; }
php
public function getOptions() { $options = []; foreach ($this->toOptionArray() as $values) { $options[$values['value']] = __($values['label']); } return $options; }
[ "public", "function", "getOptions", "(", ")", "{", "$", "options", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "toOptionArray", "(", ")", "as", "$", "values", ")", "{", "$", "options", "[", "$", "values", "[", "'value'", "]", "]", "=", ...
get options as key value pair @return array
[ "get", "options", "as", "key", "value", "pair" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Source/AbstractSource.php#L67-L74
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Index/Index.php
Index.execute
public function execute() { $resultPage = $this->resultPageFactory->create(); $pageTitle = $this->scopeConfig->getValue(self::META_TITLE_CONFIG_PATH, ScopeInterface::SCOPE_STORE); $resultPage->getConfig()->getTitle()->set($pageTitle); $resultPage->getConfig()->setDescription( $this->scopeConfig->getValue(self::META_DESCRIPTION_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); $resultPage->getConfig()->setKeywords( $this->scopeConfig->getValue(self::META_KEYWORDS_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); if ($this->scopeConfig->isSetFlag(self::BREADCRUMBS_CONFIG_PATH, ScopeInterface::SCOPE_STORE)) { /** @var \Magento\Theme\Block\Html\Breadcrumbs $breadcrumbsBlock */ $breadcrumbsBlock = $resultPage->getLayout()->getBlock('breadcrumbs'); if ($breadcrumbsBlock) { $breadcrumbsBlock->addCrumb( 'home', [ 'label' => __('Home'), 'link' => $this->_url->getUrl('') ] ); $breadcrumbsBlock->addCrumb( 'stockists', [ 'label' => $pageTitle, ] ); } } return $resultPage; }
php
public function execute() { $resultPage = $this->resultPageFactory->create(); $pageTitle = $this->scopeConfig->getValue(self::META_TITLE_CONFIG_PATH, ScopeInterface::SCOPE_STORE); $resultPage->getConfig()->getTitle()->set($pageTitle); $resultPage->getConfig()->setDescription( $this->scopeConfig->getValue(self::META_DESCRIPTION_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); $resultPage->getConfig()->setKeywords( $this->scopeConfig->getValue(self::META_KEYWORDS_CONFIG_PATH, ScopeInterface::SCOPE_STORE) ); if ($this->scopeConfig->isSetFlag(self::BREADCRUMBS_CONFIG_PATH, ScopeInterface::SCOPE_STORE)) { /** @var \Magento\Theme\Block\Html\Breadcrumbs $breadcrumbsBlock */ $breadcrumbsBlock = $resultPage->getLayout()->getBlock('breadcrumbs'); if ($breadcrumbsBlock) { $breadcrumbsBlock->addCrumb( 'home', [ 'label' => __('Home'), 'link' => $this->_url->getUrl('') ] ); $breadcrumbsBlock->addCrumb( 'stockists', [ 'label' => $pageTitle, ] ); } } return $resultPage; }
[ "public", "function", "execute", "(", ")", "{", "$", "resultPage", "=", "$", "this", "->", "resultPageFactory", "->", "create", "(", ")", ";", "$", "pageTitle", "=", "$", "this", "->", "scopeConfig", "->", "getValue", "(", "self", "::", "META_TITLE_CONFIG_...
Load the page defined in view/frontend/layout/stockists_index_index.xml @return \Magento\Framework\View\Result\Page
[ "Load", "the", "page", "defined", "in", "view", "/", "frontend", "/", "layout", "/", "stockists_index_index", ".", "xml" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Index/Index.php#L65-L100
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Image.php
Image.rgbToString
public function rgbToString($rgbArray) { $result = []; foreach ($rgbArray as $value) { if (null === $value) { $result[] = 'null'; } else { $result[] = sprintf('%02s', dechex($value)); } } return implode($result); }
php
public function rgbToString($rgbArray) { $result = []; foreach ($rgbArray as $value) { if (null === $value) { $result[] = 'null'; } else { $result[] = sprintf('%02s', dechex($value)); } } return implode($result); }
[ "public", "function", "rgbToString", "(", "$", "rgbArray", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "rgbArray", "as", "$", "value", ")", "{", "if", "(", "null", "===", "$", "value", ")", "{", "$", "result", "[", "]", "=",...
Convert array of 3 items (decimal r, g, b) to string of their hex values @param int[] $rgbArray @return string
[ "Convert", "array", "of", "3", "items", "(", "decimal", "r", "g", "b", ")", "to", "string", "of", "their", "hex", "values" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Image.php#L460-L471
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Image.php
Image.setBaseFile
public function setBaseFile($file) { $this->isBaseFilePlaceholder = false; if ($file && 0 !== strpos($file, '/', 0)) { $file = '/' . $file; } $baseDir = $this->uploader->getBasePath(); if ($file) { if (!$this->fileExists($baseDir . $file) || !$this->checkMemory($baseDir . $file)) { $file = null; } } if (!$file) { $this->isBaseFilePlaceholder = true; $this->newFile = true; return $this; } $baseFile = $baseDir . $file; if (!$file || !$this->mediaDirectory->isFile($baseFile)) { throw new \Exception(__('We can\'t find the image file.')); } $this->baseFile = $baseFile; // build new filename (most important params) $path = [ $this->uploader->getBasePath(), 'cache', $this->storeManager->getStore()->getId(), $path[] = $this->getDestinationSubdir(), ]; if (!empty($this->width) || !empty($this->height)) { $path[] = "{$this->width}x{$this->height}"; } // add misk params as a hash $miscParams = [ ($this->keepAspectRatio ? '' : 'non') . 'proportional', ($this->keepFrame ? '' : 'no') . 'frame', ($this->keepTransparency ? '' : 'no') . 'transparency', ($this->constrainOnly ? 'do' : 'not') . 'constrainonly', $this->rgbToString($this->backgroundColor), 'angle' . $this->angle, 'quality' . $this->quality, ]; // if has watermark add watermark params to hash if ($this->getWatermarkFile()) { $miscParams[] = $this->getWatermarkFile(); $miscParams[] = $this->getWatermarkImageOpacity(); $miscParams[] = $this->getWatermarkPosition(); $miscParams[] = $this->getWatermarkWidth(); $miscParams[] = $this->getWatermarkHeight(); } $path[] = md5(implode('_', $miscParams)); // append prepared filename $this->newFile = implode('/', $path) . $file; // the $file contains heading slash return $this; }
php
public function setBaseFile($file) { $this->isBaseFilePlaceholder = false; if ($file && 0 !== strpos($file, '/', 0)) { $file = '/' . $file; } $baseDir = $this->uploader->getBasePath(); if ($file) { if (!$this->fileExists($baseDir . $file) || !$this->checkMemory($baseDir . $file)) { $file = null; } } if (!$file) { $this->isBaseFilePlaceholder = true; $this->newFile = true; return $this; } $baseFile = $baseDir . $file; if (!$file || !$this->mediaDirectory->isFile($baseFile)) { throw new \Exception(__('We can\'t find the image file.')); } $this->baseFile = $baseFile; // build new filename (most important params) $path = [ $this->uploader->getBasePath(), 'cache', $this->storeManager->getStore()->getId(), $path[] = $this->getDestinationSubdir(), ]; if (!empty($this->width) || !empty($this->height)) { $path[] = "{$this->width}x{$this->height}"; } // add misk params as a hash $miscParams = [ ($this->keepAspectRatio ? '' : 'non') . 'proportional', ($this->keepFrame ? '' : 'no') . 'frame', ($this->keepTransparency ? '' : 'no') . 'transparency', ($this->constrainOnly ? 'do' : 'not') . 'constrainonly', $this->rgbToString($this->backgroundColor), 'angle' . $this->angle, 'quality' . $this->quality, ]; // if has watermark add watermark params to hash if ($this->getWatermarkFile()) { $miscParams[] = $this->getWatermarkFile(); $miscParams[] = $this->getWatermarkImageOpacity(); $miscParams[] = $this->getWatermarkPosition(); $miscParams[] = $this->getWatermarkWidth(); $miscParams[] = $this->getWatermarkHeight(); } $path[] = md5(implode('_', $miscParams)); // append prepared filename $this->newFile = implode('/', $path) . $file; // the $file contains heading slash return $this; }
[ "public", "function", "setBaseFile", "(", "$", "file", ")", "{", "$", "this", "->", "isBaseFilePlaceholder", "=", "false", ";", "if", "(", "$", "file", "&&", "0", "!==", "strpos", "(", "$", "file", ",", "'/'", ",", "0", ")", ")", "{", "$", "file", ...
Set filenames for base file and new file @param string $file @return $this @throws \Exception @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.NPathComplexity)
[ "Set", "filenames", "for", "base", "file", "and", "new", "file" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Image.php#L482-L548
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Image.php
Image.setWatermark
public function setWatermark( $file, $position = null, $size = null, $width = null, $height = null, $opacity = null ) { if ($this->isBaseFilePlaceholder) { return $this; } if ($file) { $this->setWatermarkFile($file); } else { return $this; } if ($position) { $this->setWatermarkPosition($position); } if ($size) { $this->setWatermarkSize($size); } if ($width) { $this->setWatermarkWidth($width); } if ($height) { $this->setWatermarkHeight($height); } if ($opacity) { $this->setWatermarkImageOpacity($opacity); } $filePath = $this->getWatermarkFilePath(); if ($filePath) { $imagePreprocessor = $this->getImageProcessor(); $imagePreprocessor->setWatermarkPosition($this->getWatermarkPosition()); $imagePreprocessor->setWatermarkImageOpacity($this->getWatermarkImageOpacity()); $imagePreprocessor->setWatermarkWidth($this->getWatermarkWidth()); $imagePreprocessor->setWatermarkHeight($this->getWatermarkHeight()); $imagePreprocessor->watermark($filePath); } return $this; }
php
public function setWatermark( $file, $position = null, $size = null, $width = null, $height = null, $opacity = null ) { if ($this->isBaseFilePlaceholder) { return $this; } if ($file) { $this->setWatermarkFile($file); } else { return $this; } if ($position) { $this->setWatermarkPosition($position); } if ($size) { $this->setWatermarkSize($size); } if ($width) { $this->setWatermarkWidth($width); } if ($height) { $this->setWatermarkHeight($height); } if ($opacity) { $this->setWatermarkImageOpacity($opacity); } $filePath = $this->getWatermarkFilePath(); if ($filePath) { $imagePreprocessor = $this->getImageProcessor(); $imagePreprocessor->setWatermarkPosition($this->getWatermarkPosition()); $imagePreprocessor->setWatermarkImageOpacity($this->getWatermarkImageOpacity()); $imagePreprocessor->setWatermarkWidth($this->getWatermarkWidth()); $imagePreprocessor->setWatermarkHeight($this->getWatermarkHeight()); $imagePreprocessor->watermark($filePath); } return $this; }
[ "public", "function", "setWatermark", "(", "$", "file", ",", "$", "position", "=", "null", ",", "$", "size", "=", "null", ",", "$", "width", "=", "null", ",", "$", "height", "=", "null", ",", "$", "opacity", "=", "null", ")", "{", "if", "(", "$",...
Add watermark to image size param in format 100x200 @param string $file @param string $position @param array $size ['width' => int, 'height' => int] @param int $width @param int $height @param int $opacity @return $this @SuppressWarnings(PHPMD.NPathComplexity)
[ "Add", "watermark", "to", "image", "size", "param", "in", "format", "100x200" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Image.php#L655-L700
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Image.php
Image.getWatermarkFilePath
public function getWatermarkFilePath() { $filePath = false; if (!($file = $this->getWatermarkFile())) { return $filePath; } $baseDir = $this->uploader->getBasePath(); $candidates = [ $baseDir . '/watermark/stores/' . $this->storeManager->getStore()->getId() . $file, $baseDir . '/watermark/websites/' . $this->storeManager->getWebsite()->getId() . $file, $baseDir . '/watermark/default/' . $file, $baseDir . '/watermark/' . $file, ]; foreach ($candidates as $candidate) { if ($this->mediaDirectory->isExist($candidate)) { $filePath = $this->mediaDirectory->getAbsolutePath($candidate); break; } } if (!$filePath) { $filePath = $this->viewFileSystem->getStaticFileName($file); } return $filePath; }
php
public function getWatermarkFilePath() { $filePath = false; if (!($file = $this->getWatermarkFile())) { return $filePath; } $baseDir = $this->uploader->getBasePath(); $candidates = [ $baseDir . '/watermark/stores/' . $this->storeManager->getStore()->getId() . $file, $baseDir . '/watermark/websites/' . $this->storeManager->getWebsite()->getId() . $file, $baseDir . '/watermark/default/' . $file, $baseDir . '/watermark/' . $file, ]; foreach ($candidates as $candidate) { if ($this->mediaDirectory->isExist($candidate)) { $filePath = $this->mediaDirectory->getAbsolutePath($candidate); break; } } if (!$filePath) { $filePath = $this->viewFileSystem->getStaticFileName($file); } return $filePath; }
[ "public", "function", "getWatermarkFilePath", "(", ")", "{", "$", "filePath", "=", "false", ";", "if", "(", "!", "(", "$", "file", "=", "$", "this", "->", "getWatermarkFile", "(", ")", ")", ")", "{", "return", "$", "filePath", ";", "}", "$", "baseDir...
Get relative watermark file path or false if file not found @return string | bool
[ "Get", "relative", "watermark", "file", "path", "or", "false", "if", "file", "not", "found" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Image.php#L791-L817
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Image.php
Image.setWatermarkSize
public function setWatermarkSize($size) { if (is_array($size)) { $this->setWatermarkWidth($size['width'])->setWatermarkHeight($size['height']); } return $this; }
php
public function setWatermarkSize($size) { if (is_array($size)) { $this->setWatermarkWidth($size['width'])->setWatermarkHeight($size['height']); } return $this; }
[ "public", "function", "setWatermarkSize", "(", "$", "size", ")", "{", "if", "(", "is_array", "(", "$", "size", ")", ")", "{", "$", "this", "->", "setWatermarkWidth", "(", "$", "size", "[", "'width'", "]", ")", "->", "setWatermarkHeight", "(", "$", "siz...
Set watermark size @param array $size @return $this
[ "Set", "watermark", "size" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Image.php#L869-L875
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Image.php
Image.fileExists
public function fileExists($filename) { if ($this->mediaDirectory->isFile($filename)) { return true; } else { return $this->coreFileStorageDatabase->saveFileToFilesystem( $this->mediaDirectory->getAbsolutePath($filename) ); } }
php
public function fileExists($filename) { if ($this->mediaDirectory->isFile($filename)) { return true; } else { return $this->coreFileStorageDatabase->saveFileToFilesystem( $this->mediaDirectory->getAbsolutePath($filename) ); } }
[ "public", "function", "fileExists", "(", "$", "filename", ")", "{", "if", "(", "$", "this", "->", "mediaDirectory", "->", "isFile", "(", "$", "filename", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "$", "this", "->", "coreFileStor...
First check this file on FS If it doesn't exist - try to download it from DB @param string $filename @return bool
[ "First", "check", "this", "file", "on", "FS", "If", "it", "doesn", "t", "exist", "-", "try", "to", "download", "it", "from", "DB" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Image.php#L939-L948
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Image.php
Image.getResizedImageInfo
public function getResizedImageInfo() { $fileInfo = null; if ($this->newFile === true) { $asset = $this->assetRepo->createAsset( "Limesharp_Stockists::images/".$this->entityCode."/placeholder/{$this->getDestinationSubdir()}.jpg" ); $img = $asset->getSourceFile(); $fileInfo = getimagesize($img); } else { if ($this->mediaDirectory->isFile($this->mediaDirectory->getAbsolutePath($this->newFile))) { $fileInfo = getimagesize($this->mediaDirectory->getAbsolutePath($this->newFile)); } } return $fileInfo; }
php
public function getResizedImageInfo() { $fileInfo = null; if ($this->newFile === true) { $asset = $this->assetRepo->createAsset( "Limesharp_Stockists::images/".$this->entityCode."/placeholder/{$this->getDestinationSubdir()}.jpg" ); $img = $asset->getSourceFile(); $fileInfo = getimagesize($img); } else { if ($this->mediaDirectory->isFile($this->mediaDirectory->getAbsolutePath($this->newFile))) { $fileInfo = getimagesize($this->mediaDirectory->getAbsolutePath($this->newFile)); } } return $fileInfo; }
[ "public", "function", "getResizedImageInfo", "(", ")", "{", "$", "fileInfo", "=", "null", ";", "if", "(", "$", "this", "->", "newFile", "===", "true", ")", "{", "$", "asset", "=", "$", "this", "->", "assetRepo", "->", "createAsset", "(", "\"Limesharp_Sto...
Return resized image information @return array
[ "Return", "resized", "image", "information" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Image.php#L955-L970
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/Edit.php
Edit._initStockist
public function _initStockist() { $stockistId = $this->getRequest()->getParam('stockist_id'); $this->coreRegistry->register(RegistryConstants::CURRENT_STOCKIST_ID, $stockistId); return $stockistId; }
php
public function _initStockist() { $stockistId = $this->getRequest()->getParam('stockist_id'); $this->coreRegistry->register(RegistryConstants::CURRENT_STOCKIST_ID, $stockistId); return $stockistId; }
[ "public", "function", "_initStockist", "(", ")", "{", "$", "stockistId", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getParam", "(", "'stockist_id'", ")", ";", "$", "this", "->", "coreRegistry", "->", "register", "(", "RegistryConstants", "::", ...
Initialize current stockist and set it in the registry. @return int
[ "Initialize", "current", "stockist", "and", "set", "it", "in", "the", "registry", "." ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/Edit.php#L31-L37
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/Edit.php
Edit.execute
public function execute() { $stockistId = $this->_initStockist(); /** @var \Magento\Backend\Model\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $resultPage->setActiveMenu('Limesharp_Stockists::stores'); $resultPage->getConfig()->getTitle()->prepend(__('Stockists')); $resultPage->addBreadcrumb(__('Stockists'), __('Stockists'), $this->getUrl('stockists/stores')); if ($stockistId === null) { $resultPage->addBreadcrumb(__('New Store'), __('New Store')); $resultPage->getConfig()->getTitle()->prepend(__('New Store')); } else { $resultPage->addBreadcrumb(__('Edit Store'), __('Edit Store')); $resultPage->getConfig()->getTitle()->prepend( $this->stockistRepository->getById($stockistId)->getName() ); } return $resultPage; }
php
public function execute() { $stockistId = $this->_initStockist(); /** @var \Magento\Backend\Model\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $resultPage->setActiveMenu('Limesharp_Stockists::stores'); $resultPage->getConfig()->getTitle()->prepend(__('Stockists')); $resultPage->addBreadcrumb(__('Stockists'), __('Stockists'), $this->getUrl('stockists/stores')); if ($stockistId === null) { $resultPage->addBreadcrumb(__('New Store'), __('New Store')); $resultPage->getConfig()->getTitle()->prepend(__('New Store')); } else { $resultPage->addBreadcrumb(__('Edit Store'), __('Edit Store')); $resultPage->getConfig()->getTitle()->prepend( $this->stockistRepository->getById($stockistId)->getName() ); } return $resultPage; }
[ "public", "function", "execute", "(", ")", "{", "$", "stockistId", "=", "$", "this", "->", "_initStockist", "(", ")", ";", "/** @var \\Magento\\Backend\\Model\\View\\Result\\Page $resultPage */", "$", "resultPage", "=", "$", "this", "->", "resultPageFactory", "->", ...
Edit or create stockist @return \Magento\Backend\Model\View\Result\Page
[ "Edit", "or", "create", "stockist" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/Edit.php#L44-L63
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/Save.php
Save.execute
public function execute() { /** @var \Limesharp\Stockists\Api\Data\StockistInterface $stockist */ $stockist = null; $data = $this->getRequest()->getPostValue(); $id = !empty($data['stockist_id']) ? $data['stockist_id'] : null; $resultRedirect = $this->resultRedirectFactory->create(); try { if ($id) { $stockist = $this->stockistRepository->getById((int)$id); } else { unset($data['stockist_id']); $stockist = $this->stockistFactory->create(); } $image = $this->getUploader('image')->uploadFileAndGetName('image', $data); $data['image'] = $image; $details_image = $this->getUploader('image')->uploadFileAndGetName('details_image', $data); $data['details_image'] = $details_image; if(!empty($data['store_id']) && is_array($data['store_id'])) { if(in_array('0',$data['store_id'])){ $data['store_id'] = '0'; } else{ $data['store_id'] = implode(",", $data['store_id']); } } $storeId = $data["store_id"] ?? $this->storeManager->getStore()->getId(); $this->dataObjectHelper->populateWithArray($stockist, $data, StockistInterface::class); $this->stockistRepository->save($stockist); if($data["link"]) { $this->saveUrlRewrite($data["link"], $stockist->getId(), $storeId); } $this->messageManager->addSuccessMessage(__('You saved the store')); if ($this->getRequest()->getParam('back')) { $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $stockist->getId()]); } else { $resultRedirect->setPath('stockists/stores'); } } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $id]); } catch (\Exception $e) { $this->messageManager->addErrorMessage(__('There was a problem saving the store')); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/edit', ['store_id' => $id]); } return $resultRedirect; }
php
public function execute() { /** @var \Limesharp\Stockists\Api\Data\StockistInterface $stockist */ $stockist = null; $data = $this->getRequest()->getPostValue(); $id = !empty($data['stockist_id']) ? $data['stockist_id'] : null; $resultRedirect = $this->resultRedirectFactory->create(); try { if ($id) { $stockist = $this->stockistRepository->getById((int)$id); } else { unset($data['stockist_id']); $stockist = $this->stockistFactory->create(); } $image = $this->getUploader('image')->uploadFileAndGetName('image', $data); $data['image'] = $image; $details_image = $this->getUploader('image')->uploadFileAndGetName('details_image', $data); $data['details_image'] = $details_image; if(!empty($data['store_id']) && is_array($data['store_id'])) { if(in_array('0',$data['store_id'])){ $data['store_id'] = '0'; } else{ $data['store_id'] = implode(",", $data['store_id']); } } $storeId = $data["store_id"] ?? $this->storeManager->getStore()->getId(); $this->dataObjectHelper->populateWithArray($stockist, $data, StockistInterface::class); $this->stockistRepository->save($stockist); if($data["link"]) { $this->saveUrlRewrite($data["link"], $stockist->getId(), $storeId); } $this->messageManager->addSuccessMessage(__('You saved the store')); if ($this->getRequest()->getParam('back')) { $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $stockist->getId()]); } else { $resultRedirect->setPath('stockists/stores'); } } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $id]); } catch (\Exception $e) { $this->messageManager->addErrorMessage(__('There was a problem saving the store')); if ($stockist != null) { $this->storeStockistDataToSession( $this->dataObjectProcessor->buildOutputDataArray( $stockist, StockistInterface::class ) ); } $resultRedirect->setPath('stockists/stores/edit', ['store_id' => $id]); } return $resultRedirect; }
[ "public", "function", "execute", "(", ")", "{", "/** @var \\Limesharp\\Stockists\\Api\\Data\\StockistInterface $stockist */", "$", "stockist", "=", "null", ";", "$", "data", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getPostValue", "(", ")", ";", "$", ...
run the action @return \Magento\Backend\Model\View\Result\Redirect
[ "run", "the", "action" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/Save.php#L149-L217
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Adminhtml/Stores/Edit/Buttons/Delete.php
Delete.getButtonData
public function getButtonData() { $data = []; if ($this->getStockistId()) { $data = [ 'label' => __('Delete Store'), 'class' => 'delete', 'on_click' => 'deleteConfirm(\'' . __( 'Are you sure you want to do this?' ) . '\', \'' . $this->getDeleteUrl() . '\')', 'sort_order' => 20, ]; } return $data; }
php
public function getButtonData() { $data = []; if ($this->getStockistId()) { $data = [ 'label' => __('Delete Store'), 'class' => 'delete', 'on_click' => 'deleteConfirm(\'' . __( 'Are you sure you want to do this?' ) . '\', \'' . $this->getDeleteUrl() . '\')', 'sort_order' => 20, ]; } return $data; }
[ "public", "function", "getButtonData", "(", ")", "{", "$", "data", "=", "[", "]", ";", "if", "(", "$", "this", "->", "getStockistId", "(", ")", ")", "{", "$", "data", "=", "[", "'label'", "=>", "__", "(", "'Delete Store'", ")", ",", "'class'", "=>"...
get button data @return array
[ "get", "button", "data" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Adminhtml/Stores/Edit/Buttons/Delete.php#L30-L44
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Stores.php
Stores.setExtensionAttributes
public function setExtensionAttributes( \Magento\Catalog\Api\Data\CategoryProductLinkExtensionInterface $extensionAttributes ) { return $this->_setExtensionAttributes($extensionAttributes); }
php
public function setExtensionAttributes( \Magento\Catalog\Api\Data\CategoryProductLinkExtensionInterface $extensionAttributes ) { return $this->_setExtensionAttributes($extensionAttributes); }
[ "public", "function", "setExtensionAttributes", "(", "\\", "Magento", "\\", "Catalog", "\\", "Api", "\\", "Data", "\\", "CategoryProductLinkExtensionInterface", "$", "extensionAttributes", ")", "{", "return", "$", "this", "->", "_setExtensionAttributes", "(", "$", "...
{@inheritdoc} @param \Magento\Catalog\Api\Data\CategoryProductLinkExtensionInterface $extensionAttributes @return $this
[ "{", "@inheritdoc", "}" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Stores.php#L770-L774
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Stores.php
Stores.getAttributeList
private function getAttributeList() { if (!$this->attributeList) { $this->attributeList = \Magento\Framework\App\ObjectManager::getInstance()->get( \Limesharp\Stockists\Api\Data\Stockist\CustomAttributeListInterface::class ); } return $this->attributeList; }
php
private function getAttributeList() { if (!$this->attributeList) { $this->attributeList = \Magento\Framework\App\ObjectManager::getInstance()->get( \Limesharp\Stockists\Api\Data\Stockist\CustomAttributeListInterface::class ); } return $this->attributeList; }
[ "private", "function", "getAttributeList", "(", ")", "{", "if", "(", "!", "$", "this", "->", "attributeList", ")", "{", "$", "this", "->", "attributeList", "=", "\\", "Magento", "\\", "Framework", "\\", "App", "\\", "ObjectManager", "::", "getInstance", "(...
Get new AttributeList dependency for application code. @return \Magento\Customer\Model\Address\CustomAttributeListInterface
[ "Get", "new", "AttributeList", "dependency", "for", "application", "code", "." ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Stores.php#L788-L796
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Ui/Component/Listing/Column/Image.php
Image.prepareDataSource
public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { $fieldName = $this->getData('name'); foreach($dataSource['data']['items'] as & $item) { $url = ''; if ($item[$fieldName] != '') { $url = $this->imageModel->getBaseUrl().$this->imageModel->getBasePath().$item[$fieldName]; } $item[$fieldName . '_src'] = $url; $item[$fieldName . '_alt'] = $this->getAlt($item) ?: ''; $item[$fieldName . '_link'] = $this->urlBuilder->getUrl( 'limesharp_stockists/stockist/edit', ['store_id' => $item['store_id']] ); $item[$fieldName . '_orig_src'] = $url; } } return $dataSource; }
php
public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { $fieldName = $this->getData('name'); foreach($dataSource['data']['items'] as & $item) { $url = ''; if ($item[$fieldName] != '') { $url = $this->imageModel->getBaseUrl().$this->imageModel->getBasePath().$item[$fieldName]; } $item[$fieldName . '_src'] = $url; $item[$fieldName . '_alt'] = $this->getAlt($item) ?: ''; $item[$fieldName . '_link'] = $this->urlBuilder->getUrl( 'limesharp_stockists/stockist/edit', ['store_id' => $item['store_id']] ); $item[$fieldName . '_orig_src'] = $url; } } return $dataSource; }
[ "public", "function", "prepareDataSource", "(", "array", "$", "dataSource", ")", "{", "if", "(", "isset", "(", "$", "dataSource", "[", "'data'", "]", "[", "'items'", "]", ")", ")", "{", "$", "fieldName", "=", "$", "this", "->", "getData", "(", "'name'"...
Prepare Data Source @param array $dataSource @return array
[ "Prepare", "Data", "Source" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Ui/Component/Listing/Column/Image.php#L73-L93
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Ui/Component/Listing/Column/Image.php
Image.getAlt
public function getAlt($row) { $altField = $this->getData('config/altField') ?: self::ALT_FIELD; return isset($row[$altField]) ? $row[$altField] : null; }
php
public function getAlt($row) { $altField = $this->getData('config/altField') ?: self::ALT_FIELD; return isset($row[$altField]) ? $row[$altField] : null; }
[ "public", "function", "getAlt", "(", "$", "row", ")", "{", "$", "altField", "=", "$", "this", "->", "getData", "(", "'config/altField'", ")", "?", ":", "self", "::", "ALT_FIELD", ";", "return", "isset", "(", "$", "row", "[", "$", "altField", "]", ")"...
@param array $row @return null|string
[ "@param", "array", "$row" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Ui/Component/Listing/Column/Image.php#L100-L104
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/MassAction.php
MassAction.execute
public function execute() { try { $collection = $this->filter->getCollection($this->collectionFactory->create()); $collectionSize = $collection->getSize(); foreach ($collection as $stockist) { $this->massAction($stockist); } $this->messageManager->addSuccessMessage(__($this->successMessage, $collectionSize)); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __($this->errorMessage)); } $redirectResult = $this->resultRedirectFactory->create(); $redirectResult->setPath('limesharp_stockists/*/index'); return $redirectResult; }
php
public function execute() { try { $collection = $this->filter->getCollection($this->collectionFactory->create()); $collectionSize = $collection->getSize(); foreach ($collection as $stockist) { $this->massAction($stockist); } $this->messageManager->addSuccessMessage(__($this->successMessage, $collectionSize)); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __($this->errorMessage)); } $redirectResult = $this->resultRedirectFactory->create(); $redirectResult->setPath('limesharp_stockists/*/index'); return $redirectResult; }
[ "public", "function", "execute", "(", ")", "{", "try", "{", "$", "collection", "=", "$", "this", "->", "filter", "->", "getCollection", "(", "$", "this", "->", "collectionFactory", "->", "create", "(", ")", ")", ";", "$", "collectionSize", "=", "$", "c...
execute action @return \Magento\Backend\Model\View\Result\Redirect
[ "execute", "action" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/MassAction.php#L92-L109
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Stores/DataProvider.php
DataProvider.prepareMeta
public function prepareMeta(array $meta) { $meta = parent::getMeta(); /** @var ModifierInterface $modifier */ foreach ($this->pool->getModifiersInstances() as $modifier) { $meta = $modifier->modifyMeta($meta); } return $meta; }
php
public function prepareMeta(array $meta) { $meta = parent::getMeta(); /** @var ModifierInterface $modifier */ foreach ($this->pool->getModifiersInstances() as $modifier) { $meta = $modifier->modifyMeta($meta); } return $meta; }
[ "public", "function", "prepareMeta", "(", "array", "$", "meta", ")", "{", "$", "meta", "=", "parent", "::", "getMeta", "(", ")", ";", "/** @var ModifierInterface $modifier */", "foreach", "(", "$", "this", "->", "pool", "->", "getModifiersInstances", "(", ")",...
Prepares Meta @param array $meta @return array
[ "Prepares", "Meta" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Stores/DataProvider.php#L68-L77
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Stores/DataProvider.php
DataProvider.getData
public function getData() { /** @var ModifierInterface $modifier */ foreach ($this->pool->getModifiersInstances() as $modifier) { $this->data = $modifier->modifyData($this->data); } return $this->data; }
php
public function getData() { /** @var ModifierInterface $modifier */ foreach ($this->pool->getModifiersInstances() as $modifier) { $this->data = $modifier->modifyData($this->data); } return $this->data; }
[ "public", "function", "getData", "(", ")", "{", "/** @var ModifierInterface $modifier */", "foreach", "(", "$", "this", "->", "pool", "->", "getModifiersInstances", "(", ")", "as", "$", "modifier", ")", "{", "$", "this", "->", "data", "=", "$", "modifier", "...
Get data @return array
[ "Get", "data" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Stores/DataProvider.php#L84-L92
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Controller/Adminhtml/Stores/Export.php
Export.execute
public function execute() { $resultRedirect = $this->resultRedirectFactory->create(); try { $content = ''; $content .= '"store_id",'; $content .= '"name",'; $content .= '"address",'; $content .= '"city",'; $content .= '"country",'; $content .= '"postcode",'; $content .= '"region",'; $content .= '"email",'; $content .= '"phone",'; $content .= '"link",'; $content .= '"image",'; $content .= '"latitude",'; $content .= '"longitude",'; $content .= '"status",'; $content .= '"updated_at",'; $content .= '"created_at",'; $content .= '"schedule",'; $content .= '"station",'; $content .= '"description",'; $content .= '"intro",'; $content .= '"details_image",'; $content .= '"distance",'; $content .= '"external_link"'; $content .= "\n"; $fileName = 'stockists_export.csv'; $collection = $this->collectionFactory->create()->getData(); foreach ($collection as $stockist) { array_shift($stockist); //skip the id $content .= implode(",", array_map([$this, 'addQuotationMarks'],$stockist)); $content .= "\n"; } return $this->fileFactory->create( $fileName, $content, DirectoryList::VAR_DIR ); $this->messageManager->addSuccessMessage(__('You exported the file. It can be found in var folder or in browser downloads.')); $resultRedirect->setPath('stockists/stores'); } catch (\Exception $e) { $this->messageManager->addErrorMessage(__('There was a problem exporting the data')); $resultRedirect->setPath('stockists/stores/export'); } return $resultRedirect; }
php
public function execute() { $resultRedirect = $this->resultRedirectFactory->create(); try { $content = ''; $content .= '"store_id",'; $content .= '"name",'; $content .= '"address",'; $content .= '"city",'; $content .= '"country",'; $content .= '"postcode",'; $content .= '"region",'; $content .= '"email",'; $content .= '"phone",'; $content .= '"link",'; $content .= '"image",'; $content .= '"latitude",'; $content .= '"longitude",'; $content .= '"status",'; $content .= '"updated_at",'; $content .= '"created_at",'; $content .= '"schedule",'; $content .= '"station",'; $content .= '"description",'; $content .= '"intro",'; $content .= '"details_image",'; $content .= '"distance",'; $content .= '"external_link"'; $content .= "\n"; $fileName = 'stockists_export.csv'; $collection = $this->collectionFactory->create()->getData(); foreach ($collection as $stockist) { array_shift($stockist); //skip the id $content .= implode(",", array_map([$this, 'addQuotationMarks'],$stockist)); $content .= "\n"; } return $this->fileFactory->create( $fileName, $content, DirectoryList::VAR_DIR ); $this->messageManager->addSuccessMessage(__('You exported the file. It can be found in var folder or in browser downloads.')); $resultRedirect->setPath('stockists/stores'); } catch (\Exception $e) { $this->messageManager->addErrorMessage(__('There was a problem exporting the data')); $resultRedirect->setPath('stockists/stores/export'); } return $resultRedirect; }
[ "public", "function", "execute", "(", ")", "{", "$", "resultRedirect", "=", "$", "this", "->", "resultRedirectFactory", "->", "create", "(", ")", ";", "try", "{", "$", "content", "=", "''", ";", "$", "content", ".=", "'\"store_id\",'", ";", "$", "content...
Export data grid to CSV format @return ResponseInterface
[ "Export", "data", "grid", "to", "CSV", "format" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Controller/Adminhtml/Stores/Export.php#L101-L158
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Uploader.php
Uploader.moveFileFromTmp
public function moveFileFromTmp($name) { $baseTmpPath = $this->getBaseTmpPath(); $basePath = $this->getBasePath(); $baseFilePath = $this->getFilePath($basePath, $name); $baseTmpFilePath = $this->getFilePath($baseTmpPath, $name); try { $this->coreFileStorageDatabase->copyFile( $baseTmpFilePath, $baseFilePath ); $this->mediaDirectory->renameFile( $baseTmpFilePath, $baseFilePath ); } catch (\Exception $e) { throw new LocalizedException( __('Something went wrong while saving the file(s).') ); } return $name; }
php
public function moveFileFromTmp($name) { $baseTmpPath = $this->getBaseTmpPath(); $basePath = $this->getBasePath(); $baseFilePath = $this->getFilePath($basePath, $name); $baseTmpFilePath = $this->getFilePath($baseTmpPath, $name); try { $this->coreFileStorageDatabase->copyFile( $baseTmpFilePath, $baseFilePath ); $this->mediaDirectory->renameFile( $baseTmpFilePath, $baseFilePath ); } catch (\Exception $e) { throw new LocalizedException( __('Something went wrong while saving the file(s).') ); } return $name; }
[ "public", "function", "moveFileFromTmp", "(", "$", "name", ")", "{", "$", "baseTmpPath", "=", "$", "this", "->", "getBaseTmpPath", "(", ")", ";", "$", "basePath", "=", "$", "this", "->", "getBasePath", "(", ")", ";", "$", "baseFilePath", "=", "$", "thi...
Checking file for moving and move it @param string $name @return string @throws \Magento\Framework\Exception\LocalizedException
[ "Checking", "file", "for", "moving", "and", "move", "it" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Uploader.php#L222-L246