sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public static function rangeFromBoundaries($from, $to)
{
$result = null;
$invalid = false;
foreach (array('from', 'to') as $param) {
if (!($$param instanceof AddressInterface)) {
$$param = (string) $$param;
if ($$param === '') {
$$param = null;
} else {
$$param = static::addressFromString($$param);
if ($$param === null) {
$invalid = true;
}
}
}
}
if ($invalid === false) {
$result = static::rangeFromBoundaryAddresses($from, $to);
}
return $result;
}
|
Create a Range instance starting from its boundaries.
@param string|\IPLib\Address\AddressInterface $from
@param string|\IPLib\Address\AddressInterface $to
@return \IPLib\Range\RangeInterface|null
|
entailment
|
protected static function rangeFromBoundaryAddresses(AddressInterface $from = null, AddressInterface $to = null)
{
if ($from === null && $to === null) {
$result = null;
} elseif ($to === null) {
$result = Range\Single::fromAddress($from);
} elseif ($from === null) {
$result = Range\Single::fromAddress($to);
} else {
$result = null;
$addressType = $from->getAddressType();
if ($addressType === $to->getAddressType()) {
$cmp = strcmp($from->getComparableString(), $to->getComparableString());
if ($cmp === 0) {
$result = Range\Single::fromAddress($from);
} else {
if ($cmp > 0) {
list($from, $to) = array($to, $from);
}
$fromBytes = $from->getBytes();
$toBytes = $to->getBytes();
$numBytes = count($fromBytes);
$sameBits = 0;
for ($byteIndex = 0; $byteIndex < $numBytes; ++$byteIndex) {
$fromByte = $fromBytes[$byteIndex];
$toByte = $toBytes[$byteIndex];
if ($fromByte === $toByte) {
$sameBits += 8;
} else {
$differentBitsInByte = decbin($fromByte ^ $toByte);
$sameBits += 8 - strlen($differentBitsInByte);
break;
}
}
$result = static::rangeFromString($from->toString(true).'/'.(string) $sameBits);
}
}
}
return $result;
}
|
@param \IPLib\Address\AddressInterface $from
@param \IPLib\Address\AddressInterface $to
@return \IPLib\Range\RangeInterface|null
|
entailment
|
public static function fromString($range)
{
$result = null;
$address = Factory::addressFromString($range);
if ($address !== null) {
$result = new static($address);
}
return $result;
}
|
Try get the range instance starting from its string representation.
@param string|mixed $range
@return static|null
|
entailment
|
public function contains(AddressInterface $address)
{
$result = false;
if ($address->getAddressType() === $this->getAddressType()) {
if ($address->toString(false) === $this->address->toString(false)) {
$result = true;
}
}
return $result;
}
|
{@inheritdoc}
@see \IPLib\Range\RangeInterface::contains()
|
entailment
|
public function containsRange(RangeInterface $range)
{
$result = false;
if ($range->getAddressType() === $this->getAddressType()) {
if ($range->toString(false) === $this->toString(false)) {
$result = true;
}
}
return $result;
}
|
{@inheritdoc}
@see \IPLib\Range\RangeInterface::containsRange()
|
entailment
|
public static function fromString($address, $mayIncludePort = true, $mayIncludeZoneID = true)
{
$result = null;
if (is_string($address) && strpos($address, ':') !== false && strpos($address, ':::') === false) {
$matches = null;
if ($mayIncludePort && $address[0] === '[' && preg_match('/^\[(.+)\]:\d+$/', $address, $matches)) {
$address = $matches[1];
}
if ($mayIncludeZoneID) {
$percentagePos = strpos($address, '%');
if ($percentagePos > 0) {
$address = substr($address, 0, $percentagePos);
}
}
if (preg_match('/^([0:]+:ffff:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i', $address, $matches)) {
// IPv4 embedded in IPv6
$address6 = static::fromString($matches[1].'0:0', false);
if ($address6 !== null) {
$address4 = IPv4::fromString($matches[2], false);
if ($address4 !== null) {
$bytes4 = $address4->getBytes();
$address6->longAddress = substr($address6->longAddress, 0, -9).sprintf('%02x%02x:%02x%02x', $bytes4[0], $bytes4[1], $bytes4[2], $bytes4[3]);
$result = $address6;
}
}
} else {
if (strpos($address, '::') === false) {
$chunks = explode(':', $address);
} else {
$chunks = array();
$parts = explode('::', $address);
if (count($parts) === 2) {
$before = ($parts[0] === '') ? array() : explode(':', $parts[0]);
$after = ($parts[1] === '') ? array() : explode(':', $parts[1]);
$missing = 8 - count($before) - count($after);
if ($missing >= 0) {
$chunks = $before;
if ($missing !== 0) {
$chunks = array_merge($chunks, array_fill(0, $missing, '0'));
}
$chunks = array_merge($chunks, $after);
}
}
}
if (count($chunks) === 8) {
$nums = array_map(
function ($chunk) {
return preg_match('/^[0-9A-Fa-f]{1,4}$/', $chunk) ? hexdec($chunk) : false;
},
$chunks
);
if (!in_array(false, $nums, true)) {
$longAddress = implode(
':',
array_map(
function ($num) {
return sprintf('%04x', $num);
},
$nums
)
);
$result = new static($longAddress);
}
}
}
}
return $result;
}
|
Parse a string and returns an IPv6 instance if the string is valid, or null otherwise.
@param string|mixed $address the address to parse
@param bool $mayIncludePort set to false to avoid parsing addresses with ports
@param bool $mayIncludeZoneID set to false to avoid parsing addresses with zone IDs (see RFC 4007)
@return static|null
|
entailment
|
public static function fromBytes(array $bytes)
{
$result = null;
if (count($bytes) === 16) {
$address = '';
for ($i = 0; $i < 16; ++$i) {
if ($i !== 0 && $i % 2 === 0) {
$address .= ':';
}
$byte = $bytes[$i];
if (is_int($byte) && $byte >= 0 && $byte <= 255) {
$address .= sprintf('%02x', $byte);
} else {
$address = null;
break;
}
}
if ($address !== null) {
$result = new static($address);
}
}
return $result;
}
|
Parse an array of bytes and returns an IPv6 instance if the array is valid, or null otherwise.
@param int[]|array $bytes
@return static|null
|
entailment
|
public static function fromWords(array $words)
{
$result = null;
if (count($words) === 8) {
$chunks = array();
for ($i = 0; $i < 8; ++$i) {
$word = $words[$i];
if (is_int($word) && $word >= 0 && $word <= 0xffff) {
$chunks[] = sprintf('%04x', $word);
} else {
$chunks = null;
break;
}
}
if ($chunks !== null) {
$result = new static(implode(':', $chunks));
}
}
return $result;
}
|
Parse an array of words and returns an IPv6 instance if the array is valid, or null otherwise.
@param int[]|array $words
@return static|null
|
entailment
|
public function toString($long = false)
{
if ($long) {
$result = $this->longAddress;
} else {
if ($this->shortAddress === null) {
if (strpos($this->longAddress, '0000:0000:0000:0000:0000:ffff:') === 0) {
$lastBytes = array_slice($this->getBytes(), -4);
$this->shortAddress = '::ffff:'.implode('.', $lastBytes);
} else {
$chunks = array_map(
function ($word) {
return dechex($word);
},
$this->getWords()
);
$shortAddress = implode(':', $chunks);
$matches = null;
for ($i = 8; $i > 1; --$i) {
$search = '(?:^|:)'.rtrim(str_repeat('0:', $i), ':').'(?:$|:)';
if (preg_match('/^(.*?)'.$search.'(.*)$/', $shortAddress, $matches)) {
$shortAddress = $matches[1].'::'.$matches[2];
break;
}
}
$this->shortAddress = $shortAddress;
}
}
$result = $this->shortAddress;
}
return $result;
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::toString()
|
entailment
|
public function getBytes()
{
if ($this->bytes === null) {
$bytes = array();
foreach ($this->getWords() as $word) {
$bytes[] = $word >> 8;
$bytes[] = $word & 0xff;
}
$this->bytes = $bytes;
}
return $this->bytes;
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getBytes()
|
entailment
|
public function getWords()
{
if ($this->words === null) {
$this->words = array_map(
function ($chunk) {
return hexdec($chunk);
},
explode(':', $this->longAddress)
);
}
return $this->words;
}
|
Get the word list of the IP address.
@return int[]
|
entailment
|
public static function getReservedRanges()
{
if (self::$reservedRanges === null) {
$reservedRanges = array();
foreach (array(
// RFC 4291
'::/128' => array(RangeType::T_UNSPECIFIED),
// RFC 4291
'::1/128' => array(RangeType::T_LOOPBACK),
// RFC 4291
'100::/8' => array(RangeType::T_DISCARD, array('100::/64' => RangeType::T_DISCARDONLY)),
//'2002::/16' => array(RangeType::),
// RFC 4291
'2000::/3' => array(RangeType::T_PUBLIC),
// RFC 4193
'fc00::/7' => array(RangeType::T_PRIVATENETWORK),
// RFC 4291
'fe80::/10' => array(RangeType::T_LINKLOCAL_UNICAST),
// RFC 4291
'ff00::/8' => array(RangeType::T_MULTICAST),
// RFC 4291
//'::/8' => array(RangeType::T_RESERVED),
// RFC 4048
//'200::/7' => array(RangeType::T_RESERVED),
// RFC 4291
//'400::/6' => array(RangeType::T_RESERVED),
// RFC 4291
//'800::/5' => array(RangeType::T_RESERVED),
// RFC 4291
//'1000::/4' => array(RangeType::T_RESERVED),
// RFC 4291
//'4000::/3' => array(RangeType::T_RESERVED),
// RFC 4291
//'6000::/3' => array(RangeType::T_RESERVED),
// RFC 4291
//'8000::/3' => array(RangeType::T_RESERVED),
// RFC 4291
//'a000::/3' => array(RangeType::T_RESERVED),
// RFC 4291
//'c000::/3' => array(RangeType::T_RESERVED),
// RFC 4291
//'e000::/4' => array(RangeType::T_RESERVED),
// RFC 4291
//'f000::/5' => array(RangeType::T_RESERVED),
// RFC 4291
//'f800::/6' => array(RangeType::T_RESERVED),
// RFC 4291
//'fe00::/9' => array(RangeType::T_RESERVED),
// RFC 3879
//'fec0::/10' => array(RangeType::T_RESERVED),
) as $range => $data) {
$exceptions = array();
if (isset($data[1])) {
foreach ($data[1] as $exceptionRange => $exceptionType) {
$exceptions[] = new AssignedRange(Subnet::fromString($exceptionRange), $exceptionType);
}
}
$reservedRanges[] = new AssignedRange(Subnet::fromString($range), $data[0], $exceptions);
}
self::$reservedRanges = $reservedRanges;
}
return self::$reservedRanges;
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getReservedRanges()
|
entailment
|
public function toIPv4()
{
$result = null;
if (strpos($this->longAddress, '2002:') === 0) {
$result = IPv4::fromBytes(array_slice($this->getBytes(), 2, 4));
}
return $result;
}
|
Create an IPv4 representation of this address (if possible, otherwise returns null).
@return \IPLib\Address\IPv4|null
|
entailment
|
public function getNextAddress()
{
$overflow = false;
$words = $this->getWords();
for ($i = count($words) - 1; $i >= 0; --$i) {
if ($words[$i] === 0xffff) {
if ($i === 0) {
$overflow = true;
break;
}
$words[$i] = 0;
} else {
++$words[$i];
break;
}
}
return $overflow ? null : static::fromWords($words);
}
|
{@inheritdoc}
@see \IPLib\Address\AddressInterface::getNextAddress()
|
entailment
|
public function findSources(string $fieldType, array $attributes, string $indexFrom, string $indexTo): array
{
foreach ($attributes as $key => $attribute) {
if ($key === 'source') {
$attributes[$key] = $this->getSource($fieldType, $attribute, $indexFrom, $indexTo);
} elseif ($key === 'sources') {
$attributes[$key] = $this->getSources($fieldType, $attribute, $indexFrom, $indexTo);
} elseif (is_array($attribute)) {
$attributes[$key] = $this->findSources($fieldType, $attribute, $indexFrom, $indexTo);
}
}
return $attributes;
}
|
Recursively find sources in definition attributes.
@param string $fieldType
@param array $attributes
@param string $indexFrom
@param string $indexTo
@return array
|
entailment
|
public function getSources(string $fieldType, $sources, string $indexFrom, string $indexTo)
{
$mappedSources = $sources;
if (is_array($sources)) {
$mappedSources = [];
$sources = array_filter($sources);
foreach ($sources as $source) {
$mappedSources[] = $this->getSource($fieldType, $source, $indexFrom, $indexTo);
}
}
return $mappedSources;
}
|
Get sources based on the indexFrom attribute and return them with the indexTo attribute.
@param string $fieldType
@param string|array $sources
@param string $indexFrom
@param string $indexTo
@return array|string
|
entailment
|
public function getSource(string $fieldType, string $source = null, string $indexFrom, string $indexTo)
{
if (false === strpos($source, ':')) {
return $source;
}
/** @var Model $sourceObject */
$sourceObject = null;
// Get service and method by source
list($sourceType, $sourceFrom) = explode(':', $source);
switch ($sourceType) {
case 'editSite':
$service = Craft::$app->sites;
$method = 'getSiteBy';
break;
case 'single':
case 'section':
case 'createEntries':
case 'editPeerEntries':
case 'deleteEntries':
case 'deletePeerEntries':
case 'deletePeerEntryDrafts':
case 'editEntries':
case 'editPeerEntryDrafts':
case 'publishEntries':
case 'publishPeerEntries':
case 'publishPeerEntryDrafts':
$service = Craft::$app->sections;
$method = 'getSectionBy';
break;
case 'assignUserGroup':
$service = Craft::$app->userGroups;
$method = 'getGroupBy';
break;
case 'group':
case 'editCategories':
$service = Users::class == $fieldType ? Craft::$app->userGroups : Craft::$app->categories;
$method = 'getGroupBy';
break;
case 'folder':
$service = $this;
$method = 'getFolderBy';
break;
case 'createFoldersInVolume':
case 'deleteFilesAndFoldersInVolume':
case 'saveAssetInVolume':
case 'viewVolume':
$service = Craft::$app->volumes;
$method = 'getVolumeBy';
break;
case 'taggroup':
$service = Craft::$app->tags;
$method = 'getTagGroupBy';
break;
case 'field':
$service = Craft::$app->fields;
$method = 'getFieldBy';
break;
case 'editGlobalSet':
$service = Craft::$app->globals;
$method = 'getSetBy';
break;
case 'utility':
return $source;
}
// Send event
$plugin = Craft::$app->controller->module;
$event = new SourceMappingEvent([
'source' => $source,
'service' => $service ?? null,
'method' => $method ?? null,
]);
$plugin->trigger($plugin::EVENT_MAP_SOURCE, $event);
$service = $event->service;
$method = $event->method;
// Try service and method
if (isset($service) && isset($method) && isset($sourceFrom)) {
$method = $method.ucfirst($indexFrom);
try {
$sourceObject = $service->$method($sourceFrom);
} catch (TypeError $e) {
Schematic::error('An error occured mapping source '.$source.' from '.$indexFrom.' to '.$indexTo);
Schematic::error($e->getMessage());
return null;
}
}
if ($sourceObject) {
return $sourceType.':'.$sourceObject->$indexTo;
}
Schematic::warning('No mapping found for source '.$source);
return null;
}
|
Gets a source by the attribute indexFrom, and returns it with attribute $indexTo.
@TODO Break up and simplify this method
@param string $fieldType
@param string $source
@param string $indexFrom
@param string $indexTo
@return string|null
@SuppressWarnings(PHPMD.CyclomaticComplexity)
@SuppressWarnings(PHPMD.NPathComplexity)
|
entailment
|
private function getFolderById(int $folderId): \stdClass
{
$folder = Craft::$app->assets->getFolderById($folderId);
if ($folder) {
$volume = $folder->getVolume();
return (object) [
'id' => $folderId,
'handle' => $volume->handle
];
}
return null;
}
|
Get a folder by id
@SuppressWarnings(PHPMD.UnusedPrivateMethod)
@param int $folderId
@return object
|
entailment
|
private function getFolderByVolumeId(int $volumeId): VolumeFolder
{
return $this->mockFolder ? $this->mockFolder : VolumeFolder::findOne(['volumeId' => $volumeId]);
}
|
Get folder by volume id
@param int $volumeId
@return VolumeFolder
|
entailment
|
private function getFolderByHandle(string $folderHandle): \stdClass
{
$volume = Craft::$app->volumes->getVolumeByHandle($folderHandle);
if ($volume) {
$folder = $this->getFolderByVolumeId($volume->id);
if ($folder) {
return (object) [
'id' => $folder->id,
'handle' => $folderHandle
];
}
}
return null;
}
|
Get a folder by volume handle
@SuppressWarnings(PHPMD.UnusedPrivateMethod)
@param string $folderHandle
@return object
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
unset($definition['attributes']['fieldId']);
unset($definition['attributes']['hasFieldErrors']);
$definition['fields'] = Craft::$app->controller->module->modelMapper->export($record->fieldLayout->getFields());
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
// Set the content table for this matrix block
$originalContentTable = Craft::$app->content->contentTable;
$matrixField = Craft::$app->fields->getFieldById($record->fieldId);
$contentTable = Craft::$app->matrix->getContentTableName($matrixField);
Craft::$app->content->contentTable = $contentTable;
// Get the matrix block fields from the definition
$modelMapper = Craft::$app->controller->module->modelMapper;
$fields = $modelMapper->import($definition['fields'], $record->getFields(), [], false);
$record->setFields($fields);
// Save the matrix block
$result = Craft::$app->matrix->saveBlockType($record, false);
// Restore the content table to what it was before
Craft::$app->content->contentTable = $originalContentTable;
return $result;
}
|
{@inheritdoc}
|
entailment
|
public static function replaceEnvVariables($yaml): string
{
$matches = null;
preg_match_all('/%\w+%/', $yaml, $matches);
$originalValues = $matches[0];
$replaceValues = [];
foreach ($originalValues as $match) {
$envVariable = substr($match, 1, -1);
$envValue = getenv($envVariable);
if (!$envValue) {
$envVariable = strtoupper($envVariable);
$envVariable = 'SCHEMATIC_'.$envVariable;
$envValue = getenv($envVariable);
if (!$envValue) {
throw new Exception("Schematic environment variable not set: {$envVariable}");
}
}
$replaceValues[] = $envValue;
}
return str_replace($originalValues, $replaceValues, $yaml);
}
|
Replace placeholders with enviroment variables.
Placeholders start with % and end with %. This will be replaced by the
environment variable with the name SCHEMATIC_{PLACEHOLDER}. If the
environment variable is not set an exception will be thrown.
@param string $yaml
@return string
@throws Exception
|
entailment
|
public static function parseYamlFile($file): array
{
if (file_exists($file)) {
$data = file_get_contents($file);
if (!empty($data)) {
$data = static::replaceEnvVariables($data);
return Yaml::parse($data);
}
}
return [];
}
|
Read yaml file and parse content.
@param $file
@return array
@throws Exception
|
entailment
|
public function export(array $settings = []): array
{
$info = Craft::$app->getInfo();
return [
'settings' => [
'edition' => $info->edition,
'timezone' => $info->timezone,
'name' => $info->name,
'on' => $info->on,
'maintenance' => $info->maintenance,
],
];
}
|
{@inheritdoc}
|
entailment
|
public function import(array $generalSettings, array $settings = []): array
{
if (array_key_exists('settings', $generalSettings)) {
Schematic::info('- Saving general settings');
$record = Craft::$app->getInfo();
$record->setAttributes($generalSettings['settings']);
if (!Craft::$app->saveInfo($record)) {
Schematic::warning('- Couldn’t save general settings.');
}
}
return [];
}
|
{@inheritdoc}
|
entailment
|
private function clearSiteCaches()
{
$obj = Craft::$app->sites;
$refObject = new \ReflectionObject($obj);
if ($refObject->hasProperty('_sitesById')) {
$refProperty1 = $refObject->getProperty('_sitesById');
$refProperty1->setAccessible(true);
$refProperty1->setValue($obj, null);
}
if ($refObject->hasProperty('_sitesByHandle')) {
$refProperty2 = $refObject->getProperty('_sitesByHandle');
$refProperty2->setAccessible(true);
$refProperty2->setValue($obj, null);
}
$obj->init(); // reload sites
}
|
Reset craft site service sites cache using reflection.
|
entailment
|
private function clearEmptyGroups()
{
foreach (Craft::$app->sites->getAllGroups() as $group) {
if (count($group->getSites()) == 0) {
Craft::$app->sites->deleteGroup($group);
}
}
}
|
Clear empty sute groups
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->tags->saveTagGroup($record);
}
|
{@inheritdoc}
|
entailment
|
public function deleteRecord(Model $record): bool
{
return Craft::$app->tags->deleteTagGroupById($record->id);
}
|
{@inheritdoc}
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
if ($record instanceof CategoryGroup_SiteSettings) {
unset($definition['attributes']['groupId']);
unset($definition['attributes']['siteId']);
}
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->categories->saveGroup($record);
}
|
{@inheritdoc}
|
entailment
|
public function deleteRecord(Model $record): bool
{
return Craft::$app->categories->deleteGroupById($record->id);
}
|
{@inheritdoc}
|
entailment
|
public function actionIndex(): int
{
$dataTypes = $this->getDataTypes();
$definitions = [];
$overrideData = Data::parseYamlFile($this->overrideFile);
$this->disableLogging();
try {
// Import from single file.
if ($this->getStorageType() === self::SINGLE_FILE) {
$definitions = $this->importDefinitionsFromFile($overrideData);
$this->importFromDefinitions($dataTypes, $definitions);
Schematic::info('Loaded schema from '.$this->file);
}
// Import from multiple files.
if ($this->getStorageType() === self::MULTIPLE_FILES) {
$definitions = $this->importDefinitionsFromDirectory($overrideData);
$this->importFromDefinitions($dataTypes, $definitions);
Schematic::info('Loaded schema from '.$this->path);
}
return 0;
} catch (\Exception $e) {
Schematic::error($e->getMessage());
return 1;
}
}
|
Imports the Craft datamodel.
@return int
@throws \Exception
|
entailment
|
private function importDefinitionsFromFile(array $overrideData): array
{
if (!file_exists($this->file)) {
throw new \Exception('File not found: ' . $this->file);
}
// Load data from yam file and replace with override data;
$definitions = Data::parseYamlFile($this->file);
return array_replace_recursive($definitions, $overrideData);
}
|
Import definitions from file
@param array $overrideData The overridden data
@throws \Exception
|
entailment
|
private function importDefinitionsFromDirectory(array $overrideData)
{
if (!file_exists($this->path)) {
throw new \Exception('Directory not found: ' . $this->path);
}
// Grab all yaml files in the schema directory.
$schemaFiles = preg_grep('~\.(yml)$~', scandir($this->path));
// Read contents of each file and add it to the definitions.
foreach ($schemaFiles as $fileName) {
$schemaStructure = explode('.', $this->fromSafeFileName($fileName));
$dataTypeHandle = $schemaStructure[0];
$recordName = $schemaStructure[1];
$definition = Data::parseYamlFile($this->path . $fileName);
// Check if there is data in the override file for the current record.
if (isset($overrideData[$dataTypeHandle][$recordName])) {
$definition = array_replace_recursive($definition, $overrideData[$dataTypeHandle][$recordName]);
}
$definitions[$dataTypeHandle][$recordName] = $definition;
}
return $definitions;
}
|
Import definitions from directory
@param array $overrideData The overridden data
@throws \Exception
|
entailment
|
private function importFromDefinitions(array $dataTypes, array $definitions)
{
foreach ($dataTypes as $dataTypeHandle) {
$dataType = $this->module->getDataType($dataTypeHandle);
if (null == $dataType) {
continue;
}
$mapper = $dataType->getMapperHandle();
if (!$this->module->checkMapper($mapper)) {
continue;
}
Schematic::info('Importing '.$dataTypeHandle);
Schematic::$force = $this->force;
if (array_key_exists($dataTypeHandle, $definitions) && is_array($definitions[$dataTypeHandle])) {
$records = $dataType->getRecords();
try {
$this->module->$mapper->import($definitions[$dataTypeHandle], $records);
$dataType->afterImport();
} catch (WrongEditionException $e) {
Schematic::error('Craft Pro is required for datatype '.$dataTypeHandle);
}
}
}
}
|
Import from definitions.
@param array $dataTypes The data types to import
@param array $definitions The definitions to use
@throws \Exception
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
$mappedPermissions = $this->getAllMappedPermissions();
$groupPermissions = [];
if ($record->id) {
foreach (Craft::$app->userPermissions->getPermissionsByGroupId($record->id) as $permission) {
if (array_key_exists($permission, $mappedPermissions)) {
$groupPermissions[] = $mappedPermissions[$permission];
} else {
$groupPermissions[] = $permission;
}
}
}
$permissionDefinitions = $this->getSources('', $groupPermissions, 'id', 'handle');
sort($permissionDefinitions);
$definition['permissions'] = $permissionDefinitions;
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
if (Craft::$app->userGroups->saveGroup($record) && array_key_exists('permissions', $definition)) {
$permissions = $this->getSources('', $definition['permissions'], 'handle', 'id');
return Craft::$app->userPermissions->saveGroupPermissions($record->id, $permissions);
}
return false;
}
|
{@inheritdoc}
|
entailment
|
private function getAllMappedPermissions(): array
{
$mappedPermissions = [];
foreach (Craft::$app->userPermissions->getAllPermissions() as $permissions) {
$mappedPermissions = array_merge($mappedPermissions, $this->getMappedPermissions($permissions));
}
return $mappedPermissions;
}
|
Get a mapping of all permissions from lowercase to camelcase
savePermissions only accepts camelcase.
@return array
|
entailment
|
private function getMappedPermissions(array $permissions): array
{
$mappedPermissions = [];
foreach ($permissions as $permission => $options) {
$mappedPermissions[strtolower($permission)] = $permission;
if (is_array($options) && array_key_exists('nested', $options)) {
$mappedPermissions = array_merge($mappedPermissions, $this->getMappedPermissions($options['nested']));
}
}
return $mappedPermissions;
}
|
Recursive function to get mapped permissions.
@param array $permissions
@return array
|
entailment
|
protected function getDataTypes(): array
{
$dataTypes = array_keys($this->module->dataTypes);
// If include is specified.
if (null !== $this->include) {
$dataTypes = $this->applyIncludes($dataTypes);
}
// If there are exclusions.
if (null !== $this->exclude) {
$dataTypes = $this->applyExcludes($dataTypes);
}
//Import fields and usergroups again after all sources have been imported
if (array_search('fields', $dataTypes) && count($dataTypes) > 1) {
$dataTypes[] = 'fields';
$dataTypes[] = 'userGroups';
}
return $dataTypes;
}
|
Get the datatypes to import and/or export.
@return array
|
entailment
|
protected function applyIncludes($dataTypes): array
{
$inclusions = explode(',', $this->include);
// Find any invalid data to include.
$invalidIncludes = array_diff($inclusions, $dataTypes);
if (count($invalidIncludes) > 0) {
$errorMessage = 'WARNING: Invalid include(s)';
$errorMessage .= ': '.implode(', ', $invalidIncludes).'.'.PHP_EOL;
$errorMessage .= ' Valid inclusions are '.implode(', ', $dataTypes);
// Output an error message outlining what invalid exclusions were specified.
Schematic::warning($errorMessage);
}
// Remove any explicitly included data types from the list of data types to export.
return array_intersect($dataTypes, $inclusions);
}
|
Apply given includes.
@param array $dataTypes
@return array
|
entailment
|
protected function applyExcludes(array $dataTypes): array
{
$exclusions = explode(',', $this->exclude);
// Find any invalid data to exclude.
$invalidExcludes = array_diff($exclusions, $dataTypes);
if (count($invalidExcludes) > 0) {
$errorMessage = 'WARNING: Invalid exlude(s)';
$errorMessage .= ': '.implode(', ', $invalidExcludes).'.'.PHP_EOL;
$errorMessage .= ' Valid exclusions are '.implode(', ', $dataTypes);
// Output an error message outlining what invalid exclusions were specified.
Schematic::warning($errorMessage);
}
// Remove any explicitly excluded data types from the list of data types to export.
return array_diff($dataTypes, $exclusions);
}
|
Apply given excludes.
@param array $dataTypes
@return array
|
entailment
|
public function export(array $plugins): array
{
$pluginDefinitions = [];
foreach ($plugins as $handle => $pluginInfo) {
$pluginDefinitions[$handle] = $this->getPluginDefinition($handle, $pluginInfo);
}
ksort($pluginDefinitions);
return $pluginDefinitions;
}
|
{@inheritdoc}
|
entailment
|
private function getPluginDefinition(string $handle, array $pluginInfo): array
{
$settings = null;
$plugin = Craft::$app->plugins->getPlugin($handle);
if ($plugin) {
$settings = $plugin->getSettings();
}
return [
'isEnabled' => $pluginInfo['isEnabled'],
'isInstalled' => $pluginInfo['isInstalled'],
'settings' => $settings ? $settings->attributes : [],
];
}
|
@param string $handle
@param array $pluginInfo
@return array
|
entailment
|
public function import(array $pluginDefinitions, array $plugins): array
{
$imported = [];
foreach ($pluginDefinitions as $handle => $definition) {
if (!array_key_exists($handle, $plugins)) {
Schematic::error(' - Plugin info not found for '.$handle.', make sure it is installed with composer');
continue;
}
if (!$definition['isInstalled']) {
continue;
}
Schematic::info('- Installing plugin '.$handle);
$pluginInfo = $plugins[$handle];
if ($this->savePlugin($handle, $definition, $pluginInfo)) {
$imported[] = Craft::$app->plugins->getPlugin($handle);
}
unset($plugins[$handle]);
}
if (Schematic::$force) {
foreach (array_keys($plugins) as $handle) {
if ($plugins[$handle]['isInstalled']) {
Schematic::info('- Uninstalling plugin '.$handle);
Craft::$app->plugins->uninstallPlugin($handle);
}
}
}
return $imported;
}
|
{@inheritdoc}
|
entailment
|
private function savePlugin(string $handle, array $definition, array $pluginInfo): bool
{
if (!$pluginInfo['isInstalled']) {
Craft::$app->plugins->installPlugin($handle);
}
if ($definition['isEnabled']) {
Craft::$app->plugins->enablePlugin($handle);
} else {
Craft::$app->plugins->disablePlugin($handle);
}
$plugin = Craft::$app->plugins->getPlugin($handle);
if ($plugin && $plugin->getSettings()) {
return Craft::$app->plugins->savePluginSettings($plugin, $definition['settings']);
}
return false;
}
|
Install, enable, disable and/or update plugin.
@param string $handle
@param array $definition
@param array $pluginInfo
@return bool
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
if ($record instanceof GlobalSetElement) {
$definition['site'] = $record->getSite()->handle;
unset($definition['attributes']['tempId']);
unset($definition['attributes']['uid']);
unset($definition['attributes']['contentId']);
unset($definition['attributes']['siteId']);
unset($definition['attributes']['hasDescendants']);
unset($definition['attributes']['ref']);
unset($definition['attributes']['status']);
unset($definition['attributes']['totalDescendants']);
unset($definition['attributes']['url']);
foreach ($record->getFieldLayout()->getFields() as $field) {
unset($definition['attributes'][$field->handle]);
}
}
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
if (array_key_exists('site', $definition)) {
$site = Craft::$app->sites->getSiteByHandle($definition['site']);
if ($site) {
$record->siteId = $site->id;
} else {
Schematic::error('Site '.$definition['site'].' could not be found');
return false;
}
}
return Craft::$app->globals->saveSet($record);
}
|
{@inheritdoc}
|
entailment
|
public function deleteRecord(Model $record): bool
{
return Craft::$app->elements->deleteElementById($record->id);
}
|
{@inheritdoc}
|
entailment
|
public function afterImport()
{
$obj = Craft::$app->sections;
$refObject = new \ReflectionObject($obj);
if ($refObject->hasProperty('_editableSectionIds')) {
$refProperty1 = $refObject->getProperty('_editableSectionIds');
$refProperty1->setAccessible(true);
$refProperty1->setValue($obj, $obj->getAllSectionIds());
}
}
|
Reset craft editable sections cache using reflection.
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->assetTransforms->saveTransform($record);
}
|
{@inheritdoc}
|
entailment
|
public function deleteRecord(Model $record): bool
{
return Craft::$app->assetTransforms->deleteTransform($record->id);
}
|
{@inheritdoc}
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
$definition['blockTypes'] = Craft::$app->controller->module->modelMapper->export($record->getBlockTypes());
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
if (parent::saveRecord($record, $definition)) {
if (array_key_exists('blockTypes', $definition)) {
$this->resetCraftMatrixServiceBlockTypesCache();
$this->resetCraftMatrixFieldBlockTypesCache($record);
Craft::$app->controller->module->modelMapper->import(
$definition['blockTypes'],
$record->getBlockTypes(),
['fieldId' => $record->id]
);
}
return true;
}
return false;
}
|
{@inheritdoc}
|
entailment
|
private function resetCraftMatrixServiceBlockTypesCache()
{
$obj = Craft::$app->matrix;
$refObject = new \ReflectionObject($obj);
if ($refObject->hasProperty('_fetchedAllBlockTypesForFieldId')) {
$refProperty1 = $refObject->getProperty('_fetchedAllBlockTypesForFieldId');
$refProperty1->setAccessible(true);
$refProperty1->setValue($obj, false);
}
}
|
Reset craft matrix service block types cache using reflection.
|
entailment
|
private function resetCraftMatrixFieldBlockTypesCache(Model $record)
{
$obj = $record;
$refObject = new \ReflectionObject($obj);
if ($refObject->hasProperty('_blockTypes')) {
$refProperty1 = $refObject->getProperty('_blockTypes');
$refProperty1->setAccessible(true);
$refProperty1->setValue($obj, null);
}
}
|
Reset craft matrix field block types cache using reflection.
@param Model $record
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = [
'class' => get_class($record),
'attributes' => $record->getAttributes(),
];
unset($definition['attributes']['id']);
unset($definition['attributes']['structureId']);
unset($definition['attributes']['dateCreated']);
unset($definition['attributes']['dateUpdated']);
// Define sources
$definition['attributes'] = $this->findSources($definition['class'], $definition['attributes'], 'id', 'handle');
// Define field layout
if (isset($definition['attributes']['fieldLayoutId'])) {
if (!$record instanceof MatrixBlockTypeModel) {
$definition['fieldLayout'] = $this->getFieldLayoutDefinition($record->getFieldLayout());
}
}
unset($definition['attributes']['fieldLayoutId']);
// Define site settings
if (isset($record->siteSettings)) {
$definition['siteSettings'] = [];
foreach ($record->getSiteSettings() as $siteSetting) {
$definition['siteSettings'][$siteSetting->site->handle] = $this->getRecordDefinition($siteSetting);
}
}
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function setRecordAttributes(Model &$record, array $definition, array $defaultAttributes)
{
// Set sources
$definition['attributes'] = $this->findSources($definition['class'], $definition['attributes'], 'handle', 'id');
$attributes = array_merge($definition['attributes'], $defaultAttributes);
$record->setAttributes($attributes, false);
// Set field layout
if (array_key_exists('fieldLayout', $definition)) {
$fieldLayout = $this->getFieldLayout($definition['fieldLayout']);
$fieldLayout->id = $record->fieldLayoutId;
$record->setFieldLayout($fieldLayout);
}
// Set site settings
if (array_key_exists('siteSettings', $definition)) {
$siteSettings = [];
foreach ($definition['siteSettings'] as $handle => $siteSettingDefinition) {
$siteSetting = new $siteSettingDefinition['class']($siteSettingDefinition['attributes']);
$site = Craft::$app->sites->getSiteByHandle($handle);
if ($site) {
$siteSetting->siteId = $site->id;
$siteSettings[$site->id] = $siteSetting;
} else {
Schematic::warning(' - Site '.$handle.' could not be found');
}
}
$record->setSiteSettings($siteSettings);
}
}
|
{@inheritdoc}
|
entailment
|
public function import(array $emailSettings, array $settings = []): array
{
if (array_key_exists('settings', $emailSettings)) {
Schematic::info('- Saving email settings');
if (!Craft::$app->systemSettings->saveSettings('email', $emailSettings['settings'])) {
Schematic::warning('- Couldn’t save email settings.');
}
}
return [];
}
|
{@inheritdoc}
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
unset($definition['attributes']['targetSiteId']);
if (isset($definition['attributes']['defaultUploadLocationSource'])) {
$definition['attributes']['defaultUploadLocationSource'] = $this->getSource(
$definition['class'],
$definition['attributes']['defaultUploadLocationSource'],
'id',
'handle'
);
}
if (isset($definition['attributes']['singleUploadLocationSource'])) {
$definition['attributes']['singleUploadLocationSource'] = $this->getSource(
$definition['class'],
$definition['attributes']['singleUploadLocationSource'],
'id',
'handle'
);
}
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function setRecordAttributes(Model &$record, array $definition, array $defaultAttributes)
{
if (isset($definition['attributes']['defaultUploadLocationSource'])) {
$definition['attributes']['defaultUploadLocationSource'] = $this->getSource(
$definition['class'],
$definition['attributes']['defaultUploadLocationSource'],
'handle',
'id'
);
}
if (isset($definition['attributes']['singleUploadLocationSource'])) {
$definition['attributes']['singleUploadLocationSource'] = $this->getSource(
$definition['class'],
$definition['attributes']['singleUploadLocationSource'],
'handle',
'id'
);
}
parent::setRecordAttributes($record, $definition, $defaultAttributes);
}
|
{@inheritdoc}
|
entailment
|
public function export(array $elementTypes): array
{
$settingDefinitions = [];
foreach ($elementTypes as $elementType) {
$settings = Craft::$app->elementIndexes->getSettings($elementType);
if (is_array($settings)) {
$settingDefinitions[$elementType] = $this->getMappedSettings($settings, 'id', 'handle');
}
}
return $settingDefinitions;
}
|
{@inheritdoc}
|
entailment
|
public function import(array $settingDefinitions, array $elementTypes): array
{
foreach ($settingDefinitions as $elementType => $settings) {
// Backwards compatibility
if (class_exists('craft\\elements\\'.$elementType)) {
$elementType = 'craft\\elements\\'.$elementType;
}
$mappedSettings = $this->getMappedSettings($settings, 'handle', 'id');
if (!Craft::$app->elementIndexes->saveSettings($elementType, $mappedSettings)) {
Schematic::error(' - Settings for '.$elementType.' could not be saved');
}
}
return [];
}
|
{@inheritdoc}
|
entailment
|
private function getMappedSettings(array $settings, $fromIndex, $toIndex)
{
$mappedSettings = ['sourceOrder' => [], 'sources' => []];
if (isset($settings['sourceOrder'])) {
foreach ($settings['sourceOrder'] as $row) {
if ('key' == $row[0]) {
$row[1] = $this->getSource('', $row[1], $fromIndex, $toIndex);
}
$mappedSettings['sourceOrder'][] = $row;
}
}
if (isset($settings['sources'])) {
foreach ($settings['sources'] as $source => $sourceSettings) {
$mappedSource = $this->getSource('', $source, $fromIndex, $toIndex);
$mappedSettings['sources'][$mappedSource] = [
'tableAttributes' => $this->getSources('', $sourceSettings['tableAttributes'], $fromIndex, $toIndex),
];
}
}
return $mappedSettings;
}
|
Get mapped element index settings, converting source ids to handles or back again.
@param array $settings
@param string $fromIndex
@param string $toIndex
@return array
|
entailment
|
public function import(array $definitions, array $records, array $defaultAttributes = [], $persist = true): array
{
$imported = [];
$recordsByHandle = $this->getRecordsByHandle($records);
foreach ($definitions as $handle => $definition) {
$modelClass = $definition['class'];
$converter = Craft::$app->controller->module->getConverter($modelClass);
if ($converter) {
$record = $this->findOrNewRecord($recordsByHandle, $definition, $handle);
if ($converter->getRecordDefinition($record) === $definition) {
Schematic::info('- Skipping '.get_class($record).' '.$handle);
} else {
$converter->setRecordAttributes($record, $definition, $defaultAttributes);
if ($persist) {
Schematic::info('- Saving '.get_class($record).' '.$handle);
if (!$converter->saveRecord($record, $definition)) {
Schematic::importError($record, $handle);
}
}
}
$imported[] = $record;
}
unset($recordsByHandle[$handle]);
}
if (Schematic::$force && $persist) {
// Delete records not in definitions
foreach ($recordsByHandle as $handle => $record) {
$modelClass = get_class($record);
Schematic::info('- Deleting '.get_class($record).' '.$handle);
$converter = Craft::$app->controller->module->getConverter($modelClass);
$converter->deleteRecord($record);
}
}
return $imported;
}
|
Import records.
@param array $definitions
@param Model $records The existing records
@param array $defaultAttributes Default attributes to use for each record
@param bool $persist Whether to persist the parsed records
@return array
|
entailment
|
private function getRecordsByHandle(array $records): array
{
$recordsByHandle = [];
foreach ($records as $record) {
$modelClass = get_class($record);
$converter = Craft::$app->controller->module->getConverter($modelClass);
$index = $converter->getRecordIndex($record);
$recordsByHandle[$index] = $record;
}
return $recordsByHandle;
}
|
Get records by handle.
@param array $records
@return array
|
entailment
|
private function findOrNewRecord(array $recordsByHandle, array $definition, string $handle): Model
{
$record = new $definition['class']();
if (array_key_exists($handle, $recordsByHandle)) {
$existing = $recordsByHandle[$handle];
if (get_class($record) == get_class($existing)) {
$record = $existing;
} else {
$record->id = $existing->id;
$record->setAttributes($existing->getAttributes());
}
}
return $record;
}
|
Find record from records by handle or new record.
@param Model[] $recordsByHandle
@param array $definition
@param string $handle
@return Model
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->sections->saveEntryType($record);
}
|
{@inheritdoc}
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
if ($record instanceof SectionModel) {
$definition['entryTypes'] = Craft::$app->controller->module->modelMapper->export($record->getEntryTypes());
}
if ($record instanceof Section_SiteSettings) {
unset($definition['attributes']['sectionId']);
unset($definition['attributes']['siteId']);
}
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
if (Craft::$app->sections->saveSection($record)) {
Craft::$app->controller->module->modelMapper->import(
$definition['entryTypes'],
$record->getEntryTypes(),
['sectionId' => $record->id]
);
return true;
}
return false;
}
|
{@inheritdoc}
|
entailment
|
public function afterImport()
{
$obj = Craft::$app->globals;
$refObject = new \ReflectionObject($obj);
if ($refObject->hasProperty('_allGlobalSets')) {
$refProperty1 = $refObject->getProperty('_allGlobalSets');
$refProperty1->setAccessible(true);
$refProperty1->setValue($obj, null);
}
}
|
Reset craft global sets cache using reflection.
|
entailment
|
public function export(array $settings = []): array
{
$settings = Craft::$app->systemSettings->getSettings('users');
$photoVolumeId = (int) $settings['photoVolumeId'];
$volume = Craft::$app->volumes->getVolumeById($photoVolumeId);
unset($settings['photoVolumeId']);
$settings['photoVolume'] = $volume ? $volume->handle : null;
$fieldLayout = Craft::$app->fields->getLayoutByType(User::class);
return [
'settings' => $settings,
'fieldLayout' => $this->getFieldLayoutDefinition($fieldLayout),
];
}
|
{@inheritdoc}
|
entailment
|
public function import(array $userSettings, array $settings = []): array
{
$photoVolumeId = null;
if (isset($userSettings['settings']['photoVolume'])) {
$volume = Craft::$app->volumes->getVolumeByHandle($userSettings['settings']['photoVolume']);
$photoVolumeId = $volume ? $volume->id : null;
}
unset($userSettings['settings']['photoVolume']);
if (array_key_exists('settings', $userSettings)) {
Schematic::info('- Saving user settings');
$userSettings['settings']['photoVolumeId'] = $photoVolumeId;
if (!Craft::$app->systemSettings->saveSettings('users', $userSettings['settings'])) {
Schematic::warning('- Couldn’t save user settings.');
}
}
if (array_key_exists('fieldLayout', $userSettings)) {
Schematic::info('- Saving user field layout');
$fieldLayout = $this->getFieldLayout($userSettings['fieldLayout']);
$fieldLayout->type = User::class;
Craft::$app->fields->deleteLayoutsByType(User::class);
if (!Craft::$app->fields->saveLayout($fieldLayout)) {
Schematic::warning('- Couldn’t save user field layout.');
Schematic::importError($fieldLayout, 'users');
}
}
return [];
}
|
{@inheritdoc}
|
entailment
|
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
if ($record->groupId) {
$definition['group'] = $record->group->name;
}
unset($definition['attributes']['groupId']);
return $definition;
}
|
{@inheritdoc}
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
if ($definition['group']) {
$record->groupId = $this->getGroupIdByName($definition['group']);
}
return Craft::$app->sites->saveSite($record);
}
|
{@inheritdoc}
|
entailment
|
public function deleteRecord(Model $record): bool
{
return Craft::$app->sites->deleteSiteById($record->id);
}
|
{@inheritdoc}
|
entailment
|
public function getGroupIdByName($name)
{
if (!isset($this->groups)) {
$this->resetCraftSitesServiceGroupsCache();
$this->groups = [];
foreach (Craft::$app->sites->getAllGroups() as $group) {
$this->groups[$group->name] = $group->id;
}
}
if (!array_key_exists($name, $this->groups)) {
$group = new SiteGroup(['name' => $name]);
if (Craft::$app->sites->saveGroup($group)) {
$this->groups[$name] = $group->id;
} else {
Schematic::importError($group, $name);
return null;
}
}
return $this->groups[$name];
}
|
Get group id by name.
@param string $name
@return int|null
|
entailment
|
private function resetCraftSitesServiceGroupsCache()
{
$obj = Craft::$app->sites;
$refObject = new \ReflectionObject($obj);
if ($refObject->hasProperty('_fetchedAllGroups')) {
$refProperty = $refObject->getProperty('_fetchedAllGroups');
$refProperty->setAccessible(true);
$refProperty->setValue($obj, false);
}
}
|
Reset craft site service groups cache using reflection.
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
if (array_key_exists('group', $definition)) {
$record->groupId = $this->getGroupIdByName($definition['group']);
}
return Craft::$app->fields->saveField($record);
}
|
{@inheritdoc}
|
entailment
|
private function getGroupIdByName(string $name)
{
if (!isset($this->groups)) {
$this->resetCraftFieldsServiceGroupsCache();
$this->groups = [];
foreach (Craft::$app->fields->getAllGroups() as $group) {
$this->groups[$group->name] = $group->id;
}
}
if (!array_key_exists($name, $this->groups)) {
$group = new FieldGroup(['name' => $name]);
if (Craft::$app->fields->saveGroup($group)) {
$this->groups[$name] = $group->id;
} else {
return Schematic::importError($group, $name);
}
}
return $this->groups[$name];
}
|
Get group id by name.
@param string $name
@return int|null
|
entailment
|
private function resetCraftFieldsServiceGroupsCache()
{
$obj = Craft::$app->fields;
$refObject = new \ReflectionObject($obj);
if ($refObject->hasProperty('_fetchedAllGroups')) {
$refProperty = $refObject->getProperty('_fetchedAllGroups');
$refProperty->setAccessible(true);
$refProperty->setValue($obj, false);
}
}
|
Reset craft fields service groups cache using reflection.
|
entailment
|
public function getFieldLayoutDefinition(FieldLayout $fieldLayout): array
{
if ($fieldLayout->getTabs()) {
$tabDefinitions = [];
foreach ($fieldLayout->getTabs() as $tab) {
$tabDefinitions[$tab->name] = $this->getFieldLayoutFieldsDefinition($tab->getFields());
}
return [
'type' => $fieldLayout->type,
'tabs' => $tabDefinitions
];
}
return [
'type' => $fieldLayout->type,
'fields' => $this->getFieldLayoutFieldsDefinition($fieldLayout->getFields()),
];
}
|
Get field layout definition.
@param FieldLayout $fieldLayout
@return array
|
entailment
|
private function getFieldLayoutFieldsDefinition(array $fields): array
{
$fieldDefinitions = [];
foreach ($fields as $field) {
$fieldDefinitions[$field->handle] = $field->required;
}
return $fieldDefinitions;
}
|
Get field layout fields definition.
@param FieldInterface[] $fields
@return array
|
entailment
|
public function getFieldLayout(array $fieldLayoutDef): FieldLayout
{
$layoutFields = [];
$requiredFields = [];
if (array_key_exists('tabs', $fieldLayoutDef)) {
foreach ($fieldLayoutDef['tabs'] as $tabName => $tabDef) {
$layoutTabFields = $this->getPrepareFieldLayout($tabDef);
$requiredFields = array_merge($requiredFields, $layoutTabFields['required']);
$layoutFields[$tabName] = $layoutTabFields['fields'];
}
} elseif (array_key_exists('fields', $fieldLayoutDef)) {
$layoutTabFields = $this->getPrepareFieldLayout($fieldLayoutDef);
$requiredFields = $layoutTabFields['required'];
$layoutFields = $layoutTabFields['fields'];
}
$fieldLayout = Craft::$app->fields->assembleLayout($layoutFields, $requiredFields);
if (array_key_exists('type', $fieldLayoutDef)) {
$fieldLayout->type = $fieldLayoutDef['type'];
} else {
$fieldLayout->type = Entry::class;
}
return $fieldLayout;
}
|
Attempt to import a field layout.
@param array $fieldLayoutDef
@return FieldLayout
|
entailment
|
private function getPrepareFieldLayout(array $fieldLayoutDef): array
{
$layoutFields = [];
$requiredFields = [];
foreach ($fieldLayoutDef as $fieldHandle => $required) {
$field = Craft::$app->fields->getFieldByHandle($fieldHandle);
if ($field instanceof Field) {
$layoutFields[] = $field->id;
if ($required) {
$requiredFields[] = $field->id;
}
}
}
return [
'fields' => $layoutFields,
'required' => $requiredFields,
];
}
|
Get a prepared fieldLayout for the craft assembleLayout function.
@param array $fieldLayoutDef
@return array
|
entailment
|
private function clearEmptyGroups()
{
foreach (Craft::$app->fields->getAllGroups() as $group) {
if (count($group->getFields()) == 0) {
Craft::$app->fields->deleteGroup($group);
}
}
}
|
Clear empty field groups
|
entailment
|
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->volumes->saveVolume($record);
}
|
{@inheritdoc}
|
entailment
|
public function init()
{
Craft::setAlias('@NerdsAndCompany/Schematic', __DIR__);
$config = [
'components' => [
'elementIndexMapper' => [
'class' => ElementIndexMapper::class,
],
'emailSettingsMapper' => [
'class' => EmailSettingsMapper::class,
],
'generalSettingsMapper' => [
'class' => GeneralSettingsMapper::class,
],
'modelMapper' => [
'class' => ModelMapper::class,
],
'pluginMapper' => [
'class' => PluginMapper::class,
],
'userSettingsMapper' => [
'class' => UserSettingsMapper::class,
],
],
'dataTypes' => [
'plugins' => PluginDataType::class,
'sites' => SiteDataType::class,
'volumes' => VolumeDataType::class,
'assetTransforms' => AssetTransformDataType::class,
'emailSettings' => EmailSettingsDataType::class,
'fields' => FieldDataType::class,
'generalSettings' => GeneralSettingsDataType::class,
'sections' => SectionDataType::class,
'globalSets' => GlobalSetDataType::class,
'categoryGroups' => CategoryGroupDataType::class,
'tagGroups' => TagGroupDataType::class,
'userGroups' => UserGroupDataType::class,
'userSettings' => UserSettingsDataType::class,
'elementIndexSettings' => ElementIndexDataType::class,
],
];
Craft::configure($this, $config);
parent::init();
}
|
Initialize the module.
|
entailment
|
public function getDataType(string $dataTypeHandle)
{
if (!isset($this->dataTypes[$dataTypeHandle])) {
Schematic::error('DataType '.$dataTypeHandle.' is not registered');
return null;
}
$dataTypeClass = $this->dataTypes[$dataTypeHandle];
if (!class_exists($dataTypeClass)) {
Schematic::error('Class '.$dataTypeClass.' does not exist');
return null;
}
$dataType = new $dataTypeClass();
if (!$dataType instanceof DataTypeInterface) {
Schematic::error($dataTypeClass.' does not implement DataTypeInterface');
return null;
}
return $dataType;
}
|
Get datatype by handle.
@param string $dataTypeHandle
@return DateTypeInterface|null
|
entailment
|
public function checkMapper(string $mapper): bool
{
if (!isset($this->$mapper)) {
Schematic::error('Mapper '.$mapper.' not found');
return false;
}
if (!$this->$mapper instanceof MapperInterface) {
Schematic::error(get_class($this->$mapper).' does not implement MapperInterface');
return false;
}
return true;
}
|
Check mapper handle is valid.
@param string $mapper
@return bool
|
entailment
|
public function getConverter(string $modelClass, string $originalClass = '')
{
if ('' === $originalClass) {
$originalClass = $modelClass;
}
$converterClass = 'NerdsAndCompany\\Schematic\\Converters\\'.ucfirst(str_replace('craft\\', '', $modelClass));
$event = new ConverterEvent([
'modelClass' => $modelClass,
'converterClass' => $converterClass,
]);
$this->trigger(self::EVENT_RESOLVE_CONVERTER, $event);
$converterClass = $event->converterClass;
if (class_exists($converterClass)) {
$converter = new $converterClass();
if ($converter instanceof ConverterInterface) {
return $converter;
}
}
$parentClass = get_parent_class($modelClass);
if (!$parentClass) {
Schematic::error('No converter found for '.$originalClass);
return null;
}
return $this->getConverter($parentClass, $originalClass);
}
|
Find converter for model class.
@param string $modelClass
@return ConverterInterface|null
|
entailment
|
public static function error($message)
{
Craft::$app->controller->stdout($message.PHP_EOL, Console::FG_RED);
}
|
Logs an error message.
@param string|array $message the message to be logged. This can be a simple string or a more
complex data structure, such as array.
|
entailment
|
public static function warning($message)
{
Craft::$app->controller->stdout($message.PHP_EOL, Console::FG_YELLOW);
}
|
Logs a warning message.
@param string|array $message the message to be logged. This can be a simple string or a more
complex data structure, such as array.
|
entailment
|
public static function importError(Model $record, string $handle)
{
static::warning('- Error importing '.get_class($record).' '.$handle);
$errors = $record->getErrors();
if (!is_array($errors)) {
static::error(' - An unknown error has occurred');
return;
}
foreach ($errors as $subErrors) {
foreach ($subErrors as $error) {
static::error(' - '.$error);
}
}
}
|
Log an import error.
@param Model $record
@param string $handle
|
entailment
|
public function actionIndex(): int
{
$this->disableLogging();
$configurations = [];
foreach ($this->getDataTypes() as $dataTypeHandle) {
$dataType = $this->module->getDataType($dataTypeHandle);
if (null == $dataType) {
continue;
}
$mapper = $dataType->getMapperHandle();
if (!$this->module->checkMapper($mapper)) {
continue;
}
$records = $dataType->getRecords();
$configurations[$dataTypeHandle] = $this->module->$mapper->export($records);
}
// Load override file.
$overrideData = [];
if (file_exists($this->overrideFile)) {
// Parse data in the overrideFile if available.
$overrideData = Data::parseYamlFile($this->overrideFile);
}
// Export the configuration to a single file.
if ($this->getStorageType() === self::SINGLE_FILE) {
$this->exportToSingle($configurations, $overrideData);
}
// Export the configuration to multiple yaml files.
if ($this->getStorageType() === self::MULTIPLE_FILES) {
$this->exportToMultiple($configurations, $overrideData);
}
return 0;
}
|
Exports the Craft datamodel.
@return int
@throws \yii\base\ErrorException
|
entailment
|
private function exportToSingle(array $configurations, array $overrideData)
{
$configurations = array_replace_recursive($configurations, $overrideData);
FileHelper::writeToFile($this->file, Data::toYaml($configurations));
Schematic::info('Exported schema to '.$this->file);
}
|
Export schema to single file
@param array $configurations configurations to export
@param array $overrideData overridden configurations
|
entailment
|
private function exportToMultiple(array $configurations, array $overrideData)
{
// Create export directory if it doesn't exist.
if (!file_exists($this->path)) {
mkdir($this->path, 2775, true);
}
foreach ($configurations as $dataTypeHandle => $configuration) {
Schematic::info('Exporting '.$dataTypeHandle);
foreach ($configuration as $recordName => $records) {
// Check if there is data in the override file for the current record.
if (isset($overrideData[$dataTypeHandle][$recordName])) {
$records = array_replace_recursive($records, $overrideData[$dataTypeHandle][$recordName]);
}
// Export records to file.
$fileName = $this->toSafeFileName($dataTypeHandle.'.'.$recordName.'.yml');
FileHelper::writeToFile($this->path.$fileName, Data::toYaml($records));
Schematic::info('Exported '.$recordName.' to '.$fileName);
}
}
}
|
Export schema to multiple files
@param array $configurations configurations to export
@param array $overrideData overridden configurations
|
entailment
|
public static function bigHexToBigDec(string $hex): string
{
$dec = '0';
$len = \strlen($hex);
for ($i = 1; $i <= $len; $i++) {
$dec = bcadd($dec, bcmul(\strval(hexdec($hex[$i - 1])), bcpow('16', \strval($len - $i))));
}
return $dec;
}
|
@see http://stackoverflow.com/questions/1273484/large-hex-values-with-php-hexdec
@param string $hex
@return string
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.