From 02f6ea170145c3f7e2549ab9b376eb039eb20ceb Mon Sep 17 00:00:00 2001 From: Robin Schambach Date: Tue, 19 Dec 2023 10:35:16 +0100 Subject: [PATCH] refactor plugin first step --- composer.json | 24 +- src/Seeder.php | 84 ++- src/console/controllers/CleanUpController.php | 12 +- .../controllers/GenerateController.php | 141 ++--- src/controllers/SeederController.php | 13 +- src/events/RegisterFieldTypeEvent.php | 9 +- src/migrations/Install.php | 10 +- .../m190205_191102_removeSectionColumn.php | 4 +- src/models/Settings.php | 6 +- src/records/SeederAssetRecord.php | 2 +- src/records/SeederCategoryRecord.php | 24 - src/records/SeederEntryRecord.php | 37 +- src/records/SeederUserRecord.php | 2 +- src/services/Categories.php | 85 --- src/services/Entries.php | 99 ++-- src/services/SeederService.php | 149 +++-- src/services/Users.php | 4 +- src/services/Weeder.php | 10 +- src/services/fields/Assets.php | 67 +++ src/services/fields/BaseField.php | 190 +++++++ src/services/fields/CTA.php | 76 --- src/services/fields/Checkboxes.php | 37 ++ src/services/fields/CkEditor.php | 4 +- src/services/fields/Color.php | 26 + src/services/fields/Date.php | 33 ++ src/services/fields/Dropdown.php | 33 ++ src/services/fields/Email.php | 33 ++ src/services/fields/Entries.php | 60 +++ src/services/fields/Fields.php | 508 +----------------- src/services/fields/Lightswitch.php | 32 ++ src/services/fields/Matrix.php | 67 +++ src/services/fields/MultiSelect.php | 38 ++ src/services/fields/Number.php | 35 ++ src/services/fields/PlainText.php | 33 ++ src/services/fields/Positionfieldtype.php | 4 +- src/services/fields/RadioButtons.php | 33 ++ src/services/fields/Redactor.php | 28 +- src/services/fields/Supertable.php | 4 +- src/services/fields/Table.php | 72 +++ src/services/fields/Url.php | 33 ++ src/templates/_index.twig | 4 +- 41 files changed, 1165 insertions(+), 1000 deletions(-) delete mode 100644 src/records/SeederCategoryRecord.php delete mode 100644 src/services/Categories.php create mode 100644 src/services/fields/Assets.php create mode 100644 src/services/fields/BaseField.php delete mode 100644 src/services/fields/CTA.php create mode 100644 src/services/fields/Checkboxes.php create mode 100644 src/services/fields/Color.php create mode 100644 src/services/fields/Date.php create mode 100644 src/services/fields/Dropdown.php create mode 100644 src/services/fields/Email.php create mode 100644 src/services/fields/Entries.php create mode 100644 src/services/fields/Lightswitch.php create mode 100644 src/services/fields/Matrix.php create mode 100644 src/services/fields/MultiSelect.php create mode 100644 src/services/fields/Number.php create mode 100644 src/services/fields/PlainText.php create mode 100644 src/services/fields/RadioButtons.php create mode 100644 src/services/fields/Table.php create mode 100644 src/services/fields/Url.php diff --git a/composer.json b/composer.json index a692c8c..477bdd1 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "studioespresso/craft-seeder", + "name": "anubarak/craft-seeder", "description": "Easy entries seeder for Craft CMS", "type": "craft-plugin", "keywords": [ @@ -9,33 +9,19 @@ "craft-plugin", "seeder" ], - "support": { - "docs": "https://github.com/studioespresso/craft3-seeder/blob/master/README.md", - "issues": "https://github.com/studioespresso/craft3-seeder/issues" - }, "license": "MIT", - "authors": [ - { - "name": "Studio Espresso", - "homepage": "https://www.studioepsresso.co" - } - ], "require": { "craftcms/cms": "^4.0.0", "fakerphp/faker": "^1.23.0" }, - "require-dev": { - "codeception/codeception": "2.4.2" - }, "autoload": { "psr-4": { - "studioespresso\\seeder\\": "src/" + "anubarak\\seeder\\": "src/" } }, "extra": { - "name": "Seeder", - "handle": "seeder", - "changelogUrl": "https://raw.githubusercontent.com/studioespresso/craft3-seeder/master/CHANGELOG.md", - "class": "studioespresso\\seeder\\Seeder" + "name": "Element Seeder", + "handle": "element-seeder", + "class": "anubarak\\seeder\\Seeder" } } diff --git a/src/Seeder.php b/src/Seeder.php index 7e87ffc..e37f8f2 100644 --- a/src/Seeder.php +++ b/src/Seeder.php @@ -1,54 +1,36 @@ SeederService::class, 'weeder' => WeederService::class, 'entries' => Entries::class, - 'categories' => Categories::class, 'users' => Users::class, 'fields' => Fields::class, 'redactor' => Redactor::class, 'ckeditor' => CkEditor::class, 'supertable' => Supertable::class, - 'cta' => CTA::class, 'positionfieldtype' => PositionService::class, ]; @@ -119,14 +104,9 @@ public function init() UrlManager::class, UrlManager::EVENT_REGISTER_CP_URL_RULES, static function (RegisterUrlRulesEvent $event) { - $event->rules['seeder'] = 'seeder/seeder/index'; + $event->rules['seeder'] = 'element-seeder/seeder/index'; } ); - - // Add in our console commands - if (Craft::$app instanceof ConsoleApplication) { - $this->controllerNamespace = 'studioespresso\seeder\console\controllers'; - } } // Protected Methods @@ -135,7 +115,7 @@ static function (RegisterUrlRulesEvent $event) { /** * Creates and returns the model used to store the plugin’s settings. * - * @return \studioespresso\seeder\models\Settings + * @return Settings */ protected function createSettingsModel(): Settings { diff --git a/src/console/controllers/CleanUpController.php b/src/console/controllers/CleanUpController.php index 3782053..f2a69dc 100644 --- a/src/console/controllers/CleanUpController.php +++ b/src/console/controllers/CleanUpController.php @@ -8,15 +8,15 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\console\controllers; +namespace anubarak\seeder\console\controllers; -use studioespresso\seeder\records\SeederAssetRecord; -use studioespresso\seeder\records\SeederEntryRecord; -use studioespresso\seeder\records\SeederUserRecord; -use studioespresso\seeder\Seeder; +use anubarak\seeder\records\SeederAssetRecord; +use anubarak\seeder\records\SeederEntryRecord; +use anubarak\seeder\records\SeederUserRecord; +use anubarak\seeder\Seeder; use Craft; -use studioespresso\seeder\services\Seeder_EntriesService; +use anubarak\seeder\services\Seeder_EntriesService; use yii\console\Controller; use yii\helpers\Console; diff --git a/src/console/controllers/GenerateController.php b/src/console/controllers/GenerateController.php index 80d27fd..0d2ad1b 100644 --- a/src/console/controllers/GenerateController.php +++ b/src/console/controllers/GenerateController.php @@ -8,17 +8,17 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\console\controllers; +namespace anubarak\seeder\console\controllers; use craft\elements\User; use craft\errors\FieldNotFoundException; use craft\helpers\Json; use secondred\base\fields\IncrementField; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; use Craft; -use studioespresso\seeder\services\Seeder_EntriesService; -use studioespresso\seeder\services\SeederService; +use anubarak\seeder\services\Seeder_EntriesService; +use anubarak\seeder\services\SeederService; use yii\console\Controller; use yii\console\ExitCode; use yii\helpers\Console; @@ -38,23 +38,27 @@ class GenerateController extends Controller /** * Section handle or id - * @var String + * @var null|string|int $section */ - public $section; - + public null|string|int $section; /** - * Categories or user group handle or id - * @var String + * user group id or handle + * + * @var string|int|null $group */ - public $group; + public null|string|int $group; /** * Number of entries to be seeded * @var Integer */ public $count = 20; - - public $site = null; + /** + * site handle or id + * + * @var string|null|int $site + */ + public string|null|int $site = null; // Public Methods // ========================================================================= @@ -64,8 +68,6 @@ public function options($actionId){ switch ($actionId) { case 'entries': return ['section','count', 'site']; - case 'categories': - return ['group','count', 'site']; case 'users': return ['group','count']; } @@ -77,46 +79,54 @@ public function options($actionId){ * The first line of this method docblock is displayed as the description * of the Console Command in ./craft help * - * @return mixed + * @return int + * @throws \Throwable * @throws \craft\errors\ElementNotFoundException * @throws \yii\base\Exception + * @throws \yii\base\ExitException * @throws \yii\base\InvalidConfigException - * @throws \Throwable */ - public function actionEntries() + public function actionEntries(): int { if(!$this->section) { - echo "Section handle or id missing, please specify\n"; - return; + $this->stderr('Section handle or id missing, please specify' . PHP_EOL); + return ExitCode::OK; } - $result = Seeder::$plugin->entries->generate($this->section, $this->count, $this->site); - return $result; - } + if (ctype_digit($this->section)) { + $section = Craft::$app->getSections()->getSectionById((int) $this->section); + } else { + $section = Craft::$app->getSections()->getSectionByHandle($this->section); + } - /** - * Generates categories for the specified group - * - * The first line of this method docblock is displayed as the description - * of the Console Command in ./craft help - * - * @return mixed - * @throws \craft\errors\ElementNotFoundException - * @throws \yii\base\Exception - * @throws \yii\base\InvalidConfigException - * @throws \Throwable - */ - public function actionCategories() - { - if(!$this->group) { - echo "Group handle or id missing, please specify\n"; - return ExitCode::CONFIG; + if(!$section){ + $this->stderr('No section found with „' . $this->section . '“' . PHP_EOL); + return ExitCode::OK; + } + + $site = null; + if($this->site){ + if (ctype_digit($this->site)) { + $site = Craft::$app->getSites()->getSiteById((int) $this->site); + } else { + $site = Craft::$app->getSites()->getSiteByHandle($this->site); + } + } + + // fallback nothing set -> use default + if ($site === null) { + $site = Craft::$app->getSites()->getPrimarySite(); } - $result = Seeder::$plugin->categories->generate($this->group, $this->count); - return ExitCode::OK; - } + + Seeder::$plugin->entries->generate( + $site, + $section, + $this->site + ); + return ExitCode::OK; + } /** * Generates users for the specified usergroup @@ -164,51 +174,4 @@ public function actionUsers() $result = Seeder::$plugin->users->generate($this->group, $this->count); return ExitCode::OK; } - - /** - * Generates a set of elements predefined in your config/seeder.php - * - * The first line of this method docblock is displayed as the description - * of the Console Command in ./craft help - * - * @param string $name - * - * @return mixed - * @throws \craft\errors\ElementNotFoundException - * @throws \yii\base\Exception - * @throws \yii\base\InvalidConfigException - * @throws \Throwable - */ - public function actionSet($name = 'default') { - if(!array_key_exists($name, Seeder::$plugin->getSettings()->sets)) { - echo "Set not found\n"; - return; - } - $settings = Seeder::$plugin->getSettings()->sets[$name]; - foreach($settings as $type => $option) { - d($type, $option); - switch ($type) { - case 'Users': - if(is_array($option)) { - foreach ($option as $group => $count) { - $result = Seeder::$plugin->users->generate($group, $count); - if($result) { - echo "Seeded " . $count . " entries in " . $result . "\n"; - } - } - } - break; - case 'Entries': - if(is_array($option)) { - foreach ($option as $section => $count) { - $result = Seeder::$plugin->entries->generate($section, $count); - if($result) { - echo "Seeded " . $count . " entries in " . $result . "\n"; - } - } - } - break; - } - } - } } diff --git a/src/controllers/SeederController.php b/src/controllers/SeederController.php index efeb877..c6ba992 100644 --- a/src/controllers/SeederController.php +++ b/src/controllers/SeederController.php @@ -8,16 +8,15 @@ * @copyright Copyright (c) 2018 studioespresso */ -namespace studioespresso\seeder\controllers; +namespace anubarak\seeder\controllers; use craft\elements\Entry; use craft\elements\User; -use studioespresso\seeder\models\SeederEntryModel; -use studioespresso\seeder\records\SeederAssetRecord; -use studioespresso\seeder\records\SeederCategoryRecord; -use studioespresso\seeder\records\SeederEntryRecord; -use studioespresso\seeder\records\SeederUserRecord; -use studioespresso\seeder\Seeder; +use anubarak\seeder\records\SeederAssetRecord; +use anubarak\seeder\records\SeederCategoryRecord; +use anubarak\seeder\records\SeederEntryRecord; +use anubarak\seeder\records\SeederUserRecord; +use anubarak\seeder\Seeder; use Craft; use craft\web\Controller; diff --git a/src/events/RegisterFieldTypeEvent.php b/src/events/RegisterFieldTypeEvent.php index a094ae8..7bd21d9 100644 --- a/src/events/RegisterFieldTypeEvent.php +++ b/src/events/RegisterFieldTypeEvent.php @@ -9,7 +9,7 @@ * @copyright Copyright (c) 2019 Robin Schambach */ -namespace studioespresso\seeder\events; +namespace anubarak\seeder\events; use craft\fields\Assets; use craft\fields\Categories; @@ -27,7 +27,7 @@ use craft\fields\Table; use craft\fields\Tags; use craft\fields\Url; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; use yii\base\Event; /** @@ -37,7 +37,10 @@ */ class RegisterFieldTypeEvent extends Event { - public $types = []; + /** + * @var string[] + */ + public array $types = []; public function init() { diff --git a/src/migrations/Install.php b/src/migrations/Install.php index 5b40d68..146f894 100644 --- a/src/migrations/Install.php +++ b/src/migrations/Install.php @@ -1,13 +1,13 @@ categories->getGroupById((int)$group); - } else { - $categoryGroup = Craft::$app->categories->getGroupByHandle($group); - } - - if (!$categoryGroup) { - echo "Group not found\n"; - return false; - } - $faker = Factory::create(); - - $fields = Craft::$app->fields->getFieldsByElementType('craft\elements\Category'); - - $current = 0; - $total = $count; - Console::startProgress($current, $count); - for ($x = 1; $x <= $count; $x++) { - $category = new Category([ - 'groupId' => (int)$categoryGroup->id, - 'title' => Seeder::$plugin->fields->Title(20), - ]); - Craft::$app->getElements()->saveElement($category); - Seeder::$plugin->seeder->saveSeededCategory($category); - Seeder::$plugin->seeder->populateFields($fields, $category); - Craft::$app->getElements()->saveElement($category); - $current++; - Console::updateProgress($current, $count); - } - Console::endProgress(); - - } - -} \ No newline at end of file diff --git a/src/services/Entries.php b/src/services/Entries.php index ee5c8ef..dcb0478 100644 --- a/src/services/Entries.php +++ b/src/services/Entries.php @@ -8,15 +8,18 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services; +namespace anubarak\seeder\services; use Craft; use craft\base\Component; use craft\base\Element; use craft\elements\Entry; use craft\elements\User; +use craft\errors\ElementException; use craft\helpers\Json; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; +use craft\models\Section; +use craft\models\Site; use yii\helpers\Console; use yii\helpers\VarDumper; @@ -36,71 +39,75 @@ class Entries extends Component { /** - * @param null $section - * @param int $count + * generate * - * @return bool|string|null + * @param int|string $section + * @param int $count + * @param int|string|null $site + * + * @return false|string|null + * @throws \Throwable * @throws \craft\errors\ElementNotFoundException + * @throws \craft\errors\SiteNotFoundException * @throws \yii\base\Exception * @throws \yii\base\ExitException * @throws \yii\base\InvalidConfigException - * @throws \Throwable + * @author Robin Schambach + * @since 19/12/2023 */ - public function generate($section = null, $count = 20, $site = null) + public function generate(Site $site, Section $section, int $count = 20) { - if (ctype_digit($section)) { - $section = Craft::$app->sections->getSectionById((int)$section); - } else { - $section = Craft::$app->sections->getSectionByHandle($section); - } - - if (!$section) { - echo "Section not found\n"; - return false; - } - - if($site && is_string($site)){ - $site = Craft::$app->getSites()->getSiteByHandle($site); - } - - if($site === null){ - $site = Craft::$app->getSites()->getPrimarySite(); - } - $entryTypes = $section->getEntryTypes(); $current = 0; $total = count($entryTypes) * $count; $admin = User::find()->admin(true)->one(); Console::startProgress($current, $count); + + + $db = Craft::$app->getDb(); + foreach ($section->getEntryTypes() as $entryType) { for ($x = 1; $x <= $count; $x++) { $current++; Console::updateProgress($current, $count); - if($entryType->fieldLayoutId) { - $typeFields = Craft::$app->fields->getFieldsByLayoutId($entryType->getFieldLayoutId()); - } - $entry = new Entry([ - 'sectionId' => (int)$section->id, - 'typeId' => $entryType->id, - 'title' => Seeder::$plugin->fields->Title(), - 'siteId' => $site->id, - ]); - $entry->authorId = $admin->id; - Craft::$app->getElements()->saveElement($entry); - Seeder::$plugin->seeder->saveSeededEntry($entry); - $entry->setScenario(Element::SCENARIO_LIVE); - if($entryType->fieldLayoutId) { - $entry = Seeder::$plugin->seeder->populateFields($typeFields, $entry); - if(!Craft::$app->getElements()->saveElement($entry)){ - Console::error(VarDumper::dumpAsString($entry->getErrors())); - Craft::$app->getElements()->deleteElement($entry); + $transaction = $db->beginTransaction(); + + try{ + $entry = new Entry([ + 'sectionId' => (int) $section->id, + 'typeId' => $entryType->id, + 'title' => Seeder::$plugin->fields->Title(), + 'siteId' => $site->id, + ]); + $entry->authorId = $admin->id; + Craft::$app->getElements()->saveElement($entry); + Seeder::$plugin->seeder->saveSeededEntry($entry); + $entry->setScenario(Element::SCENARIO_LIVE); + + + if ($entryType->fieldLayoutId) { + $entry = Seeder::$plugin->seeder->populateFields($entry); + if (!Craft::$app->getElements()->saveElement($entry)) { + Console::error(VarDumper::dumpAsString($entry->getErrors())); + throw new ElementException($entry, 'Could not save element due to validation errors'); + } + } + $transaction->rollBack(); + } catch (\Throwable $throwable){ + $transaction->rollBack(); + Craft::error($throwable); + Console::error('Error during seed'); + Console::error($throwable->getMessage()); + + if($throwable instanceof ElementException){ + Console::error(Json::encode($throwable->element->getErrors())); } } + } } Console::endProgress(); - return $section->name; + return $section->name; } - } \ No newline at end of file diff --git a/src/services/SeederService.php b/src/services/SeederService.php index 25ec4bd..2d6320e 100644 --- a/src/services/SeederService.php +++ b/src/services/SeederService.php @@ -8,18 +8,35 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services; +namespace anubarak\seeder\services; +use anubarak\seeder\services\fields\BaseField; +use anubarak\seeder\services\fields\Redactor; use Craft; use craft\base\Component; use craft\base\ElementInterface; +use craft\base\FieldInterface; +use craft\elements\Entry; use craft\errors\FieldNotFoundException; -use studioespresso\seeder\events\RegisterFieldTypeEvent; -use studioespresso\seeder\records\SeederAssetRecord; -use studioespresso\seeder\records\SeederCategoryRecord; -use studioespresso\seeder\records\SeederEntryRecord; -use studioespresso\seeder\records\SeederUserRecord; -use studioespresso\seeder\Seeder; +use anubarak\seeder\events\RegisterFieldTypeEvent; +use anubarak\seeder\records\SeederAssetRecord; +use anubarak\seeder\records\SeederEntryRecord; +use anubarak\seeder\records\SeederUserRecord; +use anubarak\seeder\Seeder; +use craft\fields\Assets; +use craft\fields\Checkboxes; +use craft\fields\Color; +use craft\fields\Date; +use craft\fields\Dropdown; +use craft\fields\Email; +use craft\fields\Lightswitch; +use craft\fields\MultiSelect; +use craft\fields\Number; +use craft\fields\PlainText; +use craft\fields\RadioButtons; +use craft\fields\Table; +use craft\fields\Url; +use Faker\Generator; /** * SeederService Service @@ -42,25 +59,53 @@ class SeederService extends Component /** * All registered Field Types * - * @var array $_registeredFieldTypes + * @var array|null $registeredFieldTypes */ - private $_registeredFieldTypes; + protected ?array $registeredFieldTypes = null; + /** + * @var \anubarak\seeder\services\fields\BaseField[] $fieldInstances + */ + protected array $fieldInstances = []; + /** + * @var \Faker\Generator $factory + */ + public Generator $factory; + + /** + * @param array $config + */ + public function __construct(array $config = []) + { + $language = Seeder::$plugin->getSettings()->fakerProvider; + $this->factory = \Faker\Factory::create($language); + + parent::__construct($config); + } /** - * @param $fields * @param ElementInterface $element * * @return \craft\base\ElementInterface * @throws \yii\base\ExitException + * @throws \yii\base\InvalidConfigException + * @throws \yii\base\NotSupportedException */ - public function populateFields($fields, ElementInterface $element): ElementInterface + public function populateFields(ElementInterface $element): ElementInterface { + $layout = $element->getFieldLayout(); + // no layout -> nothing we can do ¯\_(ツ)_/¯ + if (!$layout) { + return $element; + } + + $fields = $layout->getCustomFields(); + foreach ($fields as $field) { try { $fieldData = $this->getFieldData($field, $element); if ($fieldData) { $element->setFieldValue($field->handle, $fieldData); - } + } } catch (FieldNotFoundException $e) { if (Seeder::$plugin->getSettings()->debug) { Craft::dd($e); @@ -76,7 +121,7 @@ public function populateFields($fields, ElementInterface $element): ElementInter /** * @param \craft\elements\Entry $entry */ - public function saveSeededEntry($entry): void + public function saveSeededEntry(Entry $entry): void { $record = new SeederEntryRecord(); $record->entryUid = $entry->uid; @@ -104,17 +149,6 @@ public function saveSeededUser($user): void $record->save(); } - /** - * @param \craft\elements\Category $category - */ - public function saveSeededCategory($category): void - { - $record = new SeederCategoryRecord(); - $record->section = $category->groupId; - $record->categoryUid = $category->uid; - $record->save(); - } - /** * Get all registered field Types * @@ -125,46 +159,64 @@ public function saveSeededCategory($category): void */ public function getRegisteredFieldTypes(): array { - if ($this->_registeredFieldTypes === null) { - $event = new RegisterFieldTypeEvent(); + if ($this->registeredFieldTypes === null) { + $event = new RegisterFieldTypeEvent([ + Dropdown::class => \anubarak\seeder\services\fields\Dropdown::class, + Lightswitch::class => \anubarak\seeder\services\fields\Lightswitch::class, + Date::class => \anubarak\seeder\services\fields\Date::class, + PlainText::class => \anubarak\seeder\services\fields\PlainText::class, + Email::class => \anubarak\seeder\services\fields\Email::class, + Url::class => \anubarak\seeder\services\fields\Url::class, + Color::class => \anubarak\seeder\services\fields\Color::class, + Checkboxes::class => \anubarak\seeder\services\fields\Checkboxes::class, + RadioButtons::class => \anubarak\seeder\services\fields\RadioButtons::class, + MultiSelect::class => \anubarak\seeder\services\fields\MultiSelect::class, + Table::class => \anubarak\seeder\services\fields\Table::class, + Entries::class => \anubarak\seeder\services\fields\Entries::class, + Assets::class => \anubarak\seeder\services\fields\Assets::class, + Number::class => \anubarak\seeder\services\fields\Number::class, + 'craft\\redactor\\Field' => Redactor::class, + ]); if ($this->hasEventHandlers(self::REGISTER_FIELD_TYPES)) { $this->trigger(self::REGISTER_FIELD_TYPES, $event); } - $this->_registeredFieldTypes = $event->types; + $this->registeredFieldTypes = $event->types; } - return $this->_registeredFieldTypes; + return $this->registeredFieldTypes; } /** * Get the Field Data * - * @param $field - * + * @param \craft\base\FieldInterface $field * @param \craft\base\ElementInterface $element * * @return mixed * * @throws \craft\errors\FieldNotFoundException + * @throws \yii\base\InvalidConfigException + * @throws \yii\base\NotSupportedException * @author Robin Schambach * @since 05.09.2019 */ - public function getFieldData($field, ElementInterface $element) + public function getFieldData(FieldInterface $field, ElementInterface $element): mixed { $class = get_class($field); $registeredFieldTypes = $this->getRegisteredFieldTypes(); if (isset($registeredFieldTypes[$class])) { - return call_user_func($registeredFieldTypes[$class], $field, $element); + $fieldClass = $this->getFieldInstance($class); + + return $fieldClass->run($field, $element); } // last chance, try to find a valid callback - foreach ($registeredFieldTypes as $fieldType){ - - if(is_string($fieldType) && $class === $fieldType){ + foreach ($registeredFieldTypes as $fieldType) { + if (is_string($fieldType) && $class === $fieldType) { $v = Seeder::$plugin->fields->checkForEvent($field, $element); - if($v){ + if ($v) { return $v; } } @@ -172,4 +224,29 @@ public function getFieldData($field, ElementInterface $element) throw new FieldNotFoundException('the field ' . $class . ' could not be found'); } + + /** + * getFieldInstance + * + * @param string $class + * + * @return \anubarak\seeder\services\fields\BaseField + * @throws \yii\base\InvalidConfigException + * @author Robin Schambach + * @since 19/12/2023 + */ + public function getFieldInstance(string $class): BaseField + { + if (!isset($this->fieldInstances[$class])) { + $object = Craft::createObject([ + 'class' => $class, + '__construct()' => [ + 'factory' => $this->factory + ] + ]); + $this->fieldInstances[$class] = $object; + } + + return $this->fieldInstances[$class]; + } } diff --git a/src/services/Users.php b/src/services/Users.php index 1a7bd97..23a437f 100644 --- a/src/services/Users.php +++ b/src/services/Users.php @@ -8,7 +8,7 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services; +namespace anubarak\seeder\services; use craft\elements\Asset; use craft\elements\Category; @@ -18,7 +18,7 @@ use craft\helpers\Console; use Faker\Factory; use Faker\Provider\Person; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; use Craft; use craft\base\Component; diff --git a/src/services/Weeder.php b/src/services/Weeder.php index d067d68..bc494eb 100644 --- a/src/services/Weeder.php +++ b/src/services/Weeder.php @@ -8,19 +8,19 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services; +namespace anubarak\seeder\services; use craft\elements\Asset; use craft\elements\Category; use craft\elements\Entry; use craft\elements\User; -use studioespresso\seeder\records\SeederAssetRecord; -use studioespresso\seeder\records\SeederCategoryRecord; -use studioespresso\seeder\records\SeederEntryRecord; +use anubarak\seeder\records\SeederAssetRecord; +use anubarak\seeder\records\SeederCategoryRecord; +use anubarak\seeder\records\SeederEntryRecord; use Craft; use craft\base\Component; -use studioespresso\seeder\records\SeederUserRecord; +use anubarak\seeder\records\SeederUserRecord; use yii\base\Model; /** diff --git a/src/services/fields/Assets.php b/src/services/fields/Assets.php new file mode 100644 index 0000000..58a0ae1 --- /dev/null +++ b/src/services/fields/Assets.php @@ -0,0 +1,67 @@ +sources; + $volumeIds = []; + if ($source !== '*') { + + if (!is_array($source)) { + $source = [$source]; + } + + foreach ($source as $s) { + $volumeUid = str_replace('folder:', '', $s); + $volumeIds[] = Db::idByUid(\craft\db\Table::VOLUMES, $volumeUid); + } + } + + $limit = 2; + if ($field->maxRelations) { + $limit = $field->maxRelations; + } + + + $query = Asset::find() + ->limit(random_int(1, $limit)) + ->orderBy(new Expression('rand()')); + if ($volumeIds) { + $query->volumeId($volumeIds); + } + + if ($field->allowedKinds) { + $query->kind($field->allowedKinds); + } + + return $query->ids(); + } +} \ No newline at end of file diff --git a/src/services/fields/BaseField.php b/src/services/fields/BaseField.php new file mode 100644 index 0000000..f3f18da --- /dev/null +++ b/src/services/fields/BaseField.php @@ -0,0 +1,190 @@ +factory = $factory; + } + + /** + * getSettings + * + * @param \craft\base\Field $field + * @param \craft\base\ElementInterface $element + * + * @return array|mixed|null + * + * @throws \yii\base\NotSupportedException + * @throws \yii\base\InvalidConfigException + * @author Robin Schambach + * @since 06.09.2019 + */ + public function getSettings(FieldInterface $field, ElementInterface $element) + { + $settings = Seeder::$plugin->getSettings()->fieldsConfig; + + // TODO refactor + $index = get_class($element); + $settingsForElement = null; + if (isset($settings[$index])) { + switch ($index) { + case Entry::class: + /** @var Entry $element */ + $section = $element->getSection(); + if (isset($settings[$index][$section->handle])) { + $settingsForElement = $settings[$index][$section->handle]; + } + break; + case User::class: + $settingsForElement = $settings[$index]; + break; + case Tag::class: + throw new NotSupportedException('Creating Tags is not supported via config yet'); + break; + case Asset::class: + throw new NotSupportedException('Creating Assets is not supported via config yet'); + break; + } + } + + if (($settingsForElement !== null) && isset($settingsForElement[$field->handle])) { + return $settingsForElement[$field->handle]; + } + + return null; + } + + /** + * getCallBack + * + * @param null $class + * + * @return mixed|null + * + * @author Robin Schambach + * @since 06.09.2019 + */ + public function getCallBack($settings, FieldInterface $field, ElementInterface $element, $class = null) + { + // just a string, no options, no class + if (is_string($settings)) { + $class = $class ?? $this->factory; + + return $class->$settings($field, $element); + } + + if (is_array($settings) === true) { + // check if it's a custom class ¯\_(ツ)_/¯ + + /// format + /// [ + /// [class, 'function'], + /// [setting1, setting2] + /// ] + if (count($settings) === 2 && is_array($settings[0])) { + return call_user_func_array($settings[0], $settings[1]); + } + + /// just a callback + /// format + /// [ + /// [class, 'function'] + /// ] + if (count($settings) === 2 && is_object($settings[0])) { + // return call_user_func($settings); + // PHPstorm says this... need trying ¯\_(ツ)_/¯ + return $settings($field, $element); + } + } + + return 'no-value'; + } + + /** + * checkForEvent + * + * @param \craft\base\Field $field + * @param \craft\base\ElementInterface $element + * + * @return mixed|string|null + * + * @throws \yii\base\NotSupportedException + * @throws \yii\base\InvalidConfigException + * @author Robin Schambach + * @since 22.06.2021 + */ + public function checkForEvent(FieldInterface $field, ElementInterface $element): mixed + { + return Seeder::$plugin->fields->checkForEvent($field, $element); + } + + /** + * run + * + * @param \craft\base\FieldInterface $field + * @param \craft\base\ElementInterface $element + * + * @return mixed|string + * @throws \yii\base\InvalidConfigException + * @throws \yii\base\NotSupportedException + * @author Robin Schambach + * @since 19/12/2023 + */ + public function run(FieldInterface $field, ElementInterface $element) + { + $callbackValue = $this->checkForEvent($field, $element); + if ($callbackValue) { + return $callbackValue; + } + + return $this->generate($field, $element); + } + + /** + * generate + * + * @param \craft\base\FieldInterface $field + * @param \craft\base\ElementInterface $element + * + * @return mixed + * @author Robin Schambach + * @since 19/12/2023 + */ + public abstract function generate(FieldInterface $field, ElementInterface $element); +} \ No newline at end of file diff --git a/src/services/fields/CTA.php b/src/services/fields/CTA.php deleted file mode 100644 index 0fdf021..0000000 --- a/src/services/fields/CTA.php +++ /dev/null @@ -1,76 +0,0 @@ -factory = Factory::create(); - } - - public function CTAField(\statikbe\cta\fields\CTAField $field, $entry) - { - - $customLabel = $field->allowCustomText; - $blank = $field->allowTarget; - - $attr = [ - 'allowCustomText' => $field->allowCustomText, - 'allowTarget' => $field->allowTarget, - 'defaultText' => $field->defaultText, - 'owner' => $entry, - ]; - - if (CTAPlugin::$plugin->getSettings()->classes) { - $classes = CTAPlugin::$plugin->getSettings()->classes; - } else { - $classes = [ - 'btn' => 'Primary', - 'btn btn--secondary' => 'Secondary', - 'btn btn--ghost' => 'Ghost', - 'link link--ext' => 'Link >', - 'link' => 'Link' - ]; - } - - $attr += [ - 'customText' => $field->allowCustomText ? $this->factory->realText(20) : null, - 'target' => $field->allowTarget ? $this->factory->boolean : null, - 'class' => array_rand($classes), - ]; - - if (isset($field->typeSettings["url"])) { - $attr['type'] = 'url'; - $attr['value'] = $this->factory->url; - } - return new \statikbe\cta\models\CTA($attr); - } -} \ No newline at end of file diff --git a/src/services/fields/Checkboxes.php b/src/services/fields/Checkboxes.php new file mode 100644 index 0000000..94c1cc4 --- /dev/null +++ b/src/services/fields/Checkboxes.php @@ -0,0 +1,37 @@ +options)); $x <= $xMax; $x++) { + $checkedBoxes[] = $field->options[array_rand($field->options)]['value']; + } + return $checkedBoxes; + } +} \ No newline at end of file diff --git a/src/services/fields/CkEditor.php b/src/services/fields/CkEditor.php index 33d10fd..3e2d652 100644 --- a/src/services/fields/CkEditor.php +++ b/src/services/fields/CkEditor.php @@ -8,12 +8,12 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services\fields; +namespace anubarak\seeder\services\fields; use Faker\Factory; use Faker\Provider\Base; use Faker\Provider\Lorem; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; use Craft; use craft\base\Component; diff --git a/src/services/fields/Color.php b/src/services/fields/Color.php new file mode 100644 index 0000000..e92c57f --- /dev/null +++ b/src/services/fields/Color.php @@ -0,0 +1,26 @@ +factory->safeHexColor; + } +} \ No newline at end of file diff --git a/src/services/fields/Date.php b/src/services/fields/Date.php new file mode 100644 index 0000000..2c87e52 --- /dev/null +++ b/src/services/fields/Date.php @@ -0,0 +1,33 @@ +factory->dateTime(); + } +} \ No newline at end of file diff --git a/src/services/fields/Dropdown.php b/src/services/fields/Dropdown.php new file mode 100644 index 0000000..cb2ca25 --- /dev/null +++ b/src/services/fields/Dropdown.php @@ -0,0 +1,33 @@ +options[array_rand($field->options)]['value']; + } +} \ No newline at end of file diff --git a/src/services/fields/Email.php b/src/services/fields/Email.php new file mode 100644 index 0000000..5b2797d --- /dev/null +++ b/src/services/fields/Email.php @@ -0,0 +1,33 @@ +factory->email(); + } +} \ No newline at end of file diff --git a/src/services/fields/Entries.php b/src/services/fields/Entries.php new file mode 100644 index 0000000..96b1ccd --- /dev/null +++ b/src/services/fields/Entries.php @@ -0,0 +1,60 @@ +sources; + $sectionIds = []; + foreach ($sources as $source) { + $sectionUid = str_replace('section:', '', $source); + $sectionIds[] = Db::idByUid(\craft\db\Table::SECTIONS, $sectionUid); + } + + $limit = 2; + if($field->maxRelations){ + $limit = $field->maxRelations; + } + + $query = Entry::find() + ->sectionId($sectionIds) + ->limit(random_int(1, $limit)) + ->orderBy(new Expression('rand()')); + + if($field->targetSiteId){ + $site = \Craft::$app->getSites()->getSiteByUid($field->targetSiteId); + $query->siteId($site->id); + }elseif ($element->siteId){ + $query->siteId($element->siteId); + } + + return $query->ids(); + } +} \ No newline at end of file diff --git a/src/services/fields/Fields.php b/src/services/fields/Fields.php index 2f43631..15715e4 100644 --- a/src/services/fields/Fields.php +++ b/src/services/fields/Fields.php @@ -8,42 +8,18 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services\fields; +namespace anubarak\seeder\services\fields; -use Craft; use craft\base\Component; use craft\base\ElementInterface; use craft\base\Field; use craft\base\FieldInterface; use craft\elements\Asset; -use craft\elements\Category; use craft\elements\Entry; -use craft\elements\MatrixBlock; use craft\elements\Tag; use craft\elements\User; -use craft\errors\FieldNotFoundException; -use craft\fields\Assets as AssetsField; -use craft\fields\Categories; -use craft\fields\Checkboxes; -use craft\fields\Dropdown; -use craft\fields\Email; -use craft\fields\Entries; -use craft\fields\Lightswitch; -use craft\fields\Matrix; -use craft\fields\MultiSelect; -use craft\fields\Number; -use craft\fields\PlainText; -use craft\fields\RadioButtons; -use craft\fields\Table; -use craft\fields\Tags; -use craft\fields\Url; -use craft\fields\Users; -use craft\helpers\Assets; -use craft\helpers\Db; -use Faker\Factory; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; use yii\base\NotSupportedException; -use yii\db\Expression; /** * Fields Service @@ -54,14 +30,16 @@ */ class Fields extends Component { - - public $factory; + /** + * @var \Faker\Generator $factory + */ + public \Faker\Generator $factory; public function __construct() { parent::__construct(); $settings = Seeder::$plugin->getSettings()->fakerProvider; - $this->factory = Factory::create($settings); + $this->factory = \Faker\Factory::create($settings); } @@ -93,13 +71,6 @@ public function getSettings(Field $field, ElementInterface $element) $settingsForElement = $settings[$index][$section->handle]; } break; - case Category::class: - /** @var Category $element */ - $group = $element->getGroup(); - if(isset($settings[$index][$group->handle])){ - $settingsForElement = $settings[$index][$group->handle]; - } - break; case User::class: $settingsForElement = $settings[$index]; break; @@ -195,7 +166,7 @@ public function Title($maxLength = 40) * @throws \yii\base\NotSupportedException * @throws \yii\base\InvalidConfigException */ - public function checkForEvent(Field $field, ElementInterface $element) + public function checkForEvent(FieldInterface $field, ElementInterface $element): mixed { $settings = $this->getSettings($field, $element); if($settings !== null){ @@ -212,467 +183,4 @@ public function checkForEvent(Field $field, ElementInterface $element) return null; } - - /** - * @param PlainText $field - * @param Entry $entry - * - * @return mixed|null - * @throws \yii\base\NotSupportedException - * @throws \yii\base\InvalidConfigException - */ - public function PlainText($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - return $this->factory->realText($field->charLimit ? $field->charLimit : 200); - } - - /** - * @param Email $field - * - * @return - */ - public function Email($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - return $this->factory->email(); - } - - /** - * @param Url $field - ** - * - * @return - */ - public function Url($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - return $this->factory->url(); - } - - public function Number(Number $field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - $min = $field->min ?? 0; - $max = $field->max ?? 100; - - return random_int($min, $max); - } - - public function Color($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - return $this->factory->safeHexColor; - - } - - public function Date($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - return $this->factory->dateTime(); - } - - /** - * @param Categories $field - * @param Entry $entry - * - * @return array - * @throws \Exception - */ - public function Categories($field, $entry): array - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - $source = $field->source; - $groupId = null; - if($source){ - $groupUid = str_replace('group:', '', $source); - $groupId = Db::idByUid(\craft\db\Table::CATEGORYGROUPS, $groupUid); - } - - $cats = Category::find() - ->groupId($groupId) - ->limit(random_int(1, 2)) - ->orderBy(new Expression('rand()')) - ->ids(); - - return $cats; - } - - /** - * @param Dropdown $field - * @param Entry $entry - * - * @return - */ - public function Dropdown($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - return $field->options[array_rand($field->options)]['value']; - } - - /** - * @param Checkboxes $field - * @param Entry $entry - * - * @return array - * @throws \Exception - */ - public function Checkboxes($field, $entry): array - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - $checkedBoxes = []; - for ($x = 1, $xMax = random_int(1, count($field->options)); $x <= $xMax; $x++) { - $checkedBoxes[] = $field->options[array_rand($field->options)]['value']; - } - return $checkedBoxes; - } - - /** - * @param RadioButtons $field - * @param Entry $entry - * - * @return - */ - public function RadioButtons($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - return $field->options[array_rand($field->options)]['value']; - } - - /** - * @param MultiSelect $field - * @param Entry $entry - * - * @return array - * @throws \Exception - */ - public function MultiSelect($field, $entry): array - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - $options = []; - for ($x = 1, $xMax = random_int(1, count($field->options)); $x <= $xMax; $x++) { - $options[] = $field->options[array_rand($field->options)]['value']; - } - return $options; - } - - /** - * @param Lightswitch $field - * @param Entry $entry - * - * @return bool - */ - public function Lightswitch($field, $entry): bool - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - return $this->factory->boolean; - } - - /** - * @param Table $field - * @param Entry $entry - * - * @return array - * @throws \Exception - */ - public function Table($field, $entry): array - { - - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - if ($field->minRows) { - $min = $field->minRows; - } else { - $min = 1; - } - if ($field->maxRows) { - $max = $field->maxRows; - } else { - $max = $min + 10; - } - - $table = []; - for ($x = 0, $xMax = random_int($min, $max); $x <= $xMax; $x++) { - foreach ($field->columns as $handle => $col) { - switch ($col['type']) { - case 'singleline': - $table[$x][$handle] = $this->factory->text(30); - break; - case 'multiline': - $table[$x][$handle] = $this->factory->realText(150, random_int(2, 5)); - break; - case 'lightswitch': - $table[$x][$handle] = $this->factory->boolean; - break; - case 'number': - $table[$x][$handle] = $this->factory->numberBetween(2, 30); - break; - case 'checkbox': - $table[$x][$handle] = $this->factory->boolean; - break; - case 'date': - $table[$x][$handle] = $this->factory->dateTime; - break; - case 'time': - $table[$x][$handle] = $this->factory->dateTime; - break; - case 'color': - $table[$x][$handle] = $this->factory->hexColor; - break; - } - } - } - return $table; - } - - /** - * @param Tags $field - * @param Entry $entry - * - * @return array - * @throws \craft\errors\ElementNotFoundException - * @throws \yii\base\Exception - * @throws \Throwable - */ - public function Tags($field, $entry): array - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - return Tag::find()->limit(random_int(1, 5))->orderBy('rand()')->ids(); - } - - /** - * @param Users $field - * @param Entry $entry - * - * @throws \craft\errors\FieldNotFoundException - */ - public function Users($field, $entry): void - { - throw new FieldNotFoundException('Users field not supported'); - } - - /** - * Assets - * - * @param \craft\fields\Assets $field - * - * @return array - * - * @author Robin Schambach - * @since 04.12.2020 - * @throws \Exception - */ - public function Assets(\craft\fields\Assets $field, ElementInterface $element): array - { - $callbackValue = $this->checkForEvent($field, $element); - if($callbackValue){ - return $callbackValue; - } - - $source = $field->sources; - $volumeIds = []; - if($source !== '*'){ - - if(!is_array($source)){ - $source = [$source]; - } - - foreach ($source as $s){ - $volumeUid = str_replace('folder:', '', $s); - $volumeIds[] = Db::idByUid(\craft\db\Table::VOLUMES, $volumeUid); - } - - } - - $limit = 2; - if($field->limit){ - $limit = $field->limit; - } - - - $query = Asset::find() - ->limit(random_int(1, $limit)) - ->orderBy(new Expression('rand()')); - if($volumeIds){ - $query->volumeId($volumeIds); - } - - if($field->allowedKinds){ - $query->kind($field->allowedKinds); - } - - $assetIds = $query->ids(); - - return $assetIds; - } - - /** - * @param Entries $field - * - * @param $entry - * - * @return array|int[] - * @throws \Exception - */ - public function Entries(Entries $field, $entry): array - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - $sources = $field->sources; - $sectionIds = []; - foreach ($sources as $source) { - $sectionUid = str_replace('section:', '', $source); - $sectionIds[] = Db::idByUid(\craft\db\Table::SECTIONS, $sectionUid); - } - - $limit = 2; - if($field->limit){ - $limit = $field->limit; - } - - $query = Entry::find() - ->sectionId($sectionIds) - ->limit(random_int(1, $limit)) - ->orderBy(new Expression('rand()')); - - if($field->targetSiteId){ - $site = Craft::$app->getSites()->getSiteByUid($field->targetSiteId); - $query->siteId($site->id); - }elseif ($entry->siteId){ - $query->siteId($entry->siteId); - } - - $entryIds = $query->ids(); - - return $entryIds; - } - - /** - * @param Matrix $field - * @param $entry - * - * @throws \Throwable - * @throws \craft\errors\ElementNotFoundException - * @throws \yii\base\Exception - * @throws \yii\base\ExitException - */ - public function Matrix($field, $entry) - { - $callbackValue = $this->checkForEvent($field, $entry); - if($callbackValue){ - return $callbackValue; - } - - $types = $field->getBlockTypes(); - - $blockIds = []; - $types = array_map( - static function ($type) { - return $type->id; - }, $types); - - if (Seeder::getInstance()->getSettings()->eachMatrixBlock) { - $blockCount = count($types); - for ($x = 0; $x < $blockCount; $x++) { - $blockIds[] = $types[$x]; - } - shuffle($blockIds); - } else { - $blockCount = random_int(!empty($field->minBlocks) ? $field->minBlocks : 1, !empty($field->maxBlocks) ? $field->maxBlocks : 6); - for ($x = 1; $x <= $blockCount; $x++) { - $blockIds[] = $types[array_rand($types, 1)]; - } - } - - foreach ($blockIds as $blockId) { - $type = Craft::$app->matrix->getBlockTypeById($blockId); - $blockTypeFields = Craft::$app->fields->getFieldsByLayoutId($type->fieldLayoutId); - $matrixBlock = new MatrixBlock(); - $matrixBlock->typeId = $type->id; - $matrixBlock->fieldId = $field->id; - $matrixBlock->ownerId = $entry->id; - Craft::$app->elements->saveElement($matrixBlock); - $matrixBlock = Seeder::$plugin->seeder->populateFields($blockTypeFields, $matrixBlock); - Craft::$app->elements->saveElement($matrixBlock); - } - return; - } - - private function uploadNewAsset($folderId, $path): Asset - { - $assets = Craft::$app->getAssets(); - $folder = $assets->findFolder(['id' => $folderId]); - - if (!$folder) { - throw new BadRequestHttpException('The target folder provided for uploading is not valid'); - } - - // Check the permissions to upload in the resolved folder. - $filename = Assets::prepareAssetName($path); - - $asset = new Asset(); - $asset->tempFilePath = $path; - $asset->filename = $filename; - $asset->newFolderId = $folder->id; - $asset->volumeId = $folder->volumeId; - $asset->avoidFilenameConflicts = true; - $asset->setScenario(Asset::SCENARIO_CREATE); - - $result = Craft::$app->getElements()->saveElement($asset); - - return $asset; - } } \ No newline at end of file diff --git a/src/services/fields/Lightswitch.php b/src/services/fields/Lightswitch.php new file mode 100644 index 0000000..8a717c6 --- /dev/null +++ b/src/services/fields/Lightswitch.php @@ -0,0 +1,32 @@ +factory->boolean; + } +} \ No newline at end of file diff --git a/src/services/fields/Matrix.php b/src/services/fields/Matrix.php new file mode 100644 index 0000000..db17c4b --- /dev/null +++ b/src/services/fields/Matrix.php @@ -0,0 +1,67 @@ +getBlockTypes(); + + $blockIds = []; + $types = array_map( + static function ($type) { + return $type->id; + }, $types); + + if (Seeder::getInstance()->getSettings()->eachMatrixBlock) { + $blockCount = count($types); + for ($x = 0; $x < $blockCount; $x++) { + $blockIds[] = $types[$x]; + } + shuffle($blockIds); + } else { + $blockCount = random_int(!empty($field->minBlocks) ? $field->minBlocks : 1, !empty($field->maxBlocks) ? $field->maxBlocks : 6); + for ($x = 1; $x <= $blockCount; $x++) { + $blockIds[] = $types[array_rand($types, 1)]; + } + } + + foreach ($blockIds as $blockId) { + $type = Craft::$app->matrix->getBlockTypeById($blockId); + $matrixBlock = new MatrixBlock(); + $matrixBlock->typeId = $type->id; + $matrixBlock->fieldId = $field->id; + $matrixBlock->ownerId = $element->id; + Craft::$app->elements->saveElement($matrixBlock); + $matrixBlock = Seeder::$plugin->seeder->populateFields($matrixBlock); + Craft::$app->elements->saveElement($matrixBlock); + } + + return null; + } +} \ No newline at end of file diff --git a/src/services/fields/MultiSelect.php b/src/services/fields/MultiSelect.php new file mode 100644 index 0000000..33d155f --- /dev/null +++ b/src/services/fields/MultiSelect.php @@ -0,0 +1,38 @@ +options)); $x <= $xMax; $x++) { + $options[] = $field->options[array_rand($field->options)]['value']; + } + + return $options; + } +} \ No newline at end of file diff --git a/src/services/fields/Number.php b/src/services/fields/Number.php new file mode 100644 index 0000000..1f65e2d --- /dev/null +++ b/src/services/fields/Number.php @@ -0,0 +1,35 @@ +min ?? 0; + $max = $field->max ?? 100; + + return random_int($min, $max); + } +} \ No newline at end of file diff --git a/src/services/fields/PlainText.php b/src/services/fields/PlainText.php new file mode 100644 index 0000000..cf2f25a --- /dev/null +++ b/src/services/fields/PlainText.php @@ -0,0 +1,33 @@ +factory->realText($field->charLimit ? $field->charLimit : 200); + } +} \ No newline at end of file diff --git a/src/services/fields/Positionfieldtype.php b/src/services/fields/Positionfieldtype.php index fb1b4d7..f6462e4 100644 --- a/src/services/fields/Positionfieldtype.php +++ b/src/services/fields/Positionfieldtype.php @@ -8,13 +8,13 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services\fields; +namespace anubarak\seeder\services\fields; use Faker\Factory; use Faker\Provider\Base; use Faker\Provider\Lorem; use rias\positionfieldtype\fields\Position; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; use Craft; use craft\base\Component; diff --git a/src/services/fields/RadioButtons.php b/src/services/fields/RadioButtons.php new file mode 100644 index 0000000..3a1ce0b --- /dev/null +++ b/src/services/fields/RadioButtons.php @@ -0,0 +1,33 @@ +options[array_rand($field->options)]['value']; + } +} \ No newline at end of file diff --git a/src/services/fields/Redactor.php b/src/services/fields/Redactor.php index c3173a3..98df354 100644 --- a/src/services/fields/Redactor.php +++ b/src/services/fields/Redactor.php @@ -8,32 +8,28 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services\fields; +namespace anubarak\seeder\services\fields; use craft\base\Component; +use craft\base\ElementInterface; +use craft\base\FieldInterface; use Faker\Factory; use Faker\Provider\Base; use Faker\Provider\Lorem; /** - * Fields Service + * Class Redactor * - * @author Studio Espresso - * @package Seeder - * @since 1.0.0 + * @package anubarak\seeder\services\fields + * @since 19/12/2023 + * @author by Robin Schambach */ -class Redactor extends Component +class Redactor extends BaseField { - public $factory; - - public function __construct() - { - parent::__construct(); - - $this->factory = Factory::create(); - } - - public function Field($field, $entry) + /** + * @inheritDoc + */ + public function generate(FieldInterface $field, ElementInterface $element) { return Lorem::sentences(rand(5, 20), true); } diff --git a/src/services/fields/Supertable.php b/src/services/fields/Supertable.php index 0cd3503..fd9be50 100644 --- a/src/services/fields/Supertable.php +++ b/src/services/fields/Supertable.php @@ -8,12 +8,12 @@ * @copyright Copyright (c) 2018 Studio Espresso */ -namespace studioespresso\seeder\services\fields; +namespace anubarak\seeder\services\fields; use Faker\Factory; use Faker\Provider\Base; use Faker\Provider\Lorem; -use studioespresso\seeder\Seeder; +use anubarak\seeder\Seeder; use Craft; use craft\base\Component; diff --git a/src/services/fields/Table.php b/src/services/fields/Table.php new file mode 100644 index 0000000..04b3ea0 --- /dev/null +++ b/src/services/fields/Table.php @@ -0,0 +1,72 @@ +minRows) { + $min = $field->minRows; + } else { + $min = 1; + } + if ($field->maxRows) { + $max = $field->maxRows; + } else { + $max = $min + 10; + } + + $table = []; + for ($x = 0, $xMax = random_int($min, $max); $x <= $xMax; $x++) { + foreach ($field->columns as $handle => $col) { + switch ($col['type']) { + case 'singleline': + $table[$x][$handle] = $this->factory->text(30); + break; + case 'multiline': + $table[$x][$handle] = $this->factory->realText(150, random_int(2, 5)); + break; + case 'checkbox': + case 'lightswitch': + $table[$x][$handle] = $this->factory->boolean; + break; + case 'number': + $table[$x][$handle] = $this->factory->numberBetween(2, 30); + break; + case 'time': + case 'date': + $table[$x][$handle] = $this->factory->dateTime; + break; + case 'color': + $table[$x][$handle] = $this->factory->hexColor; + break; + } + } + } + + return $table; + } +} \ No newline at end of file diff --git a/src/services/fields/Url.php b/src/services/fields/Url.php new file mode 100644 index 0000000..4a15dac --- /dev/null +++ b/src/services/fields/Url.php @@ -0,0 +1,33 @@ +factory->url(); + } +} \ No newline at end of file diff --git a/src/templates/_index.twig b/src/templates/_index.twig index e707249..225e40a 100644 --- a/src/templates/_index.twig +++ b/src/templates/_index.twig @@ -21,10 +21,10 @@ {% set pluginCpUrl = url('seeder') %} {% set content %} -
+ {% if data|length %} {{ csrfInput() }} - {{ redirectInput('seeder') }} + {{ redirectInput('element-seeder') }} Select the seeded entries you want to remove