repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/ArbitraryLengthValidatorTest.php | tests/Unit/Validators/ArbitraryLengthValidatorTest.php | <?php
use TailwindMerge\Validators\ArbitraryLengthValidator;
test('is arbitrary length', function ($input, $output) {
expect(ArbitraryLengthValidator::validate($input))->toBe($output);
})->with([
['[3.7%]', true],
['[481px]', true],
['[19.1rem]', true],
['[50vw]', true],
['[56vh]', true],
['[length:var(--arbitrary)]', true],
['1', false],
['3px', false],
['1d5', false],
['[1]', false],
['[12px', false],
['12px]', false],
['one', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/ArbitraryValueValidatorTest.php | tests/Unit/Validators/ArbitraryValueValidatorTest.php | <?php
use TailwindMerge\Validators\ArbitraryValueValidator;
test('is arbitrary value', function ($input, $output) {
expect(ArbitraryValueValidator::validate($input))->toBe($output);
})->with([
['[1]', true],
['[bla]', true],
['[not-an-arbitrary-value?]', true],
['[auto,auto,minmax(0,1fr),calc(100vw-50%)]', true],
['[]', false],
['[1', false],
['1]', false],
['1', false],
['one', false],
['o[n]e', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/LengthValidatorTest.php | tests/Unit/Validators/LengthValidatorTest.php | <?php
use TailwindMerge\Validators\LengthValidator;
test('is length', function ($input, $output) {
expect(LengthValidator::validate($input))->toBe($output);
})->with([
['1', true],
['1023713', true],
['1.5', true],
['1231.503761', true],
['px', true],
['full', true],
['screen', true],
['1/2', true],
['123/345', true],
['[3.7%]', false],
['[481px]', false],
['[19.1rem]', false],
['[50vw]', false],
['[56vh]', false],
['[length:var(--arbitrary)]', false],
['1d5', false],
['[1]', false],
['[12px', false],
['12px]', false],
['one', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/IntegerValidatorTest.php | tests/Unit/Validators/IntegerValidatorTest.php | <?php
use TailwindMerge\Validators\IntegerValidator;
test('is integer', function ($input, $output) {
expect(IntegerValidator::validate($input))->toBe($output);
})->with([
['1', true],
['123', true],
['8312', true],
['[8312]', false],
['[2]', false],
['[8312px]', false],
['[8312%]', false],
['[8312rem]', false],
['8312.2', false],
['1.2', false],
['one', false],
['1/2', false],
['1%', false],
['1px', false],
['', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/AnyValueValidatorTest.php | tests/Unit/Validators/AnyValueValidatorTest.php | <?php
use TailwindMerge\Validators\AnyValueValidator;
test('is any value', function ($input, $output) {
expect(AnyValueValidator::validate($input))->toBe($output);
})->with([
['', true],
['something', true],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/ArbitrarySizeValidatorTest.php | tests/Unit/Validators/ArbitrarySizeValidatorTest.php | <?php
use TailwindMerge\Validators\ArbitrarySizeValidator;
test('is arbitrary size', function ($input, $output) {
expect(ArbitrarySizeValidator::validate($input))->toBe($output);
})->with([
['[size:2px]', true],
['[size:bla]', true],
['[length:bla]', true],
['[percentage:bla]', true],
['[2px]', false],
['[bla]', false],
['size:2px', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/TshirtSizeValidatorTest.php | tests/Unit/Validators/TshirtSizeValidatorTest.php | <?php
use TailwindMerge\Validators\TshirtSizeValidator;
test('is t-shirt size', function ($input, $output) {
expect(TshirtSizeValidator::validate($input))->toBe($output);
})->with([
['xs', true],
['sm', true],
['md', true],
['lg', true],
['xl', true],
['2xl', true],
['2.5xl', true],
['10xl', true],
['2xs', true],
['2lg', true],
['', false],
['hello', false],
['1', false],
['xl3', false],
['2xl3', false],
['-xl', false],
['[sm]', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/ArbitraryPositionValidatorTest.php | tests/Unit/Validators/ArbitraryPositionValidatorTest.php | <?php
use TailwindMerge\Validators\ArbitraryPositionValidator;
test('is arbitrary position', function ($input, $output) {
expect(ArbitraryPositionValidator::validate($input))->toBe($output);
})->with([
['[position:2px]', true],
['[position:bla]', true],
['[2px]', false],
['[bla]', false],
['position:2px', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/PercentValidatorTest.php | tests/Unit/Validators/PercentValidatorTest.php | <?php
use TailwindMerge\Validators\PercentValidator;
test('is number', function ($input, $output) {
expect(PercentValidator::validate($input))->toBe($output);
})->with([
['1%', true],
['100.001%', true],
['.01%', true],
['0%', true],
['0', false],
['one%', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/ArbitraryImageValidatorTest.php | tests/Unit/Validators/ArbitraryImageValidatorTest.php | <?php
use TailwindMerge\Validators\ArbitraryImageValidator;
test('is arbitrary image', function ($input, $output) {
expect(ArbitraryImageValidator::validate($input))->toBe($output);
})->with([
['[url:var(--my-url)]', true],
['[url(something)]', true],
['[url:bla]', true],
['[image:bla]', true],
['[linear-gradient(something)]', true],
['[repeating-conic-gradient(something)]', true],
['[var(--my-url)]', false],
['[bla]', false],
['url:2px', false],
['url(2px)', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/NumberValidatorTest.php | tests/Unit/Validators/NumberValidatorTest.php | <?php
use TailwindMerge\Validators\NumberValidator;
test('is number', function ($input, $output) {
expect(NumberValidator::validate($input))->toBe($output);
})->with([
['1', true],
['1.5', true],
['one', false],
['1px', false],
['', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/ArbitraryShadowValidatorTest.php | tests/Unit/Validators/ArbitraryShadowValidatorTest.php | <?php
use TailwindMerge\Validators\ArbitraryShadowValidator;
test('is arbitrary shadow', function ($input, $output) {
expect(ArbitraryShadowValidator::validate($input))->toBe($output);
})->with([
['[0_35px_60px_-15px_rgba(0,0,0,0.3)]', true],
['[inset_0_1px_0,inset_0_-1px_0]', true],
['[0_0_#00f]', true],
['[.5rem_0_rgba(5,5,5,5)]', true],
['[-.5rem_0_#123456]', true],
['[0.5rem_-0_#123456]', true],
['[0.5rem_-0.005vh_#123456]', true],
['[0.5rem_-0.005vh]', true],
['[rgba(5,5,5,5)]', false],
['[#00f]', false],
['[something-else]', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
gehrisandro/tailwind-merge-php | https://github.com/gehrisandro/tailwind-merge-php/blob/dc11b9d4a625dd5be885900e5ef14c3efa260277/tests/Unit/Validators/ArbitraryNumberValidatorTest.php | tests/Unit/Validators/ArbitraryNumberValidatorTest.php | <?php
use TailwindMerge\Validators\ArbitraryNumberValidator;
test('is arbitrary number', function ($input, $output) {
expect(ArbitraryNumberValidator::validate($input))->toBe($output);
})->with([
['[number:black]', true],
['[number:bla]', true],
['[number:230]', true],
['[450]', true],
['[2px]', false],
['[bla]', false],
['[black]', false],
['black', false],
['450', false],
]);
| php | MIT | dc11b9d4a625dd5be885900e5ef14c3efa260277 | 2026-01-05T04:59:39.669817Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Schematic.php | src/Schematic.php | <?php
namespace NerdsAndCompany\Schematic;
use Craft;
use craft\base\Model;
use craft\base\Plugin;
use yii\helpers\Console;
use NerdsAndCompany\Schematic\DataTypes\AssetTransformDataType;
use NerdsAndCompany\Schematic\DataTypes\CategoryGroupDataType;
use NerdsAndCompany\Schematic\DataTypes\ElementIndexDataType;
use NerdsAndCompany\Schematic\DataTypes\EmailSettingsDataType;
use NerdsAndCompany\Schematic\DataTypes\FieldDataType;
use NerdsAndCompany\Schematic\DataTypes\GeneralSettingsDataType;
use NerdsAndCompany\Schematic\DataTypes\GlobalSetDataType;
use NerdsAndCompany\Schematic\DataTypes\PluginDataType;
use NerdsAndCompany\Schematic\DataTypes\SectionDataType;
use NerdsAndCompany\Schematic\DataTypes\SiteDataType;
use NerdsAndCompany\Schematic\DataTypes\TagGroupDataType;
use NerdsAndCompany\Schematic\DataTypes\UserGroupDataType;
use NerdsAndCompany\Schematic\DataTypes\UserSettingsDataType;
use NerdsAndCompany\Schematic\DataTypes\VolumeDataType;
use NerdsAndCompany\Schematic\Mappers\ElementIndexMapper;
use NerdsAndCompany\Schematic\Mappers\EmailSettingsMapper;
use NerdsAndCompany\Schematic\Mappers\GeneralSettingsMapper;
use NerdsAndCompany\Schematic\Mappers\ModelMapper;
use NerdsAndCompany\Schematic\Mappers\PluginMapper;
use NerdsAndCompany\Schematic\Mappers\UserSettingsMapper;
use NerdsAndCompany\Schematic\Interfaces\ConverterInterface;
use NerdsAndCompany\Schematic\Interfaces\DataTypeInterface;
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
use NerdsAndCompany\Schematic\Events\ConverterEvent;
/**
* Schematic.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Schematic extends Plugin
{
const EVENT_RESOLVE_CONVERTER = 'resolve_converter';
const EVENT_MAP_SOURCE = 'map_source';
/**
* @var string
*/
public $controllerNamespace = 'NerdsAndCompany\Schematic\Controllers';
/**
* @var array
*/
public $dataTypes = [];
/**
* Initialize the module.
*/
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();
}
/**
* Get datatype by handle.
*
* @param string $dataTypeHandle
*
* @return DateTypeInterface|null
*/
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;
}
/**
* Check mapper handle is valid.
*
* @param string $mapper
*
* @return bool
*/
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;
}
/**
* Find converter for model class.
*
* @param string $modelClass
*
* @return ConverterInterface|null
*/
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);
}
/**
* Is force enabled?
*
* @var bool
*/
public static $force = false;
/**
* 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.
*/
public static function error($message)
{
Craft::$app->controller->stdout($message.PHP_EOL, Console::FG_RED);
}
/**
* 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.
*/
public static function warning($message)
{
Craft::$app->controller->stdout($message.PHP_EOL, Console::FG_YELLOW);
}
/**
* Logs an info 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.
*/
public static function info($message)
{
Craft::$app->controller->stdout($message.PHP_EOL);
}
/**
* Log an import error.
*
* @param Model $record
* @param string $handle
*/
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);
}
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Controllers/Base.php | src/Controllers/Base.php | <?php
namespace NerdsAndCompany\Schematic\Controllers;
use Craft;
use NerdsAndCompany\Schematic\Models\Data;
use yii\console\Controller;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Base Controller.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Base extends Controller
{
const SINGLE_FILE = 'single';
const MULTIPLE_FILES = 'multiple';
public $file = 'config/schema.yml';
public $path = 'config/schema/';
public $overrideFile = 'config/override.yml';
public $configFile = 'config/schematic.yml';
public $exclude;
public $include;
/** @var array */
private $config;
/**
* {@inheritdoc}
*
* @return array
*/
public function options($actionID): array
{
return ['file', 'overrideFile', 'include', 'exclude'];
}
/**
* Get the datatypes to import and/or export.
*
* @return array
*/
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;
}
/**
* Apply given includes.
*
* @param array $dataTypes
*
* @return array
*/
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 excludes.
*
* @param array $dataTypes
*
* @return array
*/
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);
}
/**
* Disable normal logging (to stdout) while running console commands.
*
* @TODO: Find a less hacky way to solve this
*/
protected function disableLogging()
{
if (Craft::$app->log) {
Craft::$app->log->targets = [];
}
}
/**
* Convert a filename to one safe to use.
*
* @param $fileName
* @return mixed
*/
protected function toSafeFileName($fileName)
{
// Remove all slashes and backslashes in the recordName to avoid file sturcture problems.
$fileName = str_replace('\\', ':', $fileName);
$fileName = str_replace('/', '::', $fileName);
return $fileName;
}
/**
* Convert a safe filename back to it's original form.
*
* @param $fileName
* @return mixed
*/
protected function fromSafeFileName($fileName)
{
// Replace the placeholders back to slashes and backslashes.
$fileName = str_replace(':', '\\', $fileName);
$fileName = str_replace('::', '/', $fileName);
return $fileName;
}
/**
* Get the storage type.
*
* @throws \Exception
*/
protected function getStorageType() : string
{
return $this->getConfigSetting('storageType') ?? self::SINGLE_FILE;
}
/**
* Get a setting from the config.
*
* @param $name
*
* @return mixed|null
* @throws \Exception
*/
public function getConfigSetting($name)
{
$config = $this->getConfig();
return $config[$name] ?? null;
}
/**
* @return array
* @throws \Exception
*/
public function getConfig(): array
{
if (empty($this->config)) {
$this->readConfigFile();
}
return $this->config ?? [];
}
/**
* @param array $config
*/
public function setConfig(array $config): void
{
$this->config = $config;
}
/**
* @throws \Exception
*/
protected function readConfigFile()
{
// Load config file.
if (file_exists($this->configFile)) {
// Parse data in the overrideFile if available.
$this->config = Data::parseYamlFile($this->configFile);
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Controllers/ExportController.php | src/Controllers/ExportController.php | <?php
namespace NerdsAndCompany\Schematic\Controllers;
use Craft;
use craft\helpers\FileHelper;
use NerdsAndCompany\Schematic\Models\Data;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Export Controller.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ExportController extends Base
{
/**
* Exports the Craft datamodel.
*
* @return int
* @throws \yii\base\ErrorException
*/
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;
}
/**
* Export schema to single file
*
* @param array $configurations configurations to export
* @param array $overrideData overridden configurations
*/
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 multiple files
*
* @param array $configurations configurations to export
* @param array $overrideData overridden configurations
*/
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);
}
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Controllers/ImportController.php | src/Controllers/ImportController.php | <?php
namespace NerdsAndCompany\Schematic\Controllers;
use Craft;
use NerdsAndCompany\Schematic\Models\Data;
use NerdsAndCompany\Schematic\Schematic;
use craft\errors\WrongEditionException;
/**
* Schematic Import Command.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ImportController extends Base
{
public $force = false;
/**
* {@inheritdoc}
*
* @return array
*/
public function options($actionID): array
{
return array_merge(parent::options($actionID), ['force']);
}
/**
* Imports the Craft datamodel.
*
* @return int
* @throws \Exception
*/
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;
}
}
/**
* Import definitions from file
*
* @param array $overrideData The overridden data
* @throws \Exception
*/
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 directory
*
* @param array $overrideData The overridden data
* @throws \Exception
*/
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 from definitions.
*
* @param array $dataTypes The data types to import
* @param array $definitions The definitions to use
* @throws \Exception
*/
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);
}
}
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Interfaces/MapperInterface.php | src/Interfaces/MapperInterface.php | <?php
namespace NerdsAndCompany\Schematic\Interfaces;
/**
* Schematic Mapper Interface.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
interface MapperInterface
{
/**
* Export given records.
*
* @param array $records
*
* @return array
*/
public function export(array $records): array;
/**
* Import given definitions.
*
* @param array $records
*
* @return array
*/
public function import(array $definitions, array $records): array;
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Interfaces/ConverterInterface.php | src/Interfaces/ConverterInterface.php | <?php
namespace NerdsAndCompany\Schematic\Interfaces;
use craft\base\Model;
/**
* Schematic Converter Interface.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
interface ConverterInterface
{
/**
* Save a record.
*
* @param Model $record
* @param array $definition
*
* @return bool
*/
public function saveRecord(Model $record, array $definition): bool;
/**
* Delete a record.
*
* @param Model $record
*
* @return bool
*/
public function deleteRecord(Model $record): bool;
/**
* Gets the record's key to index by.
*
* @param Model $record
*
* @return string
*/
public function getRecordIndex(Model $record): string;
/**
* Get single record definition.
*
* @param Model $record
*
* @return array
*/
public function getRecordDefinition(Model $record): array;
/**
* Set record attributes from definition.
*
* @param Model $record
* @param array $definition
* @param array $defaultAttributes to also use
*/
public function setRecordAttributes(Model &$record, array $definition, array $defaultAttributes);
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Interfaces/DataTypeInterface.php | src/Interfaces/DataTypeInterface.php | <?php
namespace NerdsAndCompany\Schematic\Interfaces;
/**
* Schematic Data Type Interface.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
interface DataTypeInterface
{
/**
* Get mapper component handle.
*
* @return string
*/
public function getMapperHandle(): string;
/**
* Get records of this type.
*
* @return array
*/
public function getRecords(): array;
/**
* Callback for actions after import.
* For example to clear caches.
*/
public function afterImport();
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Mappers/UserSettingsMapper.php | src/Mappers/UserSettingsMapper.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use craft\elements\User;
use NerdsAndCompany\Schematic\Behaviors\FieldLayoutBehavior;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
use yii\base\Component as BaseComponent;
/**
* Schematic User Settings Mapper.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*
* @method getFieldLayoutDefinition(FieldLayout $fieldLayout): array
* @method getFieldLayout(array $fieldLayoutDef): FieldLayout
*/
class UserSettingsMapper extends BaseComponent implements MapperInterface
{
/**
* Load fieldlayout behavior.
*
* @return array
*/
public function behaviors(): array
{
return [
FieldLayoutBehavior::class,
];
}
/**
* {@inheritdoc}
*/
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}
*/
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 [];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Mappers/PluginMapper.php | src/Mappers/PluginMapper.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
use yii\base\Component as BaseComponent;
/**
* Schematic Plugin Mapper.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class PluginMapper extends BaseComponent implements MapperInterface
{
/**
* {@inheritdoc}
*/
public function export(array $plugins): array
{
$pluginDefinitions = [];
foreach ($plugins as $handle => $pluginInfo) {
$pluginDefinitions[$handle] = $this->getPluginDefinition($handle, $pluginInfo);
}
ksort($pluginDefinitions);
return $pluginDefinitions;
}
/**
* @param string $handle
* @param array $pluginInfo
*
* @return array
*/
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 : [],
];
}
/**
* {@inheritdoc}
*/
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;
}
/**
* Install, enable, disable and/or update plugin.
*
* @param string $handle
* @param array $definition
* @param array $pluginInfo
*
* @return bool
*/
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;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Mappers/ElementIndexMapper.php | src/Mappers/ElementIndexMapper.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use NerdsAndCompany\Schematic\Behaviors\SourcesBehavior;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
use yii\base\Component as BaseComponent;
/**
* Schematic Element Index Mapper.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*
* @method getSources(string $fieldType, $sources, string $indexFrom, string $indexTo)
* @method getSource(string $fieldType, string $source, string $indexFrom, string $indexTo)
*/
class ElementIndexMapper extends BaseComponent implements MapperInterface
{
/**
* Load sources behaviors.
*
* @return array
*/
public function behaviors(): array
{
return [
SourcesBehavior::class,
];
}
/**
* {@inheritdoc}
*/
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}
*/
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 [];
}
/**
* Get mapped element index settings, converting source ids to handles or back again.
*
* @param array $settings
* @param string $fromIndex
* @param string $toIndex
*
* @return array
*/
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;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Mappers/ModelMapper.php | src/Mappers/ModelMapper.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use craft\base\Model;
use yii\base\Component as BaseComponent;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
/**
* Schematic Model Mapper.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ModelMapper extends BaseComponent implements MapperInterface
{
/**
* {@inheritdoc}
*/
public function export(array $records): array
{
$result = [];
foreach ($records as $record) {
$modelClass = get_class($record);
$converter = Craft::$app->controller->module->getConverter($modelClass);
if ($converter) {
$index = $converter->getRecordIndex($record);
$result[$index] = $converter->getRecordDefinition($record);
}
}
return $result;
}
/**
* 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
*/
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;
}
/**
* Get records by handle.
*
* @param array $records
*
* @return array
*/
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;
}
/**
* Find record from records by handle or new record.
*
* @param Model[] $recordsByHandle
* @param array $definition
* @param string $handle
*
* @return Model
*/
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;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Mappers/EmailSettingsMapper.php | src/Mappers/EmailSettingsMapper.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
use yii\base\Component as BaseComponent;
/**
* Schematic Email Settings Mapper.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class EmailSettingsMapper extends BaseComponent implements MapperInterface
{
/**
* {@inheritdoc}
*/
public function export(array $settings = []): array
{
$settings = Craft::$app->systemSettings->getSettings('email');
return [
'settings' => $settings,
];
}
/**
* {@inheritdoc}
*/
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 [];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Mappers/GeneralSettingsMapper.php | src/Mappers/GeneralSettingsMapper.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Interfaces\MapperInterface;
use yii\base\Component as BaseComponent;
use craft\models\Info;
/**
* Schematic General Settings Mapper.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GeneralSettingsMapper extends BaseComponent implements MapperInterface
{
/**
* {@inheritdoc}
*/
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}
*/
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 [];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Elements/GlobalSet.php | src/Converters/Elements/GlobalSet.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Elements;
use Craft;
use craft\elements\GlobalSet as GlobalSetElement;
use craft\base\Model;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Converters\Models\Base;
/**
* Schematic Globals Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GlobalSet extends Base
{
/**
* {@inheritdoc}
*/
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}
*/
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}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->elements->deleteElementById($record->id);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Base/Field.php | src/Converters/Base/Field.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Base;
use Craft;
use craft\base\Model;
use craft\models\FieldGroup;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Converters\Models\Base;
/**
* Schematic Fields Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Field extends Base
{
/**
* @var number[]
*/
private $groups;
/**
* {@inheritdoc}
*/
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
if ($record->groupId) {
$definition['group'] = $record->group->name;
}
$definition['attributes']['required'] = $definition['attributes']['required'] == true;
unset($definition['attributes']['context']);
unset($definition['attributes']['groupId']);
unset($definition['attributes']['layoutId']);
unset($definition['attributes']['tabId']);
return $definition;
}
/**
* {@inheritdoc}
*/
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}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->fields->deleteField($record);
}
/**
* Get group id by name.
*
* @param string $name
*
* @return int|null
*/
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];
}
/**
* Reset craft fields service groups cache using reflection.
*/
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);
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Base/Volume.php | src/Converters/Base/Volume.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Base;
use Craft;
use craft\base\Model;
use NerdsAndCompany\Schematic\Converters\Models\Base;
/**
* Schematic Volume Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Volume extends Base
{
/**
* {@inheritdoc}
*/
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->volumes->saveVolume($record);
}
/**
* {@inheritdoc}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->volumes->deleteVolume($record);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Fields/Assets.php | src/Converters/Fields/Assets.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Fields;
use Craft;
use craft\base\Model;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Converters\Base\Field;
/**
* Schematic Asset Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Assets extends Field
{
/**
* {@inheritdoc}
*/
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}
*/
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);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Fields/Matrix.php | src/Converters/Fields/Matrix.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Fields;
use Craft;
use craft\base\Model;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Converters\Base\Field;
/**
* Schematic Matrix Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Matrix extends Field
{
/**
* {@inheritdoc}
*/
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
$definition['blockTypes'] = Craft::$app->controller->module->modelMapper->export($record->getBlockTypes());
return $definition;
}
/**
* {@inheritdoc}
*/
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;
}
/**
* Reset craft matrix service block types cache using reflection.
*/
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 field block types cache using reflection.
*
* @param Model $record
*/
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);
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/TagGroup.php | src/Converters/Models/TagGroup.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
/**
* Schematic TagGroups Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class TagGroup extends Base
{
/**
* {@inheritdoc}
*/
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->tags->saveTagGroup($record);
}
/**
* {@inheritdoc}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->tags->deleteTagGroupById($record->id);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/AssetTransform.php | src/Converters/Models/AssetTransform.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
/**
* Schematic Asset Transforms Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class AssetTransform extends Base
{
/**
* {@inheritdoc}
*/
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
unset($definition['attributes']['dimensionChangeTime']);
return $definition;
}
/**
* {@inheritdoc}
*/
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->assetTransforms->saveTransform($record);
}
/**
* {@inheritdoc}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->assetTransforms->deleteTransform($record->id);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/Base.php | src/Converters/Models/Base.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
use craft\models\MatrixBlockType as MatrixBlockTypeModel;
use yii\base\Component as BaseComponent;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Behaviors\FieldLayoutBehavior;
use NerdsAndCompany\Schematic\Behaviors\SourcesBehavior;
use NerdsAndCompany\Schematic\Interfaces\ConverterInterface;
/**
* Schematic Base Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*
* @method getSources(string $fieldType, $sources, string $indexFrom, string $indexTo)
* @method getSource(string $fieldType, string $source, string $indexFrom, string $indexTo)
* @method getFieldLayoutDefinition(FieldLayout $fieldLayout): array
* @method getFieldLayout(array $fieldLayoutDef): FieldLayout
*/
abstract class Base extends BaseComponent implements ConverterInterface
{
/**
* Load fieldlayout and sources behaviors.
*
* @return array
*/
public function behaviors()
{
return [
FieldLayoutBehavior::class,
SourcesBehavior::class,
];
}
/**
* {@inheritdoc}
*/
abstract public function saveRecord(Model $record, array $definition): bool;
/**
* {@inheritdoc}
*/
abstract public function deleteRecord(Model $record): bool;
/**
* {@inheritdoc}
*/
public function getRecordIndex(Model $record): string
{
return $record->handle;
}
/**
* {@inheritdoc}
*/
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}
*/
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);
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/MatrixBlockType.php | src/Converters/Models/MatrixBlockType.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
/**
* Schematic Matrix Block Types Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class MatrixBlockType extends Base
{
/**
* {@inheritdoc}
*/
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}
*/
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}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->matrix->deleteBlockType($record);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/Section.php | src/Converters/Models/Section.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
use craft\models\Section as SectionModel;
use craft\models\Section_SiteSettings;
/**
* Schematic Sections Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Section extends Base
{
/**
* {@inheritdoc}
*/
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}
*/
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}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->sections->deleteSection($record);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/Site.php | src/Converters/Models/Site.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\models\SiteGroup;
use craft\base\Model;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Sites Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Site extends Base
{
/**
* @var number[]
*/
private $groups;
/**
* {@inheritdoc}
*/
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}
*/
public function saveRecord(Model $record, array $definition): bool
{
if ($definition['group']) {
$record->groupId = $this->getGroupIdByName($definition['group']);
}
return Craft::$app->sites->saveSite($record);
}
/**
* {@inheritdoc}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->sites->deleteSiteById($record->id);
}
/**
* Get group id by name.
*
* @param string $name
*
* @return int|null
*/
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];
}
/**
* Reset craft site service groups cache using reflection.
*/
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);
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/CategoryGroup.php | src/Converters/Models/CategoryGroup.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
use craft\models\CategoryGroup_SiteSettings;
/**
* Schematic Category Groups Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class CategoryGroup extends Base
{
/**
* {@inheritdoc}
*/
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}
*/
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->categories->saveGroup($record);
}
/**
* {@inheritdoc}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->categories->deleteGroupById($record->id);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/UserGroup.php | src/Converters/Models/UserGroup.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
/**
* Schematic User Groups Service.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class UserGroup extends Base
{
/**
* {@inheritdoc}
*/
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}
*/
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}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->userGroups->deleteGroupById($record->id);
}
/**
* Get a mapping of all permissions from lowercase to camelcase
* savePermissions only accepts camelcase.
*
* @return array
*/
private function getAllMappedPermissions(): array
{
$mappedPermissions = [];
foreach (Craft::$app->userPermissions->getAllPermissions() as $permissions) {
$mappedPermissions = array_merge($mappedPermissions, $this->getMappedPermissions($permissions));
}
return $mappedPermissions;
}
/**
* Recursive function to get mapped permissions.
*
* @param array $permissions
*
* @return array
*/
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;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Converters/Models/EntryType.php | src/Converters/Models/EntryType.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Model;
/**
* Schematic Entry Types Converter.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class EntryType extends Base
{
/**
* {@inheritdoc}
*/
public function getRecordDefinition(Model $record): array
{
$definition = parent::getRecordDefinition($record);
unset($definition['attributes']['sectionId']);
return $definition;
}
/**
* {@inheritdoc}
*/
public function saveRecord(Model $record, array $definition): bool
{
return Craft::$app->sections->saveEntryType($record);
}
/**
* {@inheritdoc}
*/
public function deleteRecord(Model $record): bool
{
return Craft::$app->sections->deleteEntryType($record);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Behaviors/FieldLayoutBehavior.php | src/Behaviors/FieldLayoutBehavior.php | <?php
namespace NerdsAndCompany\Schematic\Behaviors;
use Craft;
use yii\base\Behavior;
use craft\base\Field;
use craft\base\FieldInterface;
use craft\models\FieldLayout;
use craft\elements\Entry;
/**
* Schematic FieldLayout Behavior.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class FieldLayoutBehavior extends Behavior
{
/**
* Get field layout definition.
*
* @param FieldLayout $fieldLayout
*
* @return array
*/
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 fields definition.
*
* @param FieldInterface[] $fields
*
* @return array
*/
private function getFieldLayoutFieldsDefinition(array $fields): array
{
$fieldDefinitions = [];
foreach ($fields as $field) {
$fieldDefinitions[$field->handle] = $field->required;
}
return $fieldDefinitions;
}
/**
* Attempt to import a field layout.
*
* @param array $fieldLayoutDef
*
* @return FieldLayout
*/
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;
}
/**
* Get a prepared fieldLayout for the craft assembleLayout function.
*
* @param array $fieldLayoutDef
*
* @return array
*/
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,
];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Behaviors/SourcesBehavior.php | src/Behaviors/SourcesBehavior.php | <?php
namespace NerdsAndCompany\Schematic\Behaviors;
use Craft;
use TypeError;
use yii\base\Behavior;
use craft\base\Model;
use craft\records\VolumeFolder;
use craft\fields\Users;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Events\SourceMappingEvent;
/**
* Schematic Sources Behavior.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SourcesBehavior extends Behavior
{
/** Hack to be able to avoid the active record call in VolumeFolder::findOne() */
public $mockFolder = null;
/**
* Recursively find sources in definition attributes.
*
* @param string $fieldType
* @param array $attributes
* @param string $indexFrom
* @param string $indexTo
*
* @return array
*/
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;
}
/**
* 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
*/
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;
}
/**
* 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)
*/
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;
}
/**
* Get a folder by id
* @SuppressWarnings(PHPMD.UnusedPrivateMethod)
*
* @param int $folderId
* @return object
*/
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 folder by volume id
*
* @param int $volumeId
* @return VolumeFolder
*/
private function getFolderByVolumeId(int $volumeId): VolumeFolder
{
return $this->mockFolder ? $this->mockFolder : VolumeFolder::findOne(['volumeId' => $volumeId]);
}
/**
* Set a mock folder for the tests
*
* @param VolumeFolder $mockFolder
*/
public function setMockFolder(VolumeFolder $mockFolder)
{
$this->mockFolder = $mockFolder;
}
/**
* Get a folder by volume handle
* @SuppressWarnings(PHPMD.UnusedPrivateMethod)
*
* @param string $folderHandle
* @return object
*/
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;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/UserGroupDataType.php | src/DataTypes/UserGroupDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic UserGroups DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class UserGroupDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->userGroups->getAllGroups();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/EmailSettingsDataType.php | src/DataTypes/EmailSettingsDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic EmailSettings DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class EmailSettingsDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'emailSettingsMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return [];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/Base.php | src/DataTypes/Base.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use NerdsAndCompany\Schematic\Interfaces\DataTypeInterface;
abstract class Base implements DataTypeInterface
{
/**
* {@inheritdoc}
*/
abstract public function getMapperHandle(): string;
/**
* {@inheritdoc}
*/
abstract public function getRecords(): array;
/**
* {@inheritdoc}
*/
public function afterImport()
{
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/GeneralSettingsDataType.php | src/DataTypes/GeneralSettingsDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic GeneralSettings DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GeneralSettingsDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'generalSettingsMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return [];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/TagGroupDataType.php | src/DataTypes/TagGroupDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic TagGroups DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class TagGroupDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->tags->getAllTagGroups();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/AssetTransformDataType.php | src/DataTypes/AssetTransformDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic AssetTransforms DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class AssetTransformDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->assetTransforms->getAllTransforms();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/SectionDataType.php | src/DataTypes/SectionDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Sections DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SectionDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->sections->getAllSections();
}
/**
* Reset craft editable sections cache using reflection.
*/
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());
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/UserSettingsDataType.php | src/DataTypes/UserSettingsDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic UserSettings DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class UserSettingsDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'userSettingsMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return [];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/SiteDataType.php | src/DataTypes/SiteDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Sites DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SiteDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->sites->getAllSites();
}
/**
* {@inheritdoc}
*/
public function afterImport()
{
$this->clearSiteCaches();
if (Schematic::$force) {
$this->clearEmptyGroups();
}
}
/**
* Reset craft site service sites cache using reflection.
*/
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
}
/**
* Clear empty sute groups
*/
private function clearEmptyGroups()
{
foreach (Craft::$app->sites->getAllGroups() as $group) {
if (count($group->getSites()) == 0) {
Craft::$app->sites->deleteGroup($group);
}
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/FieldDataType.php | src/DataTypes/FieldDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Fields DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class FieldDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->fields->getAllFields();
}
/**
* {@inheritdoc}
*/
public function afterImport()
{
Craft::$app->fields->updateFieldVersion();
if (Schematic::$force) {
$this->clearEmptyGroups();
}
}
/**
* Clear empty field groups
*/
private function clearEmptyGroups()
{
foreach (Craft::$app->fields->getAllGroups() as $group) {
if (count($group->getFields()) == 0) {
Craft::$app->fields->deleteGroup($group);
}
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/VolumeDataType.php | src/DataTypes/VolumeDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Volumes DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class VolumeDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->volumes->getAllVolumes();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/CategoryGroupDataType.php | src/DataTypes/CategoryGroupDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic CategoryGroups DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class CategoryGroupDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->categories->getAllGroups();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/PluginDataType.php | src/DataTypes/PluginDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic Plugin DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class PluginDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'pluginMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->plugins->getAllPluginInfo();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/GlobalSetDataType.php | src/DataTypes/GlobalSetDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic GlobalSets DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GlobalSetDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'modelMapper';
}
/**
* Get data of this type.
*
* @return array
*/
public function getRecords(): array
{
return Craft::$app->globals->getAllSets();
}
/**
* Reset craft global sets cache using reflection.
*/
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);
}
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/DataTypes/ElementIndexDataType.php | src/DataTypes/ElementIndexDataType.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use NerdsAndCompany\Schematic\Schematic;
/**
* Schematic ElementIndexs DataType.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ElementIndexDataType extends Base
{
/**
* {@inheritdoc}
*/
public function getMapperHandle(): string
{
return 'elementIndexMapper';
}
/**
* {@inheritdoc}
*/
public function getRecords(): array
{
return Craft::$app->elements->getAllElementTypes();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Models/Data.php | src/Models/Data.php | <?php
namespace NerdsAndCompany\Schematic\Models;
use Exception;
use craft\base\Model;
use Symfony\Component\Yaml\Yaml;
/**
* Schematic Data Model.
*
* Encapsulates data that has been exported via schematic.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class Data extends Model
{
/**
* 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
*/
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);
}
/**
* Convert array to yaml.
*
* @param array $data
*
* @return string
*/
public static function toYaml(array $data): string
{
return Yaml::dump($data, 12, 2);
}
/**
* Read yaml file and parse content.
*
* @param $file
* @return array
* @throws Exception
*/
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 [];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Events/ConverterEvent.php | src/Events/ConverterEvent.php | <?php
namespace NerdsAndCompany\Schematic\Events;
use yii\base\Event;
/**
* Schematic Converter Event.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ConverterEvent extends Event
{
/**
* @var string
*/
public $modelClass;
/**
* @var string
*/
public $converterClass;
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/src/Events/SourceMappingEvent.php | src/Events/SourceMappingEvent.php | <?php
namespace NerdsAndCompany\Schematic\Events;
use yii\base\Event;
/**
* Schematic Source Mapping Event.
*
* Sync Craft Setups.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SourceMappingEvent extends Event
{
/**
* @var string
*/
public $source;
/**
* @var string
*/
public $service;
/**
* @var string
*/
public $method;
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/_bootstrap.php | tests/unit/_bootstrap.php | <?php
require_once __DIR__.'/../../vendor/yiisoft/yii2/Yii.php';
require_once __DIR__.'/../../vendor/craftcms/cms/src/Craft.php';
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/SchematicTest.php | tests/unit/SchematicTest.php | <?php
namespace NerdsAndCompany\Schematic;
use craft\base\Element;
use craft\fields\PlainText;
use craft\models\Section;
use Codeception\Test\Unit;
use NerdsAndCompany\Schematic\Converters\Base\Field as FieldConverter;
use NerdsAndCompany\Schematic\Converters\Models\Section as SectionConverter;
use NerdsAndCompany\Schematic\Interfaces\DataTypeInterface;
/**
* Class SchematicTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SchematicTest extends Unit
{
/**
* @var Schematic
*/
private $module;
/**
* Set the mapper.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->module = new Schematic('schematic');
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideDataTypes
*
* @param string $dataTypeHandle
* @param bool $valid
* @param string $dataTypeClass
*/
public function testGetDataType(string $dataTypeHandle, bool $valid, string $dataTypeClass)
{
if ($dataTypeClass) {
$this->module->dataTypes[$dataTypeHandle] = $dataTypeClass;
}
$result = $this->module->getDataType($dataTypeHandle);
if ($valid) {
$this->assertInstanceOf(DataTypeInterface::class, $result);
} else {
$this->assertNull($result);
}
}
/**
* @dataProvider provideMappers
*
* @param string $mapperHandle
* @param bool $valid
* @param string $mapperClass
*/
public function testCheckMapper(string $mapperHandle, bool $valid, string $mapperClass)
{
if ($mapperClass) {
$this->module->setComponents([
$mapperHandle => [
'class' => $mapperClass,
],
]);
}
$result = $this->module->checkMapper($mapperHandle);
$this->assertSame($valid, $result);
}
/**
* @dataProvider provideConverters
*
* @param string $modelClass
* @param bool $valid
* @param string $converterClass
*/
public function testGetConverter(string $modelClass, bool $valid, string $converterClass)
{
$result = $this->module->getConverter($modelClass);
if ($valid) {
$this->assertInstanceOf($converterClass, $result);
} else {
$this->assertNull($result);
}
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideDataTypes()
{
return [
'existing dataType' => [
'dataTypeHandle' => 'sections',
'valid' => true,
'dataTypeClass' => '',
],
'dataType not registerd' => [
'dataTypeHandle' => 'unregistered',
'valid' => false,
'dataTypeClass' => '',
],
'dataTypeClass does not exist' => [
'dataTypeHandle' => 'notExists',
'valid' => false,
'dataTypeClass' => 'NotExists',
],
'dataTypeClass does not implement interface' => [
'dataTypeHandle' => 'implements',
'valid' => false,
'dataTypeClass' => \stdClass::class,
],
];
}
/**
* @return array
*/
public function provideMappers()
{
return [
'existing mapper' => [
'mapperHandle' => 'modelMapper',
'valid' => true,
'mapper' => '',
],
'mapper not registerd' => [
'mapperHandle' => 'unregistered',
'valid' => false,
'mapper' => '',
],
'mapper does not implement interface' => [
'mapperHandle' => 'fakeMapper',
'valid' => false,
'mapper' => \stdClass::class,
],
];
}
/**
* @return array
*/
public function provideConverters()
{
return [
'direct match' => [
'modelClass' => Section::class,
'valid' => true,
'converterClass' => SectionConverter::class,
],
'parent match' => [
'modelClass' => PlainText::class,
'valid' => true,
'converterClass' => FieldConverter::class,
],
'no match' => [
'modelClass' => Element::class,
'valid' => false,
'converterClass' => '',
],
];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Mappers/ModelMapperTest.php | tests/unit/Mappers/ModelMapperTest.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use craft\base\Model;
use Codeception\Test\Unit;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Converters\Models\Base as Converter;
/**
* Class ModelMapperTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ModelMapperTest extends Unit
{
/**
* @var ModelMapper
*/
private $mapper;
/**
* Set the mapper.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->mapper = new ModelMapper();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideExportModels
*
* @param Model[] $models
* @param array $expectedResult
*/
public function testSuccessfulExport(array $models, array $expectedResult = [])
{
$converter = $this->getMockConverter();
$this->expectConverter($converter, count($models));
$actualResult = $this->mapper->export($models);
$this->assertSame($expectedResult, $actualResult);
}
/**
* @dataProvider provideImportModels
*
* @param Model[] $existingGroups
* @param array $modelDefinitions
* @param int $saveCount
*/
public function testUnSuccessfulImport(array $existingGroups, array $modelDefinitions, int $saveCount)
{
$converter = $this->getMockConverter();
$this->expectConverter($converter, count($existingGroups) + count($modelDefinitions));
$this->expectSaves($converter, $saveCount, false);
$this->expectDeletes($converter, 0);
$this->mapper->import($modelDefinitions, $existingGroups);
}
/**
* @dataProvider provideImportModels
*
* @param Model[] $existingGroups
* @param array $modelDefinitions
* @param int $saveCount
*/
public function testSuccessfulImport(array $existingGroups, array $modelDefinitions, int $saveCount)
{
$converter = $this->getMockConverter();
$this->expectConverter($converter, count($existingGroups) + count($modelDefinitions));
$this->expectSaves($converter, $saveCount);
$this->expectDeletes($converter, 0);
$this->mapper->import($modelDefinitions, $existingGroups);
}
/**
* @dataProvider provideImportModels
*
* @param Model[] $existingGroups
* @param array $modelDefinitions
* @param int $saveCount
* @param int $deleteCount
*/
public function testSuccessfulImportWithForceOption(
array $existingGroups,
array $modelDefinitions,
int $saveCount,
int $deleteCount
) {
Schematic::$force = true;
$converter = $this->getMockConverter();
$this->expectConverter($converter, count($existingGroups) + count($modelDefinitions) + $deleteCount);
$this->expectSaves($converter, $saveCount);
$this->expectDeletes($converter, $deleteCount);
$this->mapper->import($modelDefinitions, $existingGroups);
}
/**
* @dataProvider provideImportModels
*
* @param Model[] $existingGroups
* @param array $modelDefinitions
* @param int $saveCount
* @param int $deleteCount
*/
public function testUnsuccessfulImportWithForceOption(
array $existingGroups,
array $modelDefinitions,
int $saveCount,
int $deleteCount
) {
Schematic::$force = true;
$converter = $this->getMockConverter();
$this->expectConverter($converter, count($existingGroups) + count($modelDefinitions) + $deleteCount);
$this->expectSaves($converter, $saveCount, false);
$this->expectDeletes($converter, $deleteCount);
$this->mapper->import($modelDefinitions, $existingGroups);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideExportModels()
{
$mockModel1 = $this->getMockModel(1);
$mockModel2 = $this->getMockModel(2);
return [
'empty array' => [
'models' => [],
'modelDefinitions' => [],
],
'single model' => [
'models' => [
$mockModel1,
],
'modelDefinitions' => [
'modelHandle1' => $this->getMockModelDefinition($mockModel1),
],
],
'multiple models' => [
'models' => [
$mockModel1,
$mockModel2,
],
'modelDefinitions' => [
'modelHandle1' => $this->getMockModelDefinition($mockModel1),
'modelHandle2' => $this->getMockModelDefinition($mockModel2),
],
],
];
}
/**
* @return array
*/
public function provideImportModels()
{
$mockModel1 = $this->getMockModel(1);
$mockModel2 = $this->getMockModel(2);
return [
'empty array' => [
'models' => [],
'modelDefinitions' => [],
'saveCount' => 0,
'deleteCount' => 0,
],
'single old model' => [
'models' => [
$mockModel1,
],
'modelDefinitions' => [],
'saveCount' => 0,
'deleteCount' => 1,
],
'single new model' => [
'models' => [
$mockModel1,
],
'modelDefinitions' => [
'modelHandle1' => $this->getMockModelDefinition($mockModel1),
'modelHandle2' => $this->getMockModelDefinition($mockModel2),
],
'saveCount' => 1,
'deleteCount' => 0,
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* Get model definition for mock model.
*
* @param Model $mockModel
*
* @return array
*/
private function getMockModelDefinition(Model $mockModel): array
{
return [
'class' => get_class($mockModel),
'attributes' => [
'name' => $mockModel->name,
'handle' => $mockModel->handle,
'max' => 100,
'other' => 'stuff',
],
];
}
/**
* Get a mock model.
*
* @param int $modelId
*
* @return Mock|Model
*/
private function getMockModel(int $modelId): Model
{
$mockModel = $this->getMockBuilder(Model::class)->getMock();
$mockModel->expects($this->any())
->method('__get')
->willReturnMap([
['id', $modelId],
['handle', 'modelHandle'.$modelId],
['name', 'modelName'.$modelId],
]);
return $mockModel;
}
/**
* Get a mock converter.
*
* @return Converter
*/
private function getMockConverter(): Converter
{
$mockConverter = $this->getMockBuilder(Converter::class)->getMock();
$mockConverter->expects($this->any())
->method('getRecordIndex')
->willReturnCallback(function ($model) {
return $model->handle;
});
$mockConverter->expects($this->any())
->method('getRecordDefinition')
->willReturnCallback(function ($model) {
return $this->getMockModelDefinition($model);
});
return $mockConverter;
}
/**
* Mock a converter.
*
* @param Mock|Converter|null $converter
*/
private function expectConverter($converter, int $count)
{
Craft::$app->controller->module->expects($this->exactly($count))
->method('getConverter')
->willReturn($converter);
}
/**
* Expect a number of model saves.
*
* @param Converter $converter
* @param int $saveCount
* @param bool $return
*/
private function expectSaves(Converter $converter, int $saveCount, bool $return = true)
{
$converter->expects($this->exactly($saveCount))
->method('saveRecord')
->willReturn($return);
}
/**
* Expect a number of model deletes.
*
* @param Converter $converter
* @param int $deleteCount
*/
private function expectDeletes(Converter $converter, int $deleteCount)
{
$converter->expects($this->exactly($deleteCount))
->method('deleteRecord');
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Mappers/PluginMapperTest.php | tests/unit/Mappers/PluginMapperTest.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use Exception;
use craft\base\Model;
use craft\base\Plugin;
use NerdsAndCompany\Schematic\Schematic;
use Codeception\Test\Unit;
/**
* Class Plugin Mapper Test.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class PluginMapperTest extends Unit
{
/**
* @var PluginMapper
*/
private $mapper;
/**
* Set the mapper.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->mapper = new PluginMapper();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Test default import functionality.
*/
public function testImportWithInstalledPlugins()
{
$definitions = $this->getPluginsDefinition();
$data = $this->getPluginsData();
$this->mockPluginsService();
$result = $this->mapper->import($definitions, $data);
$this->assertCount(count($definitions), $result);
}
/**
* Test default import functionality.
*/
public function testImportWithInstalledDisabledPlugins()
{
$this->getMockplugin();
$definitions = $this->getPluginsDefinition();
$definitions['pluginHandle']['isEnabled'] = false;
$data = $this->getPluginsData();
$this->mockPluginsService();
$result = $this->mapper->import($definitions, $data);
$this->assertCount(count($definitions), $result);
}
/**
* Test default import functionality.
*/
public function testImportWithMissingPlugin()
{
$definitions = $this->getPluginsDefinition();
$this->mockPluginsService(false);
$result = $this->mapper->import($definitions, []);
$this->assertCount(0, $result);
}
/**
* Test default import functionality.
*/
public function testImportWithInstallException()
{
$definitions = $this->getPluginsDefinition();
$data = $this->getPluginsData();
$this->mockPluginsService(true, false);
$this->expectException(Exception::class);
$this->mapper->import($definitions, $data);
}
/**
* Test default import functionality.
*/
public function testImportWithNotInstalledPlugin()
{
$this->getMockplugin();
$definitions = $this->getPluginsDefinition();
$definitions['pluginHandle']['isInstalled'] = false;
$data = $this->getPluginsData();
$this->mockPluginsService();
$result = $this->mapper->import($definitions, $data);
$this->assertCount(0, $result);
}
/**
* Test default import functionality.
*/
public function testImportWithForce()
{
$data = $this->getPluginsData();
$data['pluginHandle']['isInstalled'] = true;
$this->mockPluginsService(false);
Craft::$app->plugins->expects($this->exactly(1))
->method('uninstallPlugin')
->willReturn(true);
Schematic::$force = true;
$result = $this->mapper->import([], $data);
$this->assertCount(0, $result);
}
/**
* Test export functionality.
*/
public function testExport()
{
$data = $this->getPluginsData();
$data['pluginHandle']['isInstalled'] = true;
$data['pluginHandle']['isEnabled'] = true;
$definitions = $this->getPluginsDefinition();
$this->mockPluginsService();
$result = $this->mapper->export($data);
$this->assertEquals($definitions, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param bool $returnPlugin
* @param bool $installPluginResponse
* @param bool $enablePluginResponse
* @param bool $disablePluginResponse
* @param bool $saveSettingsResponse
*/
private function mockPluginsService(
$returnPlugin = true,
$installPluginResponse = true,
$enablePluginResponse = true,
$disablePluginResponse = true,
$saveSettingsResponse = true
) {
Craft::$app->plugins->expects($this->any())
->method('getPlugin')
->willReturn(($returnPlugin) ? $this->getMockplugin() : null);
if ($installPluginResponse) {
Craft::$app->plugins->expects($this->any())->method('installPlugin')->willReturn($installPluginResponse);
} else {
Craft::$app->plugins->expects($this->any())->method('installPlugin')->willThrowException(new Exception());
}
Craft::$app->plugins->expects($this->any())->method('enablePlugin')->willReturn($enablePluginResponse);
Craft::$app->plugins->expects($this->any())->method('disablePlugin')->willReturn($disablePluginResponse);
Craft::$app->plugins->expects($this->any())->method('savePluginSettings')->willReturn($saveSettingsResponse);
}
/**
* @return Mock|plugin
*/
private function getMockplugin()
{
$mockPlugin = $this->getMockBuilder(Plugin::class)
->disableOriginalConstructor()
->getMock();
$mockPlugin->expects($this->any())
->method('getSettings')
->willReturn($this->getMockSettings());
return $mockPlugin;
}
/**
* Get mock settings.
*
* @return Mock|Model
*/
private function getMockSettings()
{
$mockSettings = $this->getMockBuilder(Model::class)->getMock();
$mockSettings->expects($this->any())
->method('__get')
->willReturnMap([
['attributes', [
'pluginName' => 'Menu',
'canDoActions' => '',
'quietErrors' => '',
]],
]);
return $mockSettings;
}
/**
* Returns plugins data.
*
* @return array
*/
private function getPluginsData()
{
return [
'pluginHandle' => [
'isInstalled' => false,
'isEnabled' => false,
'settings' => [
'pluginName' => 'Menu',
'canDoActions' => '',
'quietErrors' => '',
],
],
];
}
/**
* Returns plugins data.
*
* @return array
*/
private function getPluginsDefinition()
{
return [
'pluginHandle' => [
'isInstalled' => true,
'isEnabled' => true,
'settings' => [
'pluginName' => 'Menu',
'canDoActions' => '',
'quietErrors' => '',
],
],
];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Mappers/UserSettingsMapperTest.php | tests/unit/Mappers/UserSettingsMapperTest.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use craft\base\Field;
use craft\base\Volume;
use craft\elements\User;
use craft\models\FieldLayout;
use craft\models\FieldLayoutTab;
use Codeception\Test\Unit;
/**
* Class UserSettingsMapperTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class UserSettingsMapperTest extends Unit
{
/**
* @var UserSettingsMapper
*/
private $mapper;
/**
* Set the mapper.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->mapper = new UserSettingsMapper();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Test UserSettings service export.
*/
public function testUserSettingsServiceExport()
{
$this->setMockServicesForExport();
$definition = $this->getUserSettingsDefinition();
$result = $this->mapper->export();
$this->assertSame($definition, $result);
}
/**
* Test UserSettings service import without fieldlayout.
*/
public function testUserSettingsServiceImportWithoutFieldLayout()
{
$this->setMockServicesForImport(false, false);
$definition = $this->getUserSettingsDefinition();
unset($definition['fieldLayout']);
$import = $this->mapper->import($definition);
$this->assertSame([], $import);
}
/**
* Test UserSettings service import with import error.
*/
public function testUserSettingsServiceImportWithImportError()
{
$this->setMockServicesForImport(true, true, true);
$definition = $this->getUserSettingsDefinition();
$import = $this->mapper->import($definition);
$this->assertSame([], $import);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* Get user settings definition.
*
* @return array
*/
private function getUserSettingsDefinition()
{
return [
'settings' => [
'requireEmailVerification' => true,
'allowPublicRegistration' => false,
'defaultGroup' => null,
'photoSubpath' => 'profile',
'photoVolume' => 'volumeHandle',
],
'fieldLayout' => [
'type' => User::class,
'tabs' => [
'Content' => [
'fieldHandle1' => true,
'fieldHandle2' => false,
],
],
],
];
}
/**
* Set mock services for export.
*/
private function setMockServicesForExport()
{
$mockFieldLayout = $this->getMockFieldLayout();
Craft::$app->fields->expects($this->exactly(1))
->method('getLayoutByType')
->with(User::class)
->willReturn($mockFieldLayout);
$settings = [
'requireEmailVerification' => true,
'allowPublicRegistration' => false,
'defaultGroup' => null,
'photoSubpath' => 'profile',
'photoVolumeId' => 1,
];
Craft::$app->systemSettings->expects($this->exactly(1))
->method('getSettings')
->with('users')
->willReturn($settings);
Craft::$app->volumes->expects($this->exactly(1))
->method('getVolumeById')
->with(1)
->willReturn($this->getMockVolume());
}
/**
* @param bool $saveLayout
* @param bool $deleteLayoutsByType
*/
private function setMockServicesForImport($saveLayout = true, $deleteLayoutsByType = true, $errors = false)
{
Craft::$app->fields->expects($this->exactly($saveLayout ? 1 : 0))->method('saveLayout')->willReturn(!$errors);
Craft::$app->fields->expects($this->exactly($deleteLayoutsByType ? 1 : 0))
->method('deleteLayoutsByType')
->willReturn(true);
$mockFieldLayout = $this->getMockFieldLayout();
if ($errors) {
$mockFieldLayout->expects($this->exactly(1))->method('getErrors')->willReturn([
'errors' => ['error 1', 'error 2', 'error 3'],
]);
}
Craft::$app->fields->expects($this->exactly($saveLayout ? 1 : 0))
->method('assembleLayout')
->willReturn($mockFieldLayout);
}
/**
* @return Mock|FieldLayout
*/
private function getMockFieldLayout()
{
$mockFieldLayout = $this->getMockBuilder(FieldLayout::class)->getMock();
$mockFieldLayout->type = User::class;
$mockFieldLayoutTab = $this->getMockBuilder(FieldLayoutTab::class)->getMock();
$mockFieldLayoutTab->name = 'Content';
$mockFieldLayout->expects($this->any())
->method('getTabs')
->willReturn([$mockFieldLayoutTab]);
$mockFieldLayoutTab->expects($this->any())
->method('getFields')
->willReturn([
$this->getMockField(1, true),
$this->getMockField(2, false),
]);
return $mockFieldLayout;
}
/**
* Get a mock field.
*
* @param int $fieldId
* @param bool $required
*
* @return Mock|Field
*/
private function getMockField(int $fieldId, bool $required)
{
$mockField = $this->getMockbuilder(Field::class)
->setMethods([])
->getMock();
$mockField->id = $fieldId;
$mockField->handle = 'fieldHandle'.$fieldId;
$mockField->required = $required;
return $mockField;
}
/**
* Get mock volume.
*
* @return Mock|Volume
*/
private function getMockVolume()
{
$mockVolume = $this->getMockBuilder(Volume::class)->getMock();
$mockVolume->handle = 'volumeHandle';
return $mockVolume;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Mappers/EmailSettingsMapperTest.php | tests/unit/Mappers/EmailSettingsMapperTest.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use Codeception\Test\Unit;
/**
* Class EmailSettingsMapperTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class EmailSettingsMapperTest extends Unit
{
/**
* @var EmailSettingsMapper
*/
private $mapper;
/**
* Set the mapper.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->mapper = new EmailSettingsMapper();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Test EmailSettings service export.
*/
public function testEmailSettingsServiceExport()
{
$this->setMockServicesForExport();
$definition = $this->getEmailSettingsDefinition();
$result = $this->mapper->export();
$this->assertSame($definition, $result);
}
/**
* Test EmailSettings service import.
*/
public function testEmailSettingsServiceImport()
{
$definition = $this->getEmailSettingsDefinition();
$import = $this->mapper->import($definition);
$this->assertSame([], $import);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* Email settings definition.
*
* @return array
*/
private function getEmailSettingsDefinition()
{
return [
'settings' => [
'fromEmail' => 'admin@example.com',
'fromName' => 'Schematic',
'template' => null,
],
];
}
/**
* Set mock services for export.
*/
private function setMockServicesForExport()
{
$settings = [
'fromEmail' => 'admin@example.com',
'fromName' => 'Schematic',
'template' => null,
];
Craft::$app->systemSettings->expects($this->exactly(1))
->method('getSettings')
->with('email')
->willReturn($settings);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Mappers/ElementIndexMapperTest.php | tests/unit/Mappers/ElementIndexMapperTest.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use craft\elements\Category;
use craft\elements\Entry;
use craft\base\Field;
use Codeception\Test\Unit;
/**
* Class ElementIndexSettingsTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ElementIndexMapperTest extends Unit
{
/**
* @var ElementIndexMapper
*/
private $mapper;
/**
* Set the mapper.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->setMockSectionsService();
$this->setMockFieldsService();
$this->setMockElementIndexesService();
$this->mapper = new ElementIndexMapper();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Test default import functionality.
*/
public function testImport()
{
$data = $this->getElementIndexSettingsExportedData();
$result = $this->mapper->import($data, $this->getElementsData());
$this->assertSame([], $result);
}
/**
* Test export functionality.
*/
public function testExport()
{
$data = $this->getElementsData();
$expected = $this->getElementIndexSettingsExportedData();
$result = $this->mapper->export($data);
$this->assertEquals($expected, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param array $getAllElementTypesResponse
*/
protected function setMockElementsService($getAllElementTypesResponse = [])
{
Craft::$app->elementTypes->expects($this->any())
->method('getAllElementTypes')
->willReturn($getAllElementTypesResponse);
}
/**
* St mock element index service.
*/
protected function setMockElementIndexesService()
{
$getSettingsResponse = $this->getElementIndexSettingsSavedData();
Craft::$app->elementIndexes
->expects($this->any())
->method('getSettings')
->willReturnMap([
[Entry::class, $getSettingsResponse[Entry::class]],
[Category::class, $getSettingsResponse[Category::class]],
]);
Craft::$app->elementIndexes->expects($this->any())
->method('saveSettings')
->willReturn(false);
}
/**
* Returns elements data.
*
* @return array
*/
public function getElementsData()
{
return [
Category::class,
Entry::class,
];
}
/**
* Returns element index settings saved data.
*
* @return array
*/
private function getElementIndexSettingsSavedData()
{
return [
Category::class => [
'sourceOrder' => [
['heading', 'Channels'],
['key', 'section:1'],
],
'sources' => [
'*' => [
'tableAttributes' => [
'0' => 'section',
'1' => 'postDate',
'2' => 'expiryDate',
'3' => 'author',
'4' => 'link',
'5' => 'field:1',
],
],
],
],
Entry::class => [
'sourceOrder' => [
['heading', 'Channels'],
['key', 'section:1'],
],
'sources' => [
'*' => [
'tableAttributes' => [
'0' => 'section',
'1' => 'postDate',
'2' => 'expiryDate',
'3' => 'author',
'4' => 'link',
],
],
],
],
];
}
/**
* Returns element index settings exported data.
*
* @return array
*/
private function getElementIndexSettingsExportedData()
{
return [
Category::class => [
'sourceOrder' => [
['heading', 'Channels'],
['key', 'section:handle'],
],
'sources' => [
'*' => [
'tableAttributes' => [
'0' => 'section',
'1' => 'postDate',
'2' => 'expiryDate',
'3' => 'author',
'4' => 'link',
'5' => 'field:handle',
],
],
],
],
Entry::class => [
'sourceOrder' => [
['heading', 'Channels'],
['key', 'section:handle'],
],
'sources' => [
'*' => [
'tableAttributes' => [
'0' => 'section',
'1' => 'postDate',
'2' => 'expiryDate',
'3' => 'author',
'4' => 'link',
],
],
],
],
];
}
/**
* @return Mock|Sources
*/
private function setMockSectionsService()
{
$mockSection = $this->getMockBuilder(Section::class)->getMock();
$mockSection->handle = 'handle';
Craft::$app->sections->expects($this->any())
->method('getSectionById')
->with('1')
->willReturn($mockSection);
}
/**
* Set mock fields service.
*/
private function setMockFieldsService()
{
$mockField = $this->getMockBuilder(Field::class)->getMock();
$mockField->handle = 'handle';
Craft::$app->fields->expects($this->any())
->method('getFieldById')
->with('1')
->willReturn($mockField);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Mappers/GeneralSettingsMapperTest.php | tests/unit/Mappers/GeneralSettingsMapperTest.php | <?php
namespace NerdsAndCompany\Schematic\Mappers;
use Craft;
use Codeception\Test\Unit;
use craft\models\Info;
/**
* Class GeneralSettingsMapperTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GeneralSettingsMapperTest extends Unit
{
/**
* @var GeneralSettingsMapper
*/
private $mapper;
/**
* Set the mapper.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->mapper = new GeneralSettingsMapper();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Test GeneralSettings service export.
*/
public function testGeneralSettingsServiceExport()
{
$this->setMockServicesForExport();
$definition = $this->getGeneralSettingsDefinition();
$result = $this->mapper->export();
$this->assertSame($definition, $result);
}
/**
* Test GeneralSettings service import.
*/
public function testGeneralSettingsServiceImport()
{
$definition = $this->getGeneralSettingsDefinition();
$import = $this->mapper->import($definition);
$this->assertSame([], $import);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* General settings definition.
*
* @return array
*/
private function getGeneralSettingsDefinition()
{
return [
'settings' => [
'edition' => Craft::Pro,
'timezone' => 'Europe/Amsterdam',
'name' => 'Schematic',
'on' => true,
'maintenance' => false,
],
];
}
/**
* Set mock services for export.
*/
private function setMockServicesForExport()
{
$mockInfoModel = $this->getMockInfoModel();
Craft::$app->expects($this->exactly(1))
->method('getInfo')
->willReturn($mockInfoModel);
}
/**
* Get a mock info model.
*
* @return Mock|Info
*/
private function getMockInfoModel(): Info
{
$mockModel = $this->getMockBuilder(Info::class)->getMock();
$mockModel->edition = Craft::Pro;
$mockModel->timezone = 'Europe/Amsterdam';
$mockModel->name = 'Schematic';
$mockModel->on = true;
$mockModel->maintenance = false;
return $mockModel;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Elements/GlobalSetTest.php | tests/unit/Converters/Elements/GlobalSetTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Elements;
use Craft;
use craft\elements\GlobalSet as GlobalSetElement;
use craft\base\Field;
use yii\base\Behavior;
use craft\models\FieldLayout;
use craft\models\Site;
use craft\services\Fields;
use Codeception\Test\Unit;
/**
* Class GlobalSetTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GlobalSetsTest extends Unit
{
/**
* @var GlobalSet
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new GlobalSet();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideGlobalSets
*
* @param GlobalSetElement $set
* @param array $definition
*/
public function testGetRecordDefinition(GlobalSetElement $set, array $definition)
{
$result = $this->converter->getRecordDefinition($set);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideGlobalSets
*
* @param GlobalSetElement $set
* @param array $definition
* @param bool $valid
*/
public function testSaveRecord(GlobalSetElement $set, array $definition, bool $valid)
{
Craft::$app->sites->expects($this->any())
->method('getSiteByHandle')
->willReturnMap([
['default', $this->getMockSite()],
['invalid', null],
]);
Craft::$app->globals->expects($this->exactly($valid ? 1 : 0))
->method('saveSet')
->with($set)
->willReturn(true);
$result = $this->converter->saveRecord($set, $definition);
$this->assertSame($valid, $result);
}
/**
* @dataProvider provideGlobalSets
*
* @param GlobalSetElement $set
*/
public function testDeleteRecord(GlobalSetElement $set)
{
Craft::$app->elements->expects($this->exactly(1))
->method('deleteElementById')
->with($set->id);
$this->converter->deleteRecord($set);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideGlobalSets()
{
$mockGlobalSet1 = $this->getMockGlobalSet(1);
$mockGlobalSet2 = $this->getMockGlobalSet(1, 'invalid');
return [
'Valid set' => [
'set' => $mockGlobalSet1,
'definition' => $this->getMockGlobalSetDefinition($mockGlobalSet1),
'validSave' => true,
],
'Invalid set' => [
'set' => $mockGlobalSet2,
'definition' => $this->getMockGlobalSetDefinition($mockGlobalSet2),
'validSave' => false,
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param GlobalSet $mockGlobalSet
*
* @return array
*/
private function getMockGlobalSetDefinition(GlobalSetElement $mockGlobalSet)
{
$fieldDefs = [];
foreach ($mockGlobalSet->getFieldLayout()->getFields() as $field) {
$fieldDefs[$field->handle] = $field->required;
}
return [
'class' => get_class($mockGlobalSet),
'attributes' => [
'name' => $mockGlobalSet->name,
'handle' => $mockGlobalSet->handle,
'enabled' => true,
'archived' => false,
'enabledForSite' => true,
'title' => null,
'slug' => null,
'uri' => null,
],
'fieldLayout' => [
'type' => GlobalSetElement::class,
'fields' => $fieldDefs,
],
'site' => $mockGlobalSet->getSite()->handle,
];
}
/**
* @param int $setId
* @param string $siteHandle
*
* @return Mock|GlobalSet
*/
private function getMockGlobalSet(int $setId, string $siteHandle = 'default')
{
$mockSet = $this->getMockBuilder(GlobalSetElement::class)
->setMethods([
'__isset',
'getSite',
'getFieldLayout',
'fieldByHandle',
'getBehavior',
'behaviors',
])
->disableOriginalConstructor()
->getMock();
$mockSet->id = $setId;
$mockSet->fieldLayoutId = $setId;
$mockSet->handle = 'setHandle'.$setId;
$mockSet->name = 'setName'.$setId;
$mockBehavior = $this->getMockbuilder(Behavior::class)->getMock();
$mockBehavior->expects($this->any())
->method('canGetProperty')
->willReturn(true);
$mockSet->expects($this->any())
->method('behaviors')
->willReturn([$mockBehavior]);
$mockSet->expects($this->any())
->method('getBehavior')
->willReturn($mockBehavior);
$mockSet->expects($this->any())
->method('getSite')
->willReturn($this->getMockSite($siteHandle));
$mockField = $this->getMockbuilder(Field::class)->getMock();
$mockField->id = $setId;
$mockField->handle = 'field'.$setId;
$mockField->required = false;
$mockSet->expects($this->any())
->method('fieldByHandle')
->willReturn($mockField);
$mockFieldLayout = $this->getMockBuilder(FieldLayout::class)->getMock();
$mockFieldLayout->type = GlobalSetElement::class;
$mockFieldLayout->expects($this->any())
->method('getFields')
->willReturn([$mockField]);
$mockSet->expects($this->any())
->method('getFieldLayout')
->willReturn($mockFieldLayout);
return $mockSet;
}
/**
* Get a mock site.
*
* @param string $handle
*
* @return Mock|Site
*/
private function getMockSite(string $handle = 'default')
{
$mockSite = new Site([
'id' => 99,
'handle' => $handle,
]);
return $mockSite;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Base/FieldTest.php | tests/unit/Converters/Base/FieldTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Base;
use Craft;
use craft\base\Field as FieldModel;
use craft\fields\Categories as CategoriesField;
use craft\fields\PlainText as PlainTextField;
use Codeception\Test\Unit;
/**
* Class FieldTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class FieldTest extends Unit
{
/**
* @var Field
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new Field();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideFields
*
* @param FieldModel $field
* @param array $definition
*/
public function testGetRecordDefinition(FieldModel $field, array $definition)
{
if ($field instanceof CategoriesField) {
$mockCategoryGroup = $this->getMockCategoryGroup(1);
Craft::$app->categories->expects($this->any())
->method('getGroupById')
->with($field->group->id)
->willReturn($mockCategoryGroup);
}
$result = $this->converter->getRecordDefinition($field);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideFields
*
* @param FieldModel $field
* @param array $definition
* @param string $groupStatus existing|new|invalid
*/
public function testSaveRecord(FieldModel $field, array $definition, string $groupStatus)
{
Craft::$app->fields->expects($this->exactly(1))
->method('getAllGroups')
->willReturn([$this->getMockFieldGroup(1)]);
Craft::$app->fields->expects($this->exactly('existing' == $groupStatus ? 0 : 1))
->method('saveGroup')
->willReturn('invalid' !== $groupStatus);
Craft::$app->fields->expects($this->exactly(1))
->method('saveField')
->with($field)
->willReturn(true);
$result = $this->converter->saveRecord($field, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideFields
*
* @param FieldModel $field
*/
public function testDeleteRecord(FieldModel $field)
{
Craft::$app->fields->expects($this->exactly(1))
->method('deleteField')
->with($field);
$this->converter->deleteRecord($field);
}
/**
* @dataProvider provideFields
*
* @param FieldModel $field
* @param array $definition
*/
public function testSetRecordAttributes(FieldModel $field, array $definition)
{
$newField = new PlainTextField();
if ($field instanceof CategoriesField) {
$newField = new CategoriesField();
$mockCategoryGroup = $this->getMockCategoryGroup(1);
Craft::$app->categories->expects($this->any())
->method('getGroupByHandle')
->with('categoryGroupHandle'.$field->group->id)
->willReturn($mockCategoryGroup);
}
$this->converter->setRecordAttributes($newField, $definition, []);
$this->assertSame($field->name, $newField->name);
$this->assertSame($field->handle, $newField->handle);
if ($field instanceof CategoriesField) {
$this->assertSame($field->source, $newField->source);
}
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideFields()
{
$mockField1 = $this->getMockField(1, 1);
$mockField2 = $this->getMockField(1, 2);
$mockField3 = $this->getMockCategoriesField(1, 1);
return [
'valid field existing group' => [
'field' => $mockField1,
'definition' => $this->getMockFieldDefinition($mockField1),
'groupStatus' => 'existing',
],
'valid field new group' => [
'field' => $mockField2,
'definition' => $this->getMockFieldDefinition($mockField2),
'groupStatus' => 'new',
],
'valid field invalid group' => [
'field' => $mockField2,
'definition' => $this->getMockFieldDefinition($mockField2),
'groupStatus' => 'invalid',
],
'categories field existing group' => [
'field' => $mockField3,
'definition' => $this->getMockCategoriesFieldDefinition($mockField3),
'groupStatus' => 'existing',
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param FieldModel $mockField
*
* @return array
*/
private function getMockFieldDefinition(FieldModel $mockField)
{
return [
'class' => get_class($mockField),
'attributes' => [
'name' => 'fieldName'.$mockField->id,
'handle' => 'fieldHandle'.$mockField->id,
'instructions' => null,
'translationMethod' => 'none',
'translationKeyFormat' => null,
'oldHandle' => null,
'columnPrefix' => null,
'required' => false,
'sortOrder' => null,
],
'group' => $mockField->group->name,
];
}
/**
* @param CategoriesField $mockField
*
* @return array
*/
private function getMockCategoriesFieldDefinition(CategoriesField $mockField)
{
$fieldDefinition = $this->getMockFieldDefinition($mockField);
$fieldDefinition['attributes'] = array_merge([
'branchLimit' => null,
'sources' => '*',
'source' => 'group:categoryGroupHandle1',
'targetSiteId' => null,
'viewMode' => null,
'limit' => null,
'selectionLabel' => null,
'localizeRelations' => false,
'allowMultipleSources' => true,
'allowLimit' => true,
], $fieldDefinition['attributes']);
return $fieldDefinition;
}
/**
* @param int $fieldId
* @param int $groupId
*
* @return Mock|FieldModel
*/
private function getMockField(int $fieldId, int $groupId)
{
$mockField = $this->getMockBuilder(FieldModel::class)
->setMethods(['getGroup'])
->disableOriginalConstructor()
->getMock();
$this->setMockFieldAttributes($mockField, $fieldId, $groupId);
return $mockField;
}
/**
* @param int $fieldId
* @param int $groupId
*
* @return Mock|Categories
*/
private function getMockCategoriesField(int $fieldId, int $groupId)
{
$mockField = $this->getMockBuilder(CategoriesField::class)
->setMethods(['getGroup'])
->disableOriginalConstructor()
->getMock();
$this->setMockFieldAttributes($mockField, $fieldId, $groupId);
$mockField->source = 'group:'.$groupId;
return $mockField;
}
/**
* @param Mock|FieldModel $mockField
* @param int $fieldId
* @param int $groupId
*/
private function setMockFieldAttributes(FieldModel &$mockField, int $fieldId, int $groupId)
{
$mockField->id = $fieldId;
$mockField->groupId = $fieldId;
$mockField->handle = 'fieldHandle'.$fieldId;
$mockField->name = 'fieldName'.$fieldId;
$mockField->expects($this->any())
->method('getGroup')
->willReturn($this->getMockFieldGroup($groupId));
}
/**
* Get a mock field group.
*
* @param int $groupId
*
* @return Mock|FieldGroup
*/
private function getMockFieldGroup(int $groupId)
{
$mockGroup = $this->getMockBuilder(FieldGroup::class)
->disableOriginalConstructor()
->getMock();
$mockGroup->id = $groupId;
$mockGroup->name = 'fieldGroup'.$groupId;
return $mockGroup;
}
/**
* @param int $groupId
*
* @return Mock|CategoryGroup
*/
private function getMockCategoryGroup(int $groupId)
{
$mockCategoryGroup = $this->getMockBuilder(CategoryGroup::class)
->disableOriginalConstructor()
->getMock();
$mockCategoryGroup->id = $groupId;
$mockCategoryGroup->handle = 'categoryGroupHandle'.$groupId;
return $mockCategoryGroup;
Craft::$app->categories->expects($this->any())
->method('getGroupByHandle')
->with('categoryGroupHandle'.$groupId)
->willReturn($mockCategoryGroup);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Base/VolumeTest.php | tests/unit/Converters/Base/VolumeTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Base;
use Craft;
use craft\base\Field as FieldModel;
use craft\base\Volume as VolumeModel;
use craft\elements\Asset;
use craft\models\FieldLayout;
use craft\volumes\Local;
use Codeception\Test\Unit;
/**
* Class VolumeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class VolumeTest extends Unit
{
/**
* @var Volume
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new Volume();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideVolumes
*
* @param VolumeModel $volume
* @param array $definition
*/
public function testGetRecordDefinition(VolumeModel $volume, array $definition)
{
$result = $this->converter->getRecordDefinition($volume);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideVolumes
*
* @param VolumeModel $volume
* @param array $definition
*/
public function testSaveRecord(VolumeModel $volume, array $definition)
{
Craft::$app->volumes->expects($this->exactly(1))
->method('saveVolume')
->with($volume)
->willReturn(true);
$result = $this->converter->saveRecord($volume, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideVolumes
*
* @param VolumeModel $volume
*/
public function testDeleteRecord(VolumeModel $volume)
{
Craft::$app->volumes->expects($this->exactly(1))
->method('deleteVolume')
->with($volume);
$this->converter->deleteRecord($volume);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideVolumes()
{
$mockVolume = $this->getMockVolume(1);
return [
'local volume' => [
'volume' => $mockVolume,
'definition' => $this->getMockVolumeDefinition($mockVolume),
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param int $volumeId
*
* @return Mock|VolumeModel
*/
private function getMockVolume(int $volumeId)
{
$mockVolume = $this->getMockBuilder(Local::class)
->setMethods(['getFieldLayout'])
->disableOriginalConstructor()
->getMock();
$mockVolume->id = $volumeId;
$mockVolume->fieldLayoutId = $volumeId;
$mockVolume->handle = 'volumeHandle'.$volumeId;
$mockVolume->name = 'volumeName'.$volumeId;
$mockField = $this->getMockbuilder(FieldModel::class)->getMock();
$mockField->id = $volumeId;
$mockField->handle = 'field'.$volumeId;
$mockField->required = true;
$mockFieldLayout = $this->getMockBuilder(FieldLayout::class)->getMock();
$mockFieldLayout->type = Asset::class;
$mockFieldLayout->expects($this->any())
->method('getFields')
->willReturn([$mockField]);
$mockVolume->expects($this->any())
->method('getFieldLayout')
->willReturn($mockFieldLayout);
return $mockVolume;
}
/**
* @param VolumeModel $mockVolume
*
* @return array
*/
private function getMockVolumeDefinition(VolumeModel $mockVolume)
{
$fieldDefs = [];
foreach ($mockVolume->getFieldLayout()->getFields() as $field) {
$fieldDefs[$field->handle] = $field->required;
}
return [
'class' => get_class($mockVolume),
'attributes' => [
'path' => null,
'name' => 'volumeName'.$mockVolume->id,
'handle' => 'volumeHandle'.$mockVolume->id,
'hasUrls' => null,
'url' => null,
'sortOrder' => null,
],
'fieldLayout' => [
'type' => Asset::class,
'fields' => $fieldDefs,
],
];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Fields/MatrixTest.php | tests/unit/Converters/Fields/MatrixTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Fields;
use Craft;
use craft\fields\Matrix as MatrixField;
use Codeception\Test\Unit;
/**
* Class MatrixTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class MatrixTest extends Unit
{
/**
* @var Matrix
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new Matrix();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideMatrices
*
* @param MatrixField $matrix
* @param array $definition
*/
public function testGetRecordDefinition(MatrixField $matrix, array $definition)
{
Craft::$app->controller->module->modelMapper->expects($this->exactly(1))
->method('export')
->with($matrix->getBlockTypes())
->willReturn($definition['blockTypes']);
$result = $this->converter->getRecordDefinition($matrix);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideMatrices
*
* @param MatrixField $matrix
* @param array $definition
* @param bool $valid
*/
public function testSaveRecord(MatrixField $matrix, array $definition, bool $valid)
{
Craft::$app->fields->expects($this->exactly(1))
->method('saveField')
->with($matrix)
->willReturn($valid);
Craft::$app->controller->module->modelMapper->expects($this->exactly($valid ? 1 : 0))
->method('import')
->with($definition['blockTypes'], $matrix->getBlockTypes(), [
'fieldId' => $matrix->id,
])
->willReturn($matrix->getBlockTypes());
$result = $this->converter->saveRecord($matrix, $definition);
$this->assertSame($valid, $result);
}
/**
* @dataProvider provideMatrices
*
* @param MatrixField $matrix
*/
public function testDeleteRecord(MatrixField $matrix)
{
Craft::$app->fields->expects($this->exactly(1))
->method('deleteField')
->with($matrix);
$this->converter->deleteRecord($matrix);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideMatrices()
{
$mockMatrix1 = $this->getMockMatrix(1, 1);
$mockMatrix2 = $this->getMockMatrix(2, 1);
return [
'valid matrix' => [
'matrix' => $mockMatrix1,
'definition' => $this->getMockMatrixDefinition($mockMatrix1),
'validSave' => true,
],
'invalid matrix' => [
'matrix' => $mockMatrix2,
'definition' => $this->getMockMatrixDefinition($mockMatrix2),
'validSave' => false,
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param MatrixField $mockMatrix
*
* @return array
*/
private function getMockMatrixDefinition(MatrixField $mockMatrix)
{
return [
'class' => get_class($mockMatrix),
'attributes' => [
'minBlocks' => null,
'maxBlocks' => null,
'localizeBlocks' => false,
'name' => 'matrixName'.$mockMatrix->id,
'handle' => 'matrixHandle'.$mockMatrix->id,
'instructions' => null,
'translationMethod' => 'none',
'translationKeyFormat' => null,
'oldHandle' => null,
'columnPrefix' => null,
'required' => false,
'sortOrder' => null,
],
'group' => $mockMatrix->group->name,
'blockTypes' => [
'blockTypeDefinition1',
'blockTypeDefinition2',
],
];
}
/**
* @param int $matrixId
* @param int $groupId
*
* @return Mock|MatrixField
*/
private function getMockMatrix(int $matrixId, int $groupId)
{
$mockMatrix = $this->getMockBuilder(MatrixField::class)
->setMethods(['getGroup', 'getBlockTypes'])
->disableOriginalConstructor()
->getMock();
$mockMatrix->id = $matrixId;
$mockMatrix->groupId = $matrixId;
$mockMatrix->handle = 'matrixHandle'.$matrixId;
$mockMatrix->name = 'matrixName'.$matrixId;
$mockMatrix->expects($this->any())
->method('getGroup')
->willReturn($this->getMockFieldGroup($groupId));
$mockMatrix->expects($this->any())
->method('getBlockTypes')
->willReturn([
$this->getMockMatrixBlockType(1),
$this->getMockMatrixBlockType(2),
]);
return $mockMatrix;
}
/**
* Get a mock field group.
*
* @param int $groupId
*
* @return Mock|FieldGroup
*/
private function getMockFieldGroup(int $groupId)
{
$mockGroup = $this->getMockBuilder(FieldGroup::class)
->disableOriginalConstructor()
->getmock();
$mockGroup->id = $groupId;
$mockGroup->name = 'fieldGroup'.$groupId;
return $mockGroup;
}
/**
* Get a mock matrix block type.
*
* @param int $blockId
*
* @return Mock|MatrixBlockType
*/
private function getMockMatrixBlockType($blockId)
{
$mockBlockType = $this->getMockBuilder(MatrixBlockType::class)
->disableOriginalConstructor()
->getmock();
$mockBlockType->id = $blockId;
$mockBlockType->handle = 'blockHandle'.$blockId;
return $mockBlockType;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Fields/AssetsTest.php | tests/unit/Converters/Fields/AssetsTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Fields;
use Craft;
use craft\fields\Assets as AssetsField;
use craft\base\Volume;
use craft\models\VolumeFolder;
use craft\records\VolumeFolder as VolumeFolderRecord;
use Codeception\Test\Unit;
/**
* Class AssetsTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class AssetsTest extends Unit
{
/**
* @var Assets
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new Assets();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideAssets
*
* @param AssetsField $assets
* @param array $definition
* @param Mock|Volume|null $mockFolder
*/
public function testGetRecordDefinition(AssetsField $assets, array $definition, $mockFolder)
{
Craft::$app->assets->expects($this->any())
->method('getFolderById')
->with($mockFolder->id)
->willReturn($mockFolder);
$result = $this->converter->getRecordDefinition($assets);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideAssets
*
* @param AssetsField $assets
* @param array $definition
* @param Mock|Volume|null $mockFolder
*/
public function testSetRecordAttributes(AssetsField $assets, array $definition, $mockFolder)
{
$this->setMockFolderRecord($mockFolder);
$mockVolume = $mockFolder->getVolume();
Craft::$app->volumes->expects($this->any())
->method('getVolumeByHandle')
->with($mockVolume->handle)
->willReturn($mockVolume);
$newAssets = new AssetsField();
$this->converter->setRecordAttributes($newAssets, $definition, []);
$this->assertSame($assets->name, $newAssets->name);
$this->assertSame($assets->handle, $newAssets->handle);
$this->assertSame($assets->defaultUploadLocationSource, $newAssets->defaultUploadLocationSource);
$this->assertSame($assets->singleUploadLocationSource, $newAssets->singleUploadLocationSource);
$this->assertSame($assets->sources, $newAssets->sources);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideAssets()
{
$mockAssets1 = $this->getMockAssets(1, 1);
$mockFolder1 = $this->getMockFolder(1);
return [
'assets' => [
'Assets' => $mockAssets1,
'definition' => $this->getMockAssetsDefinition($mockAssets1),
'volume' => $mockFolder1,
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param AssetsField $mockAssets
*
* @return array
*/
private function getMockAssetsDefinition(AssetsField $mockAssets)
{
return [
'class' => get_class($mockAssets),
'attributes' => [
'useSingleFolder' => null,
'defaultUploadLocationSource' => 'folder:volumeHandle1',
'defaultUploadLocationSubpath' => null,
'singleUploadLocationSource' => 'folder:volumeHandle1',
'singleUploadLocationSubpath' => null,
'restrictFiles' => null,
'allowedKinds' => null,
'sources' => [
'folder:volumeHandle1',
],
'source' => null,
'viewMode' => null,
'limit' => null,
'selectionLabel' => null,
'localizeRelations' => false,
'allowMultipleSources' => true,
'allowLimit' => true,
'name' => 'assetsName'.$mockAssets->id,
'handle' => 'assetsHandle'.$mockAssets->id,
'instructions' => null,
'translationMethod' => 'none',
'translationKeyFormat' => null,
'oldHandle' => null,
'columnPrefix' => null,
'required' => false,
'sortOrder' => null,
],
'group' => 'fieldGroup1',
];
}
/**
* @param int $assetsId
* @param int $groupId
*
* @return Mock|AssetsField
*/
private function getMockAssets(int $assetsId, int $groupId)
{
$mockAssets = $this->getMockBuilder(AssetsField::class)
->setMethods(['getGroup', 'getBlockTypes'])
->disableOriginalConstructor()
->getMock();
$mockAssets->id = $assetsId;
$mockAssets->groupId = $assetsId;
$mockAssets->handle = 'assetsHandle'.$assetsId;
$mockAssets->name = 'assetsName'.$assetsId;
$mockAssets->defaultUploadLocationSource = 'folder:'.$assetsId;
$mockAssets->singleUploadLocationSource = 'folder:'.$assetsId;
$mockAssets->sources = ['folder:'.$assetsId];
$mockAssets->expects($this->any())
->method('getGroup')
->willReturn($this->getMockFieldGroup($groupId));
return $mockAssets;
}
/**
* Get a mock Field group.
*
* @param int $groupId
*
* @return Mock|FieldGroup
*/
private function getMockFieldGroup(int $groupId)
{
$mockGroup = $this->getMockBuilder(FieldGroup::class)
->disableOriginalConstructor()
->getmock();
$mockGroup->id = $groupId;
$mockGroup->name = 'fieldGroup'.$groupId;
return $mockGroup;
}
/**
* Get a mock folder.
*
* @param int $folderId
*
* @return Mock|VolumeFolder
*/
private function getMockFolder(int $folderId)
{
$mockVolume = $this->getMockVolume($folderId);
$mockFolder = $this->getMockBuilder(VolumeFolder::class)
->disableOriginalConstructor()
->getmock();
$mockFolder->id = $folderId;
$mockFolder->handle = 'folderHandle'.$folderId;
$mockFolder->expects($this->any())
->method('getVolume')
->willReturn($mockVolume);
return $mockFolder;
}
/**
* Get a mock volume.
*
* @param int $volumeId
*
* @return Mock|Volume
*/
private function getMockVolume(int $volumeId)
{
$mockVolume = $this->getMockBuilder(Volume::class)
->disableOriginalConstructor()
->getmock();
$mockVolume->id = $volumeId;
$mockVolume->handle = 'volumeHandle'.$volumeId;
return $mockVolume;
}
/**
* Set a mock folder record on converter based on mock folder
*
* @param VolumeFolder $mockFolder
*/
private function setMockFolderRecord(VolumeFolder $mockFolder)
{
$mockFolderRecord = $this->getMockBuilder(VolumeFolderRecord::class)->getMock();
$mockFolderRecord->expects($this->any())
->method('__get')
->willReturnMap([['id', $mockFolder->id]]);
$this->converter->setMockFolder($mockFolderRecord);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/EntryTypeTest.php | tests/unit/Converters/Models/EntryTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Field as FieldModel;
use craft\elements\Entry;
use craft\models\EntryType as EntryTypeModel;
use craft\models\FieldLayout;
use craft\models\FieldLayoutTab;
use Codeception\Test\Unit;
/**
* Class EntryTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class EntryTypeTest extends Unit
{
/**
* @var EntryType
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new EntryType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideEntryTypes
*
* @param EntryTypeModel $entryType
* @param array $definition
*/
public function testGetRecordDefinition(EntryTypeModel $entryType, array $definition)
{
$result = $this->converter->getRecordDefinition($entryType);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideEntryTypes
*
* @param EntryTypeModel $entryType
* @param array $definition
* @param array $defaultAttributes
*/
public function testSetRecordAttributes(EntryTypeModel $entryType, array $definition, array $defaultAttributes)
{
$newEntryType = $this->getMockBuilder(EntryTypeModel::class)
->setMethods(['setFieldLayout'])
->getMock();
$newEntryType->expects($this->exactly(1))
->method('setFieldLayout');
Craft::$app->fields->expects($this->any())
->method('getFieldByHandle')
->willReturn($this->getMockField($entryType->id));
$this->converter->setRecordAttributes($newEntryType, $definition, $defaultAttributes);
$this->assertSame($defaultAttributes['sectionId'], $newEntryType->sectionId);
$this->assertSame($entryType->name, $newEntryType->name);
$this->assertSame($entryType->handle, $newEntryType->handle);
}
/**
* @dataProvider provideEntryTypes
*
* @param EntryTypeModel $entryType
* @param array $definition
*/
public function testSaveRecord(EntryTypeModel $entryType, array $definition)
{
Craft::$app->sections->expects($this->exactly(1))
->method('saveEntryType')
->with($entryType)
->willReturn(true);
$result = $this->converter->saveRecord($entryType, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideEntryTypes
*
* @param EntryTypeModel $entryType
*/
public function testDeleteRecord(EntryTypeModel $entryType)
{
Craft::$app->sections->expects($this->exactly(1))
->method('deleteEntryType')
->with($entryType);
$this->converter->deleteRecord($entryType);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideEntryTypes()
{
$mockEntryType = $this->getMockEntryType(1);
return [
'valid entryType' => [
'entryType' => $mockEntryType,
'definition' => $this->getMockEntryTypeDefinition($mockEntryType),
'defaultAttributes' => ['sectionId' => 1],
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param EntryTypeModel $mockEntryType
*
* @return array
*/
private function getMockEntryTypeDefinition(EntryTypeModel $mockEntryType)
{
return [
'class' => get_class($mockEntryType),
'attributes' => [
'name' => 'entryTypeName'.$mockEntryType->id,
'handle' => 'entryTypeHandle'.$mockEntryType->id,
'hasTitleField' => true,
'titleLabel' => 'Title',
'titleFormat' => null,
],
'fieldLayout' => $this->getMockFieldLayoutDefinition($mockEntryType->getFieldLayout()),
];
}
/**
* Get mock field layout definition.
*
* @param FieldLayout $fieldLayout
*
* @return array
*/
private function getMockFieldLayoutDefinition(FieldLayout $fieldLayout)
{
$tabsDef = [];
foreach ($fieldLayout->getTabs() as $tab) {
$tabsDef[$tab->name] = [];
foreach ($tab->getFields() as $field) {
$tabsDef[$tab->name][$field->handle] = $field->required;
}
}
return [
'type' => Entry::class,
'tabs' => $tabsDef,
];
}
/**
* @param int $entryTypeId
*
* @return Mock|EntryTypeModel
*/
private function getMockEntryType(int $entryTypeId)
{
$mockEntryType = $this->getMockBuilder(EntryTypeModel::class)
->setMethods(['getFieldLayout'])
->disableOriginalConstructor()
->getMock();
$mockEntryType->id = $entryTypeId;
$mockEntryType->fieldLayoutId = $entryTypeId;
$mockEntryType->handle = 'entryTypeHandle'.$entryTypeId;
$mockEntryType->name = 'entryTypeName'.$entryTypeId;
$mockField = $this->getMockField($entryTypeId);
$mockFieldLayout = $this->getMockBuilder(FieldLayout::class)->getMock();
$mockFieldLayout->type = Entry::class;
$mockFieldLayoutTab = $this->getMockBuilder(FieldLayoutTab::class)->getMock();
$mockFieldLayoutTab->name = 'Content';
$mockFieldLayout->expects($this->any())
->method('getTabs')
->willReturn([$mockFieldLayoutTab]);
$mockFieldLayoutTab->expects($this->any())
->method('getFields')
->willReturn([$mockField]);
$mockEntryType->expects($this->any())
->method('getFieldLayout')
->willReturn($mockFieldLayout);
return $mockEntryType;
}
/**
* Get a mock field.
*
* @param int $fieldId
*
* @return Mock|FieldModel
*/
private function getMockField(int $fieldId)
{
$mockField = $this->getMockbuilder(FieldModel::class)
->setMethods([])
->getMock();
$mockField->id = $fieldId;
$mockField->handle = 'field'.$fieldId;
$mockField->required = true;
return $mockField;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/SiteTest.php | tests/unit/Converters/Models/SiteTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\models\Site as SiteModel;
use craft\models\SiteGroup;
use Codeception\Test\Unit;
/**
* Class SiteTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SiteTest extends Unit
{
/**
* @var Site
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new Site();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideSites
*
* @param SiteModel $site
* @param array $definition
*/
public function testGetRecordDefinition(SiteModel $site, array $definition)
{
$result = $this->converter->getRecordDefinition($site);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideSites
*
* @param SiteModel $site
* @param array $definition
* @param string $groupStatus existing|new|invalid
*/
public function testSaveRecord(SiteModel $site, array $definition, string $groupStatus)
{
Craft::$app->sites->expects($this->exactly(1))
->method('getAllGroups')
->willReturn([$this->getMockSiteGroup(1)]);
Craft::$app->sites->expects($this->exactly('existing' == $groupStatus ? 0 : 1))
->method('saveGroup')
->willReturn('invalid' !== $groupStatus);
Craft::$app->sites->expects($this->exactly(1))
->method('saveSite')
->with($site)
->willReturn(true);
$result = $this->converter->saveRecord($site, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideSites
*
* @param SiteModel $site
*/
public function testDeleteRecord(SiteModel $site)
{
Craft::$app->sites->expects($this->exactly(1))
->method('deleteSiteById')
->with($site->id);
$this->converter->deleteRecord($site);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideSites()
{
$mockSite1 = $this->getMockSite(1, 1);
$mockSite2 = $this->getMockSite(1, 2);
return [
'valid site existing group' => [
'site' => $mockSite1,
'definition' => $this->getMockSiteDefinition($mockSite1),
'groupStatus' => 'existing',
],
'valid site new group' => [
'site' => $mockSite2,
'definition' => $this->getMockSiteDefinition($mockSite2),
'groupStatus' => 'new',
],
'valid site invalid group' => [
'site' => $mockSite2,
'definition' => $this->getMockSiteDefinition($mockSite2),
'groupStatus' => 'invalid',
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param SiteModel $mockSite
*
* @return array
*/
private function getMockSiteDefinition(SiteModel $mockSite)
{
return [
'class' => get_class($mockSite),
'attributes' => [
'name' => $mockSite->name,
'handle' => $mockSite->handle,
'language' => 'nl',
'primary' => true,
'hasUrls' => true,
'originalName' => null,
'originalBaseUrl' => null,
'baseUrl' => '@web/',
'sortOrder' => 1,
],
'group' => $mockSite->group->name,
];
}
/**
* @param int $siteId
*
* @return Mock|SiteModel
*/
private function getMockSite(int $siteId, int $groupId)
{
$mockSite = $this->getMockBuilder(SiteModel::class)
->setMethods(['getGroup'])
->disableOriginalConstructor()
->getMock();
$mockSite->id = $siteId;
$mockSite->groupId = $groupId;
$mockSite->handle = 'siteHandle'.$siteId;
$mockSite->language = 'nl';
$mockSite->primary = true;
$mockSite->hasUrls = true;
$mockSite->originalName = null;
$mockSite->originalBaseUrl = null;
$mockSite->baseUrl = '@web/';
$mockSite->sortOrder = 1;
$mockSite->expects($this->any())
->method('getGroup')
->willReturn($this->getMockSiteGroup($groupId));
return $mockSite;
}
/**
* Get a mock site group.
*
* @param int $groupId
*
* @return Mock|SiteGroup
*/
private function getMockSiteGroup(int $groupId)
{
$mockGroup = $this->getMockBuilder(SiteGroup::class)
->disableOriginalConstructor()
->getmock();
$mockGroup->id = $groupId;
$mockGroup->name = 'siteGroup'.$groupId;
return $mockGroup;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/UserGroupTest.php | tests/unit/Converters/Models/UserGroupTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\console\Application;
use craft\models\UserGroup as UserGroupModel;
use craft\models\Section as SectionModel;
use craft\models\CategoryGroup as CategoryGroupModel;
use craft\base\Volume as VolumeModel;
use Codeception\Test\Unit;
/**
* Class UserGroupTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class UserGroupTest extends Unit
{
/**
* @var UserGroup
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new UserGroup();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideUserGroups
*
* @param UserGroupModel $group
* @param array $definition
* @param array $groupPermissions
* @param array $allPermissions
*/
public function testGetRecordDefinition(
UserGroupModel $group,
array $definition,
array $groupPermissions,
array $allPermissions
) {
Craft::$app->userPermissions->expects($this->exactly(1))
->method('getPermissionsByGroupId')
->with($group->id)
->willReturn($groupPermissions);
Craft::$app->userPermissions->expects($this->exactly(1))
->method('getAllPermissions')
->willReturn($allPermissions);
Craft::$app->sections->expects($this->exactly(1))
->method('getSectionById')
->with(1)
->willReturn($this->getMockSection(1));
Craft::$app->categories->expects($this->exactly(1))
->method('getGroupById')
->with(2)
->willReturn($this->getMockCategoryGroup(2));
Craft::$app->volumes->expects($this->exactly(1))
->method('getVolumeById')
->with(3)
->willReturn($this->getmockVolume(3));
$result = $this->converter->getRecordDefinition($group);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideUserGroups
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @param UserGroupModel $group
* @param array $definition
* @param array $groupPermissions
* @param array $allPermissions
* @param bool $valid
*/
public function testSaveRecord(
UserGroupModel $group,
array $definition,
array $groupPermissions,
array $allPermissions,
bool $valid
) {
Craft::$app->userGroups->expects($this->exactly(1))
->method('saveGroup')
->with($group)
->willReturn($valid);
$mappedPermissions = ['createEntries:1', 'editCategories:2', 'performUpdates', 'viewVolume:3'];
if ($valid) {
Craft::$app->userPermissions->expects($this->exactly(1))
->method('saveGroupPermissions')
->with($group->id, $mappedPermissions)
->willReturn(true);
Craft::$app->sections->expects($this->exactly(1))
->method('getSectionByHandle')
->with('section1')
->willReturn($this->getMockSection(1));
Craft::$app->categories->expects($this->exactly(1))
->method('getGroupByHandle')
->with('group2')
->willReturn($this->getMockCategoryGroup(2));
Craft::$app->volumes->expects($this->exactly(1))
->method('getVolumeByHandle')
->with('volume3')
->willReturn($this->getmockVolume(3));
}
$result = $this->converter->saveRecord($group, $definition);
$this->assertSame($valid, $result);
}
/**
* @dataProvider provideUserGroups
*
* @param UserGroupModel $group
*/
public function testDeleteRecord(UserGroupModel $group)
{
Craft::$app->userGroups->expects($this->exactly(1))
->method('deleteGroupById')
->with($group->id);
$this->converter->deleteRecord($group);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideUserGroups()
{
$mockUserGroup = $this->getMockUserGroup(1);
return [
'valid user group' => [
'group' => $mockUserGroup,
'definition' => $this->getMockUserGroupDefinition($mockUserGroup),
'groupPermissions' => [
'createentries:1',
'editcategories:2',
'performupdates',
'viewvolume:3',
],
'allPermissions' => [
['createEntries:1' => []],
['editCategories:2' => []],
['performUpdates' => []],
['viewVolume:3' => []],
],
'validSave' => true,
],
'invalid user group' => [
'group' => $mockUserGroup,
'definition' => $this->getMockUserGroupDefinition($mockUserGroup),
'groupPermissions' => [
'createentries:1',
'editcategories:2',
'performupdates',
'viewvolume:3',
],
'allPermissions' => [
['createEntries:1' => []],
['editCategories:2' => []],
['performUpdates' => []],
['viewVolume:3' => []],
],
'validSave' => false,
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param UserGroupModel $userGroup
*
* @return array
*/
private function getMockUserGroupDefinition(UserGroupModel $userGroup)
{
return [
'class' => get_class($userGroup),
'attributes' => [
'name' => 'userGroupName'.$userGroup->id,
'handle' => 'userGroupHandle'.$userGroup->id,
],
'permissions' => [
'createEntries:section1',
'editCategories:group2',
'performUpdates',
'viewVolume:volume3',
],
];
}
/**
* @param int $userGroupId
*
* @return UserGroupModel
*/
private function getMockUserGroup(int $userGroupId)
{
$mockApp = $this->getMockBuilder(Application::class)
->disableOriginalConstructor()
->getMock();
$mockApp->expects($this->exactly(1))
->method('requireEdition')
->with(Craft::Pro)
->willReturn(true);
Craft::$app = $mockApp;
$mockUserGroup = $this->getmockBuilder(UserGroupModel::class)
->setMethods(['__toString'])
->getMock();
$mockUserGroup->id = $userGroupId;
$mockUserGroup->handle = 'userGroupHandle'.$userGroupId;
$mockUserGroup->name = 'userGroupName'.$userGroupId;
return $mockUserGroup;
}
/**
* @param int $sectionId
*
* @return Mock|SectionModel
*/
private function getMockSection(int $sectionId)
{
$mockSection = $this->getMockBuilder(SectionModel::class)
->disableOriginalConstructor()
->getMock();
$mockSection->id = $sectionId;
$mockSection->handle = 'section'.$sectionId;
return $mockSection;
}
/**
* @param int $groupId
*
* @return Mock|CategoryGroupModel
*/
private function getMockCategoryGroup(int $groupId)
{
$mockGroup = $this->getMockBuilder(CategoryGroupModel::class)
->disableOriginalConstructor()
->getMock();
$mockGroup->id = $groupId;
$mockGroup->handle = 'group'.$groupId;
return $mockGroup;
}
/**
* @param int $volumeId
*
* @return Mock|VolumeModel
*/
private function getMockVolume(int $volumeId)
{
$mockVolume = $this->getMockBuilder(VolumeModel::class)
->disableOriginalConstructor()
->getMock();
$mockVolume->id = $volumeId;
$mockVolume->handle = 'volume'.$volumeId;
return $mockVolume;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/MatrixBlockTypeTest.php | tests/unit/Converters/Models/MatrixBlockTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\base\Field as FieldModel;
use craft\fields\Matrix as MatrixField;
use craft\models\MatrixBlockType as MatrixBlockTypeModel;
use craft\models\FieldLayout;
use Codeception\Test\Unit;
/**
* Class MatrixBlockTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class MatrixBlockTypeTest extends Unit
{
/**
* @var MatrixBlockType
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new MatrixBlockType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideMatrixBlockTypes
*
* @param MatrixBlockTypeModel $blockType
* @param array $definition
*/
public function testGetRecordDefinition(MatrixBlockTypeModel $blockType, array $definition)
{
Craft::$app->controller->module->modelMapper->expects($this->exactly(1))
->method('export')
->with($blockType->getFieldLayout()->getFields())
->willReturn($definition['fields']);
$result = $this->converter->getRecordDefinition($blockType);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideMatrixBlockTypes
*
* @param MatrixBlockTypeModel $blockType
* @param array $definition
* @param array $defaultAttributes
*/
public function testSetRecordAttributes(
MatrixBlockTypeModel $blockType,
array $definition,
array $defaultAttributes
) {
$newMatrixBlockType = $this->getMockBuilder(MatrixBlockTypeModel::class)
->setMethods(['setFieldLayout'])
->getMock();
$newMatrixBlockType->expects($this->exactly(0))
->method('setFieldLayout');
$this->converter->setRecordAttributes($newMatrixBlockType, $definition, $defaultAttributes);
$this->assertSame($defaultAttributes['fieldId'], $newMatrixBlockType->fieldId);
$this->assertSame($blockType->name, $newMatrixBlockType->name);
$this->assertSame($blockType->handle, $newMatrixBlockType->handle);
}
/**
* @dataProvider provideMatrixBlockTypes
*
* @param MatrixBlockTypeModel $blockType
* @param array $definition
*/
public function testSaveRecord(MatrixBlockTypeModel $blockType, array $definition)
{
Craft::$app->fields->expects($this->exactly(1))
->method('getFieldById')
->with(1)
->willReturn($this->getMockbuilder(MatrixField::class)->getMock());
Craft::$app->getFields()->expects($this->exactly(1))
->method('getFieldsByLayoutId')
->willReturn([$this->getMockField(1)]);
Craft::$app->matrix->expects($this->exactly(1))
->method('getContentTableName')
->willReturn('matrix_content');
Craft::$app->matrix->expects($this->exactly(1))
->method('saveBlockType')
->with($blockType, false)
->willReturn(true);
$existingFields = $blockType->getFieldLayout()->getFields();
Craft::$app->controller->module->modelMapper->expects($this->exactly(1))
->method('import')
->with($definition['fields'], $existingFields, [], false)
->willReturn($existingFields);
$result = $this->converter->saveRecord($blockType, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideMatrixBlockTypes
*
* @param MatrixBlockTypeModel $blockType
*/
public function testDeleteRecord(MatrixBlockTypeModel $blockType)
{
Craft::$app->matrix->expects($this->exactly(1))
->method('deleteBlockType')
->with($blockType);
$this->converter->deleteRecord($blockType);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideMatrixBlockTypes()
{
$mockMatrixBlockType = $this->getMockMatrixBlockType(1);
return [
'valid blockType' => [
'blockType' => $mockMatrixBlockType,
'definition' => $this->getMockMatrixBlockTypeDefinition($mockMatrixBlockType),
'defaultAttributes' => ['fieldId' => 1],
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param MatrixBlockTypeModel $mockMatrixBlockType
*
* @return array
*/
private function getMockMatrixBlockTypeDefinition(MatrixBlockTypeModel $mockMatrixBlockType)
{
return [
'class' => get_class($mockMatrixBlockType),
'attributes' => [
'name' => 'blockTypeName'.$mockMatrixBlockType->id,
'handle' => 'blockTypeHandle'.$mockMatrixBlockType->id,
'sortOrder' => null,
],
'fields' => [
'fieldDefinition',
],
];
}
/**
* @param int $blockTypeId
*
* @return Mock|MatrixBlockTypeModel
*/
private function getMockMatrixBlockType(int $blockTypeId)
{
$mockMatrixBlockType = $this->getMockBuilder(MatrixBlockTypeModel::class)
->setMethods(['getFieldLayout'])
->disableOriginalConstructor()
->getMock();
$mockMatrixBlockType->id = $blockTypeId;
$mockMatrixBlockType->fieldId = 1;
$mockMatrixBlockType->fieldLayoutId = $blockTypeId;
$mockMatrixBlockType->handle = 'blockTypeHandle'.$blockTypeId;
$mockMatrixBlockType->name = 'blockTypeName'.$blockTypeId;
$mockField = $this->getMockField($blockTypeId);
$mockFieldLayout = $this->getMockBuilder(FieldLayout::class)->getMock();
$mockFieldLayout->expects($this->any())
->method('getFields')
->willReturn([$mockField]);
$mockMatrixBlockType->expects($this->any())
->method('getFieldLayout')
->willReturn($mockFieldLayout);
return $mockMatrixBlockType;
}
/**
* Get a mock field.
*
* @param int $fieldId
*
* @return Mock|FieldModel
*/
private function getMockField(int $fieldId)
{
$mockField = $this->getMockbuilder(FieldModel::class)
->setMethods([])
->getMock();
$mockField->id = $fieldId;
$mockField->handle = 'field'.$fieldId;
$mockField->required = true;
return $mockField;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/SectionTest.php | tests/unit/Converters/Models/SectionTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\models\Section as SectionModel;
use craft\models\Section_SiteSettings;
use craft\models\Site;
use Codeception\Test\Unit;
/**
* Class SectionTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SectionTest extends Unit
{
/**
* @var Section
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new Section();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideSections
*
* @param SectionModel $section
* @param array $definition
*/
public function testGetRecordDefinition(SectionModel $section, array $definition)
{
Craft::$app->controller->module->modelMapper->expects($this->exactly(1))
->method('export')
->with($section->getEntryTypes())
->willReturn($definition['entryTypes']);
$result = $this->converter->getRecordDefinition($section);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideSections
*
* @param SectionModel $section
* @param array $definition
* @param bool $valid
*/
public function testSaveRecord(SectionModel $section, array $definition, bool $valid)
{
Craft::$app->sections->expects($this->exactly(1))
->method('saveSection')
->with($section)
->willReturn($valid);
Craft::$app->controller->module->modelMapper->expects($this->exactly($valid ? 1 : 0))
->method('import')
->with($definition['entryTypes'], $section->getEntryTypes(), [
'sectionId' => $section->id,
])
->willReturn($section->getEntryTypes());
$result = $this->converter->saveRecord($section, $definition);
$this->assertSame($valid, $result);
}
/**
* @dataProvider provideSections
*
* @param SectionModel $section
*/
public function testDeleteRecord(SectionModel $section)
{
Craft::$app->sections->expects($this->exactly(1))
->method('deleteSection')
->with($section);
$this->converter->deleteRecord($section);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideSections()
{
$mockSection1 = $this->getMockSection(1);
$mockSection2 = $this->getMockSection(2);
return [
'valid section' => [
'section' => $mockSection1,
'definition' => $this->getMockSectionDefinition($mockSection1),
'validSave' => true,
],
'invalid section' => [
'section' => $mockSection2,
'definition' => $this->getMockSectionDefinition($mockSection2),
'validSave' => false,
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param SectionModel $mockSection
*
* @return array
*/
private function getMockSectionDefinition(SectionModel $mockSection)
{
$siteSettingsDef = [];
foreach ($mockSection->getSiteSettings() as $siteSetting) {
$siteSettingsDef[$siteSetting->site->handle] = [
'class' => get_class($siteSetting),
'attributes' => [
'enabledByDefault' => true,
'hasUrls' => null,
'uriFormat' => null,
'template' => null,
],
];
}
return [
'class' => get_class($mockSection),
'attributes' => [
'name' => 'sectionName'.$mockSection->id,
'handle' => 'sectionHandle'.$mockSection->id,
'type' => null,
'maxLevels' => null,
'enableVersioning' => true,
'propagateEntries' => true,
],
'siteSettings' => $siteSettingsDef,
'entryTypes' => [
'entryTypeDefinition1',
'entryTypeDefinition2',
],
];
}
/**
* @param int $sectionId
*
* @return Mock|SectionModel
*/
private function getMockSection(int $sectionId)
{
$mockSection = $this->getMockBuilder(SectionModel::class)
->setMethods(['getGroup', 'getEntryTypes', 'getSiteSettings'])
->disableOriginalConstructor()
->getMock();
$mockSection->id = $sectionId;
$mockSection->handle = 'sectionHandle'.$sectionId;
$mockSection->name = 'sectionName'.$sectionId;
$mockSection->expects($this->any())
->method('getEntryTypes')
->willReturn([
$this->getMockEntryType(1),
$this->getMockEntryType(2),
]);
$mockSection->expects($this->any())
->method('getSiteSettings')
->willReturn([$this->getMockSiteSettings()]);
return $mockSection;
}
/**
* Get a mock entry block type.
*
* @param int $blockId
*
* @return Mock|EntryType
*/
private function getMockEntryType($blockId)
{
$mockBlockType = $this->getMockBuilder(EntryType::class)
->disableOriginalConstructor()
->getmock();
$mockBlockType->id = $blockId;
$mockBlockType->handle = 'blockHandle'.$blockId;
return $mockBlockType;
}
/**
* Get mock siteSettings.
*
* @param string $class
*
* @return Mock|Section_SiteSettings
*/
private function getMockSiteSettings()
{
$mockSiteSettings = $this->getMockBuilder(Section_SiteSettings::class)
->setMethods(['getSite'])
->getMock();
$mockSiteSettings->expects($this->any())
->method('getSite')
->willReturn($this->getMockSite());
return $mockSiteSettings;
}
/**
* Get a mock site.
*
* @return Mock|Site
*/
private function getMockSite()
{
$mockSite = $this->getMockBuilder(Site::class)->getMock();
$mockSite->handle = 'default';
return $mockSite;
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/AssetTransformTest.php | tests/unit/Converters/Models/AssetTransformTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\models\AssetTransform as AssetTransformModel;
use Codeception\Test\Unit;
/**
* Class AssetTransformTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class AssetTransformTest extends Unit
{
/**
* @var AssetTransform
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new AssetTransform();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideAssetTransforms
*
* @param AssetTransformModel $transform
* @param array $definition
*/
public function testGetRecordDefinition(AssetTransformModel $transform, array $definition)
{
$result = $this->converter->getRecordDefinition($transform);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideAssetTransforms
*
* @param AssetTransformModel $transform
* @param array $definition
*/
public function testSaveRecord(AssetTransformModel $transform, array $definition)
{
Craft::$app->assetTransforms->expects($this->exactly(1))
->method('saveTransform')
->with($transform)
->willReturn(true);
$result = $this->converter->saveRecord($transform, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideAssetTransforms
*
* @param AssetTransformModel $transform
*/
public function testDeleteRecord(AssetTransformModel $transform)
{
Craft::$app->assetTransforms->expects($this->exactly(1))
->method('deleteTransform')
->with($transform->id);
$this->converter->deleteRecord($transform);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideAssetTransforms()
{
$mockAssetTransform = $this->getMockAssetTransform(1);
return [
'valid transform existing group' => [
'transform' => $mockAssetTransform,
'definition' => $this->getMockAssetTransformDefinition($mockAssetTransform),
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param int $assetTransformId
*
* @return AssetTransformModel
*/
private function getMockAssetTransform(int $assetTransformId)
{
return new AssetTransformModel([
'id' => $assetTransformId,
'handle' => 'assetTransformHandle'.$assetTransformId,
'name' => 'assetTransformName'.$assetTransformId,
]);
}
/**
* @param AssetTransformModel $assetTransform
*
* @return array
*/
private function getMockAssetTransformDefinition(AssetTransformModel $assetTransform)
{
return [
'class' => get_class($assetTransform),
'attributes' => [
'name' => 'assetTransformName'.$assetTransform->id,
'handle' => 'assetTransformHandle'.$assetTransform->id,
'width' => null,
'height' => null,
'format' => null,
'mode' => 'crop',
'position' => 'center-center',
'interlace' => 'none',
'quality' => null,
],
];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/CategoryGroupTest.php | tests/unit/Converters/Models/CategoryGroupTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\elements\Category;
use craft\models\CategoryGroup as CategoryGroupModel;
use craft\models\CategoryGroup_SiteSettings;
use craft\models\FieldLayout;
use craft\models\Site;
use Codeception\Test\Unit;
/**
* Class CategoryGroupTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class CategoryGroupTest extends Unit
{
/**
* @var CategoryGroup
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new CategoryGroup();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideCategoryGroups
*
* @param CategoryGroupModel $group
* @param array $definition
*/
public function testGetRecordDefinition(CategoryGroupModel $group, array $definition)
{
$result = $this->converter->getRecordDefinition($group);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideCategoryGroups
*
* @param CategoryGroupModel $group
* @param array $definition
* @param Site|null $site
*/
public function testSetRecordAttributes(CategoryGroupModel $group, array $definition, $site)
{
$newGroup = $this->getMockBuilder(CategoryGroupModel::class)
->setMethods(['setSiteSettings'])
->getMock();
$newGroup->expects($this->exactly(1))
->method('setSiteSettings');
Craft::$app->sites->expects($this->any())
->method('getSiteByHandle')
->willReturn($site);
$this->converter->setRecordAttributes($newGroup, $definition, []);
$this->assertSame($group->name, $newGroup->name);
$this->assertSame($group->handle, $newGroup->handle);
}
/**
* @dataProvider provideCategoryGroups
*
* @param CategoryGroupModel $group
* @param array $definition
*/
public function testSaveRecord(CategoryGroupModel $group, array $definition)
{
Craft::$app->categories->expects($this->exactly(1))
->method('saveGroup')
->with($group)
->willReturn(true);
$result = $this->converter->saveRecord($group, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideCategoryGroups
*
* @param CategoryGroupModel $group
*/
public function testDeleteRecord(CategoryGroupModel $group)
{
Craft::$app->categories->expects($this->exactly(1))
->method('deleteGroupById')
->with($group->id);
$this->converter->deleteRecord($group);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideCategoryGroups()
{
$mockCategoryGroup = $this->getMockCategoryGroup(1);
return [
'category group with site' => [
'group' => $mockCategoryGroup,
'definition' => $this->getMockCategoryGroupDefinition($mockCategoryGroup),
'site' => $this->getMockSite(),
],
'category group without site' => [
'group' => $mockCategoryGroup,
'definition' => $this->getMockCategoryGroupDefinition($mockCategoryGroup),
'site' => null,
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param CategoryGroupModel $mockCategoryGroup
*
* @return array
*/
private function getMockCategoryGroupDefinition(CategoryGroupModel $mockCategoryGroup)
{
return [
'class' => get_class($mockCategoryGroup),
'attributes' => [
'name' => $mockCategoryGroup->name,
'handle' => $mockCategoryGroup->handle,
'maxLevels' => 3,
],
'fieldLayout' => [
'type' => Category::class,
'fields' => [],
],
'siteSettings' => [
'' => [
'class' => get_class($mockCategoryGroup->getSiteSettings()[0]),
'attributes' => [
'hasUrls' => null,
'uriFormat' => null,
'template' => null,
],
],
],
];
}
/**
* @param int $groupId
*
* @return Mock|CategoryGroupModel
*/
private function getMockCategoryGroup(int $groupId)
{
$mockGroup = $this->getMockBuilder(CategoryGroupModel::class)
->setMethods(['getFieldLayout', 'getSiteSettings'])
->getMock();
$mockGroup->setAttributes([
'id' => $groupId,
'fieldLayoutId' => $groupId,
'handle' => 'groupHandle'.$groupId,
'name' => 'groupName'.$groupId,
'maxLevels' => 3,
]);
$mockFieldLayout = $this->getMockBuilder(FieldLayout::class)->getMock();
$mockFieldLayout->type = Category::class;
$mockGroup->expects($this->any())
->method('getFieldLayout')
->willReturn($mockFieldLayout);
$mockSiteSettings = $this->getMockSiteSettings();
$mockGroup->expects($this->any())
->method('getSiteSettings')
->willReturn([$mockSiteSettings]);
return $mockGroup;
}
/**
* Get mock siteSettings.
*
* @param string $class
*
* @return Mock|CategoryGroup_SiteSettings
*/
private function getMockSiteSettings()
{
$mockSiteSettings = $this->getMockBuilder(CategoryGroup_SiteSettings::class)
->setMethods(['getSite'])
->getMock();
$mockSiteSettings->expects($this->any())
->method('getSite')
->willReturn($this->getMockSite());
return $mockSiteSettings;
}
/**
* Get a mock site.
*
* @return Mock|Site
*/
private function getMockSite()
{
return $this->getMockBuilder(Site::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Converters/Models/TagGroupTest.php | tests/unit/Converters/Models/TagGroupTest.php | <?php
namespace NerdsAndCompany\Schematic\Converters\Models;
use Craft;
use craft\models\TagGroup as TagGroupModel;
use Codeception\Test\Unit;
/**
* Class TagGroupTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class TagGroupTest extends Unit
{
/**
* @var TagGroup
*/
private $converter;
/**
* Set the converter.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->converter = new TagGroup();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* @dataProvider provideTagGroups
*
* @param TagGroupModel $group
* @param array $definition
*/
public function testGetRecordDefinition(TagGroupModel $group, array $definition)
{
$result = $this->converter->getRecordDefinition($group);
$this->assertSame($definition, $result);
}
/**
* @dataProvider provideTagGroups
*
* @param TagGroupModel $group
* @param array $definition
*/
public function testSaveRecord(TagGroupModel $group, array $definition)
{
Craft::$app->tags->expects($this->exactly(1))
->method('saveTagGroup')
->with($group)
->willReturn(true);
$result = $this->converter->saveRecord($group, $definition);
$this->assertTrue($result);
}
/**
* @dataProvider provideTagGroups
*
* @param TagGroupModel $group
*/
public function testDeleteRecord(TagGroupModel $group)
{
Craft::$app->tags->expects($this->exactly(1))
->method('deleteTagGroupById')
->with($group->id);
$this->converter->deleteRecord($group);
}
//==============================================================================================================
//============================================== PROVIDERS ===================================================
//==============================================================================================================
/**
* @return array
*/
public function provideTagGroups()
{
$mockTagGroup = $this->getMockTagGroup(1);
return [
'valid tag group' => [
'group' => $mockTagGroup,
'definition' => $this->getMockTagGroupDefinition($mockTagGroup),
],
];
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @param int $tagGroupId
*
* @return TagGroupModel
*/
private function getMockTagGroup(int $tagGroupId)
{
return new TagGroupModel([
'id' => $tagGroupId,
'handle' => 'tagGroupHandle'.$tagGroupId,
'name' => 'tagGroupName'.$tagGroupId,
]);
}
/**
* @param TagGroupModel $tagGroup
*
* @return array
*/
private function getMockTagGroupDefinition(TagGroupModel $tagGroup)
{
return [
'class' => get_class($tagGroup),
'attributes' => [
'name' => 'tagGroupName'.$tagGroup->id,
'handle' => 'tagGroupHandle'.$tagGroup->id,
],
];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/VolumeDataTypeTest.php | tests/unit/DataTypes/VolumeDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\Volume;
use Codeception\Test\Unit;
/**
* Class VolumeDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class VolumeDataTypeTest extends Unit
{
/**
* @var VolumeDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new VolumeDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockVolume()];
Craft::$app->volumes->expects($this->exactly(1))
->method('getAllVolumes')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|Volume
*/
private function getMockVolume()
{
return $this->getMockBuilder(Volume::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/GeneralSettingsDataTypeTest.php | tests/unit/DataTypes/GeneralSettingsDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Codeception\Test\Unit;
/**
* Class GeneralSettingsDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GeneralSettingsDataTypeTest extends Unit
{
/**
* @var GeneralSettingsDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new GeneralSettingsDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('generalSettingsMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$result = $this->dataType->getRecords();
$this->assertSame([], $result);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/PluginDataTypeTest.php | tests/unit/DataTypes/PluginDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use Codeception\Test\Unit;
/**
* Class PluginDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class PluginDataTypeTest extends Unit
{
/**
* @var PluginDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new PluginDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('pluginMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockPluginInfo()];
Craft::$app->plugins->expects($this->exactly(1))
->method('getAllPluginInfo')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return array
*/
private function getMockPluginInfo()
{
return ['pluginInfo'];
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/FieldDataTypeTest.php | tests/unit/DataTypes/FieldDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\Field;
use Codeception\Test\Unit;
/**
* Class FieldDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class FieldDataTypeTest extends Unit
{
/**
* @var FieldDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new FieldDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockField()];
Craft::$app->fields->expects($this->exactly(1))
->method('getAllFields')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|Field
*/
private function getMockField()
{
return $this->getMockBuilder(Field::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/GlobalSetDataTypeTest.php | tests/unit/DataTypes/GlobalSetDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\GlobalSet;
use Codeception\Test\Unit;
/**
* Class GlobalSetDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class GlobalSetDataTypeTest extends Unit
{
/**
* @var GlobalSetDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new GlobalSetDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockGlobalSet()];
Craft::$app->globals->expects($this->exactly(1))
->method('getAllSets')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|GlobalSet
*/
private function getMockGlobalSet()
{
return $this->getMockBuilder(GlobalSet::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/ElementIndexDataTypeTest.php | tests/unit/DataTypes/ElementIndexDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\ElementType;
use Codeception\Test\Unit;
/**
* Class ElementTypeDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class ElementIndexDataTypeTest extends Unit
{
/**
* @var ElementIndexDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new ElementIndexDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('elementIndexMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockElementType()];
Craft::$app->elements->expects($this->exactly(1))
->method('getAllElementTypes')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|ElementType
*/
private function getMockElementType()
{
return $this->getMockBuilder(ElementType::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/AssetTransformDataTypeTest.php | tests/unit/DataTypes/AssetTransformDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\AssetTransform;
use Codeception\Test\Unit;
/**
* Class AssetTransformDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class AssetTransformDataTypeTest extends Unit
{
/**
* @var AssetTransformDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new AssetTransformDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockAssetTransform()];
Craft::$app->assetTransforms->expects($this->exactly(1))
->method('getAllTransforms')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|AssetTransform
*/
private function getMockAssetTransform()
{
return $this->getMockBuilder(AssetTransform::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/CategoryGroupDataTypeTest.php | tests/unit/DataTypes/CategoryGroupDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\CategoryGroup;
use Codeception\Test\Unit;
/**
* Class CategoryGroupDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class CategoryGroupDataTypeTest extends Unit
{
/**
* @var CategoryGroupDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new CategoryGroupDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockCategoryGroup()];
Craft::$app->categories->expects($this->exactly(1))
->method('getAllGroups')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|CategoryGroup
*/
private function getMockCategoryGroup()
{
return $this->getMockBuilder(CategoryGroup::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/EmailSettingsDataTypeTest.php | tests/unit/DataTypes/EmailSettingsDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Codeception\Test\Unit;
/**
* Class EmailSettingsDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class EmailSettingsDataTypeTest extends Unit
{
/**
* @var EmailSettingsDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new EmailSettingsDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('emailSettingsMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$result = $this->dataType->getRecords();
$this->assertSame([], $result);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/UserGroupDataTypeTest.php | tests/unit/DataTypes/UserGroupDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\UserGroup;
use Codeception\Test\Unit;
/**
* Class UserGroupDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class UserGroupDataTypeTest extends Unit
{
/**
* @var UserGroupDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new UserGroupDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockUserGroup()];
Craft::$app->userGroups->expects($this->exactly(1))
->method('getAllGroups')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|UserGroup
*/
private function getMockUserGroup()
{
return $this->getMockBuilder(UserGroup::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/UserSettingsDataTypeTest.php | tests/unit/DataTypes/UserSettingsDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Codeception\Test\Unit;
/**
* Class UserSettingsDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class UserSettingsDataTypeTest extends Unit
{
/**
* @var UserSettingsDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new UserSettingsDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('userSettingsMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$result = $this->dataType->getRecords();
$this->assertSame([], $result);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/SiteDataTypeTest.php | tests/unit/DataTypes/SiteDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\Site;
use Codeception\Test\Unit;
/**
* Class SiteDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SiteDataTypeTest extends Unit
{
/**
* @var SiteDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new SiteDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockSite()];
Craft::$app->sites->expects($this->exactly(1))
->method('getAllSites')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|Site
*/
private function getMockSite()
{
return $this->getMockBuilder(Site::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/TagGroupDataTypeTest.php | tests/unit/DataTypes/TagGroupDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\TagGroup;
use Codeception\Test\Unit;
/**
* Class TagGroupDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class TagGroupDataTypeTest extends Unit
{
/**
* @var TagGroupDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new TagGroupDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockTagGroup()];
Craft::$app->tags->expects($this->exactly(1))
->method('getAllTagGroups')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|TagGroup
*/
private function getMockTagGroup()
{
return $this->getMockBuilder(TagGroup::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/DataTypes/SectionDataTypeTest.php | tests/unit/DataTypes/SectionDataTypeTest.php | <?php
namespace NerdsAndCompany\Schematic\DataTypes;
use Craft;
use craft\models\Section;
use Codeception\Test\Unit;
/**
* Class SectionDataTypeTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class SectionDataTypeTest extends Unit
{
/**
* @var SectionDataType
*/
private $dataType;
/**
* Set the dataType.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*/
protected function _before()
{
$this->dataType = new SectionDataType();
}
//==============================================================================================================
//================================================= TESTS ====================================================
//==============================================================================================================
/**
* Get mapper handle test.
*/
public function testGetMapperHandle()
{
$result = $this->dataType->getMapperHandle();
$this->assertSame('modelMapper', $result);
}
/**
* Get records test.
*/
public function testGetRecords()
{
$records = [$this->getMockSection()];
Craft::$app->sections->expects($this->exactly(1))
->method('getAllSections')
->willReturn($records);
$result = $this->dataType->getRecords();
$this->assertSame($records, $result);
}
//==============================================================================================================
//================================================ HELPERS ===================================================
//==============================================================================================================
/**
* @return Mock|Section
*/
private function getMockSection()
{
return $this->getMockBuilder(Section::class)->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/unit/Models/DataTest.php | tests/unit/Models/DataTest.php | <?php
namespace NerdsAndCompany\Schematic\Models;
use Symfony\Component\Yaml\Yaml;
use Codeception\Test\Unit;
/**
* Class DataTest.
*
* @author Nerds & Company
* @copyright Copyright (c) 2015-2019, Nerds & Company
* @license MIT
*
* @see http://www.nerds.company
*/
class DataTest extends Unit
{
/**
* @return string
*/
private function getSchemaTestFile()
{
return __DIR__.'/../../_data/test_schema.yml';
}
/**
* @return string
*/
private function getOverrideTestFile()
{
return __DIR__.'/../../_data/test_override.yml';
}
/**
* @return Data
*
* @param bool $useOverride Whether to use the override file or not
*/
private function generateDataModel($useOverride = false)
{
putenv('SCHEMATIC_S3_SECRET_ACCESS_KEY=secret');
$schema = Data::parseYamlFile($this->getSchemaTestFile());
$override = $useOverride ? Data::parseYamlFile($this->getOverrideTestFile()) : [];
return array_replace_recursive($schema, $override);
}
public function testEnvironment()
{
putenv('S3_BUCKET=bucket_name');
$result = $this->generateDataModel();
$this->assertEquals('bucket_name', $result['volumes']['uploads']['attributes']['bucket']);
}
public function testEnvironmentFallback()
{
putenv('S3_BUCKET'); // unset
putenv('SCHEMATIC_S3_BUCKET=bucket_name');
$result = $this->generateDataModel();
$this->assertEquals('bucket_name', $result['volumes']['uploads']['attributes']['bucket']);
$this->assertEquals('secret', $result['volumes']['uploads']['attributes']['secret']);
}
public function testRegularOverride()
{
putenv('S3_BUCKET=bucket_name');
$result = $this->generateDataModel(true);
$this->assertEquals('override_key', $result['volumes']['uploads']['attributes']['keyId']);
}
public function testEnvironmentOverride()
{
putenv('S3_BUCKET=override_bucket_name');
$result = $this->generateDataModel(true);
$this->assertEquals('override_bucket_name', $result['volumes']['uploads']['attributes']['bucket']);
}
public function testEnvironmentOverrideFallback()
{
putenv('S3_BUCKET'); // unset
putenv('SCHEMATIC_S3_BUCKET=override_bucket_name');
$result = $this->generateDataModel(true);
$this->assertEquals('override_bucket_name', $result['volumes']['uploads']['attributes']['bucket']);
$this->assertEquals('secret', $result['volumes']['uploads']['attributes']['secret']);
}
public function testErrorWhenEnvironmentVariableNotSet()
{
// unset environment variables
putenv('S3_BUCKET');
putenv('SCHEMATIC_S3_BUCKET');
$this->expectException('Exception');
$this->generateDataModel(true);
}
public function testToYamlIsValidYaml()
{
putenv('S3_BUCKET=bucket_name');
$dataModel = $this->generateDataModel();
$yaml = Data::toYaml($dataModel);
$this->assertInternalType('array', Yaml::parse($yaml));
}
public function testToYamlContainsCorrectText()
{
putenv('S3_BUCKET=bucket_name');
$dataModel = $this->generateDataModel();
$yaml = Data::toYaml($dataModel);
$this->assertContains('bucket_name', $yaml);
}
public function testToYamlOverride()
{
putenv('S3_BUCKET=%S3_BUCKET%');
$dataModel = $this->generateDataModel();
$override = $this->getOverrideTestFile();
$yaml = Data::toYaml($dataModel, $override);
$this->assertContains("'%S3_BUCKET%'", $yaml);
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/_support/UnitTester.php | tests/_support/UnitTester.php | <?php
/**
* Inherited Methods.
*
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
* phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace
*/
class UnitTester extends \Codeception\Actor
{
use _generated\UnitTesterActions;
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
nerds-and-company/schematic | https://github.com/nerds-and-company/schematic/blob/e7a101fabf1cef492c5acc6f880c84a647b8b63e/tests/_support/Helper/Unit.php | tests/_support/Helper/Unit.php | <?php
namespace Helper;
use Craft;
use Yii;
use craft\console\Application;
use yii\console\Controller;
use craft\i18n\I18n;
use craft\services\Assets;
use craft\services\AssetTransforms;
use craft\services\Categories;
use craft\services\Content;
use craft\services\Elements;
use craft\services\ElementIndexes;
use craft\services\Fields;
use craft\services\Globals;
use craft\services\Matrix;
use craft\services\Path;
use craft\services\Plugins;
use craft\services\Sections;
use craft\services\Sites;
use craft\services\SystemSettings;
use craft\services\Tags;
use craft\services\UserGroups;
use craft\services\UserPermissions;
use craft\services\Volumes;
use Codeception\Module;
use Codeception\TestCase;
use NerdsAndCompany\Schematic\Schematic;
use NerdsAndCompany\Schematic\Mappers\ModelMapper;
/**
* UnitTest helper.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Unit extends Module
{
/**
* Mock craft Mappers.
*
* @SuppressWarnings(PHPMD.CamelCaseMethodName)
* phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
*
* @param TestCase $test
*/
public function _before(TestCase $test)
{
$mockApp = $this->getMockApp($test);
$mockApp->controller = $this->getMock($test, Controller::class);
$mockApp->controller->module = $this->getMockModule($test);
Craft::$app = $mockApp;
Yii::$app = $mockApp;
Schematic::$force = false;
}
/**
* Get a preconfigured mock module.
*
* @param TestCase $test
*
* @return Mock|Schematic
*/
private function getMockModule(TestCase $test)
{
$mockModule = $this->getMock($test, Schematic::class);
$mockModelMapper = $this->getMock($test, ModelMapper::class);
$mockModule->expects($test->any())
->method('__get')
->willReturnMap([
['modelMapper', $mockModelMapper],
]);
return $mockModule;
}
/**
* Get a preconfigured mock app.
*
* @param TestCase $test
*
* @return Mock|Application
*/
private function getMockApp(TestCase $test)
{
$mockApp = $this->getMock($test, Application::class);
$mockAssets = $this->getMock($test, Assets::class);
$mockAssetTransforms = $this->getMock($test, AssetTransforms::class);
$mockCategoryGroups = $this->getMock($test, Categories::class);
$mockContent = $this->getMock($test, Content::class);
$mockElements = $this->getMock($test, Elements::class);
$mockElementIndexes = $this->getMock($test, ElementIndexes::class);
$mockFields = $this->getMock($test, Fields::class);
$mockGlobals = $this->getMock($test, Globals::class);
$mockI18n = $this->getMock($test, I18n::class);
$mockMatrix = $this->getMock($test, Matrix::class);
$mockPath = $this->getMock($test, Path::class);
$mockPlugins = $this->getMock($test, Plugins::class);
$mockSections = $this->getMock($test, Sections::class);
$mockSites = $this->getMock($test, Sites::class);
$mockSystemSettings = $this->getMock($test, SystemSettings::class);
$mockTags = $this->getMock($test, Tags::class);
$mockUserGroups = $this->getMock($test, UserGroups::class);
$mockUserPermissions = $this->getMock($test, UserPermissions::class);
$mockVolumes = $this->getMock($test, Volumes::class);
$mockApp->expects($test->any())
->method('__get')
->willReturnMap([
['assets', $mockAssets],
['assetTransforms', $mockAssetTransforms],
['categories', $mockCategoryGroups],
['content', $mockContent],
['elements', $mockElements],
['elementIndexes', $mockElementIndexes],
['fields', $mockFields],
['globals', $mockGlobals],
['matrix', $mockMatrix],
['plugins', $mockPlugins],
['sections', $mockSections],
['sites', $mockSites],
['systemSettings', $mockSystemSettings],
['tags', $mockTags],
['userGroups', $mockUserGroups],
['userPermissions', $mockUserPermissions],
['volumes', $mockVolumes],
]);
$mockApp->expects($test->any())
->method('getPath')
->willReturn($mockPath);
$mockApp->expects($test->any())
->method('getI18n')
->willReturn($mockI18n);
$mockApp->expects($test->any())
->method('getMatrix')
->willReturn($mockMatrix);
$mockApp->expects($test->any())
->method('getFields')
->willReturn($mockFields);
return $mockApp;
}
/**
* Get a mock object for class.
*
* @param TestCase $test
* @param string $class
*
* @return Mock
*/
private function getMock(TestCase $test, string $class)
{
return $test->getMockBuilder($class)
->disableOriginalConstructor()
->getMock();
}
}
| php | MIT | e7a101fabf1cef492c5acc6f880c84a647b8b63e | 2026-01-05T04:59:46.951375Z | false |
ahmadnassri/restful-zend-framework | https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Controller.php | Controller.php | <?php
/**
* REST Controller default actions
*
*/
abstract class REST_Controller extends Zend_Controller_Action
{
/**
* The index action handles index/list requests; it should respond with a
* list of the requested resources.
*/
public function indexAction()
{
$this->notAllowed();
}
/**
* The get action handles GET requests and receives an 'id' parameter; it
* should respond with the server resource state of the resource identified
* by the 'id' value.
*/
public function getAction()
{
$this->notAllowed();
}
/**
* The post action handles POST requests; it should accept and digest a
* POSTed resource representation and persist the resource state.
*/
public function postAction()
{
$this->notAllowed();
}
/**
* The put action handles PUT requests and receives an 'id' parameter; it
* should update the server resource state of the resource identified by
* the 'id' value.
*/
public function putAction()
{
$this->notAllowed();
}
/**
* The delete action handles DELETE requests and receives an 'id'
* parameter; it should update the server resource state of the resource
* identified by the 'id' value.
*/
public function deleteAction()
{
$this->notAllowed();
}
/**
* The head action handles HEAD requests; it should respond with an
* identical response to the one that would correspond to a GET request,
* but without the response body.
*/
public function headAction()
{
$this->_forward('get');
}
/**
* The options action handles OPTIONS requests; it should respond with
* the HTTP methods that the server supports for specified URL.
*/
public function optionsAction()
{
$this->_response->setBody(null);
$this->_response->setHeader('Allow', $this->_response->getHeaderValue('Access-Control-Allow-Methods'));
$this->_response->ok();
}
protected function notAllowed()
{
$this->_response->setBody(null);
$this->_response->notAllowed();
}
}
| php | MIT | 1a030f213a133336e9f8caa325ea7c002dc5ef41 | 2026-01-05T04:59:58.834463Z | false |
ahmadnassri/restful-zend-framework | https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Request.php | Request.php | <?php
class REST_Request extends Zend_Controller_Request_Http
{
private $_error = false;
public function setError($code, $message)
{
$this->_error = new stdClass;
$this->_error->code = $code;
$this->_error->message = $message;
return $this;
}
public function getError()
{
return $this->_error;
}
public function hasError()
{
return $this->_error !== false;
}
public function getMethod()
{
if ($this->getParam('_method', false)) {
return strtoupper($this->getParam('_method'));
}
if ($this->getHeader('X-HTTP-Method-Override')) {
return strtoupper($this->getHeader('X-HTTP-Method-Override'));
}
return $this->getServer('REQUEST_METHOD');
}
public function dispatchError($code, $message)
{
$this->setError($code, $message);
$this->setControllerName('error');
$this->setActionName('error');
$this->setDispatched(true);
}
}
| php | MIT | 1a030f213a133336e9f8caa325ea7c002dc5ef41 | 2026-01-05T04:59:58.834463Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.