├── Api
├── CodeTemplateEngineInterface.php
├── GeneratorInterface.php
├── GeneratorResultInterface.php
├── ModulesDirProviderInterface.php
└── TemplateResolverInterface.php
├── Console
└── Command
│ ├── AbstractCommand.php
│ ├── GenerateCrud.php
│ ├── GenerateModule.php
│ ├── GeneratePlugin.php
│ └── TriadGenerateCommand.php
├── LICENSE
├── Model
├── CodeTemplate
│ ├── Engine.php
│ ├── NotEnoughVariablesPassedException.php
│ └── TemplateResolver.php
├── Command
│ ├── AbstractCommand.php
│ ├── Crud.php
│ ├── Module.php
│ ├── Plugin.php
│ ├── Plugin
│ │ ├── ClassValidator.php
│ │ ├── InputConverter.php
│ │ └── Method.php
│ └── Triad.php
├── Generator
│ ├── AbstractGenerator.php
│ ├── AbstractXmlGenerator.php
│ ├── Crud
│ │ ├── Config
│ │ │ ├── Adminhtml
│ │ │ │ └── RoutesGenerator.php
│ │ │ └── DiGenerator.php
│ │ ├── Controller
│ │ │ └── Adminhtml
│ │ │ │ ├── AbstractAction.php
│ │ │ │ ├── DeleteActionGenerator.php
│ │ │ │ ├── EditActionGenerator.php
│ │ │ │ ├── IndexActionGenerator.php
│ │ │ │ ├── InlineEditActionGenerator.php
│ │ │ │ ├── MassDeleteActionGenerator.php
│ │ │ │ ├── NewActionGenerator.php
│ │ │ │ └── SaveActionGenerator.php
│ │ ├── Grid
│ │ │ └── CollectionGenerator.php
│ │ ├── Layout
│ │ │ ├── EditGenerator.php
│ │ │ ├── IndexGenerator.php
│ │ │ └── NewLayoutGenerator.php
│ │ ├── Model
│ │ │ └── DataProviderGenerator.php
│ │ └── UiComponent
│ │ │ ├── FormGenerator.php
│ │ │ ├── Listing
│ │ │ └── Column
│ │ │ │ └── EntityActionsGenerator.php
│ │ │ └── ListingGenerator.php
│ ├── Module
│ │ ├── ComposerJsonGenerator.php
│ │ ├── InstallDataGenerator.php
│ │ ├── InstallSchemaGenerator.php
│ │ ├── ModuleXml.php
│ │ ├── Registration.php
│ │ ├── UninstallGenerator.php
│ │ ├── UpgradeDataGenerator.php
│ │ └── UpgradeSchemaGenerator.php
│ ├── NameUtil.php
│ ├── Plugin
│ │ └── DiGenerator.php
│ ├── PluginGenerator.php
│ └── Triad
│ │ ├── CollectionGenerator.php
│ │ ├── DiGenerator.php
│ │ ├── EntityGenerator.php
│ │ ├── EntityInterfaceGenerator.php
│ │ ├── Repository
│ │ ├── RepositoryGenerator.php
│ │ └── RepositoryInterfaceGenerator.php
│ │ ├── ResourceGenerator.php
│ │ └── SearchResultInterfaceGenerator.php
├── GeneratorResult.php
├── GeneratorResult
│ └── Container.php
├── MethodInjector.php
├── ModuleNameEntity.php
├── ModulesDirProvider.php
├── NodeBuilder.php
├── TableDescriber.php
└── TableDescriber
│ ├── Result.php
│ └── Result
│ └── Column.php
├── README.md
├── composer.json
├── etc
├── code_template
│ ├── crud
│ │ ├── controller
│ │ │ └── adminhtml
│ │ │ │ ├── delete.pct
│ │ │ │ ├── edit.pct
│ │ │ │ ├── index.pct
│ │ │ │ ├── inlineEdit.pct
│ │ │ │ ├── massDelete.pct
│ │ │ │ ├── new.pct
│ │ │ │ └── save.pct
│ │ ├── grid
│ │ │ └── collection.pct
│ │ ├── model
│ │ │ └── dataProvider.pct
│ │ └── uiComponent
│ │ │ └── listing
│ │ │ └── column
│ │ │ └── actions.pct
│ ├── entity
│ │ ├── collection.pct
│ │ ├── interface.pct
│ │ ├── interface
│ │ │ └── getterSetter.pct
│ │ ├── model.pct
│ │ ├── model
│ │ │ └── getterSetter.pct
│ │ ├── repository.pct
│ │ ├── repositoryInterface.pct
│ │ ├── resource.pct
│ │ └── searchResultInterface.pct
│ ├── module
│ │ ├── composer.pct
│ │ ├── installData.pct
│ │ ├── installSchema.pct
│ │ ├── uninstall.pct
│ │ ├── upgradeData.pct
│ │ └── upgradeSchema.pct
│ └── plugin
│ │ ├── after_method.pct
│ │ ├── around_method.pct
│ │ ├── before_method.pct
│ │ └── class.pct
├── di.xml
└── module.xml
└── registration.php
/Api/CodeTemplateEngineInterface.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Api;
13 |
14 | /**
15 | * Class Engine
16 | *
17 | * @package Krifollk\CodeGenerator\Model\CodeTemplate
18 | */
19 | interface CodeTemplateEngineInterface
20 | {
21 | /**
22 | * Render php code template
23 | *
24 | * @param string $template
25 | * @param array $variables
26 | *
27 | * @return string
28 | */
29 | public function render(string $template, array $variables = []): string;
30 | }
31 |
--------------------------------------------------------------------------------
/Api/GeneratorInterface.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Api;
13 |
14 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
15 |
16 | /**
17 | * Interface GeneratorInterface
18 | *
19 | * @package Krifollk\CodeGenerator\Api
20 | */
21 | interface GeneratorInterface
22 | {
23 | /**
24 | * Generate entity
25 | *
26 | * @param ModuleNameEntity $moduleNameEntity
27 | * @param array $additionalArguments
28 | *
29 | * @return GeneratorResultInterface
30 | */
31 | public function generate(
32 | ModuleNameEntity $moduleNameEntity,
33 | array $additionalArguments = []
34 | ): GeneratorResultInterface;
35 | }
36 |
--------------------------------------------------------------------------------
/Api/GeneratorResultInterface.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Api;
13 |
14 | /**
15 | * Interface GeneratorResultInterface
16 | *
17 | * @package Krifollk\CodeGenerator\Api
18 | */
19 | interface GeneratorResultInterface
20 | {
21 | /**
22 | * Get content
23 | *
24 | * @return string
25 | */
26 | public function getContent(): string;
27 |
28 | /**
29 | * Get destination path
30 | *
31 | * @return string
32 | */
33 | public function getDestinationFile(): string;
34 |
35 | /**
36 | * Get entity name
37 | *
38 | * @return string
39 | */
40 | public function getEntityName(): string;
41 | }
42 |
--------------------------------------------------------------------------------
/Api/ModulesDirProviderInterface.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Api;
13 |
14 | /**
15 | * Interface ModulesDirProviderInterface
16 | *
17 | * @package Krifollk\CodeGenerator\Api
18 | */
19 | interface ModulesDirProviderInterface
20 | {
21 | public function getModulesDir(): string;
22 | }
23 |
--------------------------------------------------------------------------------
/Api/TemplateResolverInterface.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Api;
13 |
14 | /**
15 | * Interface TemplateResolverInterface
16 | *
17 | * @package Krifollk\CodeGenerator\Api
18 | */
19 | interface TemplateResolverInterface
20 | {
21 | const TEMPLATES_DIRECTORY = 'code_template';
22 |
23 | /**
24 | * Resolve template
25 | *
26 | * Returns absolute path to template
27 | *
28 | * @param string $template
29 | *
30 | * @return string
31 | */
32 | public function resolve(string $template): string;
33 | }
34 |
--------------------------------------------------------------------------------
/Console/Command/AbstractCommand.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Console\Command;
13 |
14 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
15 | use Symfony\Component\Console\Command\Command;
16 | use Symfony\Component\Console\Input\InputArgument;
17 | use Symfony\Component\Console\Input\InputInterface;
18 | use Symfony\Component\Console\Input\InputOption;
19 |
20 | /**
21 | * Class AbstractCommand
22 | *
23 | * @package Krifollk\CodeGenerator\Console\Command
24 | */
25 | abstract class AbstractCommand extends Command
26 | {
27 | const DIR_OPTION = 'dir';
28 | const MODULE_NAME_ARGUMENT = 'module_name';
29 |
30 | /**
31 | * Create module name entity
32 | *
33 | * @param string $moduleName
34 | *
35 | * @return ModuleNameEntity
36 | * @throws \InvalidArgumentException
37 | */
38 | protected function createModuleNameEntity($moduleName): ModuleNameEntity
39 | {
40 | return new ModuleNameEntity($moduleName);
41 | }
42 |
43 | /**
44 | * @inheritdoc
45 | */
46 | protected function configure()
47 | {
48 | $this->addOption(
49 | self::DIR_OPTION,
50 | null,
51 | InputOption::VALUE_OPTIONAL,
52 | 'Module directory. Ex: app/module-some-module',
53 | ''
54 | );
55 |
56 | $this->addArgument(self::MODULE_NAME_ARGUMENT, InputArgument::REQUIRED, 'Module name');
57 |
58 | parent::configure();
59 | }
60 |
61 | /**
62 | * Get Directory option
63 | *
64 | * @param InputInterface $input
65 | *
66 | * @return string
67 | */
68 | protected function getDirOption(InputInterface $input): string
69 | {
70 | return trim($input->getOption(self::DIR_OPTION), " \t\n\r \v/\\");
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Console/Command/GenerateCrud.php:
--------------------------------------------------------------------------------
1 |
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | namespace Krifollk\CodeGenerator\Console\Command;
10 |
11 | use Krifollk\CodeGenerator\Model\Command\Crud;
12 |
13 | /**
14 | * Class GenerateCrud
15 | *
16 | * @package Krifollk\CodeGenerator\Console\Command
17 | */
18 | class GenerateCrud extends TriadGenerateCommand
19 | {
20 | const COMMAND_NAME = 'generate:crud';
21 |
22 | /**
23 | * @inheritdoc
24 | * @param Crud $crud
25 | */
26 | public function __construct(Crud $crud)
27 | {
28 | parent::__construct($crud);
29 | }
30 |
31 | /**
32 | * {@inheritdoc}
33 | * @throws \InvalidArgumentException
34 | */
35 | protected function configure()
36 | {
37 | parent::configure();
38 | $this->setName(self::COMMAND_NAME);
39 | $this->setDescription('Generate CRUD by db table.');
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Console/Command/GenerateModule.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Console\Command;
13 |
14 | use Krifollk\CodeGenerator\Model\Command\Module;
15 | use Symfony\Component\Console\Input\InputArgument;
16 | use Symfony\Component\Console\Input\InputInterface;
17 | use Symfony\Component\Console\Output\OutputInterface;
18 |
19 | /**
20 | * Class GenerateModule
21 | *
22 | * @package Krifollk\CodeGenerator\Console\Command
23 | */
24 | class GenerateModule extends AbstractCommand
25 | {
26 | const COMMAND_NAME = 'generate:module';
27 |
28 | /**#@+
29 | * Arguments
30 | */
31 | const MODULE_VERSION = 'module_version';
32 | /**#@-*/
33 |
34 | /** @var Module */
35 | private $moduleGenerator;
36 |
37 | /**
38 | * GenerateModule constructor.
39 | *
40 | * @param Module $moduleGenerator
41 | *
42 | * @throws \LogicException
43 | */
44 | public function __construct(Module $moduleGenerator)
45 | {
46 | $this->moduleGenerator = $moduleGenerator;
47 | parent::__construct(self::COMMAND_NAME);
48 | }
49 |
50 | /**
51 | * @inheritdoc
52 | */
53 | protected function configure()
54 | {
55 | parent::configure();
56 | $this->setDescription('Generate base module files.')
57 | ->addArgument(self::MODULE_VERSION, InputArgument::OPTIONAL, 'Module version');
58 | }
59 |
60 | /**
61 | * @inheritdoc
62 | */
63 | protected function execute(InputInterface $input, OutputInterface $output)
64 | {
65 | $moduleName = $this->createModuleNameEntity($input->getArgument(self::MODULE_NAME_ARGUMENT));
66 | $moduleVersion = $input->getArgument(self::MODULE_VERSION);
67 | $dir = $this->getDirOption($input);
68 |
69 | try {
70 | $generatedFiles = $this->moduleGenerator->generate($moduleName, $moduleVersion, $dir);
71 | foreach ($generatedFiles as $generatedFile) {
72 | $output->writeln(sprintf('File %s was generated.', $generatedFile));
73 | }
74 | } catch (\Exception $e) {
75 | $output->writeln('' . $e->getMessage() . '');
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/Console/Command/GeneratePlugin.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Console\Command;
13 |
14 | use Krifollk\CodeGenerator\Model\Command\Plugin;
15 | use Krifollk\CodeGenerator\Model\Generator\PluginGenerator;
16 | use Symfony\Component\Console\Helper\Table;
17 | use Symfony\Component\Console\Input\InputInterface;
18 | use Symfony\Component\Console\Output\OutputInterface;
19 | use Symfony\Component\Console\Question\ConfirmationQuestion;
20 | use Symfony\Component\Console\Question\Question;
21 |
22 | /**
23 | * Class GeneratePlugin
24 | *
25 | * @package Krifollk\CodeGenerator\Console\Command
26 | */
27 | class GeneratePlugin extends AbstractCommand
28 | {
29 | /** @var \Krifollk\CodeGenerator\Model\Command\Plugin */
30 | private $plugin;
31 |
32 | /** @var \Krifollk\CodeGenerator\Model\Command\Plugin\ClassValidator */
33 | private $classValidator;
34 |
35 | /** @var \Krifollk\CodeGenerator\Model\Command\Plugin\InputConverter */
36 | private $inputConverter;
37 |
38 | /**
39 | * GeneratePlugin constructor.
40 | *
41 | * @param Plugin $plugin
42 | * @param Plugin\ClassValidator $classValidator
43 | * @param \Krifollk\CodeGenerator\Model\Command\Plugin\InputConverter $inputConverter
44 | *
45 | * @throws \LogicException
46 | */
47 | public function __construct(
48 | Plugin $plugin,
49 | Plugin\ClassValidator $classValidator,
50 | Plugin\InputConverter $inputConverter
51 | ) {
52 | parent::__construct('generate:plugin');
53 | $this->plugin = $plugin;
54 | $this->classValidator = $classValidator;
55 | $this->inputConverter = $inputConverter;
56 | }
57 |
58 | /**
59 | * @inheritdoc
60 | */
61 | protected function configure()
62 | {
63 | parent::configure();
64 | $this->setDescription('Generate plugin.');
65 | }
66 |
67 | /**
68 | * @inheritdoc
69 | * @throws \ReflectionException
70 | * @throws \InvalidArgumentException
71 | * @throws \Zend\Validator\Exception\RuntimeException
72 | * @throws \RuntimeException
73 | * @throws \Magento\Framework\Exception\FileSystemException
74 | */
75 | protected function execute(InputInterface $input, OutputInterface $output)
76 | {
77 | $moduleNameEntity = $this->createModuleNameEntity($input->getArgument(self::MODULE_NAME_ARGUMENT));
78 | $dir = $this->getDirOption($input);
79 | /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
80 | $helper = $this->getHelper('question');
81 | $question = new Question('Enter the name of the class for which you want to create plugin: ');
82 | $className = $helper->ask($input, $output, $question);
83 |
84 | if (!$this->classValidator->isValid($className)) {
85 | foreach ($this->classValidator->getMessages() as $message) {
86 | $output->writeln(sprintf('%s', $message));
87 | }
88 |
89 | return;
90 | }
91 |
92 | $question = new Question(sprintf(
93 | 'Enter the name of the plugin class (\Module\Name\ part not required) Default: %s:',
94 | PluginGenerator::generateDefaultPluginName($moduleNameEntity, $className)),
95 | ''
96 | );
97 |
98 | $destinationClassName = $helper->ask($input, $output, $question);
99 |
100 | $table = new Table($output);
101 | $table->setHeaders(['#id', 'Allowed methods']);
102 |
103 | $allowedMethods = $this->extractAllowedMethods($className);
104 |
105 | foreach ($allowedMethods as $index => $allowedMethod) {
106 | $table->addRow([$index, $allowedMethod]);
107 | }
108 |
109 | $table->render();
110 |
111 | if ($destinationClassName !== '') {
112 | $output->writeln(
113 | sprintf(
114 | 'Plugin Name is: %s',
115 | sprintf('%s\%s', $moduleNameEntity->asPartOfNamespace(), $destinationClassName)
116 | )
117 | );
118 | }
119 |
120 | $methods = [];
121 | while (true) {
122 | $question = new Question(
123 | 'Enter method ids and types of interception(a - after, b - before, ar - around)'
124 | . "\n"
125 | . 'for which you want to create plugin using next format: id:b-ar-a, id:a-b :'
126 | );
127 |
128 | $result = $helper->ask($input, $output, $question);
129 | $methods = $this->inputConverter->convert($result, $allowedMethods);
130 |
131 | $table = new Table($output);
132 | $table->setHeaders(['Method Name', 'Interception types']);
133 |
134 | foreach ($methods as $method) {
135 | $interceptionTypes = '';
136 | if ($method->isRequireBeforeInterceptor()) {
137 | $interceptionTypes .= "Before\n";
138 | }
139 | if ($method->isRequireAroundInterceptor()) {
140 | $interceptionTypes .= "Around\n";
141 | }
142 | if ($method->isRequireAfterInterceptor()) {
143 | $interceptionTypes .= "After\n";
144 | }
145 | $table->addRow([$method->getMethodName(), $interceptionTypes]);
146 | }
147 |
148 | $table->render();
149 |
150 | $question = new ConfirmationQuestion('Is everything alright ? (y\n - yes by default)');
151 |
152 | if ($helper->ask($input, $output, $question)) {
153 | break;
154 | }
155 | }
156 |
157 | try {
158 | $generatedFiles = $this->plugin->generate(
159 | $moduleNameEntity,
160 | $methods,
161 | $className,
162 | $destinationClassName,
163 | $dir
164 | );
165 | foreach ($generatedFiles as $generatedFile) {
166 | $output->writeln(sprintf('File %s has been generated.', $generatedFile));
167 | }
168 | } catch (\Exception $e) {
169 | $output->writeln('' . $e->getMessage() . '');
170 | }
171 | }
172 |
173 | /**
174 | * @param string $className
175 | *
176 | * @return string[]
177 | * @throws \ReflectionException
178 | */
179 | private function extractAllowedMethods(string $className): array
180 | {
181 | $class = new \ReflectionClass($className);
182 | $methods = $class->getMethods();
183 | $allowedMethods = [];
184 | foreach ($methods as $method) {
185 | if ($method->isPublic() && !$method->isConstructor()) {
186 | $allowedMethods[] = $method->getName();
187 | }
188 | }
189 |
190 | return $allowedMethods;
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/Console/Command/TriadGenerateCommand.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Console\Command;
13 |
14 | use Krifollk\CodeGenerator\Model\Command\Triad;
15 | use Symfony\Component\Console\Input\InputArgument;
16 | use Symfony\Component\Console\Input\InputInterface;
17 | use Symfony\Component\Console\Output\OutputInterface;
18 |
19 | /**
20 | * Class TriadGenerateCommand
21 | *
22 | * @package Krifollk\CodeGenerator\Console\Command
23 | */
24 | class TriadGenerateCommand extends AbstractCommand
25 | {
26 | const COMMAND_NAME = 'generate:model:triad';
27 |
28 | /**#@+
29 | * Arguments
30 | */
31 | const TABLE_NAME_ARGUMENT = 'table_name';
32 | const MODULE_NAME_ARGUMENT = 'module_name';
33 | const ENTITY_NAME_ARGUMENT = 'entity_name';
34 | /**#@-*/
35 |
36 | /**
37 | * Triad command generator helper
38 | *
39 | * @var Triad
40 | */
41 | private $triad;
42 |
43 | /**
44 | * Inject dependencies
45 | *
46 | * @param Triad $triad
47 | *
48 | * @throws \LogicException
49 | */
50 | public function __construct(Triad $triad)
51 | {
52 | parent::__construct(self::COMMAND_NAME);
53 | $this->triad = $triad;
54 | }
55 |
56 | /**
57 | * {@inheritdoc}
58 | * @throws \InvalidArgumentException
59 | */
60 | protected function configure()
61 | {
62 | parent::configure();
63 | $this->setDescription('Generate Model, Resource, Collection and also Repository, by db table.')
64 | ->addArgument(self::ENTITY_NAME_ARGUMENT, InputArgument::REQUIRED, 'Entity name')
65 | ->addArgument(self::TABLE_NAME_ARGUMENT, InputArgument::REQUIRED, 'Table name');
66 | }
67 |
68 | /**
69 | * @todo
70 | * {@inheritdoc}
71 | * @throws \DomainException
72 | * @throws \InvalidArgumentException
73 | * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
74 | * @throws \Zend\Code\Generator\Exception\RuntimeException
75 | * @throws \Magento\Framework\Exception\FileSystemException
76 | */
77 | protected function execute(InputInterface $input, OutputInterface $output)
78 | {
79 | $moduleName = $this->createModuleNameEntity($input->getArgument(self::MODULE_NAME_ARGUMENT));
80 | $tableName = $input->getArgument(self::TABLE_NAME_ARGUMENT);
81 | $entityName = ucfirst($input->getArgument(self::ENTITY_NAME_ARGUMENT));
82 | $dir = $this->getDirOption($input);
83 |
84 | try {
85 | $generatedFiles = $this->triad->generate($moduleName, $tableName, $entityName, $dir);
86 |
87 | foreach ($generatedFiles as $generatedFile) {
88 | $output->writeln(sprintf('File %s was generated.', $generatedFile));
89 | }
90 | } catch (\Exception $e) {
91 | $output->writeln('' . $e->getMessage() . '');
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Rostyslav Tymoshenko
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Model/CodeTemplate/Engine.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\CodeTemplate;
13 |
14 | use Krifollk\CodeGenerator\Api\CodeTemplateEngineInterface;
15 | use Krifollk\CodeGenerator\Api\TemplateResolverInterface;
16 |
17 | /**
18 | * Class Engine
19 | *
20 | * @package Krifollk\CodeGenerator\Model\CodeTemplate
21 | */
22 | class Engine implements CodeTemplateEngineInterface
23 | {
24 | const REQUIRED_VARIABLE_REGEX = '~\{\{\s*(.*?)\s*\}\}~';
25 |
26 | /** @var TemplateResolverInterface */
27 | private $templateResolver;
28 |
29 | /**
30 | * Engine constructor.
31 | *
32 | * @param TemplateResolverInterface $templateResolver
33 | */
34 | public function __construct(TemplateResolverInterface $templateResolver)
35 | {
36 | $this->templateResolver = $templateResolver;
37 | }
38 |
39 | /**
40 | * @inheritdoc
41 | * @throws \RuntimeException
42 | */
43 | public function render(string $template, array $variables = []): string
44 | {
45 | $resolvedTemplate = $this->templateResolver->resolve($template);
46 |
47 | $content = file_get_contents($resolvedTemplate);
48 |
49 | if ($content === false) {
50 | throw new \RuntimeException(sprintf('Something went wrong while reading %s template.', $resolvedTemplate));
51 | }
52 |
53 | $variablesOfTemplate = $this->extractRequiredVariables($content);
54 |
55 | $missedVariables = array_diff($variablesOfTemplate, array_keys($variables));
56 |
57 | if (count($missedVariables) !== 0) {
58 | throw new NotEnoughVariablesPassedException($missedVariables, $resolvedTemplate);
59 | }
60 |
61 | return $this->applyVariables($variables, $variablesOfTemplate, $content);
62 | }
63 |
64 | private function extractRequiredVariables(string $content): array
65 | {
66 | $matches = [];
67 | preg_match_all(self::REQUIRED_VARIABLE_REGEX, $content, $matches);
68 |
69 | if (!isset($matches[1])) {
70 | return [];
71 | }
72 |
73 | return array_unique($matches[1]);
74 | }
75 |
76 | private function applyVariables(array $variables, array $variablesOfTemplate, string $content): string
77 | {
78 | $patterns = [];
79 | $replacements = [];
80 |
81 | foreach ($variablesOfTemplate as $variable) {
82 | $patterns[] = str_replace('(.*?)', $variable, self::REQUIRED_VARIABLE_REGEX);
83 | $replacements[] = $variables[$variable];
84 | }
85 |
86 | /** @var string|null $result */
87 | $result = preg_replace($patterns, $replacements, $content);
88 |
89 | if ($result === null) {
90 | throw new \RuntimeException('Something went wrong while applying variables to template.');
91 | }
92 |
93 | return $result;
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/Model/CodeTemplate/NotEnoughVariablesPassedException.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\CodeTemplate;
13 |
14 | use Krifollk\CodeGenerator\Api\TemplateResolverInterface;
15 |
16 | /**
17 | * Class TemplateResolver
18 | *
19 | * @package Krifollk\CodeGenerator\Model\CodeTemplate
20 | */
21 | class TemplateResolver implements TemplateResolverInterface
22 | {
23 | const FILE_EXTENSION = 'pct';
24 |
25 | /** @var \Magento\Framework\Module\Dir\Reader */
26 | private $moduleDirReader;
27 |
28 | /**
29 | * TemplateResolver constructor.
30 | *
31 | * @param \Magento\Framework\Module\Dir\Reader $moduleDirReader
32 | */
33 | public function __construct(\Magento\Framework\Module\Dir\Reader $moduleDirReader)
34 | {
35 | $this->moduleDirReader = $moduleDirReader;
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | * @throws \RuntimeException
41 | */
42 | public function resolve(string $template): string
43 | {
44 | $fullPathToTemplate = sprintf('%s%s.%s', $this->getTemplateDir(), $template, self::FILE_EXTENSION);
45 |
46 | if (!file_exists($fullPathToTemplate)) {
47 | throw new \RuntimeException(sprintf('%s template not exist.', $fullPathToTemplate));
48 | }
49 |
50 | return $fullPathToTemplate;
51 | }
52 |
53 | private function getTemplateDir(): string
54 | {
55 | return $this->moduleDirReader->getModuleDir('etc', 'Krifollk_CodeGenerator')
56 | . DIRECTORY_SEPARATOR
57 | . self::TEMPLATES_DIRECTORY
58 | . DIRECTORY_SEPARATOR;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Model/Command/AbstractCommand.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Command;
13 |
14 | use Krifollk\CodeGenerator\Api\ModulesDirProviderInterface;
15 | use Krifollk\CodeGenerator\Model\GeneratorResult\Container;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 | use Magento\Framework\Filesystem\Driver\File;
18 | use Krifollk\CodeGenerator\Model\GeneratorResult;
19 |
20 | /**
21 | * Class AbstractCommand
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Command
24 | */
25 | class AbstractCommand
26 | {
27 | /** @var File */
28 | private $file;
29 |
30 | /** @var ModulesDirProviderInterface */
31 | private $modulesDirProvider;
32 |
33 | /**
34 | * AbstractCommand constructor.
35 | *
36 | * @param File $file
37 | * @param ModulesDirProviderInterface $modulesDirProvider
38 | */
39 | public function __construct(File $file, ModulesDirProviderInterface $modulesDirProvider)
40 | {
41 | $this->file = $file;
42 | $this->modulesDirProvider = $modulesDirProvider;
43 | }
44 |
45 | /**
46 | * Generate files
47 | *
48 | * @param Container $container
49 | * @param ModuleNameEntity $moduleNameEntity
50 | * @param string $dir
51 | *
52 | * @return \Generator
53 | * @throws \Magento\Framework\Exception\FileSystemException
54 | */
55 | protected function generateFiles(
56 | Container $container,
57 | ModuleNameEntity $moduleNameEntity,
58 | string $dir
59 | ) {
60 | /** @var GeneratorResult $entity */
61 | foreach ($container->getAll() as $entity) {
62 | $absoluteFilePath = $this->getAbsoluteFilePath($moduleNameEntity, $dir, $entity);
63 |
64 | $absoluteDir = dirname($absoluteFilePath);
65 | $this->file->createDirectory($absoluteDir);
66 | $this->file->filePutContents($absoluteFilePath, $entity->getContent());
67 |
68 | yield $absoluteFilePath;
69 | }
70 | }
71 |
72 | /**
73 | * @return Container
74 | */
75 | protected function createResultContainer(): Container
76 | {
77 | return new Container();
78 | }
79 |
80 | private function getModulesDir(): string
81 | {
82 | return $this->modulesDirProvider->getModulesDir();
83 | }
84 |
85 | private function getAbsoluteFilePath(
86 | ModuleNameEntity $moduleNameEntity,
87 | string $dir,
88 | GeneratorResult $entity
89 | ): string {
90 | $absoluteFilePath = $this->getModulesDir() . $entity->getDestinationFile();
91 |
92 | if ($dir !== '') {
93 | $absoluteFilePath = sprintf('%s/%s%s', BP, $dir,
94 | str_replace($moduleNameEntity->asPartOfPath(), '', $entity->getDestinationFile())
95 | );
96 | }
97 |
98 | return $absoluteFilePath;
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/Model/Command/Module.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Command;
13 |
14 | use Krifollk\CodeGenerator\Api\ModulesDirProviderInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\Module\ComposerJsonGenerator;
16 | use Krifollk\CodeGenerator\Model\Generator\Module\InstallDataGenerator;
17 | use Krifollk\CodeGenerator\Model\Generator\Module\InstallSchemaGenerator;
18 | use Krifollk\CodeGenerator\Model\Generator\Module\ModuleXml;
19 | use Krifollk\CodeGenerator\Model\Generator\Module\Registration;
20 | use Krifollk\CodeGenerator\Model\Generator\Module\UninstallGenerator;
21 | use Krifollk\CodeGenerator\Model\Generator\Module\UpgradeDataGenerator;
22 | use Krifollk\CodeGenerator\Model\Generator\Module\UpgradeSchemaGenerator;
23 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
24 | use Magento\Framework\Filesystem\Driver\File;
25 |
26 | /**
27 | * Class Module
28 | *
29 | * @package Krifollk\CodeGenerator\Model\Command
30 | */
31 | class Module extends AbstractCommand
32 | {
33 | /** @var Registration */
34 | private $registration;
35 |
36 | /** @var ModuleXml */
37 | private $moduleXml;
38 |
39 | /** @var ComposerJsonGenerator */
40 | private $composerJsonGenerator;
41 |
42 | /** @var InstallDataGenerator */
43 | private $installDataGenerator;
44 |
45 | /** @var InstallSchemaGenerator */
46 | private $installSchemaGenerator;
47 |
48 | /** @var UninstallGenerator */
49 | private $uninstallGenerator;
50 |
51 | /** @var UpgradeDataGenerator */
52 | private $upgradeDataGenerator;
53 |
54 | /** @var UpgradeSchemaGenerator */
55 | private $upgradeSchemaGenerator;
56 |
57 | /**
58 | * Module constructor.
59 | *
60 | * @param Registration $registration
61 | * @param ModuleXml $moduleXml
62 | * @param File $file
63 | * @param ModulesDirProviderInterface $modulesDirProvider
64 | * @param ComposerJsonGenerator $composerJsonGenerator
65 | * @param InstallDataGenerator $installDataGenerator
66 | * @param InstallSchemaGenerator $installSchemaGenerator
67 | * @param UninstallGenerator $uninstallGenerator
68 | * @param UpgradeDataGenerator $upgradeDataGenerator
69 | * @param UpgradeSchemaGenerator $upgradeSchemaGenerator
70 | */
71 | public function __construct(
72 | Registration $registration,
73 | ModuleXml $moduleXml,
74 | File $file,
75 | ModulesDirProviderInterface $modulesDirProvider,
76 | ComposerJsonGenerator $composerJsonGenerator,
77 | InstallDataGenerator $installDataGenerator,
78 | InstallSchemaGenerator $installSchemaGenerator,
79 | UninstallGenerator $uninstallGenerator,
80 | UpgradeDataGenerator $upgradeDataGenerator,
81 | UpgradeSchemaGenerator $upgradeSchemaGenerator
82 | ) {
83 | $this->registration = $registration;
84 | $this->moduleXml = $moduleXml;
85 | $this->composerJsonGenerator = $composerJsonGenerator;
86 | $this->installDataGenerator = $installDataGenerator;
87 | $this->installSchemaGenerator = $installSchemaGenerator;
88 | $this->uninstallGenerator = $uninstallGenerator;
89 | $this->upgradeDataGenerator = $upgradeDataGenerator;
90 | $this->upgradeSchemaGenerator = $upgradeSchemaGenerator;
91 | parent::__construct($file, $modulesDirProvider);
92 | }
93 |
94 | /**
95 | * Generate base module files
96 | *
97 | * @param ModuleNameEntity $moduleNameEntity
98 | * @param string $version
99 | * @param string $dir
100 | *
101 | * @return \Generator
102 | * @throws \Magento\Framework\Exception\FileSystemException
103 | * @throws \InvalidArgumentException
104 | */
105 | public function generate(ModuleNameEntity $moduleNameEntity, $version = '', string $dir = ''): \Generator
106 | {
107 | $container = $this->createResultContainer();
108 |
109 | $container->insert('registration', $this->registration->generate($moduleNameEntity));
110 | $container->insert(
111 | 'module_xml',
112 | $this->moduleXml->generate($moduleNameEntity, ['moduleName' => $moduleNameEntity, 'version' => $version])
113 | );
114 |
115 | $container->insert(
116 | 'composer_json',
117 | $this->composerJsonGenerator->generate($moduleNameEntity, ['version' => $version])
118 | );
119 |
120 | $container->insert(
121 | 'install_data',
122 | $this->installDataGenerator->generate($moduleNameEntity)
123 | );
124 |
125 | $container->insert(
126 | 'install_schema',
127 | $this->installSchemaGenerator->generate($moduleNameEntity)
128 | );
129 |
130 | $container->insert(
131 | 'uninstall',
132 | $this->uninstallGenerator->generate($moduleNameEntity)
133 | );
134 |
135 | $container->insert(
136 | 'upgrade_data',
137 | $this->upgradeDataGenerator->generate($moduleNameEntity)
138 | );
139 |
140 | $container->insert(
141 | 'upgrade_schema',
142 | $this->upgradeSchemaGenerator->generate($moduleNameEntity)
143 | );
144 |
145 | return $this->generateFiles($container, $moduleNameEntity, $dir);
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/Model/Command/Plugin.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Command;
13 |
14 | use Krifollk\CodeGenerator\Api\ModulesDirProviderInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\Plugin\DiGenerator;
16 | use Krifollk\CodeGenerator\Model\Generator\PluginGenerator;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 | use Magento\Framework\Filesystem\Driver\File;
19 |
20 | /**
21 | * Class Plugin
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Command
24 | */
25 | class Plugin extends AbstractCommand
26 | {
27 | /** @var \Krifollk\CodeGenerator\Model\Generator\PluginGenerator */
28 | private $pluginGenerator;
29 |
30 | /** @var \Krifollk\CodeGenerator\Model\Generator\Plugin\DiGenerator */
31 | private $diGenerator;
32 |
33 | /**
34 | * Plugin constructor.
35 | *
36 | * @param \Magento\Framework\Filesystem\Driver\File $file
37 | * @param \Krifollk\CodeGenerator\Api\ModulesDirProviderInterface $modulesDirProvider
38 | * @param \Krifollk\CodeGenerator\Model\Generator\PluginGenerator $pluginGenerator
39 | */
40 | public function __construct(
41 | File $file,
42 | ModulesDirProviderInterface $modulesDirProvider,
43 | PluginGenerator $pluginGenerator,
44 | DiGenerator $diGenerator
45 | ) {
46 | parent::__construct($file, $modulesDirProvider);
47 | $this->pluginGenerator = $pluginGenerator;
48 | $this->diGenerator = $diGenerator;
49 | }
50 |
51 | /**
52 | * @param \Krifollk\CodeGenerator\Model\ModuleNameEntity $moduleNameEntity
53 | * @param array $methods
54 | * @param string $interceptedClassName
55 | * @param string $destinationClass
56 | * @param string $dir
57 | *
58 | * @return \Generator
59 | * @throws \Magento\Framework\Exception\FileSystemException
60 | * @throws \InvalidArgumentException
61 | */
62 | public function generate(
63 | ModuleNameEntity $moduleNameEntity,
64 | array $methods,
65 | string $interceptedClassName,
66 | string $destinationClass = '',
67 | string $dir = ''
68 | ) {
69 | $container = $this->createResultContainer();
70 | $container->insert('plugin_generator',
71 | $this->pluginGenerator->generate($moduleNameEntity,
72 | [
73 | 'methods' => $methods,
74 | 'interceptedClassName' => $interceptedClassName,
75 | 'pluginClass' => $destinationClass
76 | ]
77 | )
78 | );
79 |
80 | $container->insert('plugin_di', $this->diGenerator->generate($moduleNameEntity, [
81 | 'pluginClassName' => $container->get('plugin_generator')->getEntityName(),
82 | 'interceptedClassName' => $interceptedClassName
83 | ]));
84 |
85 | return $this->generateFiles($container, $moduleNameEntity, $dir);
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/Model/Command/Plugin/ClassValidator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Command\Plugin;
13 |
14 | /**
15 | * Class ClassValidator
16 | *
17 | * @package Krifollk\CodeGenerator\Model\Command\Plugin
18 | */
19 | class ClassValidator implements \Zend\Validator\ValidatorInterface
20 | {
21 | /** @var array */
22 | private $messages = [];
23 |
24 | /**
25 | * @inheritdoc
26 | * @throws \ReflectionException
27 | */
28 | public function isValid($className): bool
29 | {
30 | $this->messages = [];
31 | if (!class_exists($className)) {
32 | $this->messages[] = sprintf('Provided class [%s] not exists.', $className);
33 |
34 | return false;
35 | }
36 |
37 | $class = new \ReflectionClass($className);
38 |
39 | if ($class->isFinal()) {
40 | $this->messages[] = 'You can not create a plugin for Final class.';
41 | }
42 |
43 | $methods = $class->getMethods();
44 |
45 | foreach ($methods as $method) {
46 | if ($method->isPublic() && $method->isStatic()) {
47 | $this->messages[] = sprintf(
48 | 'You can not create a plugin for class which contain at least one final public method.[%s]',
49 | $method->getName()
50 | );
51 | }
52 | }
53 |
54 | return count($this->messages) === 0;
55 | }
56 |
57 | /**
58 | * @inheritdoc
59 | */
60 | public function getMessages(): array
61 | {
62 | return $this->messages;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Model/Command/Plugin/InputConverter.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Command\Plugin;
13 |
14 | /**
15 | * Class InputConverter
16 | *
17 | * @package Krifollk\CodeGenerator\Model\Command\Plugin
18 | */
19 | class InputConverter
20 | {
21 | const BEFORE_INTERCEPTOR = 'b';
22 | const AROUND_INTERCEPTOR = 'ar';
23 | const AFTER_INTERCEPTOR = 'a';
24 |
25 | /**
26 | * Convert input string to object representation of it
27 | *
28 | * Input EX: id1:b-ar-a,id2:a-b, id3:a
29 | *
30 | * @param string $userInput
31 | * @param array $allowedMethods
32 | *
33 | * @return array|\Krifollk\CodeGenerator\Model\Command\Plugin\Method[]
34 | * @throws \InvalidArgumentException
35 | */
36 | public function convert(string $userInput, array $allowedMethods): array
37 | {
38 | $explodedUserInput = explode(',', trim($userInput));
39 |
40 | $methodIds = array_keys($allowedMethods);
41 | $methods = [];
42 |
43 | foreach ($explodedUserInput as $method) {
44 | list($id, $plugins) = explode(':', $method, 2);
45 | $id = (int)$id;
46 | $plugins = explode('-', $plugins, 3);
47 |
48 | if (!in_array($id, $methodIds, true)) {
49 | throw new \InvalidArgumentException(sprintf('Provided method id not found [%s]', $id));
50 | }
51 |
52 | $methodName = $allowedMethods[$id];
53 | $beforePlugin = in_array(self::BEFORE_INTERCEPTOR, $plugins, true);
54 | $aroundPlugin = in_array(self::AROUND_INTERCEPTOR, $plugins, true);
55 | $afterPlugin = in_array(self::AFTER_INTERCEPTOR, $plugins, true);
56 |
57 | $methods[] = new Method($methodName, $beforePlugin, $aroundPlugin, $afterPlugin);
58 | }
59 |
60 | return $methods;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Model/Command/Plugin/Method.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Command\Plugin;
13 |
14 | /**
15 | * Class Method
16 | *
17 | * @package Krifollk\CodeGenerator\Model\Command\Plugin
18 | */
19 | class Method
20 | {
21 | /** @var string */
22 | private $methodName;
23 |
24 | /** @var bool */
25 | private $requireBeforeInterceptor;
26 |
27 | /** @var bool */
28 | private $requireAroundInterceptor;
29 |
30 | /** @var bool */
31 | private $requireAfterInterceptor;
32 |
33 | /**
34 | * Method constructor.
35 | *
36 | * @param string $methodName
37 | * @param bool $requireBeforeInterceptor
38 | * @param bool $requireAroundInterceptor
39 | * @param bool $requireAfterInterceptor
40 | */
41 | public function __construct(
42 | string $methodName,
43 | bool $requireBeforeInterceptor,
44 | bool $requireAroundInterceptor,
45 | bool $requireAfterInterceptor
46 | ) {
47 | $this->methodName = $methodName;
48 | $this->requireBeforeInterceptor = $requireBeforeInterceptor;
49 | $this->requireAroundInterceptor = $requireAroundInterceptor;
50 | $this->requireAfterInterceptor = $requireAfterInterceptor;
51 | }
52 |
53 | public function getMethodName(): string
54 | {
55 | return $this->methodName;
56 | }
57 |
58 | public function isRequireBeforeInterceptor(): bool
59 | {
60 | return $this->requireBeforeInterceptor;
61 | }
62 |
63 | public function isRequireAroundInterceptor(): bool
64 | {
65 | return $this->requireAroundInterceptor;
66 | }
67 |
68 | public function isRequireAfterInterceptor(): bool
69 | {
70 | return $this->requireAfterInterceptor;
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Model/Command/Triad.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Command;
13 |
14 | use Krifollk\CodeGenerator\Api\ModulesDirProviderInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
16 | use Krifollk\CodeGenerator\Model\Generator\Triad\CollectionGenerator;
17 | use Krifollk\CodeGenerator\Model\Generator\Triad\DiGenerator;
18 | use Krifollk\CodeGenerator\Model\Generator\Triad\EntityInterfaceGenerator;
19 | use Krifollk\CodeGenerator\Model\Generator\Triad\EntityGenerator;
20 | use Krifollk\CodeGenerator\Model\Generator\Triad\Repository\RepositoryInterfaceGenerator;
21 | use Krifollk\CodeGenerator\Model\Generator\Triad\Repository\RepositoryGenerator;
22 | use Krifollk\CodeGenerator\Model\Generator\Triad\ResourceGenerator;
23 | use Krifollk\CodeGenerator\Model\Generator\Triad\SearchResultInterfaceGenerator;
24 | use Krifollk\CodeGenerator\Model\GeneratorResult;
25 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
26 | use Krifollk\CodeGenerator\Model\TableDescriber;
27 |
28 | /**
29 | * Class Triad
30 | *
31 | * @package Krifollk\CodeGenerator\Model\Command
32 | */
33 | class Triad extends AbstractCommand
34 | {
35 | /** @var EntityGenerator */
36 | private $entityGenerator;
37 |
38 | /** @var EntityInterfaceGenerator */
39 | private $interfaceGenerator;
40 |
41 | /** @var ResourceGenerator */
42 | private $resourceGenerator;
43 |
44 | /** @var CollectionGenerator */
45 | private $collectionGenerator;
46 |
47 | /** @var RepositoryInterfaceGenerator */
48 | private $repositoryInterfaceGenerator;
49 |
50 | /** @var RepositoryGenerator */
51 | private $repositoryGenerator;
52 |
53 | /** @var TableDescriber */
54 | protected $tableDescriber;
55 |
56 | /** @var DiGenerator */
57 | private $diGenerator;
58 |
59 | /** @var SearchResultInterfaceGenerator */
60 | private $searchResultInterfaceGenerator;
61 |
62 | public function __construct(
63 | EntityGenerator $entityGenerator,
64 | EntityInterfaceGenerator $interfaceGenerator,
65 | ResourceGenerator $resourceGenerator,
66 | CollectionGenerator $collectionGenerator,
67 | RepositoryInterfaceGenerator $repositoryInterfaceGenerator,
68 | RepositoryGenerator $repositoryGenerator,
69 | DiGenerator $diGenerator,
70 | \Magento\Framework\Filesystem\Driver\File $file,
71 | TableDescriber $tableDescriber,
72 | ModulesDirProviderInterface $modulesDirProvider,
73 | SearchResultInterfaceGenerator $searchResultInterfaceGenerator
74 | ) {
75 | $this->entityGenerator = $entityGenerator;
76 | $this->interfaceGenerator = $interfaceGenerator;
77 | $this->resourceGenerator = $resourceGenerator;
78 | $this->collectionGenerator = $collectionGenerator;
79 | $this->repositoryInterfaceGenerator = $repositoryInterfaceGenerator;
80 | $this->repositoryGenerator = $repositoryGenerator;
81 | $this->tableDescriber = $tableDescriber;
82 | $this->diGenerator = $diGenerator;
83 | $this->searchResultInterfaceGenerator = $searchResultInterfaceGenerator;
84 | parent::__construct($file, $modulesDirProvider);
85 | }
86 |
87 | /**
88 | * Generate triad
89 | *
90 | * @param ModuleNameEntity $moduleName
91 | * @param string $tableName
92 | * @param string $entityName
93 | * @param string $dir
94 | *
95 | * @return \Generator
96 | * @throws \Magento\Framework\Exception\FileSystemException
97 | * @throws \Zend\Code\Generator\Exception\RuntimeException
98 | * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
99 | * @throws \InvalidArgumentException
100 | */
101 | public function generate(ModuleNameEntity $moduleName, string $tableName, string $entityName, string $dir)
102 | {
103 | /** @var GeneratorResult[] $entities */
104 | $entities = $this->prepareEntities($moduleName, $tableName, $entityName);
105 |
106 | return $this->generateFiles($entities, $moduleName, $dir);
107 | }
108 |
109 | /**
110 | * @param ModuleNameEntity $moduleName
111 | * @param string $tableName
112 | * @param string $entityName
113 | *
114 | * @return GeneratorResult\Container
115 | * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
116 | * @throws \Zend\Code\Generator\Exception\RuntimeException
117 | * @throws \InvalidArgumentException
118 | */
119 | protected function prepareEntities(
120 | ModuleNameEntity $moduleName,
121 | string $tableName,
122 | string $entityName
123 | ): GeneratorResult\Container {
124 | $resultContainer = $this->createResultContainer();
125 | /** @var TableDescriber\Result $tableDescriberResult */
126 | $tableDescriberResult = $this->tableDescriber->describe($tableName);
127 |
128 | $resultContainer->insert('entity_interface', $this->interfaceGenerator->generate($moduleName, [
129 | 'entityName' => $entityName,
130 | 'tableDescriberResult' => $tableDescriberResult
131 | ]
132 | ));
133 |
134 | $resultContainer->insert('resource', $this->resourceGenerator->generate($moduleName, [
135 | 'tableDescriberResult' => $tableDescriberResult,
136 | 'entityName' => $entityName
137 | ]
138 | ));
139 |
140 | $resultContainer->insert('entity', $this->entityGenerator->generate($moduleName, [
141 | 'entityName' => $entityName,
142 | 'entityInterface' => $resultContainer->get('entity_interface')->getEntityName(),
143 | 'tableDescriberResult' => $tableDescriberResult,
144 | 'resourceEntityName' => $resultContainer->get('resource')->getEntityName(),
145 | 'entityCollectionName' => NameUtil::generateCollectionName($moduleName, $entityName),
146 | ]
147 | ));
148 |
149 | $resultContainer->insert('collection', $this->collectionGenerator->generate($moduleName, [
150 | 'entityName' => $entityName,
151 | 'resourceClass' => $resultContainer->get('resource')->getEntityName(),
152 | 'modelClass' => $resultContainer->get('entity')->getEntityName()
153 | ]
154 | ));
155 |
156 | $resultContainer->insert('search_result_interface', $this->searchResultInterfaceGenerator->generate(
157 | $moduleName,
158 | [
159 | 'entityName' => $entityName,
160 | 'entityInterface' => $resultContainer->get('entity_interface')->getEntityName(),
161 | 'primaryFieldName' => $tableDescriberResult->primaryColumn()
162 | ]
163 | ));
164 |
165 | $resultContainer->insert('repository_interface', $this->repositoryInterfaceGenerator->generate($moduleName, [
166 | 'entityName' => $entityName,
167 | 'entityInterfaceName' => $resultContainer->get('entity_interface')->getEntityName(),
168 | 'searchResultInterface' => $resultContainer->get('search_result_interface')->getEntityName()
169 | ]));
170 |
171 | $resultContainer->insert('repository', $this->repositoryGenerator->generate($moduleName, [
172 | 'entityName' => $entityName,
173 | 'entityInterfaceName' => $resultContainer->get('entity_interface')->getEntityName(),
174 | 'resourceEntityName' => $resultContainer->get('resource')->getEntityName(),
175 | 'entityCollectionName' => $resultContainer->get('collection')->getEntityName(),
176 | 'repositoryInterfaceName' => $resultContainer->get('repository_interface')->getEntityName(),
177 | 'searchResultName' => $resultContainer->get('search_result_interface')->getEntityName()
178 | ]));
179 |
180 |
181 | $resultContainer->insert('di', $this->diGenerator->generate($moduleName, [
182 | 'entityClass' => $resultContainer->get('entity')->getEntityName(),
183 | 'entityInterface' => $resultContainer->get('entity_interface')->getEntityName(),
184 | 'repository' => $resultContainer->get('repository')->getEntityName(),
185 | 'repositoryInterface' => $resultContainer->get('repository_interface')->getEntityName(),
186 | 'searchResultInterface' => $resultContainer->get('search_result_interface')->getEntityName()
187 | ]));
188 |
189 | return $resultContainer;
190 | }
191 | }
192 |
--------------------------------------------------------------------------------
/Model/Generator/AbstractGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorInterface;
15 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class AbstractGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator
22 | */
23 | abstract class AbstractGenerator implements GeneratorInterface
24 | {
25 | /**
26 | * Directory separator
27 | */
28 | const DS = DIRECTORY_SEPARATOR;
29 |
30 | /**
31 | * @inheritdoc
32 | * @throws \InvalidArgumentException
33 | */
34 | public function generate(
35 | ModuleNameEntity $moduleNameEntity,
36 | array $additionalArguments = []
37 | ): GeneratorResultInterface {
38 | $this->checkArguments($additionalArguments);
39 |
40 | return $this->internalGenerate($moduleNameEntity, $additionalArguments);
41 | }
42 |
43 | /**
44 | * Checks that all required arguments passed
45 | *
46 | * @param array $arguments
47 | *
48 | * @throws \InvalidArgumentException
49 | */
50 | protected function checkArguments(array $arguments)
51 | {
52 | foreach ($this->requiredArguments() as $requiredArgument) {
53 | if (array_key_exists($requiredArgument, $arguments)) {
54 | continue;
55 | }
56 |
57 | throw new \InvalidArgumentException(sprintf('{%s} is required. [%s]', $requiredArgument, get_class($this)));
58 | }
59 | }
60 |
61 | /**
62 | * Return array of required arguments
63 | *
64 | * @return array
65 | */
66 | abstract protected function requiredArguments(): array;
67 |
68 | /**
69 | * @param ModuleNameEntity $moduleNameEntity
70 | * @param array $additionalArguments
71 | *
72 | * @return GeneratorResultInterface
73 | */
74 | abstract protected function internalGenerate(
75 | ModuleNameEntity $moduleNameEntity,
76 | array $additionalArguments = []
77 | ): GeneratorResultInterface;
78 | }
79 |
--------------------------------------------------------------------------------
/Model/Generator/AbstractXmlGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator;
13 |
14 | use DOMDocument;
15 | use Krifollk\CodeGenerator\Api\ModulesDirProviderInterface;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 | use Magento\Framework\Filesystem\Driver\File;
18 |
19 | /**
20 | * Class AbstractXmlGenerator
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator
23 | */
24 | abstract class AbstractXmlGenerator extends AbstractGenerator
25 | {
26 | const ERROR_PATTERN = '[%s %s] %s (in %s file - line %d)';
27 |
28 | const LIBXML_ERRORS_TYPE_MAP = [
29 | LIBXML_ERR_FATAL => 'FATAL',
30 | LIBXML_ERR_WARNING => 'WARNING',
31 | LIBXML_ERR_ERROR => 'ERROR',
32 | ];
33 |
34 | /** @var ModulesDirProviderInterface */
35 | protected $modulesDirProvider;
36 |
37 | /** @var File */
38 | protected $file;
39 |
40 | /**
41 | * AbstractXmlGenerator constructor.
42 | *
43 | * @param File $file
44 | * @param ModulesDirProviderInterface $modulesDirProvider
45 | */
46 | public function __construct(File $file, ModulesDirProviderInterface $modulesDirProvider)
47 | {
48 | $this->modulesDirProvider = $modulesDirProvider;
49 | $this->file = $file;
50 | }
51 |
52 | protected function load(string $file): DOMDocument
53 | {
54 | $previousValue = libxml_use_internal_errors(true);
55 | $dom = new DOMDocument();
56 | if (!$dom->load($file, LIBXML_COMPACT | LIBXML_NONET)) {
57 | throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
58 | }
59 | libxml_use_internal_errors($previousValue);
60 |
61 | return $dom;
62 | }
63 |
64 | private function getXmlErrors(): array
65 | {
66 | $errors = [];
67 | /** @var \LibXMLError $error */
68 | foreach (libxml_get_errors() as $error) {
69 | $errors[] = sprintf(
70 | self::ERROR_PATTERN,
71 | self::LIBXML_ERRORS_TYPE_MAP[$error->level],
72 | $error->code,
73 | trim($error->message),
74 | $error->file ?: 'unknown',
75 | $error->line
76 | );
77 | }
78 |
79 | libxml_clear_errors();
80 |
81 | return $errors;
82 | }
83 |
84 | protected function getDiConfigFile(ModuleNameEntity $moduleNameEntity, string $scope = ''): string
85 | {
86 | if ($scope === '') {
87 | return sprintf('%s/etc/di.xml', $moduleNameEntity->asPartOfPath());
88 | }
89 |
90 | $allowedScopes = ['frontend', 'adminhtml', 'webapi_rest', 'webapi_soap'];
91 |
92 | if (!in_array($scope, $allowedScopes, true)) {
93 | throw new \InvalidArgumentException(
94 | sprintf('Provided scope [%s] not allowed. Allowed scopes [%s]', $scope, implode(', ', $allowedScopes))
95 | );
96 | }
97 |
98 | return sprintf('%s/etc/%s/di.xml', $moduleNameEntity->asPartOfPath(), $scope);
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Config/Adminhtml/RoutesGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Config\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
17 | use Krifollk\CodeGenerator\Model\GeneratorResult;
18 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
19 | use Krifollk\CodeGenerator\Model\NodeBuilder;
20 |
21 | /**
22 | * Class RoutesGenerator
23 | *
24 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Config\Adminhtml
25 | */
26 | class RoutesGenerator extends AbstractGenerator
27 | {
28 | /**
29 | * @inheritdoc
30 | */
31 | protected function requiredArguments(): array
32 | {
33 | return [];
34 | }
35 |
36 | /**
37 | * @inheritdoc
38 | */
39 | protected function internalGenerate(
40 | ModuleNameEntity $moduleNameEntity,
41 | array $additionalArguments = []
42 | ): GeneratorResultInterface {
43 | $moduleFrontName = NameUtil::generateModuleFrontName($moduleNameEntity);
44 |
45 | $nodeBuilder = new NodeBuilder('config', [
46 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
47 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:App/etc/routes.xsd'
48 | ]);
49 |
50 | $nodeBuilder
51 | ->elementNode('router', ['id' => 'admin'])->children()
52 | ->elementNode('route', ['id' => $moduleFrontName, 'frontName' => $moduleFrontName])->children()
53 | ->elementNode('module', ['name' => $moduleNameEntity->value(), 'before' => 'Magento_Backend'])
54 | ->endNode()
55 | ->endNode();
56 |
57 | return new GeneratorResult(
58 | $nodeBuilder->toXml(),
59 | sprintf('%s/etc/adminhtml/routes.xml', $moduleNameEntity->asPartOfPath()),
60 | $moduleFrontName
61 | );
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Config/DiGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Config;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractXmlGenerator;
16 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
17 | use Krifollk\CodeGenerator\Model\Generator\Triad\DiGenerator as TriadDiGenerator;
18 | use Krifollk\CodeGenerator\Model\GeneratorResult;
19 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
20 | use Krifollk\CodeGenerator\Model\NodeBuilder;
21 | use Krifollk\CodeGenerator\Model\TableDescriber\Result;
22 | use Magento\Framework\Api\SearchResults;
23 | use Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory;
24 |
25 | /**
26 | * Class DiGenerator
27 | *
28 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Config
29 | */
30 | class DiGenerator extends AbstractXmlGenerator
31 | {
32 | const UI_COMPONENT_GRID_COLLECTIONS_XPATH = "//config/type[contains(@name,'Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory')]/arguments/argument[@name ='collections']";
33 | const UI_COMPONENT_GRID_COLLECTION_ITEM_XPATH = self ::UI_COMPONENT_GRID_COLLECTIONS_XPATH . "/item[contains(@name, '%s')]";
34 | const UI_COMPONENT_COLLECTION_XPATH = "//config/type[contains(@name,'%s')]";
35 |
36 | /**
37 | * @inheritdoc
38 | */
39 | protected function requiredArguments(): array
40 | {
41 | return [
42 | 'entityName',
43 | 'resourceModelName',
44 | 'gridCollectionClass',
45 | 'tableDescriberResult',
46 | 'entityClass',
47 | 'entityInterface',
48 | 'repository',
49 | 'repositoryInterface',
50 | 'searchResultInterface'
51 | ];
52 | }
53 |
54 | /**
55 | * @inheritdoc
56 | * @throws \Magento\Framework\Exception\FileSystemException
57 | */
58 | protected function internalGenerate(
59 | ModuleNameEntity $moduleNameEntity,
60 | array $additionalArguments = []
61 | ): GeneratorResultInterface {
62 | $entityName = $additionalArguments['entityName'];
63 | $resourceModelName = $additionalArguments['resourceModelName'];
64 | $gridCollectionClass = ltrim($additionalArguments['gridCollectionClass'], '\\');
65 | /** @var Result $tableDescriberResult */
66 | $tableDescriberResult = $additionalArguments['tableDescriberResult'];
67 | $entityClass = ltrim($additionalArguments['entityClass'], '\\');
68 | $entityInterface = ltrim($additionalArguments['entityInterface'], '\\');
69 | $repository = ltrim($additionalArguments['repository'], '\\');
70 | $repositoryInterface = ltrim($additionalArguments['repositoryInterface'], '\\');
71 | $searchResultInterface = ltrim($additionalArguments['searchResultInterface'], '\\');
72 |
73 | $dataSourceName = NameUtil::generateDataSourceName($moduleNameEntity, $entityName);
74 | $diFile = $this->modulesDirProvider->getModulesDir() . $this->getDiConfigFile($moduleNameEntity);
75 | if ($this->file->isExists($diFile)) {
76 | $domDocument = $this->load($diFile);
77 | $nodeBuilder = new NodeBuilder('', [], $domDocument);
78 |
79 | if ($nodeBuilder->isExistByPath(self::UI_COMPONENT_GRID_COLLECTIONS_XPATH)) {
80 | if (!$nodeBuilder->isExistByPath(sprintf(self::UI_COMPONENT_GRID_COLLECTION_ITEM_XPATH, NameUtil::generateDataSourceName($moduleNameEntity, $entityName)))) {
81 | $nodeBuilder->trySetPointerToElement(self::UI_COMPONENT_GRID_COLLECTIONS_XPATH);
82 | $nodeBuilder
83 | ->elementNode('item', ['name' => $dataSourceName, 'xsi:type' => 'string'], $gridCollectionClass)
84 | ->endNode();
85 | }
86 | } else {
87 | $this->addDataSourceCollectionsDefinition($nodeBuilder, $dataSourceName, $gridCollectionClass);
88 | }
89 |
90 | if (!$nodeBuilder->isExistByPath(sprintf(self::UI_COMPONENT_COLLECTION_XPATH, $gridCollectionClass))) {
91 | $this->addCollectionDifinition($nodeBuilder, $gridCollectionClass, $tableDescriberResult, $resourceModelName);
92 | }
93 |
94 | if (!$nodeBuilder->isExistByPath(sprintf(TriadDiGenerator::PREFERENCE_XPATH, $entityInterface))) {
95 | $nodeBuilder->elementNode('preference', ['for' => $entityInterface, 'type' => $entityClass]);
96 | }
97 |
98 | if (!$nodeBuilder->isExistByPath(sprintf(TriadDiGenerator::PREFERENCE_XPATH, $repositoryInterface))) {
99 | $nodeBuilder->elementNode('preference', ['for' => $repositoryInterface, 'type' => $repository]);
100 | }
101 |
102 | if (!$nodeBuilder->isExistByPath(sprintf(TriadDiGenerator::PREFERENCE_XPATH, $searchResultInterface))) {
103 | $nodeBuilder->elementNode('preference', [
104 | 'for' => $searchResultInterface,
105 | 'type' => SearchResults::class
106 | ]);
107 | }
108 |
109 | } else {
110 | $nodeBuilder = new NodeBuilder('config', [
111 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
112 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:ObjectManager/etc/config.xsd'
113 | ]);
114 |
115 | $nodeBuilder
116 | ->elementNode('preference', ['for' => $entityInterface, 'type' => $entityClass])
117 | ->elementNode('preference', ['for' => $repositoryInterface, 'type' => $repository])
118 | ->elementNode('preference', ['for' => $searchResultInterface, 'type' => SearchResults::class]);
119 | $this->addDataSourceCollectionsDefinition($nodeBuilder, $dataSourceName, $gridCollectionClass);
120 | $this->addCollectionDifinition($nodeBuilder, $gridCollectionClass, $tableDescriberResult, $resourceModelName);
121 | }
122 |
123 | return new GeneratorResult(
124 | $nodeBuilder->toXml(),
125 | sprintf('%s/etc/di.xml', $moduleNameEntity->asPartOfPath()),
126 | ''
127 | );
128 | }
129 |
130 | private function addDataSourceCollectionsDefinition(
131 | NodeBuilder $nodeBuilder,
132 | string $dataSourceName,
133 | string $gridCollectionClass
134 | ) {
135 | $nodeBuilder
136 | ->elementNode('type', ['name' => CollectionFactory::class])->children()
137 | ->elementNode('arguments')->children()
138 | ->elementNode('argument', ['name' => 'collections', 'xsi:type' => 'array'])->children()
139 | ->elementNode('item', ['name' => $dataSourceName, 'xsi:type' => 'string'], $gridCollectionClass)
140 | ->endNode()
141 | ->endNode()
142 | ->endNode();
143 | }
144 |
145 | private function addCollectionDifinition(
146 | NodeBuilder $nodeBuilder,
147 | string $gridCollectionClass,
148 | Result $tableDescriberResult,
149 | string $resourceModelName
150 | ) {
151 | $nodeBuilder
152 | ->elementNode('type', ['name' => $gridCollectionClass])->children()
153 | ->elementNode('arguments')->children()
154 | ->elementNode('argument', ['name' => 'mainTable', 'xsi:type' => 'string'], $tableDescriberResult->tableName())
155 | ->elementNode('argument', ['name' => 'resourceModel', 'xsi:type' => 'string'], $resourceModelName)
156 | ->endNode()
157 | ->endNode();
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/AbstractAction.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Model\CodeTemplate\Engine;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 | use Zend\Code\Generator\FileGenerator;
18 |
19 | /**
20 | * Class AbstractAction
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
23 | */
24 | abstract class AbstractAction extends AbstractGenerator
25 | {
26 | /** @var Engine */
27 | protected $codeTemplateEngine;
28 |
29 | /**
30 | * IndexActionGenerator constructor.
31 | *
32 | * @param Engine $codeTemplateEngine
33 | */
34 | public function __construct(Engine $codeTemplateEngine)
35 | {
36 | $this->codeTemplateEngine = $codeTemplateEngine;
37 | }
38 |
39 | protected function requiredArguments(): array
40 | {
41 | return ['entityName'];
42 | }
43 |
44 | protected function wrapToFile($generatorObject)
45 | {
46 | $fileGenerator = new FileGenerator();
47 | $fileGenerator->setClass($generatorObject);
48 |
49 | return $fileGenerator;
50 | }
51 |
52 | protected function generateFilePath(
53 | ModuleNameEntity $moduleNameEntity,
54 | string $entityName,
55 | string $actionName
56 | ): string {
57 | return sprintf(
58 | '%s/Controller/Adminhtml/%s/%s.php',
59 | $moduleNameEntity->asPartOfPath(),
60 | $entityName,
61 | $actionName
62 | );
63 | }
64 |
65 | protected function generateEntityName(
66 | ModuleNameEntity $moduleNameEntity,
67 | string $entityName,
68 | string $actionName
69 | ): string {
70 | return sprintf(
71 | '\%s\Controller\Adminhtml\%s\%s',
72 | $moduleNameEntity->asPartOfNamespace(),
73 | $entityName,
74 | $actionName
75 | );
76 | }
77 |
78 | protected function generateNamespace(ModuleNameEntity $moduleNameEntity, string $entityName): string
79 | {
80 | return sprintf('%s\Controller\Adminhtml\%s', $moduleNameEntity->asPartOfNamespace(), $entityName);
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/DeleteActionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\Crud\UiComponent\ListingGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class DeleteActionGenerator
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
23 | */
24 | class DeleteActionGenerator extends AbstractAction
25 | {
26 | /**
27 | * @inheritdoc
28 | */
29 | protected function requiredArguments(): array
30 | {
31 | return array_merge(parent::requiredArguments(), ['entityRepositoryInterface']);
32 | }
33 |
34 | /**
35 | * @inheritdoc
36 | * @throws \InvalidArgumentException
37 | * @throws \RuntimeException
38 | */
39 | protected function internalGenerate(
40 | ModuleNameEntity $moduleNameEntity,
41 | array $additionalArguments = []
42 | ): GeneratorResultInterface {
43 | $entityName = $additionalArguments['entityName'];
44 | $entityRepositoryInterface = $additionalArguments['entityRepositoryInterface'];
45 |
46 | return new GeneratorResult(
47 | $this->codeTemplateEngine->render('crud/controller/adminhtml/delete', [
48 | 'namespace' => $this->generateNamespace($moduleNameEntity, $entityName),
49 | 'entityRepositoryInterface' => $entityRepositoryInterface,
50 | 'requestIdFiledName' => ListingGenerator::REQUEST_FIELD_NAME
51 | ]
52 | ),
53 | $this->generateFilePath($moduleNameEntity, $entityName, 'Delete'),
54 | $this->generateEntityName($moduleNameEntity, $entityName, 'Delete')
55 | );
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/EditActionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\Crud\UiComponent\ListingGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class EditActionGenerator
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
23 | */
24 | class EditActionGenerator extends AbstractAction
25 | {
26 | /**
27 | * @inheritdoc
28 | */
29 | protected function requiredArguments(): array
30 | {
31 | return array_merge(parent::requiredArguments(), ['entityRepository']);
32 | }
33 |
34 | /**
35 | * @inheritdoc
36 | * @throws \RuntimeException
37 | */
38 | protected function internalGenerate(
39 | ModuleNameEntity $moduleNameEntity,
40 | array $additionalArguments = []
41 | ): GeneratorResultInterface {
42 | $entityName = $additionalArguments['entityName'];
43 |
44 | return new GeneratorResult(
45 | $this->codeTemplateEngine->render('crud/controller/adminhtml/edit', [
46 | 'namespace' => $this->generateNamespace($moduleNameEntity, $entityName),
47 | 'entityRepositoryInterface' => $additionalArguments['entityRepository'],
48 | 'requestIdFiledName' => ListingGenerator::REQUEST_FIELD_NAME
49 | ]
50 | ),
51 | $this->generateFilePath($moduleNameEntity, $entityName, 'Edit'),
52 | $this->generateEntityName($moduleNameEntity, $entityName, 'Edit')
53 | );
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/IndexActionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 |
16 |
17 | use Krifollk\CodeGenerator\Model\GeneratorResult;
18 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
19 |
20 | /**
21 | * Class IndexActionGenerator
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
24 | */
25 | class IndexActionGenerator extends AbstractAction
26 | {
27 | /**
28 | * @inheritdoc
29 | * @throws \RuntimeException
30 | */
31 | protected function internalGenerate(
32 | ModuleNameEntity $moduleNameEntity,
33 | array $additionalArguments = []
34 | ): GeneratorResultInterface {
35 | $entityName = $additionalArguments['entityName'];
36 |
37 | return new GeneratorResult(
38 | $this->codeTemplateEngine->render('crud/controller/adminhtml/index', [
39 | 'namespace' => $this->generateNamespace($moduleNameEntity, $entityName)
40 | ]
41 | ),
42 | $this->generateFilePath($moduleNameEntity, $entityName, 'Index'),
43 | $this->generateEntityName($moduleNameEntity, $entityName, 'Index')
44 | );
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/InlineEditActionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\GeneratorResult;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class InlineEditActionGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
22 | */
23 | class InlineEditActionGenerator extends AbstractAction
24 | {
25 | /**
26 | * @inheritdoc
27 | */
28 | protected function requiredArguments(): array
29 | {
30 | return array_merge(parent::requiredArguments(), ['entityRepository', 'entityName', 'entityInterface']);
31 | }
32 |
33 | /**
34 | * @inheritdoc
35 | * @throws \RuntimeException
36 | */
37 | protected function internalGenerate(
38 | ModuleNameEntity $moduleNameEntity,
39 | array $additionalArguments = []
40 | ): GeneratorResultInterface {
41 | $entityName = $additionalArguments['entityName'];
42 | $entityRepository = $additionalArguments['entityRepository'];
43 | $entityInterface = $additionalArguments['entityInterface'];
44 |
45 | return new GeneratorResult(
46 | $this->codeTemplateEngine->render('crud/controller/adminhtml/inlineEdit', [
47 | 'namespace' => $this->generateNamespace($moduleNameEntity, $entityName),
48 | 'entityRepositoryInterface' => $entityRepository,
49 | 'entityInterface' => $entityInterface
50 | ]
51 | ),
52 | $this->generateFilePath($moduleNameEntity, $entityName, 'InlineEdit'),
53 | $this->generateEntityName($moduleNameEntity, $entityName, 'InlineEdit')
54 | );
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/MassDeleteActionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\GeneratorResult;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class MassDeleteActionGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
22 | */
23 | class MassDeleteActionGenerator extends AbstractAction
24 | {
25 | /**
26 | * @inheritdoc
27 | */
28 | protected function requiredArguments(): array
29 | {
30 | return array_merge(parent::requiredArguments(), ['entityRepository', 'entityCollection']);
31 | }
32 |
33 | /**
34 | * @inheritdoc
35 | * @throws \RuntimeException
36 | */
37 | protected function internalGenerate(
38 | ModuleNameEntity $moduleNameEntity,
39 | array $additionalArguments = []
40 | ): GeneratorResultInterface {
41 | $entityName = $additionalArguments['entityName'];
42 | $entityRepository = $additionalArguments['entityRepository'];
43 | $entityCollection = $additionalArguments['entityCollection'];
44 |
45 | return new GeneratorResult(
46 | $this->codeTemplateEngine->render('crud/controller/adminhtml/massDelete', [
47 | 'namespace' => $this->generateNamespace($moduleNameEntity, $entityName),
48 | 'entityRepository' => $entityRepository,
49 | 'entityCollection' => $entityCollection
50 | ]
51 | ),
52 | $this->generateFilePath($moduleNameEntity, $entityName, 'MassDelete'),
53 | $this->generateEntityName($moduleNameEntity, $entityName, 'MassDelete')
54 | );
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/NewActionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 |
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class NewActionGenerator
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
23 | */
24 | class NewActionGenerator extends AbstractAction
25 | {
26 | /**
27 | * @inheritdoc
28 | * @throws \RuntimeException
29 | */
30 | protected function internalGenerate(
31 | ModuleNameEntity $moduleNameEntity,
32 | array $additionalArguments = []
33 | ): GeneratorResultInterface {
34 | $entityName = $additionalArguments['entityName'];
35 |
36 | return new GeneratorResult(
37 | $this->codeTemplateEngine->render('crud/controller/adminhtml/new', [
38 | 'namespace' => $this->generateNamespace($moduleNameEntity, $entityName)
39 | ]
40 | ),
41 | $this->generateFilePath($moduleNameEntity, $entityName, 'NewAction'),
42 | $this->generateEntityName($moduleNameEntity, $entityName, 'NewAction')
43 | );
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Controller/Adminhtml/SaveActionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 |
16 | use Krifollk\CodeGenerator\Model\Generator\Crud\UiComponent\ListingGenerator;
17 | use Krifollk\CodeGenerator\Model\GeneratorResult;
18 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
19 |
20 | /**
21 | * Class SaveActionGenerator
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Controller\Adminhtml
24 | */
25 | class SaveActionGenerator extends AbstractAction
26 | {
27 | /**
28 | * @inheritdoc
29 | */
30 | protected function requiredArguments(): array
31 | {
32 | return array_merge(
33 | parent::requiredArguments(),
34 | ['entityRepository', 'entity', 'dataPersistorEntityKey', 'entityInterface']
35 | );
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | * @throws \RuntimeException
41 | */
42 | protected function internalGenerate(
43 | ModuleNameEntity $moduleNameEntity,
44 | array $additionalArguments = []
45 | ): GeneratorResultInterface {
46 | $entityName = $additionalArguments['entityName'];
47 | $dataPersistorEntityKey = $additionalArguments['dataPersistorEntityKey'];
48 | $entityRepository = $additionalArguments['entityRepository'];
49 | $entityInterface = $additionalArguments['entityInterface'];
50 | $requestFieldName = ListingGenerator::REQUEST_FIELD_NAME;
51 | $entityFactory = sprintf('%sFactory', $additionalArguments['entity']);
52 |
53 | return new GeneratorResult(
54 | $this->codeTemplateEngine->render('crud/controller/adminhtml/save', [
55 | 'namespace' => $this->generateNamespace($moduleNameEntity, $entityName),
56 | 'entityRepository' => $entityRepository,
57 | 'entityFactory' => $entityFactory,
58 | 'idFieldName' => $requestFieldName,
59 | 'dataPersistorKey' => $dataPersistorEntityKey,
60 | 'entityInterface' => $entityInterface
61 | ]
62 | ),
63 | $this->generateFilePath($moduleNameEntity, $entityName, 'Save'),
64 | $this->generateEntityName($moduleNameEntity, $entityName, 'Save')
65 | );
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Grid/CollectionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Grid;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class Collection
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Grid
23 | */
24 | class CollectionGenerator extends AbstractGenerator
25 | {
26 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
27 | private $codeTemplateEngine;
28 |
29 | /**
30 | * CollectionGenerator constructor.
31 | *
32 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
33 | */
34 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
35 | {
36 | $this->codeTemplateEngine = $codeTemplateEngine;
37 | }
38 |
39 | /**
40 | * @inheritdoc
41 | */
42 | protected function requiredArguments(): array
43 | {
44 | return ['entityName'];
45 | }
46 |
47 | /**
48 | * @inheritdoc
49 | * @throws \RuntimeException
50 | */
51 | protected function internalGenerate(
52 | ModuleNameEntity $moduleNameEntity,
53 | array $additionalArguments = []
54 | ): GeneratorResultInterface {
55 | $entityName = $additionalArguments['entityName'];
56 |
57 | $className = sprintf(
58 | '\%s\Model\ResourceModel\%s\Grid\Collection',
59 | $moduleNameEntity->asPartOfNamespace(),
60 | $entityName
61 | );
62 |
63 | return new GeneratorResult(
64 | $this->codeTemplateEngine->render('crud/grid/collection', [
65 | 'namespace' => sprintf(
66 | '%s\Model\ResourceModel\%s\Grid',
67 | $moduleNameEntity->asPartOfNamespace(),
68 | $entityName
69 | ),
70 | ]
71 | ),
72 | sprintf('%s/Model/ResourceModel/%s/Grid/Collection.php', $moduleNameEntity->asPartOfPath(), $entityName),
73 | $className
74 | );
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Layout/EditGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Layout;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 | use Krifollk\CodeGenerator\Model\NodeBuilder;
19 |
20 | /**
21 | * Class Edit
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Layout
24 | */
25 | class EditGenerator extends AbstractGenerator
26 | {
27 | /**
28 | * @inheritdoc
29 | */
30 | protected function requiredArguments(): array
31 | {
32 | return ['entityName'];
33 | }
34 |
35 | /**
36 | * @inheritdoc
37 | */
38 | protected function internalGenerate(
39 | ModuleNameEntity $moduleNameEntity,
40 | array $additionalArguments = []
41 | ): GeneratorResultInterface {
42 | $entityName = $additionalArguments['entityName'];
43 |
44 | $nodeBuilder = new NodeBuilder('page',
45 | [
46 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
47 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:View/Layout/etc/page_configuration.xsd'
48 | ]
49 | );
50 |
51 | $nodeBuilder
52 | ->elementNode('body')->children()
53 | ->elementNode('referenceContainer', ['name'=> 'content'])->children()
54 | ->elementNode('uiComponent', ['name' => $this->getUiComponentName($moduleNameEntity, $entityName)])
55 | ->children()
56 | ->children();
57 |
58 | return new GeneratorResult(
59 | $nodeBuilder->toXml(),
60 | sprintf(
61 | '%s/view/adminhtml/layout/%s_%s_edit.xml',
62 | $moduleNameEntity->asPartOfPath(),
63 | mb_strtolower($moduleNameEntity->value()),
64 | mb_strtolower($entityName)),
65 | $entityName
66 | );
67 | }
68 |
69 | private function getUiComponentName(ModuleNameEntity $moduleNameEntity, string $entityName): string
70 | {
71 | $moduleName = mb_strtolower($moduleNameEntity->value());
72 | $entityName = strtolower($entityName);
73 |
74 | return sprintf('%s_%s_form', $moduleName, $entityName);
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Layout/IndexGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Layout;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 | use Krifollk\CodeGenerator\Model\NodeBuilder;
19 |
20 | /**
21 | * Class Index
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Layout
24 | */
25 | class IndexGenerator extends AbstractGenerator
26 | {
27 | /**
28 | * @inheritdoc
29 | */
30 | protected function requiredArguments(): array
31 | {
32 | return ['entityName'];
33 | }
34 |
35 | /**
36 | * @inheritdoc
37 | */
38 | protected function internalGenerate(
39 | ModuleNameEntity $moduleNameEntity,
40 | array $additionalArguments = []
41 | ): GeneratorResultInterface {
42 | $entityName = $additionalArguments['entityName'];
43 |
44 | $nodeBuilder = new NodeBuilder('page',
45 | [
46 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
47 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:View/Layout/etc/page_configuration.xsd'
48 | ]
49 | );
50 |
51 | $nodeBuilder
52 | ->elementNode('body')->children()
53 | ->elementNode('referenceContainer', ['name'=> 'content'])->children()
54 | ->elementNode('uiComponent', ['name' => $this->getUiComponentName($moduleNameEntity, $entityName)])
55 | ->children()
56 | ->children();
57 |
58 | return new GeneratorResult(
59 | $nodeBuilder->toXml(),
60 | sprintf(
61 | '%s/view/adminhtml/layout/%s_%s_index.xml',
62 | $moduleNameEntity->asPartOfPath(),
63 | mb_strtolower($moduleNameEntity->value()),
64 | mb_strtolower($entityName)),
65 | $entityName
66 | );
67 | }
68 |
69 | private function getUiComponentName(ModuleNameEntity $moduleNameEntity, string $entityName): string
70 | {
71 | $moduleName = mb_strtolower($moduleNameEntity->value());
72 | $entityName = mb_strtolower($entityName);
73 |
74 | return sprintf('%s_%s_listing', $moduleName, $entityName);
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Layout/NewLayoutGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Layout;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 | use Krifollk\CodeGenerator\Model\NodeBuilder;
19 |
20 | /**
21 | * Class NewLayout
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Layout
24 | */
25 | class NewLayoutGenerator extends AbstractGenerator
26 | {
27 | /**
28 | * @inheritdoc
29 | */
30 | protected function requiredArguments(): array
31 | {
32 | return ['entityName'];
33 | }
34 |
35 | /**
36 | * @inheritdoc
37 | */
38 | protected function internalGenerate(
39 | ModuleNameEntity $moduleNameEntity,
40 | array $additionalArguments = []
41 | ): GeneratorResultInterface {
42 | $entityName = $additionalArguments['entityName'];
43 |
44 | $nodeBuilder = new NodeBuilder('page',
45 | [
46 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
47 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:View/Layout/etc/page_configuration.xsd'
48 | ]
49 | );
50 |
51 | $nodeBuilder->elementNode('update', ['handle' => $this->generateEditHandleName($moduleNameEntity, $entityName)]);
52 |
53 | return new GeneratorResult(
54 | $nodeBuilder->toXml(),
55 | sprintf(
56 | '%s/view/adminhtml/layout/%s_%s_new.xml',
57 | $moduleNameEntity->asPartOfPath(),
58 | mb_strtolower($moduleNameEntity->value()),
59 | mb_strtolower($entityName)
60 | ),
61 | $entityName
62 | );
63 | }
64 |
65 | private function generateEditHandleName(ModuleNameEntity $moduleNameEntity, string $entityName): string
66 | {
67 | $normalizedModuleName = mb_strtolower($moduleNameEntity->value());
68 | $entityName = mb_strtolower($entityName);
69 |
70 | return sprintf('%s_%s_edit', $normalizedModuleName, $entityName);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/Model/DataProviderGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\Model;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class DataProvider
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\Model
23 | */
24 | class DataProviderGenerator extends AbstractGenerator
25 | {
26 | const NAME_PATTERN = '\%s\Model\%s\DataProvider';
27 | const FILE_NAME_PATTERN = '%s/Model/%s/DataProvider.php';
28 |
29 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
30 | private $codeTemplateEngine;
31 |
32 | /**
33 | * CollectionGenerator constructor.
34 | *
35 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
36 | */
37 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
38 | {
39 | $this->codeTemplateEngine = $codeTemplateEngine;
40 | }
41 |
42 | /**
43 | * @inheritdoc
44 | */
45 | protected function requiredArguments(): array
46 | {
47 | return ['entityName', 'collectionClassName', 'dataPersistorEntityKey'];
48 | }
49 |
50 | /**
51 | * @inheritdoc
52 | * @throws \RuntimeException
53 | */
54 | protected function internalGenerate(
55 | ModuleNameEntity $moduleNameEntity,
56 | array $additionalArguments = []
57 | ): GeneratorResultInterface {
58 | $entityName = $additionalArguments['entityName'];
59 | $collectionClassName = $additionalArguments['collectionClassName'];
60 | $dataPersistorEntityKey = $additionalArguments['dataPersistorEntityKey'];
61 |
62 | $className = sprintf('\%s\Model\%s\DataProvider', $moduleNameEntity->asPartOfNamespace(), $entityName);
63 |
64 | return new GeneratorResult(
65 | $this->codeTemplateEngine->render('crud/model/dataProvider', [
66 | 'namespace' => sprintf('%s\Model\%s', $moduleNameEntity->asPartOfNamespace(), $entityName),
67 | 'dataPersistorKey' => $dataPersistorEntityKey,
68 | 'collectionFactory' => sprintf('%sFactory', $collectionClassName)
69 | ]
70 | ),
71 | sprintf('%s/Model/%s/DataProvider.php', $moduleNameEntity->asPartOfPath(), $entityName),
72 | $className
73 | );
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/Model/Generator/Crud/UiComponent/Listing/Column/EntityActionsGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Crud\UiComponent\Listing\Column;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
17 | use Krifollk\CodeGenerator\Model\GeneratorResult;
18 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
19 | use Krifollk\CodeGenerator\Model\TableDescriber\Result;
20 |
21 | /**
22 | * Class EntityActions
23 | *
24 | * @package Krifollk\CodeGenerator\Model\Generator\Crud\UiComponent\Listing\Column
25 | */
26 | class EntityActionsGenerator extends AbstractGenerator
27 | {
28 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
29 | private $codeTemplateEngine;
30 |
31 | /**
32 | * CollectionGenerator constructor.
33 | *
34 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
35 | */
36 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
37 | {
38 | $this->codeTemplateEngine = $codeTemplateEngine;
39 | }
40 |
41 | /**
42 | * @inheritdoc
43 | */
44 | protected function requiredArguments(): array
45 | {
46 | return ['entityName', 'tableDescriberResult'];
47 | }
48 |
49 | /**
50 | * @inheritdoc
51 | * @throws \RuntimeException
52 | */
53 | protected function internalGenerate(
54 | ModuleNameEntity $moduleNameEntity,
55 | array $additionalArguments = []
56 | ): GeneratorResultInterface {
57 | $entityName = $additionalArguments['entityName'];
58 | /** @var Result $tableDescriberResult */
59 | $tableDescriberResult = $additionalArguments['tableDescriberResult'];
60 |
61 | $className = sprintf(
62 | '\%s\Model\UiComponent\Listing\Column\%sActions',
63 | $moduleNameEntity->asPartOfNamespace(),
64 | $entityName
65 | );
66 |
67 | $deleteUrl = $this->getActionUrl($moduleNameEntity, $entityName, 'delete');
68 | $editUrl = $this->getActionUrl($moduleNameEntity, $entityName, 'edit');
69 |
70 | return new GeneratorResult(
71 | $this->codeTemplateEngine->render('crud/uiComponent/listing/column/actions', [
72 | 'namespace' => sprintf('%s\Model\UiComponent\Listing\Column', $moduleNameEntity->asPartOfNamespace()),
73 | 'entityName' => ucfirst($entityName),
74 | 'idFieldName' => $tableDescriberResult->primaryColumn()->name(),
75 | 'editUrlPath' => $editUrl,
76 | 'deleteUrlPath' => $deleteUrl
77 | ]
78 | ),
79 | sprintf(
80 | '%s/Model/UiComponent/Listing/Column/%sActions.php',
81 | $moduleNameEntity->asPartOfPath(),
82 | $entityName
83 | ),
84 | $className
85 | );
86 | }
87 |
88 | private function getActionUrl(ModuleNameEntity $moduleName, string $entityName, string $action): string
89 | {
90 | return sprintf('%s/%s/%s', NameUtil::generateModuleFrontName($moduleName), mb_strtolower($entityName), $action);
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/Model/Generator/Module/ComposerJsonGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class ComposerJsonGenerator
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Module
23 | */
24 | class ComposerJsonGenerator extends AbstractGenerator
25 | {
26 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
27 | private $codeTemplateEngine;
28 |
29 | /**
30 | * IndexActionGenerator constructor.
31 | *
32 | * @param Engine $codeTemplateEngine
33 | */
34 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
35 | {
36 | $this->codeTemplateEngine = $codeTemplateEngine;
37 | }
38 |
39 | /**
40 | * @inheritdoc
41 | */
42 | protected function requiredArguments(): array
43 | {
44 | return ['version'];
45 | }
46 |
47 | /**
48 | * @inheritdoc
49 | * @throws \RuntimeException
50 | */
51 | protected function internalGenerate(
52 | ModuleNameEntity $moduleNameEntity,
53 | array $additionalArguments = []
54 | ): GeneratorResultInterface {
55 | list($vendorName, $moduleName) = explode('_', $moduleNameEntity->value());
56 |
57 | $content = $this->codeTemplateEngine->render('module/composer', [
58 | 'version' => $additionalArguments['version'] ?: '0.1.0',
59 | 'namespace' => sprintf('%s\\\\\\\\', str_replace('\\', '\\\\\\\\', $moduleNameEntity->asPartOfNamespace())),
60 | 'vendorName' => lcfirst($vendorName),
61 | 'moduleName' => strtolower(preg_replace('/([a-zA-Z])(?=[A-Z])/', '$1-', $moduleName))
62 | ]);
63 | $destinationFile = sprintf('%s/composer.json', $moduleNameEntity->asPartOfPath());
64 |
65 | return new GeneratorResult($content, $destinationFile, 'composer.json');
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Model/Generator/Module/InstallDataGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class InstallDataGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator\Module
22 | */
23 | class InstallDataGenerator extends AbstractGenerator
24 | {
25 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
26 | private $codeTemplateEngine;
27 |
28 | /**
29 | * IndexActionGenerator constructor.
30 | *
31 | * @param Engine $codeTemplateEngine
32 | */
33 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
34 | {
35 | $this->codeTemplateEngine = $codeTemplateEngine;
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | */
41 | protected function requiredArguments(): array
42 | {
43 | return [];
44 | }
45 |
46 | /**
47 | * @inheritdoc
48 | * @throws \RuntimeException
49 | */
50 | protected function internalGenerate(
51 | ModuleNameEntity $moduleNameEntity,
52 | array $additionalArguments = []
53 | ): GeneratorResultInterface {
54 | $content = $this->codeTemplateEngine->render('module/installData', [
55 | 'namespace' => sprintf('%s\Setup', $moduleNameEntity->asPartOfNamespace())
56 | ]);
57 | $destinationFile = sprintf('%s/Setup/InstallData.php', $moduleNameEntity->asPartOfPath());
58 | $entityName = sprintf('\%s\Setup\InstallData', $moduleNameEntity->asPartOfNamespace());
59 |
60 | return new \Krifollk\CodeGenerator\Model\GeneratorResult(
61 | $content,
62 | $destinationFile,
63 | $entityName
64 | );
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Model/Generator/Module/InstallSchemaGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class InstallSchemaGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator\Module
22 | */
23 | class InstallSchemaGenerator extends AbstractGenerator
24 | {
25 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
26 | private $codeTemplateEngine;
27 |
28 | /**
29 | * IndexActionGenerator constructor.
30 | *
31 | * @param Engine $codeTemplateEngine
32 | */
33 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
34 | {
35 | $this->codeTemplateEngine = $codeTemplateEngine;
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | */
41 | protected function requiredArguments(): array
42 | {
43 | return [];
44 | }
45 |
46 | /**
47 | * @inheritdoc
48 | * @throws \RuntimeException
49 | */
50 | protected function internalGenerate(
51 | ModuleNameEntity $moduleNameEntity,
52 | array $additionalArguments = []
53 | ): GeneratorResultInterface {
54 | $content = $this->codeTemplateEngine->render('module/installSchema', [
55 | 'namespace' => sprintf('%s\Setup', $moduleNameEntity->asPartOfNamespace())
56 | ]);
57 | $destinationFile = sprintf('%s/Setup/InstallSchema.php', $moduleNameEntity->asPartOfPath());
58 | $entityName = sprintf('\%s\Setup\InstallSchema', $moduleNameEntity->asPartOfNamespace());
59 |
60 | return new \Krifollk\CodeGenerator\Model\GeneratorResult(
61 | $content,
62 | $destinationFile,
63 | $entityName
64 | );
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Model/Generator/Module/ModuleXml.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 | use Krifollk\CodeGenerator\Model\NodeBuilder;
19 |
20 | /**
21 | * Class ModuleXml
22 | *
23 | * @package Krifollk\CodeGenerator\Model\Generator\Module
24 | */
25 | class ModuleXml extends AbstractGenerator
26 | {
27 | const FILE = '%s/etc/module.xml';
28 | const DEFAULT_VERSION = '0.1.0';
29 |
30 | /**
31 | * @inheritdoc
32 | */
33 | protected function requiredArguments(): array
34 | {
35 | return ['version'];
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | */
41 | protected function internalGenerate(
42 | ModuleNameEntity $moduleNameEntity,
43 | array $additionalArguments = []
44 | ): GeneratorResultInterface {
45 | $version = $additionalArguments['version'] ?? self::DEFAULT_VERSION;
46 |
47 | return new GeneratorResult(
48 | $this->generateContent($moduleNameEntity, $version),
49 | $this->generateFilePath($moduleNameEntity)
50 | );
51 | }
52 |
53 | /**
54 | * Generate module.xml content
55 | *
56 | * @param ModuleNameEntity $moduleNameEntity
57 | * @param string $version
58 | *
59 | * @return string
60 | */
61 | protected function generateContent(ModuleNameEntity $moduleNameEntity, string $version): string
62 | {
63 | $moduleName = $moduleNameEntity->value();
64 |
65 | $nodeBuilder = (new NodeBuilder('config', [
66 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
67 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:Module/etc/module.xsd'
68 | ]
69 | ))->elementNode('module', ['name' => $moduleName, 'setup_version' => $version]);
70 |
71 | return $nodeBuilder->toXml();
72 | }
73 |
74 | /**
75 | * Generate file path
76 | *
77 | * @param ModuleNameEntity $moduleNameEntity
78 | *
79 | * @return string
80 | */
81 | protected function generateFilePath(ModuleNameEntity $moduleNameEntity): string
82 | {
83 | return sprintf(self::FILE, $moduleNameEntity->asPartOfPath());
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/Model/Generator/Module/Registration.php:
--------------------------------------------------------------------------------
1 |
5 | * For the full copyright and license information, please view the LICENSE
6 | * file that was distributed with this source code.
7 | */
8 |
9 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
10 |
11 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
12 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
13 | use Krifollk\CodeGenerator\Model\GeneratorResult;
14 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
15 | use Zend\Code\Generator\FileGenerator;
16 |
17 | /**
18 | * Class Registration
19 | *
20 | * @package Krifollk\CodeGenerator\Model\Generator\Module
21 | */
22 | class Registration extends AbstractGenerator
23 | {
24 | const FILE = '%s/registration.php';
25 | const BODY_PATTERN = 'ComponentRegistrar::register(ComponentRegistrar::MODULE, \'%s\', __DIR__);';
26 |
27 | /**
28 | * @inheritdoc
29 | */
30 | protected function requiredArguments(): array
31 | {
32 | return [];
33 | }
34 |
35 | /**
36 | * @inheritdoc
37 | */
38 | protected function internalGenerate(
39 | ModuleNameEntity $moduleNameEntity,
40 | array $additionalArguments = []
41 | ): GeneratorResultInterface {
42 | $fileGenerator = new FileGenerator();
43 | $fileGenerator->setUse(\Magento\Framework\Component\ComponentRegistrar::class);
44 | $fileGenerator->setBody($this->generateBody($moduleNameEntity));
45 |
46 | return new GeneratorResult(
47 | $fileGenerator->generate(),
48 | $this->generateFilePath($moduleNameEntity)
49 | );
50 | }
51 |
52 | protected function generateBody(ModuleNameEntity $moduleNameEntity): string
53 | {
54 | return sprintf(self::BODY_PATTERN, str_replace('/', '_', $moduleNameEntity->asPartOfPath()));
55 | }
56 |
57 | protected function generateFilePath(ModuleNameEntity $moduleNameEntity): string
58 | {
59 | return sprintf(self::FILE, $moduleNameEntity->asPartOfPath());
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Model/Generator/Module/UninstallGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class UninstallGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator\Module
22 | */
23 | class UninstallGenerator extends AbstractGenerator
24 | {
25 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
26 | private $codeTemplateEngine;
27 |
28 | /**
29 | * IndexActionGenerator constructor.
30 | *
31 | * @param Engine $codeTemplateEngine
32 | */
33 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
34 | {
35 | $this->codeTemplateEngine = $codeTemplateEngine;
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | */
41 | protected function requiredArguments(): array
42 | {
43 | return [];
44 | }
45 |
46 | /**
47 | * @inheritdoc
48 | * @throws \RuntimeException
49 | */
50 | protected function internalGenerate(
51 | ModuleNameEntity $moduleNameEntity,
52 | array $additionalArguments = []
53 | ): GeneratorResultInterface {
54 | $content = $this->codeTemplateEngine->render('module/uninstall', [
55 | 'namespace' => sprintf('%s\Setup', $moduleNameEntity->asPartOfNamespace())
56 | ]);
57 | $destinationFile = sprintf('%s/Setup/Uninstall.php', $moduleNameEntity->asPartOfPath());
58 | $entityName = sprintf('\%s\Setup\Uninstall', $moduleNameEntity->asPartOfNamespace());
59 |
60 | return new \Krifollk\CodeGenerator\Model\GeneratorResult(
61 | $content,
62 | $destinationFile,
63 | $entityName
64 | );
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Model/Generator/Module/UpgradeDataGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class UpgradeDataGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator\Module
22 | */
23 | class UpgradeDataGenerator extends AbstractGenerator
24 | {
25 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
26 | private $codeTemplateEngine;
27 |
28 | /**
29 | * IndexActionGenerator constructor.
30 | *
31 | * @param Engine $codeTemplateEngine
32 | */
33 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
34 | {
35 | $this->codeTemplateEngine = $codeTemplateEngine;
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | */
41 | protected function requiredArguments(): array
42 | {
43 | return [];
44 | }
45 |
46 | /**
47 | * @inheritdoc
48 | * @throws \RuntimeException
49 | */
50 | protected function internalGenerate(
51 | ModuleNameEntity $moduleNameEntity,
52 | array $additionalArguments = []
53 | ): GeneratorResultInterface {
54 | $content = $this->codeTemplateEngine->render('module/upgradeData', [
55 | 'namespace' => sprintf('%s\Setup', $moduleNameEntity->asPartOfNamespace())
56 | ]);
57 | $destinationFile = sprintf('%s/Setup/UpgradeData.php', $moduleNameEntity->asPartOfPath());
58 | $entityName = sprintf('\%s\Setup\UpgradeData', $moduleNameEntity->asPartOfNamespace());
59 |
60 | return new \Krifollk\CodeGenerator\Model\GeneratorResult(
61 | $content,
62 | $destinationFile,
63 | $entityName
64 | );
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Model/Generator/Module/UpgradeSchemaGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Module;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
17 |
18 | /**
19 | * Class UpgradeSchemaGenerator
20 | *
21 | * @package Krifollk\CodeGenerator\Model\Generator\Module
22 | */
23 | class UpgradeSchemaGenerator extends AbstractGenerator
24 | {
25 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
26 | private $codeTemplateEngine;
27 |
28 | /**
29 | * IndexActionGenerator constructor.
30 | *
31 | * @param Engine $codeTemplateEngine
32 | */
33 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
34 | {
35 | $this->codeTemplateEngine = $codeTemplateEngine;
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | */
41 | protected function requiredArguments(): array
42 | {
43 | return [];
44 | }
45 |
46 | /**
47 | * @inheritdoc
48 | * @throws \RuntimeException
49 | */
50 | protected function internalGenerate(
51 | ModuleNameEntity $moduleNameEntity,
52 | array $additionalArguments = []
53 | ): GeneratorResultInterface {
54 | $content = $this->codeTemplateEngine->render('module/upgradeSchema', [
55 | 'namespace' => sprintf('%s\Setup', $moduleNameEntity->asPartOfNamespace())
56 | ]);
57 | $destinationFile = sprintf('%s/Setup/UpgradeSchema.php', $moduleNameEntity->asPartOfPath());
58 | $entityName = sprintf('\%s\Setup\UpgradeSchema', $moduleNameEntity->asPartOfNamespace());
59 |
60 | return new \Krifollk\CodeGenerator\Model\GeneratorResult(
61 | $content,
62 | $destinationFile,
63 | $entityName
64 | );
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Model/Generator/NameUtil.php:
--------------------------------------------------------------------------------
1 | value()), mb_strtolower($entityName));
28 | }
29 |
30 | public static function camelize(string $columnName): string
31 | {
32 | return str_replace('_', '', ucwords($columnName, '_'));
33 | }
34 |
35 | public static function generateResourceName(ModuleNameEntity $moduleNameEntity, string $entityName): string
36 | {
37 | return sprintf('\%s\Model\ResourceModel\%s', $moduleNameEntity->asPartOfNamespace(), $entityName);
38 | }
39 |
40 | public static function generateCollectionName(ModuleNameEntity $moduleNameEntity, $entityName): string
41 | {
42 | return sprintf('\%s\Model\ResourceModel\%s\Collection', $moduleNameEntity->asPartOfNamespace(), $entityName);
43 | }
44 |
45 | public static function generateModuleFrontName(ModuleNameEntity $moduleNameEntity): string
46 | {
47 | return implode('_', array_map('lcfirst', explode('_', $moduleNameEntity->value(), 2)));
48 | }
49 |
50 | public static function generateLabelFromColumn(\Krifollk\CodeGenerator\Model\TableDescriber\Result\Column $column): string
51 | {
52 | return implode(' ', array_map('ucfirst', explode('_', $column->name())));
53 | }
54 |
55 | public static function generateDataPersistorKey(ModuleNameEntity $moduleNameEntity, $entityName): string
56 | {
57 | return mb_strtolower($moduleNameEntity->value()) . '_' . mb_strtolower($entityName);
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Model/Generator/Plugin/DiGenerator.php:
--------------------------------------------------------------------------------
1 | modulesDirProvider->getModulesDir() . $this->getDiConfigFile($moduleNameEntity, $scope);
45 |
46 | if ($this->file->isExists($file)) {
47 | $domDocument = $this->load($file);
48 |
49 | $nodeBuilder = new NodeBuilder('', [], $domDocument);
50 |
51 | if (!$nodeBuilder->isExistByPath(sprintf(self::TYPE_XPATH, $interceptedClassName))) {
52 | $nodeBuilder
53 | ->elementNode('type', ['name' => $interceptedClassName])->children()
54 | ->elementNode('plugin', ['name' => $pluginName, 'type' => $pluginClassName, 'sortOrder' => $sortOrder])
55 | ->endNode();
56 | } else {
57 | $nodeBuilder->trySetPointerToElement(sprintf(self::TYPE_XPATH, $interceptedClassName));
58 | $nodeBuilder->elementNode('plugin', [
59 | 'name' => $pluginName,
60 | 'type' => $pluginClassName,
61 | 'sortOrder' => $sortOrder
62 | ]
63 | );
64 | }
65 |
66 | } else {
67 | $nodeBuilder = new NodeBuilder('config', [
68 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
69 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:ObjectManager/etc/config.xsd'
70 | ]);
71 |
72 | $nodeBuilder
73 | ->elementNode('type', ['name' => $interceptedClassName])->children()
74 | ->elementNode('plugin', ['name' => $pluginName, 'type' => $pluginClassName, 'sortOrder' => $sortOrder])
75 | ->endNode();
76 | }
77 |
78 | return new GeneratorResult(
79 | $nodeBuilder->toXml(),
80 | $this->getDiConfigFile($moduleNameEntity, $scope),
81 | 'di'
82 | );
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/CollectionGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 |
16 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
17 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
18 | use Krifollk\CodeGenerator\Model\GeneratorResult;
19 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
20 |
21 |
22 | /**
23 | * Class CollectionPart
24 | *
25 | * @package Krifollk\CodeGenerator\Model\Generator\Triad
26 | */
27 | class CollectionGenerator extends AbstractGenerator
28 | {
29 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
30 | private $codeTemplateEngine;
31 |
32 | /**
33 | * RepositoryGenerator constructor.
34 | *
35 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
36 | */
37 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
38 | {
39 | $this->codeTemplateEngine = $codeTemplateEngine;
40 | }
41 |
42 | /**
43 | * @inheritdoc
44 | */
45 | protected function requiredArguments(): array
46 | {
47 | return ['entityName', 'resourceClass', 'modelClass'];
48 | }
49 |
50 | /**
51 | * @inheritdoc
52 | * @throws \RuntimeException
53 | */
54 | protected function internalGenerate(
55 | ModuleNameEntity $moduleNameEntity,
56 | array $additionalArguments = []
57 | ): GeneratorResultInterface {
58 | $entityName = $additionalArguments['entityName'];
59 | $resourceClass = $additionalArguments['resourceClass'];
60 | $modelClass = $additionalArguments['modelClass'];
61 | $className = NameUtil::generateCollectionName($moduleNameEntity, $entityName);
62 |
63 | $namespace = sprintf('%s\Model\ResourceModel\%s', $moduleNameEntity->asPartOfNamespace(), $entityName);
64 | $eventPrefix = mb_strtolower(sprintf('%s_%s_collection', $moduleNameEntity->value(), $entityName));
65 |
66 | return new GeneratorResult(
67 | $this->codeTemplateEngine->render('entity/collection', [
68 | 'namespace' => $namespace,
69 | 'entity' => $modelClass,
70 | 'entityResource' => $resourceClass,
71 | 'eventPrefix' => $eventPrefix
72 | ]
73 | ),
74 | sprintf('%s/Model/ResourceModel/%s/Collection.php', $moduleNameEntity->asPartOfPath(), $entityName),
75 | $className
76 | );
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/DiGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractXmlGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 | use Krifollk\CodeGenerator\Model\NodeBuilder;
19 | use Magento\Framework\Api\SearchResults;
20 |
21 | /**
22 | * Class DiGenerator
23 | *
24 | * @package Krifollk\CodeGenerator\Model\Generator\Triad
25 | */
26 | class DiGenerator extends AbstractXmlGenerator
27 | {
28 | const PREFERENCE_XPATH = "//config/preference[contains(@for,'%s')]";
29 |
30 | /**
31 | * @inheritdoc
32 | */
33 | protected function requiredArguments(): array
34 | {
35 | return ['entityClass', 'entityInterface', 'repository', 'repositoryInterface', 'searchResultInterface'];
36 | }
37 |
38 | /**
39 | * @inheritdoc
40 | * @throws \Magento\Framework\Exception\FileSystemException
41 | */
42 | protected function internalGenerate(
43 | ModuleNameEntity $moduleNameEntity,
44 | array $additionalArguments = []
45 | ): GeneratorResultInterface {
46 | $entityClass = ltrim($additionalArguments['entityClass'], '\\');
47 | $entityInterface = ltrim($additionalArguments['entityInterface'], '\\');
48 | $repository = ltrim($additionalArguments['repository'], '\\');
49 | $repositoryInterface = ltrim($additionalArguments['repositoryInterface'], '\\');
50 | $searchResultInterface = ltrim($additionalArguments['searchResultInterface'], '\\');
51 | $exposedMessages = [];
52 |
53 | $file = $this->modulesDirProvider->getModulesDir() . $this->getDiConfigFile($moduleNameEntity);
54 |
55 | if ($this->file->isExists($file)) {
56 | $domDocument = $this->load($file);
57 |
58 | $nodeBuilder = new NodeBuilder('', [], $domDocument);
59 |
60 | if (!$nodeBuilder->isExistByPath(sprintf(self::PREFERENCE_XPATH, $entityInterface))) {
61 | $nodeBuilder->elementNode('preference', ['for' => $entityInterface, 'type' => $entityClass]);
62 | $exposedMessages[] = '';//TODO
63 | }
64 |
65 | if (!$nodeBuilder->isExistByPath(sprintf(self::PREFERENCE_XPATH, $repositoryInterface))) {
66 | $nodeBuilder->elementNode('preference', ['for' => $repositoryInterface, 'type' => $repository]);
67 | $exposedMessages[] = '';//TODO
68 | }
69 |
70 | if (!$nodeBuilder->isExistByPath(sprintf(self::PREFERENCE_XPATH, $searchResultInterface))) {
71 | $nodeBuilder->elementNode('preference', [
72 | 'for' => $searchResultInterface,
73 | 'type' => SearchResults::class
74 | ]);
75 | $exposedMessages[] = '';//TODO
76 | }
77 | } else {
78 | $nodeBuilder = new NodeBuilder('config', [
79 | 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
80 | 'xsi:noNamespaceSchemaLocation' => 'urn:magento:framework:ObjectManager/etc/config.xsd'
81 | ]);
82 |
83 | $nodeBuilder
84 | ->elementNode('preference', ['for' => $searchResultInterface, 'type' => SearchResults::class])
85 | ->elementNode('preference', ['for' => $entityInterface, 'type' => $entityClass])
86 | ->elementNode('preference', ['for' => $repositoryInterface, 'type' => $repository]);
87 | }
88 |
89 | return new GeneratorResult(
90 | $nodeBuilder->toXml(),
91 | $this->getDiConfigFile($moduleNameEntity),
92 | 'di',
93 | $exposedMessages
94 | );
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/EntityGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 |
16 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
17 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
18 | use Krifollk\CodeGenerator\Model\GeneratorResult;
19 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
20 | use Krifollk\CodeGenerator\Model\TableDescriber\Result;
21 |
22 |
23 | /**
24 | * Class Model
25 | *
26 | * @package Krifollk\CodeGenerator\Model\Generator
27 | */
28 | class EntityGenerator extends AbstractGenerator
29 | {
30 | const MODEL_NAME_PATTERN = '\%s\Model\%s';
31 | const PACKAGE_NAME_PATTERN = '%s\Model';
32 | const MODEL_FILE_NAME_PATTERN = '%s/Model/%s.php';
33 |
34 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
35 | private $codeTemplateEngine;
36 |
37 | /**
38 | * RepositoryGenerator constructor.
39 | *
40 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
41 | */
42 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
43 | {
44 | $this->codeTemplateEngine = $codeTemplateEngine;
45 | }
46 |
47 | /**
48 | * @inheritdoc
49 | */
50 | protected function requiredArguments(): array
51 | {
52 | return [
53 | 'entityName',
54 | 'entityInterface',
55 | 'tableDescriberResult',
56 | 'resourceEntityName',
57 | 'entityCollectionName',
58 | ];
59 | }
60 |
61 | /**
62 | * @inheritdoc
63 | * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
64 | * @throws \InvalidArgumentException
65 | * @throws \RuntimeException
66 | */
67 | protected function internalGenerate(
68 | ModuleNameEntity $moduleNameEntity,
69 | array $additionalArguments = []
70 | ): GeneratorResultInterface {
71 | $entityName = $additionalArguments['entityName'];
72 | /** @var Result $tableDescriberResult */
73 | $tableDescriberResult = $additionalArguments['tableDescriberResult'];
74 | $resourceEntityName = $additionalArguments['resourceEntityName'];
75 | $entityCollectionName = $additionalArguments['entityCollectionName'];
76 | $entityInterface = $additionalArguments['entityInterface'];
77 |
78 | $fullEntityName = sprintf(
79 | self::MODEL_NAME_PATTERN,
80 | $moduleNameEntity->asPartOfNamespace(),
81 | $entityName
82 | );
83 |
84 | $gettersSetters = '';
85 | $columnsCount = count($tableDescriberResult->columns());
86 | $counter = 1;
87 | foreach ($tableDescriberResult->columns() as $column) {
88 | $camelizeColumnName = NameUtil::camelize($column->name());
89 | $gettersSetters .= $this->codeTemplateEngine->render('entity/model/getterSetter', [
90 | 'name' => $camelizeColumnName,
91 | 'constField' => strtoupper($column->name()),
92 | ]
93 | );
94 |
95 | if ($counter !== $columnsCount) {
96 | $gettersSetters .= "\n\n";
97 | }
98 |
99 | $counter++;
100 | }
101 |
102 | return new GeneratorResult(
103 | $this->codeTemplateEngine->render('entity/model', [
104 | 'namespace' => sprintf(self::PACKAGE_NAME_PATTERN, $moduleNameEntity->asPartOfNamespace()),
105 | 'resourceModel' => $resourceEntityName,
106 | 'eventPrefix' => mb_strtolower(sprintf('%s_model_%s', $moduleNameEntity->value(), $entityName)),
107 | 'entityName' => $entityName,
108 | 'collection' => $entityCollectionName,
109 | 'gettersSetters' => $gettersSetters,
110 | 'entityInterface' => $entityInterface
111 |
112 | ]
113 | ),
114 | sprintf(self::MODEL_FILE_NAME_PATTERN, $moduleNameEntity->asPartOfPath(), $entityName),
115 | $fullEntityName
116 | );
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/EntityInterfaceGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
17 | use Krifollk\CodeGenerator\Model\GeneratorResult;
18 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
19 | use Krifollk\CodeGenerator\Model\TableDescriber\Result;
20 |
21 | /**
22 | * Class ModelInterface
23 | *
24 | * @package Krifollk\CodeGenerator\Model\Generator
25 | */
26 | class EntityInterfaceGenerator extends AbstractGenerator
27 | {
28 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
29 | private $codeTemplateEngine;
30 |
31 | /**
32 | * RepositoryGenerator constructor.
33 | *
34 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
35 | */
36 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
37 | {
38 | $this->codeTemplateEngine = $codeTemplateEngine;
39 | }
40 |
41 | /**
42 | * @inheritdoc
43 | */
44 | protected function requiredArguments(): array
45 | {
46 | return ['entityName', 'tableDescriberResult'];
47 | }
48 |
49 | /**
50 | * @inheritdoc
51 | * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
52 | * @throws \RuntimeException
53 | */
54 | protected function internalGenerate(
55 | ModuleNameEntity $moduleNameEntity,
56 | array $additionalArguments = []
57 | ): GeneratorResultInterface {
58 | $entityName = $additionalArguments['entityName'];
59 | /** @var Result $tableDescriberResult */
60 | $tableDescriberResult = $additionalArguments['tableDescriberResult'];
61 |
62 | $fullEntityName = sprintf(
63 | '\%s\Api\Data\%sInterface',
64 | $moduleNameEntity->asPartOfNamespace(),
65 | $entityName
66 | );
67 |
68 | $gettersSetters = '';
69 | $constants = '';
70 | $columnsCount = count($tableDescriberResult->columns());
71 | $counter = 1;
72 | foreach ($tableDescriberResult->columns() as $column) {
73 | $camelizedColumnName = NameUtil::camelize($column->name());
74 |
75 | $gettersSetters .= $this->codeTemplateEngine->render('entity/interface/getterSetter', [
76 | 'name' => $camelizedColumnName,
77 | 'type' => $column->type(),
78 | ]
79 | );
80 |
81 | $constants .= sprintf(' const %s = \'%s\';', strtoupper($column->name()), $column->name());
82 |
83 | if ($counter !== $columnsCount) {
84 | $gettersSetters .= "\n\n";
85 | $constants .= "\n";
86 | }
87 |
88 | $counter++;
89 | }
90 |
91 | return new GeneratorResult(
92 | $this->codeTemplateEngine->render('entity/interface', [
93 | 'namespace' => sprintf('%s\Api\Data', $moduleNameEntity->asPartOfNamespace()),
94 | 'constants' => $constants,
95 | 'entityName' => $entityName,
96 | 'gettersSetters' => $gettersSetters,
97 |
98 | ]
99 | ),
100 | sprintf('%s/Api/Data/%sInterface.php', $moduleNameEntity->asPartOfPath(), $entityName),
101 | $fullEntityName
102 | );
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/Repository/RepositoryGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad\Repository;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class RepositoryGenerator
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Triad\Repository
23 | */
24 | class RepositoryGenerator extends AbstractGenerator
25 | {
26 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
27 | private $codeTemplateEngine;
28 |
29 | /**
30 | * RepositoryGenerator constructor.
31 | *
32 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
33 | */
34 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
35 | {
36 | $this->codeTemplateEngine = $codeTemplateEngine;
37 | }
38 |
39 | /**
40 | * @inheritdoc
41 | */
42 | protected function requiredArguments(): array
43 | {
44 | return [
45 | 'entityName',
46 | 'entityInterfaceName',
47 | 'resourceEntityName',
48 | 'entityCollectionName',
49 | 'resourceEntityName',
50 | 'repositoryInterfaceName',
51 | 'searchResultName'
52 | ];
53 | }
54 |
55 | /**
56 | * @inheritdoc
57 | * @throws \RuntimeException
58 | */
59 | protected function internalGenerate(
60 | ModuleNameEntity $moduleNameEntity,
61 | array $additionalArguments = []
62 | ): GeneratorResultInterface {
63 | $entityName = $additionalArguments['entityName'];
64 | $entityInterfaceName = $additionalArguments['entityInterfaceName'];
65 | $resourceEntityName = $additionalArguments['resourceEntityName'];
66 | $entityCollectionName = $additionalArguments['entityCollectionName'];
67 | $repositoryInterfaceName = $additionalArguments['repositoryInterfaceName'];
68 | $searchResultName = $additionalArguments['searchResultName'];
69 | $currentClassName = sprintf('\%s\Model\%sRepository', $moduleNameEntity->asPartOfNamespace(), $entityName);
70 | $lcFirstEntityName = lcfirst($entityName);
71 |
72 | return new GeneratorResult(
73 | $this->codeTemplateEngine->render('entity/repository', [
74 | 'namespace' => sprintf('%s\Model', $moduleNameEntity->asPartOfNamespace()),
75 | 'entityName' => $entityName,
76 | 'entityRepositoryInterface' => $repositoryInterfaceName,
77 | 'entityCollectionName' => $entityCollectionName,
78 | 'entityInterface' => $entityInterfaceName,
79 | 'entityResource' => $resourceEntityName,
80 | 'entityNameVar' => $lcFirstEntityName,
81 | 'searchResultName' => $searchResultName
82 | ]
83 | ),
84 | sprintf('%s/Model/%sRepository.php', $moduleNameEntity->asPartOfPath(), $entityName),
85 | $currentClassName
86 | );
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/Repository/RepositoryInterfaceGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad\Repository;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class RepositoryInterfacePart
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Triad
23 | */
24 | class RepositoryInterfaceGenerator extends AbstractGenerator
25 | {
26 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
27 | private $codeTemplateEngine;
28 |
29 | /**
30 | * RepositoryGenerator constructor.
31 | *
32 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
33 | */
34 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
35 | {
36 | $this->codeTemplateEngine = $codeTemplateEngine;
37 | }
38 |
39 | /**
40 | * @inheritdoc
41 | */
42 | protected function requiredArguments(): array
43 | {
44 | return ['entityName', 'entityInterfaceName', 'searchResultInterface'];
45 | }
46 |
47 | /**
48 | * @inheritdoc
49 | * @throws \RuntimeException
50 | */
51 | protected function internalGenerate(
52 | ModuleNameEntity $moduleNameEntity,
53 | array $additionalArguments = []
54 | ): GeneratorResultInterface {
55 | $entityName = $additionalArguments['entityName'];
56 | $entityInterfaceName = $additionalArguments['entityInterfaceName'];
57 | $searchResultInterface = $additionalArguments['searchResultInterface'];
58 |
59 | $currentClassName = sprintf('\%s\Api\%sRepositoryInterface',
60 | $moduleNameEntity->asPartOfNamespace(),
61 | $entityName
62 | );
63 |
64 | $lcFirstEntityName = lcfirst($entityName);
65 |
66 | return new GeneratorResult(
67 | $this->codeTemplateEngine->render('entity/repositoryInterface', [
68 | 'namespace' => sprintf('%s\Api', $moduleNameEntity->asPartOfNamespace()),
69 | 'entityName' => $entityName,
70 | 'entityInterface' => $entityInterfaceName,
71 | 'entityNameVar' => $lcFirstEntityName,
72 | 'searchResultInterface' => $searchResultInterface
73 | ]
74 | ),
75 | sprintf('%s/Api/%sRepositoryInterface.php', $moduleNameEntity->asPartOfPath(), $entityName),
76 | $currentClassName
77 | );
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/ResourceGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\Generator\NameUtil;
17 | use Krifollk\CodeGenerator\Model\GeneratorResult;
18 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
19 | use Krifollk\CodeGenerator\Model\TableDescriber\Result;
20 |
21 | /**
22 | * Class ResourcePart
23 | *
24 | * @package Krifollk\CodeGenerator\Model\Generator\Triad
25 | */
26 | class ResourceGenerator extends AbstractGenerator
27 | {
28 | const RESOURCE_MODEL_FILE_NAME_PATTERN = '%s/Model/ResourceModel/%s.php';
29 |
30 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
31 | private $codeTemplateEngine;
32 |
33 | /**
34 | * RepositoryGenerator constructor.
35 | *
36 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
37 | */
38 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
39 | {
40 | $this->codeTemplateEngine = $codeTemplateEngine;
41 | }
42 |
43 | /**
44 | * @inheritdoc
45 | */
46 | protected function requiredArguments(): array
47 | {
48 | return ['tableDescriberResult', 'entityName'];
49 | }
50 |
51 | /**
52 | * @inheritdoc
53 | * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
54 | * @throws \InvalidArgumentException
55 | * @throws \RuntimeException
56 | */
57 | protected function internalGenerate(
58 | ModuleNameEntity $moduleNameEntity,
59 | array $additionalArguments = []
60 | ): GeneratorResultInterface {
61 | $entityName = $additionalArguments['entityName'];
62 | /** @var Result $tableDescriberResult */
63 | $tableDescriberResult = $additionalArguments['tableDescriberResult'];
64 |
65 | $exposedMessagesContainer = [];
66 | $className = NameUtil::generateResourceName($moduleNameEntity, $entityName);
67 |
68 | return new GeneratorResult(
69 | $this->codeTemplateEngine->render('entity/resource', [
70 | 'namespace' => sprintf('%s\Model\ResourceModel', $moduleNameEntity->asPartOfNamespace()),
71 | 'tableName' => $tableDescriberResult->tableName(),
72 | 'primaryField' => $this->getPrimaryFieldName($tableDescriberResult, $exposedMessagesContainer),
73 | 'entityName' => $entityName
74 |
75 | ]
76 | ),
77 | sprintf(self::RESOURCE_MODEL_FILE_NAME_PATTERN, $moduleNameEntity->asPartOfPath(), $entityName),
78 | $className,
79 | $exposedMessagesContainer
80 | );
81 | }
82 |
83 | private function getPrimaryFieldName(Result $tableDescriberResult, array &$exposedMessagesContainer): string
84 | {
85 | $primaryFieldName = '';
86 |
87 | try {
88 | $primaryFieldName = $tableDescriberResult->primaryColumn()->name();
89 | } catch (\RuntimeException $e) {
90 | $exposedMessagesContainer[] = 'Primary column not found. Resource model will be generated with errors.';
91 | }
92 |
93 | return $primaryFieldName;
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/Model/Generator/Triad/SearchResultInterfaceGenerator.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\Generator\Triad;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 | use Krifollk\CodeGenerator\Model\Generator\AbstractGenerator;
16 | use Krifollk\CodeGenerator\Model\GeneratorResult;
17 | use Krifollk\CodeGenerator\Model\ModuleNameEntity;
18 |
19 | /**
20 | * Class SearchResultInterfaceGenerator
21 | *
22 | * @package Krifollk\CodeGenerator\Model\Generator\Triad
23 | */
24 | class SearchResultInterfaceGenerator extends AbstractGenerator
25 | {
26 | /** @var \Krifollk\CodeGenerator\Model\CodeTemplate\Engine */
27 | private $codeTemplateEngine;
28 |
29 | /**
30 | * RepositoryGenerator constructor.
31 | *
32 | * @param \Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine
33 | */
34 | public function __construct(\Krifollk\CodeGenerator\Model\CodeTemplate\Engine $codeTemplateEngine)
35 | {
36 | $this->codeTemplateEngine = $codeTemplateEngine;
37 | }
38 |
39 | /**
40 | * @inheritdoc
41 | */
42 | protected function requiredArguments(): array
43 | {
44 | return ['entityName', 'entityInterface'];
45 | }
46 |
47 | /**
48 | * @inheritdoc
49 | * @throws \RuntimeException
50 | */
51 | protected function internalGenerate(
52 | ModuleNameEntity $moduleNameEntity,
53 | array $additionalArguments = []
54 | ): GeneratorResultInterface {
55 | $entityName = $additionalArguments['entityName'];
56 | $entityInterface = $additionalArguments['entityInterface'];
57 | $primaryFieldName = $additionalArguments['primaryFieldName'];
58 |
59 | $className = sprintf(
60 | '\%s\Api\Data\%sSearchResultsInterface',
61 | $moduleNameEntity->asPartOfNamespace(),
62 | $entityName
63 | );
64 |
65 | return new GeneratorResult(
66 | $this->codeTemplateEngine->render('entity/searchResultInterface', [
67 | 'namespace' => sprintf('%s\Api\Data', $moduleNameEntity->asPartOfNamespace()),
68 | 'entityName' => $entityName,
69 | 'entityInterface' => $entityInterface,
70 | 'primaryFieldName' => $primaryFieldName
71 | ]
72 | ),
73 | sprintf('%s/Api/Data/%sSearchResultsInterface.php', $moduleNameEntity->asPartOfPath(), $entityName),
74 | $className
75 | );
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/Model/GeneratorResult.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 |
16 | /**
17 | * Class GeneratorResult
18 | *
19 | * @package Krifollk\CodeGenerator\Model
20 | */
21 | class GeneratorResult implements GeneratorResultInterface
22 | {
23 | /** @var string */
24 | private $content;
25 |
26 | /** @var string */
27 | private $destinationFile;
28 |
29 | /** @var string */
30 | private $entityName;
31 |
32 | /** @var array */
33 | private $exposedMessages;
34 |
35 | /**
36 | * GeneratorResult constructor.
37 | *
38 | * @param string $content
39 | * @param string $destinationFile
40 | * @param string $entityName
41 | * @param array $exposedMessages
42 | */
43 | public function __construct(
44 | string $content,
45 | string $destinationFile,
46 | string $entityName = '',
47 | array $exposedMessages = []
48 | ) {
49 | $this->content = $content;
50 | $this->destinationFile = $destinationFile;
51 | $this->entityName = $entityName;
52 | $this->exposedMessages = $exposedMessages;
53 | }
54 |
55 | public function getContent(): string
56 | {
57 | return $this->content;
58 | }
59 |
60 | public function getDestinationDir(): string
61 | {
62 | return dirname($this->getDestinationFile());
63 | }
64 |
65 | public function getDestinationFile(): string
66 | {
67 | return $this->destinationFile;
68 | }
69 |
70 | public function getEntityName(): string
71 | {
72 | return $this->entityName;
73 | }
74 |
75 | public function getExposedMessages(): array
76 | {
77 | return $this->exposedMessages;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/Model/GeneratorResult/Container.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\GeneratorResult;
13 |
14 | use Krifollk\CodeGenerator\Api\GeneratorResultInterface;
15 |
16 | /**
17 | * Class Container
18 | *
19 | * @package Krifollk\CodeGenerator\Model\GeneratorResult
20 | */
21 | class Container
22 | {
23 | /** @var GeneratorResultInterface[] */
24 | private $container = [];
25 |
26 | /**
27 | * Insert result to container
28 | *
29 | * @param string $name
30 | * @param GeneratorResultInterface $generatorResult
31 | *
32 | * @return void
33 | * @throws \InvalidArgumentException
34 | */
35 | public function insert(string $name, GeneratorResultInterface $generatorResult)
36 | {
37 | if (isset($this->container[$name])) {
38 | throw new \InvalidArgumentException(sprintf('{%s} result already exists.', $name));
39 | }
40 |
41 | $this->container[$name] = $generatorResult;
42 | }
43 |
44 | /**
45 | * Get result from container by name
46 | *
47 | * @param string $name
48 | *
49 | * @return GeneratorResultInterface
50 | * @throws \InvalidArgumentException
51 | */
52 | public function get(string $name): GeneratorResultInterface
53 | {
54 | if (!isset($this->container[$name])) {
55 | throw new \InvalidArgumentException(sprintf('{%s} result not found.', $name));
56 | }
57 |
58 | return $this->container[$name];
59 | }
60 |
61 | /**
62 | * Get all results
63 | *
64 | * @return GeneratorResultInterface[]
65 | */
66 | public function getAll(): array
67 | {
68 | return $this->container;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Model/MethodInjector.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model;
13 |
14 | /**
15 | * Class ModuleNameEntity
16 | *
17 | * @package Krifollk\CodeGenerator\Model
18 | */
19 | class ModuleNameEntity
20 | {
21 | /** @var string */
22 | private $moduleName;
23 |
24 | /**
25 | * ModuleNameEntity constructor.
26 | *
27 | * @param string $moduleName
28 | *
29 | * @throws \InvalidArgumentException
30 | */
31 | public function __construct(string $moduleName)
32 | {
33 | if (!$this->validate($moduleName)) {
34 | throw new \InvalidArgumentException(
35 | sprintf('{%s} Wrong module name. Ex: CompanyCode_ModuleName', $moduleName)
36 | );
37 | }
38 | $this->moduleName = $moduleName;
39 | }
40 |
41 | public function value(): string
42 | {
43 | return $this->moduleName;
44 | }
45 |
46 | public function asPartOfNamespace(): string
47 | {
48 | return str_replace('_', '\\', $this->moduleName);
49 | }
50 |
51 | public function asPartOfPath(): string
52 | {
53 | return str_replace('_', '/', $this->moduleName);
54 | }
55 |
56 | private function validate(string $moduleName): bool
57 | {
58 | return (bool)preg_match('/[A-Z]+[A-Za-z0-9]+_[A-Z]+[A-Z0-9a-z]+/', $moduleName);
59 | }
60 |
61 | public function __toString()
62 | {
63 | return $this->value();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Model/ModulesDirProvider.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model;
13 |
14 | use Krifollk\CodeGenerator\Api\ModulesDirProviderInterface;
15 |
16 | /**
17 | * Class ModulesDirProvider
18 | *
19 | * @package Krifollk\CodeGenerator\Model
20 | */
21 | class ModulesDirProvider implements ModulesDirProviderInterface
22 | {
23 | public function getModulesDir(): string
24 | {
25 | return BP . '/app/code/';
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Model/NodeBuilder.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model;
13 |
14 | /**
15 | * Class NodeBuilder
16 | *
17 | * @package Krifollk\CodeGenerator\Model
18 | */
19 | class NodeBuilder
20 | {
21 | /** @var \DOMDocument */
22 | private $domDocument;
23 |
24 | /** @var \SplStack */
25 | private $stack;
26 |
27 | /** @var \DOMElement */
28 | private $rootElement;
29 |
30 | /** @var \DOMElement */
31 | private $lastCreatedElement;
32 |
33 | /**
34 | * NodeBuilder constructor.
35 | *
36 | * @param string $name
37 | * @param array $attributes
38 | * @param \DOMDocument|null $document
39 | */
40 | public function __construct($name, array $attributes = [], \DOMDocument $document = null)
41 | {
42 | $this->stack = new \SplStack();
43 | if ($document === null) {
44 | $this->initnew($name, $attributes);
45 | return;
46 | }
47 |
48 | $this->domDocument = $document;
49 | $this->lastCreatedElement = $document->documentElement;
50 | $this->rootElement = $this->lastCreatedElement;
51 | $this->children();
52 | }
53 |
54 | /**
55 | * @param string $name
56 | * @param array $attributes
57 | * @return void
58 | */
59 | private function initnew($name, array $attributes)
60 | {
61 | $this->domDocument = new \DOMDocument('1.0', 'UTF-8');
62 | $this->elementNode($name, $attributes, '');
63 | $this->rootElement = $this->lastCreatedElement;
64 | $this->children();
65 | }
66 |
67 | /**
68 | * @param string $name
69 | * @param array $attributes
70 | *
71 | * @param string $value
72 | *
73 | * @return $this
74 | */
75 | public function elementNode($name, array $attributes = [], $value = '')
76 | {
77 | $element = $this->domDocument->createElement($name);
78 |
79 | foreach ($attributes as $attributeName => $attributeValue) {
80 | $element->setAttribute($attributeName, $attributeValue);
81 | }
82 |
83 | if ($value !== '') {
84 | $element->nodeValue = $value;
85 | }
86 |
87 | $this->lastCreatedElement = $element;
88 |
89 | if ($this->stack->isEmpty()) {
90 | return $this;
91 | }
92 |
93 | /** @var \DOMDocument $currentElement */
94 | $currentElement = $this->stack->top();
95 | $currentElement->appendChild($element);
96 |
97 | return $this;
98 | }
99 |
100 | /**
101 | * @return $this
102 | */
103 | public function children()
104 | {
105 | $this->stack->push($this->lastCreatedElement);
106 |
107 | return $this;
108 | }
109 |
110 | /**
111 | * @return $this
112 | */
113 | public function endNode()
114 | {
115 | $this->stack->pop();
116 |
117 | return $this;
118 | }
119 |
120 | /**
121 | * @param string $name
122 | * @param string $type
123 | * @param string $value
124 | * @param array $additionalAttributes
125 | *
126 | * @return $this
127 | */
128 | public function itemNode($name, $type, $value = '', array $additionalAttributes = [])
129 | {
130 | $baseAttributes = ['name' => $name, 'xsi:type' => $type];
131 | $attributes = array_merge($baseAttributes, $additionalAttributes);
132 | $this->elementNode('item', $attributes, $value);
133 |
134 | return $this;
135 | }
136 |
137 | /**
138 | * @param string $name
139 | * @param string $type
140 | * @param string $value
141 | *
142 | * @return $this
143 | */
144 | public function argumentNode($name, $type, $value = '')
145 | {
146 | $baseAttributes = ['name' => $name, 'xsi:type' => $type];
147 | $this->elementNode('argument', $baseAttributes, $value);
148 |
149 | return $this;
150 | }
151 |
152 | public function trySetPointerToElement(string $query): bool
153 | {
154 | $xpath = new \DOMXPath($this->domDocument);
155 | $result = $xpath->query($query);
156 |
157 | if ($result->length === 0) {
158 | return false;
159 | }
160 |
161 | $this->lastCreatedElement = $result->item(0);
162 | $this->children();
163 |
164 | return true;
165 | }
166 |
167 | public function isExistByPath(string $path): bool
168 | {
169 | $xpath = new \DOMXPath($this->domDocument);
170 | $result = $xpath->query($path);
171 |
172 | if ($result->length === 0) {
173 | return false;
174 | }
175 |
176 | return true;
177 | }
178 |
179 | public function getRootElement()
180 | {
181 | return $this->rootElement;
182 | }
183 |
184 | /**
185 | * @return string
186 | */
187 | public function toXml()
188 | {
189 | $this->domDocument->appendChild($this->rootElement);
190 | $this->domDocument->formatOutput = true;
191 |
192 | return $this->domDocument->saveXML();
193 | }
194 | }
195 |
--------------------------------------------------------------------------------
/Model/TableDescriber.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model;
13 |
14 | use Krifollk\CodeGenerator\Model\TableDescriber\Result;
15 |
16 | /**
17 | * Class TableDescriber
18 | *
19 | * @package Krifollk\CodeGenerator\Model
20 | */
21 | class TableDescriber
22 | {
23 | /** @var \Magento\Framework\App\ResourceConnection */
24 | private $connection;
25 |
26 | /**
27 | * DB -> PHP map of types
28 | *
29 | * @var array
30 | */
31 | public static $typeMap = [
32 | 'smallint' => 'int',
33 | 'tinyint' => 'int',
34 | 'mediumint' => 'int',
35 | 'bigint' => 'int',
36 | 'decimal' => 'float',
37 | ];
38 |
39 | /**
40 | * TableDescriber constructor.
41 | *
42 | * @param \Magento\Framework\App\ResourceConnection $connection
43 | */
44 | public function __construct(\Magento\Framework\App\ResourceConnection $connection)
45 | {
46 | $this->connection = $connection;
47 | }
48 |
49 | public function describe(string $tableName): Result
50 | {
51 | $columnsData = $this->connection->getConnection()->describeTable($tableName);
52 | $columnObjects = [];
53 | $primaryColumn = null;
54 | foreach ($columnsData as $columnName => $data) {
55 | $dbType = $this->extractDbType($data);
56 | $type = $this->getPhpType($dbType);
57 |
58 | $columnObject = new Result\Column($columnName, $type, $dbType, $this->isPrimary($data), !$data['NULLABLE']);
59 | $columnObjects[] = $columnObject;
60 |
61 | if ($columnObject->isPrimary()) {
62 | $primaryColumn = $columnObject;
63 | }
64 | }
65 |
66 | return new Result($tableName, $primaryColumn, ...$columnObjects);
67 | }
68 |
69 | private function isPrimary(array $data): bool
70 | {
71 | return $data['PRIMARY'] === true;
72 | }
73 |
74 | private function extractDbType(array $data): string
75 | {
76 | return explode('(', $data['DATA_TYPE'])[0];
77 | }
78 |
79 | private function getPhpType(string $dbType): string
80 | {
81 | return self::$typeMap[$dbType] ?? 'string';
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Model/TableDescriber/Result.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\TableDescriber;
13 |
14 | use Krifollk\CodeGenerator\Model\TableDescriber\Result\Column;
15 |
16 | /**
17 | * Class Result
18 | *
19 | * @package Krifollk\CodeGenerator\Model\TableDescriber
20 | */
21 | class Result
22 | {
23 | /** @var Column|null */
24 | private $primaryColumn;
25 |
26 | /** @var Column[] */
27 | private $columns;
28 |
29 | /** @var string */
30 | private $tableName;
31 |
32 | /**
33 | * Result constructor.
34 | *
35 | * @param string $tableName
36 | * @param Column $primaryColumn
37 | * @param Column[] $columns
38 | */
39 | public function __construct(string $tableName, Column $primaryColumn = null, Column ...$columns)
40 | {
41 | $this->primaryColumn = $primaryColumn;
42 | $this->columns = $columns;
43 | $this->tableName = $tableName;
44 | }
45 |
46 | /**
47 | * @throws \RuntimeException
48 | */
49 | public function primaryColumn(): Column
50 | {
51 | if ($this->primaryColumn === null) {
52 | throw new \RuntimeException('Primary column not found.');
53 | }
54 |
55 | return $this->primaryColumn;
56 | }
57 |
58 | /**
59 | * @return Column[]
60 | */
61 | public function columns(): array
62 | {
63 | return $this->columns;
64 | }
65 |
66 | public function tableName(): string
67 | {
68 | return $this->tableName;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Model/TableDescriber/Result/Column.php:
--------------------------------------------------------------------------------
1 |
8 | * For the full copyright and license information, please view the LICENSE
9 | * file that was distributed with this source code.
10 | */
11 |
12 | namespace Krifollk\CodeGenerator\Model\TableDescriber\Result;
13 |
14 | /**
15 | * Class Column
16 | *
17 | * @package Krifollk\CodeGenerator\Model\TableDescriber\Result
18 | */
19 | class Column
20 | {
21 | /** @var string */
22 | private $name;
23 |
24 | /** @var string */
25 | private $type;
26 |
27 | /** @var string */
28 | private $dbType;
29 |
30 | /** @var bool */
31 | private $isPrimary;
32 |
33 | /** @var bool */
34 | private $isRequired;
35 |
36 | /**
37 | * Column constructor.
38 | *
39 | * @param string $name
40 | * @param string $type
41 | * @param string $dbType
42 | * @param bool $isPrimary
43 | * @param bool $isRequired
44 | */
45 | public function __construct(string $name, string $type, string $dbType, bool $isPrimary, bool $isRequired)
46 | {
47 | $this->name = $name;
48 | $this->type = $type;
49 | $this->dbType = $dbType;
50 | $this->isPrimary = $isPrimary;
51 | $this->isRequired = $isRequired;
52 | }
53 |
54 | public function isPrimary(): bool
55 | {
56 | return $this->isPrimary;
57 | }
58 |
59 | public function name(): string
60 | {
61 | return $this->name;
62 | }
63 |
64 | public function type(): string
65 | {
66 | return $this->type;
67 | }
68 |
69 | public function dbType(): string
70 | {
71 | return $this->dbType;
72 | }
73 |
74 | public function isRequired(): bool
75 | {
76 | return $this->isRequired;
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Magento2 Code Generator
2 |
3 | This module provide possibility to generate code via command line tool.
4 |
5 | ## Requirements
6 |
7 | - Magento 2 (CE, EE) 2.1.0 and later
8 | - PHP >=7.0
9 |
10 | ## Installation
11 |
12 | Install the latest version with
13 |
14 | ```bash
15 | $ composer require krifollk/module-code-generator
16 | ```
17 |
18 | ## Usage
19 |
20 | Currently, module supports the next commands:
21 |
22 | Generating module skeleton.
23 | - 1-st param is module name.
24 | - 2-nd module version (not required, by default 0.1.0).
25 | ```bash
26 | $ php bin/magento generate:module Config_Editor 0.2.0
27 |
28 | Output:
29 | File /var/www/magento2/app/code/Config/Editor/registration.php was generated.
30 | File /var/www/magento2/app/code/Config/Editor/etc/module.xml was generated.
31 | File /var/www/magento2/app/code/Config/Editor/composer.json was generated.
32 | File /var/www/magento2/app/code/Config/Editor/Setup/InstallData.php was generated.
33 | File /var/www/magento2/app/code/Config/Editor/Setup/InstallSchema.php was generated.
34 | File /var/www/magento2/app/code/Config/Editor/Setup/Uninstall.php was generated.
35 | File /var/www/magento2/app/code/Config/Editor/Setup/UpgradeData.php was generated.
36 | File /var/www/magento2/app/code/Config/Editor/Setup/UpgradeSchema.php was generated.
37 | ```
38 |
39 | Generating 'Model Triad' by DB table.
40 | - 1-st param is module name.
41 | - 2-nd entity name.
42 | - 3-th table name.
43 |
44 | ```bash
45 | $ php bin/magento generate:model:triad Config_Editor Config core_config_data
46 |
47 | Output:
48 | File /var/www/magento2/app/code/Config/Editor/Api/Data/ConfigInterface.php was generated.
49 | File /var/www/magento2/app/code/Config/Editor/Model/ResourceModel/Config.php was generated.
50 | File /var/www/magento2/app/code/Config/Editor/Model/Config.php was generated.
51 | File /var/www/magento2/app/code/Config/Editor/Model/ResourceModel/Config/Collection.php was generated.
52 | File /var/www/magento2/app/code/Config/Editor/Api/Data/ConfigSearchResultsInterface.php was generated.
53 | File /var/www/magento2/app/code/Config/Editor/Api/ConfigRepositoryInterface.php was generated.
54 | File /var/www/magento2/app/code/Config/Editor/Model/ConfigRepository.php was generated.
55 | File /var/www/magento2/app/code/Config/Editor/etc/di.xml was generated.
56 | ```
57 |
58 | Generating 'Crud' by DB table.
59 | - 1-st param is module name.
60 | - 2-nd entity name.
61 | - 3-th table name.
62 |
63 | ```bash
64 | $ php bin/magento generate:crud Config_Editor Config core_config_data
65 |
66 | Output:
67 | File /var/www/magento2/app/code/Config/Editor/Api/Data/ConfigInterface.php was generated.
68 | File /var/www/magento2/app/code/Config/Editor/Model/ResourceModel/Config.php was generated.
69 | File /var/www/magento2/app/code/Config/Editor/Model/Config.php was generated.
70 | File /var/www/magento2/app/code/Config/Editor/Model/ResourceModel/Config/Collection.php was generated.
71 | File /var/www/magento2/app/code/Config/Editor/Api/Data/ConfigSearchResultsInterface.php was generated.
72 | File /var/www/magento2/app/code/Config/Editor/Api/ConfigRepositoryInterface.php was generated.
73 | File /var/www/magento2/app/code/Config/Editor/Model/ConfigRepository.php was generated.
74 | File /var/www/magento2/app/code/Config/Editor/etc/di.xml was generated.
75 | File /var/www/magento2/app/code/Config/Editor/Model/UiComponent/Listing/Column/ConfigActions.php was generated.
76 | File /var/www/magento2/app/code/Config/Editor/Model/Config/DataProvider.php was generated.
77 | File /var/www/magento2/app/code/Config/Editor/Model/ResourceModel/Config/Grid/Collection.php was generated.
78 | File /var/www/magento2/app/code/Config/Editor/view/adminhtml/ui_component/config_editor_config_form.xml was generated.
79 | File /var/www/magento2/app/code/Config/Editor/view/adminhtml/ui_component/config_editor_config_listing.xml was generated.
80 | File /var/www/magento2/app/code/Config/Editor/view/adminhtml/layout/config_editor_config_edit.xml was generated.
81 | File /var/www/magento2/app/code/Config/Editor/view/adminhtml/layout/config_editor_config_index.xml was generated.
82 | File /var/www/magento2/app/code/Config/Editor/view/adminhtml/layout/config_editor_config_new.xml was generated.
83 | File /var/www/magento2/app/code/Config/Editor/Controller/Adminhtml/Config/Index.php was generated.
84 | File /var/www/magento2/app/code/Config/Editor/etc/adminhtml/routes.xml was generated.
85 | File /var/www/magento2/app/code/Config/Editor/etc/di.xml was generated.
86 | File /var/www/magento2/app/code/Config/Editor/Controller/Adminhtml/Config/Edit.php was generated.
87 | File /var/www/magento2/app/code/Config/Editor/Controller/Adminhtml/Config/NewAction.php was generated.
88 | File /var/www/magento2/app/code/Config/Editor/Controller/Adminhtml/Config/Save.php was generated.
89 | File /var/www/magento2/app/code/Config/Editor/Controller/Adminhtml/Config/Delete.php was generated.
90 | File /var/www/magento2/app/code/Config/Editor/Controller/Adminhtml/Config/MassDelete.php was generated.
91 | File /var/www/magento2/app/code/Config/Editor/Controller/Adminhtml/Config/InlineEdit.php was generated.
92 | ```
93 |
94 | Generating 'Plugins' (Interactive mode)
95 | - 1-st param is module name.
96 |
97 | ```bash
98 | $ php bin/magento generate:plugin Config_Editor
99 |
100 | Output:
101 | Enter the name of the class for which you want to create plugin: \Magento\Cms\Controller\Index\Index
102 | Enter the name of the plugin class (\Module\Name\ part not required) Default: \Config\Editor\Plugin\Magento\Cms\Controller\Index\Index:
103 | +-----+-----------------+
104 | | #id | Allowed methods |
105 | +-----+-----------------+
106 | | 0 | execute |
107 | | 1 | dispatch |
108 | | 2 | getActionFlag |
109 | | 3 | getRequest |
110 | | 4 | getResponse |
111 | +-----+-----------------+
112 | Enter method ids and types of interception(a - after, b - before, ar - around)
113 | for which you want to create plugin using next format: id:b-ar-a, id:a-b: 0:a-b-ar
114 | +-------------+--------------------+
115 | | Method Name | Interception types |
116 | +-------------+--------------------+
117 | | execute | Before |
118 | | | Around |
119 | | | After |
120 | | | |
121 | +-------------+--------------------+
122 | Is everything alright ? (y\n - yes by default)
123 | File /var/www/magento2/app/code/Config/Editor/Plugin/Magento/Cms/Controller/Index/Index.php has been generated.
124 | File /var/www/magento2/app/code/Config/Editor/etc/di.xml has been generated.
125 | ```
126 |
127 | In additional, all commands supports --dir option where you can specify your custom module directory.
128 |
129 | Ex: --dir=modules/module-some-dir
130 |
131 | ## Submitting bugs and feature requests
132 |
133 | Bugs and feature request are tracked on [GitHub](https://github.com/Krifollk/magento-code-generator/issues)
134 |
135 | ## Author
136 |
137 | Rostyslav Tymoshenko
138 |
139 | ## License
140 |
141 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
142 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "krifollk/module-code-generator",
3 | "license": "MIT",
4 | "description": "Code generator for magento 2",
5 | "require": {
6 | "php": "~7.0"
7 | },
8 | "type": "magento2-module",
9 | "autoload": {
10 | "files": [
11 | "registration.php"
12 | ],
13 | "psr-4": {
14 | "Krifollk\\CodeGenerator\\": ""
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/etc/code_template/crud/controller/adminhtml/delete.pct:
--------------------------------------------------------------------------------
1 | entityRepository = $entityRepository;
29 | parent::__construct($context);
30 | }
31 |
32 | /**
33 | * @inheritdoc
34 | */
35 | public function execute()
36 | {
37 | /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
38 | $resultRedirect = $this->resultRedirectFactory->create();
39 | $id = $this->getRequest()->getParam('{{ requestIdFiledName }}');
40 | if ($id === null) {
41 | $this->messageManager->addErrorMessage(__('We can\'t find an entity to delete.'));
42 |
43 | return $resultRedirect->setPath('*/*/');
44 | }
45 | try {
46 | $this->entityRepository->deleteById($id);
47 | $this->messageManager->addSuccessMessage(__('Entity has been deleted.'));
48 |
49 | return $resultRedirect->setPath('*/*/');
50 | } catch (\Exception $e) {
51 | $this->messageManager->addErrorMessage($e->getMessage());
52 |
53 | return $resultRedirect->setPath('*/*/edit', ['{{ requestIdFiledName }}' => $id]);
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/etc/code_template/crud/controller/adminhtml/edit.pct:
--------------------------------------------------------------------------------
1 | entityRepository = $entityRepository;
31 | parent::__construct($context);
32 | }
33 |
34 | /**
35 | * @inheritdoc
36 | */
37 | public function execute()
38 | {
39 | $id = $this->getRequest()->getParam('{{ requestIdFiledName }}');
40 | if ($id === null) {
41 | return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
42 | }
43 | try {
44 | $this->entityRepository->getById($id);
45 | } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
46 | $this->messageManager->addErrorMessage($e->getMessage());
47 | $resultRedirect = $this->resultRedirectFactory->create();
48 |
49 | return $resultRedirect->setPath('*/*/');
50 | }
51 |
52 | return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/etc/code_template/crud/controller/adminhtml/index.pct:
--------------------------------------------------------------------------------
1 | resultFactory->create(ResultFactory::TYPE_PAGE);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/etc/code_template/crud/controller/adminhtml/inlineEdit.pct:
--------------------------------------------------------------------------------
1 | entityRepository = $entityRepository;
36 | $this->dataObjectHelper = $dataObjectHelper;
37 | parent::__construct($context);
38 | }
39 |
40 | /**
41 | * @inheritdoc
42 | */
43 | public function execute()
44 | {
45 | /** @var \Magento\Framework\Controller\Result\Json $resultJson */
46 | $resultJson = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON);
47 | $error = false;
48 | $messages = [];
49 |
50 | $items = $this->getRequest()->getParam('items', []);
51 | if (!(count($items) && $this->getRequest()->getParam('isAjax'))) {
52 | return $resultJson->setData([
53 | 'messages' => [__('Please correct the data sent.')],
54 | 'error' => true,
55 | ]);
56 | }
57 |
58 | foreach (array_keys($items) as $itemId) {
59 | try {
60 | $entity = $this->entityRepository->getById($itemId);
61 | $this->dataObjectHelper->populateWithArray(
62 | $entity,
63 | $items[$itemId],
64 | {{ entityInterface }}::class
65 | );
66 | $this->entityRepository->save($entity);
67 | } catch (\Magento\Framework\Exception\LocalizedException $e) {
68 | $messages[] = sprintf('[%s]: %s', $itemId, $e->getMessage());
69 | } catch (\Exception $e) {
70 | $messages[] = sprintf('[%s]: %s', $itemId, __('Something went wrong while saving the entity.'));
71 | $error = true;
72 | }
73 | }
74 |
75 | return $resultJson->setData([
76 | 'messages' => $messages,
77 | 'error' => $error
78 | ]);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/etc/code_template/crud/controller/adminhtml/massDelete.pct:
--------------------------------------------------------------------------------
1 | filter = $filter;
42 | $this->entityCollectionFactory = $entityCollectionFactory;
43 | $this->entityRepository = $entityRepository;
44 | parent::__construct($context);
45 | }
46 |
47 | /**
48 | * @inheritdoc
49 | */
50 | public function execute()
51 | {
52 | $collection = $this->filter->getCollection($this->entityCollectionFactory->create());
53 |
54 | foreach ($collection as $item) {
55 | $this->entityRepository->delete($item);
56 | }
57 |
58 | $this->messageManager->addSuccessMessage(
59 | __('A total of %1 record(s) have been deleted.', $collection->count())
60 | );
61 |
62 | /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
63 | $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
64 |
65 | return $resultRedirect->setPath('*/*/');
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/etc/code_template/crud/controller/adminhtml/new.pct:
--------------------------------------------------------------------------------
1 | resultFactory->create(ResultFactory::TYPE_FORWARD);
24 |
25 | return $resultForward->forward('edit');
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/etc/code_template/crud/controller/adminhtml/save.pct:
--------------------------------------------------------------------------------
1 | dataPersistor = $dataPersistor;
47 | $this->entityRepository = $entityRepository;
48 | $this->entityFactory = $entityFactory;
49 | $this->resultRedirectFactory = $context->getResultRedirectFactory();
50 | $this->dataObjectHelper = $dataObjectHelper;
51 | parent::__construct($context);
52 | }
53 |
54 | /**
55 | * @inheritdoc
56 | */
57 | public function execute()
58 | {
59 | /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
60 | $resultRedirect = $this->resultRedirectFactory->create();
61 | $data = $this->getRequest()->getPostValue();
62 |
63 | if (!$data) {
64 | return $resultRedirect->setPath('*/*/');
65 | }
66 |
67 | $id = $this->getRequest()->getParam('{{ idFieldName }}');
68 |
69 | try {
70 | if ($id === null) {
71 | $entity = $this->entityFactory->create();
72 | } else {
73 | $entity = $this->entityRepository->getById($id);
74 | }
75 |
76 | $this->dataObjectHelper->populateWithArray($entity, $data, {{ entityInterface }}::class);
77 | $this->entityRepository->save($entity);
78 | $this->messageManager->addSuccessMessage(__('You saved the entity.'));
79 | $this->dataPersistor->clear('{{ dataPersistorKey }}');
80 |
81 | if ($this->getRequest()->getParam('back')) {
82 | return $resultRedirect->setPath('*/*/edit', ['{{ idFieldName }}' => $entity->getId()]);
83 | }
84 |
85 | return $resultRedirect->setPath('*/*/');
86 |
87 | } catch (\Magento\Framework\Exception\LocalizedException $e) {
88 | $this->messageManager->addErrorMessage($e->getMessage());
89 | } catch (\Exception $e) {
90 | $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the entity.'));
91 | }
92 |
93 | $this->dataPersistor->set('{{ dataPersistorKey }}', $data);
94 |
95 | return $resultRedirect->setPath('*/*/edit', ['{{ idFieldName }}' => $this->getRequest()->getParam('{{ idFieldName }}')]);
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/etc/code_template/crud/grid/collection.pct:
--------------------------------------------------------------------------------
1 | collection = $collectionFactory->create();
39 | $this->dataPersistor = $dataPersistor;
40 | parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
41 | }
42 |
43 | /**
44 | * @inheritdoc
45 | */
46 | public function getData()
47 | {
48 | if ($this->loadedData) {
49 | return $this->loadedData;
50 | }
51 | $items = $this->collection->getItems();
52 |
53 | foreach ($items as $item) {
54 | $this->loadedData[$item->getId()] = $item->getData();
55 | }
56 |
57 | $data = $this->dataPersistor->get('{{ dataPersistorKey }}');
58 | if (!empty($data)) {
59 | $item = $this->collection->getNewEmptyItem();
60 | $item->setData($data);
61 | $this->loadedData[$item->getId()] = $item->getData();
62 | $this->dataPersistor->clear('{{ dataPersistorKey }}');
63 | }
64 |
65 | return $this->loadedData;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/etc/code_template/crud/uiComponent/listing/column/actions.pct:
--------------------------------------------------------------------------------
1 | urlBuilder = $urlBuilder;
32 | parent::__construct($context, $uiComponentFactory, $components, $data);
33 | }
34 |
35 | /**
36 | * @inheritdoc
37 | */
38 | public function prepareDataSource(array $dataSource)
39 | {
40 | if (!isset($dataSource['data']['items'])) {
41 | return $dataSource;
42 | }
43 |
44 | foreach ($dataSource['data']['items'] as &$item) {
45 | if (!isset($item['{{ idFieldName }}'])) {
46 | continue;
47 | }
48 | $item[$this->getData('name')] = [
49 | 'edit' => [
50 | 'href' => $this->urlBuilder->getUrl(
51 | '{{ editUrlPath }}',
52 | [
53 | 'id' => $item['{{ idFieldName }}']
54 | ]
55 | ),
56 | 'label' => __('Edit')
57 | ],
58 | 'delete' => [
59 | 'href' => $this->urlBuilder->getUrl(
60 | '{{ deleteUrlPath }}',
61 | [
62 | 'id' => $item['{{ idFieldName }}']
63 | ]
64 | ),
65 | 'label' => __('Delete'),
66 | 'confirm' => [
67 | 'title' => __('Delete "${ $.$data.title }"'),
68 | 'message' => __('Are you sure you wan\'t to delete a "${ $.$data.title }" record?')
69 | ]
70 | ]
71 | ];
72 | }
73 |
74 | return $dataSource;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/etc/code_template/entity/collection.pct:
--------------------------------------------------------------------------------
1 | _init({{ entity }}::class, {{ entityResource }}::class);
38 | $this->_setIdFieldName($this->getResource()->getIdFieldName());
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/etc/code_template/entity/interface.pct:
--------------------------------------------------------------------------------
1 | _init({{ resourceModel }}::class);
27 | }
28 |
29 | {{ gettersSetters }}
30 | }
31 |
--------------------------------------------------------------------------------
/etc/code_template/entity/model/getterSetter.pct:
--------------------------------------------------------------------------------
1 | /**
2 | * @inheritdoc
3 | */
4 | public function get{{ name }}()
5 | {
6 | return $this->_getData(self::{{ constField }});
7 | }
8 |
9 | /**
10 | * @inheritdoc
11 | */
12 | public function set{{ name }}($value)
13 | {
14 | $this->setData(self::{{ constField }}, $value);
15 |
16 | return $this;
17 | }
--------------------------------------------------------------------------------
/etc/code_template/entity/repository.pct:
--------------------------------------------------------------------------------
1 | resource = $resource;
44 | $this->entityFactory = ${{ entityNameVar }}Factory;
45 | $this->collectionFactory = $collectionFactory;
46 | $this->searchResultFactory = $searchResultFactory;
47 | }
48 |
49 | /**
50 | * @inheritdoc
51 | */
52 | public function save({{ entityInterface }} ${{ entityNameVar }})
53 | {
54 | try {
55 | $this->resource->save(${{ entityNameVar }});
56 | } catch (\Exception $exception) {
57 | throw new \Magento\Framework\Exception\CouldNotSaveException(__($exception->getMessage()));
58 | }
59 |
60 | return ${{ entityNameVar }};
61 | }
62 |
63 | /**
64 | * @inheritdoc
65 | */
66 | public function getById(${{ entityNameVar }}Id)
67 | {
68 | ${{ entityNameVar }} = $this->entityFactory->create();
69 | $this->resource->load(${{ entityNameVar }}, ${{ entityNameVar }}Id);
70 | if (!${{ entityNameVar }}->getId()) {
71 | throw new NoSuchEntityException(__('{{ entityName }} with id "%1" does not exist.', ${{ entityNameVar }}Id));
72 | }
73 |
74 | return ${{ entityNameVar }};
75 | }
76 |
77 | /**
78 | * @inheritdoc
79 | */
80 | public function findById(${{ entityNameVar }}Id)
81 | {
82 | ${{ entityNameVar }} = $this->entityFactory->create();
83 | $this->resource->load(${{ entityNameVar }}, ${{ entityNameVar }}Id);
84 |
85 | if (!${{ entityNameVar }}->getId()) {
86 | return null;
87 | }
88 |
89 | return ${{ entityNameVar }};
90 | }
91 |
92 | /**
93 | * @inheritdoc
94 | */
95 | public function getList(SearchCriteriaInterface $searchCriteria)
96 | {
97 | $searchResult = $this->searchResultFactory->create();
98 | $searchResult->setSearchCriteria($searchCriteria);
99 | $collection = $this->collectionFactory->create();
100 |
101 | foreach ($searchCriteria->getFilterGroups() as $filterGroup) {
102 | foreach ($filterGroup->getFilters() as $filter) {
103 | $condition = $filter->getConditionType() ?: 'eq';
104 | $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
105 | }
106 | }
107 |
108 | $sortOrders = $searchCriteria->getSortOrders();
109 | $searchResult->setTotalCount($collection->getSize());
110 | if ($sortOrders) {
111 | foreach ($sortOrders as $sortOrder) {
112 | $collection->addOrder(
113 | $sortOrder->getField(),
114 | ($sortOrder->getDirection() === SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
115 | );
116 | }
117 | }
118 | $collection->setCurPage($searchCriteria->getCurrentPage());
119 | $collection->setPageSize($searchCriteria->getPageSize());
120 |
121 | return $searchResult->setItems($collection->getItems());
122 | }
123 |
124 | /**
125 | * @inheritdoc
126 | */
127 | public function delete({{ entityInterface }} ${{ entityNameVar }})
128 | {
129 | try {
130 | $this->resource->delete(${{ entityNameVar }});
131 | } catch (\Exception $exception) {
132 | throw new CouldNotDeleteException(__($exception->getMessage()));
133 | }
134 |
135 | return true;
136 | }
137 |
138 | /**
139 | * @inheritdoc
140 | */
141 | public function deleteById(${{ entityNameVar }}Id)
142 | {
143 | return $this->delete($this->getById(${{ entityNameVar }}Id));
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/etc/code_template/entity/repositoryInterface.pct:
--------------------------------------------------------------------------------
1 | _init('{{ tableName }}', '{{ primaryField }}');
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/etc/code_template/entity/searchResultInterface.pct:
--------------------------------------------------------------------------------
1 | startSetup();
22 |
23 | $setup->endSetup();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/etc/code_template/module/installSchema.pct:
--------------------------------------------------------------------------------
1 | startSetup();
22 |
23 | $setup->endSetup();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/etc/code_template/module/uninstall.pct:
--------------------------------------------------------------------------------
1 | startSetup();
25 | foreach ($tables as $table) {
26 | $setup->getConnection()->dropTable($table);
27 | }
28 | $setup->endSetup();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/etc/code_template/module/upgradeData.pct:
--------------------------------------------------------------------------------
1 | startSetup();
22 |
23 | $setup->endSetup();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/etc/code_template/module/upgradeSchema.pct:
--------------------------------------------------------------------------------
1 | startSetup();
22 |
23 | $setup->endSetup();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/etc/code_template/plugin/after_method.pct:
--------------------------------------------------------------------------------
1 | public function after{{ methodName }}({{ subject }} $subject, $result{{ arguments }})
2 | {
3 | //TODO
4 | }
--------------------------------------------------------------------------------
/etc/code_template/plugin/around_method.pct:
--------------------------------------------------------------------------------
1 | public function around{{ methodName }}({{ subject }} $subject, callable $proceed{{ arguments }})
2 | {
3 | //TODO
4 | }
--------------------------------------------------------------------------------
/etc/code_template/plugin/before_method.pct:
--------------------------------------------------------------------------------
1 | public function before{{ methodName }}({{ subject }} $subject{{ arguments }})
2 | {
3 | //TODO
4 | }
--------------------------------------------------------------------------------
/etc/code_template/plugin/class.pct:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | - Krifollk\CodeGenerator\Console\Command\TriadGenerateCommand
11 | - Krifollk\CodeGenerator\Console\Command\GenerateModule
12 | - Krifollk\CodeGenerator\Console\Command\GenerateCrud
13 | - Krifollk\CodeGenerator\Console\Command\GeneratePlugin
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/etc/module.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/registration.php:
--------------------------------------------------------------------------------
1 |