Beispiel #1
0
	def add(self, event, scope=SCOPE_ALL, extra_params=None):
		split_event = event.split('_')

		observer = Phpclass(
			'\\'.join(['Observer', split_event[0], ''.join(upperfirst(item) for item in split_event[1:])]),
			implements=['\Magento\Framework\Event\ObserverInterface'])
		observer.add_method(Phpmethod(
			'execute',
			params=['\Magento\Framework\Event\Observer $observer']
		))

		self.add_class(observer)	

		config = Xmlnode('config', attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:framework:Event/etc/events.xsd"}, nodes=[
			Xmlnode('event', attributes={'name': event}, nodes=[
				Xmlnode('observer', attributes={
					'name': '{}_{}'.format(observer.class_namespace.replace('\\', '_').lower(), event),
					'instance':observer.class_namespace,
				})
			])
		])

		xml_path = ['etc']
		if scope == self.SCOPE_FRONTEND:
			xml_path.append('frontend')
		elif scope == self.SCOPE_ADMINHTML:
			xml_path.append('adminhtml')

		xml_path.append('events.xml')


		self.add_xml(os.path.join(*xml_path), config)
Beispiel #2
0
    def add(self, event, scope=SCOPE_ALL, extra_params=None):
        split_event = event.split('_')

        observer = Phpclass(
            '\\'.join([
                'Observer', split_event[0],
                ''.join(upperfirst(item) for item in split_event[1:])
            ]),
            implements=['\Magento\Framework\Event\ObserverInterface'])
        observer.add_method(
            Phpmethod(
                'execute',
                params=['\\Magento\\Framework\\Event\\Observer $observer'],
                body="//Your observer code",
                docstring=[
                    'Execute observer', '',
                    '@param \\Magento\\Framework\\Event\\Observer $observer',
                    '@return void'
                ]))

        self.add_class(observer)

        config = Xmlnode(
            'config',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:framework:Event/etc/events.xsd"
            },
            nodes=[
                Xmlnode('event',
                        attributes={'name': event},
                        nodes=[
                            Xmlnode('observer',
                                    attributes={
                                        'name':
                                        '{}_{}'.format(
                                            observer.class_namespace.replace(
                                                '\\', '_').lower(), event),
                                        'instance':
                                        observer.class_namespace,
                                    })
                        ])
            ])

        xml_path = ['etc']
        if scope == self.SCOPE_FRONTEND:
            xml_path.append('frontend')
        elif scope == self.SCOPE_ADMINHTML:
            xml_path.append('adminhtml')
        elif scope == self.SCOPE_WEBAPI:
            soap_xml_path = ['etc']
            xml_path.append('webapi_rest')
            soap_xml_path.append('webapi_soap')
            soap_xml_path.append('events.xml')
            self.add_xml(os.path.join(*soap_xml_path), config)

        xml_path.append('events.xml')
        self.add_xml(os.path.join(*xml_path), config)
Beispiel #3
0
	def add(self,action_name,short_description, extra_params=None):

		console = Phpclass(
			'Console\\Command\\'+action_name, 
			extends='Command',
			dependencies = [
			'Symfony\Component\Console\Command\Command',
			'Symfony\Component\Console\Input\InputArgument',
			'Symfony\Component\Console\Input\InputOption',
			'Symfony\Component\Console\Input\InputInterface',
			'Symfony\Component\Console\Output\OutputInterface'
			],
			attributes = ['const NAME_ARGUMENT = "name";','const NAME_OPTION = "option";']
		)

		console.add_method(
			Phpmethod(
			'execute',
			access='protected',
			params=['InputInterface $input','OutputInterface $output'],
			body='$name = $input->getArgument(self::NAME_ARGUMENT); $option = $input->getOption(self::NAME_OPTION);\n$output->writeln("Hello " . $name);'
			)
		)

		console.add_method(
			Phpmethod(
				'configure',
				access='protected',
				body='$this->setName("'+self.module_name.lower()+':'+action_name.lower()+'");\n$this->setDescription("'+short_description+'");\n$this->setDefinition([new InputArgument(self::NAME_ARGUMENT,InputArgument::OPTIONAL,"Name"),new InputOption(self::NAME_OPTION,"-a",InputOption::VALUE_NONE,"Option functionality")]);\nparent::configure();'
			)
		)

		self.add_class(console);

		config = Xmlnode('config', attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:framework:ObjectManager/etc/config.xsd"}, nodes=[
			Xmlnode('type', attributes={'name': 'Magento\Framework\Console\CommandList'}, nodes=[
				Xmlnode('arguments', nodes=[
					Xmlnode('argument', 
							attributes={
								'name':'commands',
								'xsi:type':'array',
							},
							nodes=[
								Xmlnode('item',
									attributes={
										'name':action_name,
										'xsi:type':'object'
									},
									node_text=console.class_namespace
								)
							])
				])
			])
		])

		self.add_xml('etc/di.xml', config)
Beispiel #4
0
    def add(self,
            classname,
            methodname,
            plugintype=TYPE_AFTER,
            sortorder=10,
            disabled=False,
            extra_params=None):
        # Add class
        plugin = Phpclass('Plugin\\{}'.format(classname))

        variable = '$result'
        if plugintype == self.TYPE_BEFORE:
            variable = '//$functionvariables'
        elif plugintype == self.TYPE_AROUND:
            variable = '\Closure $proceed'

        plugin.add_method(
            Phpmethod(plugintype + methodname[0].capitalize() + methodname[1:],
                      body="//Your plugin code",
                      params=['\\' + classname + ' $subject', variable]))

        # Add plug first will add the module namespace to PhpClass
        self.add_class(plugin)

        # Plugin XML
        config = Xmlnode(
            'config',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:framework:ObjectManager/etc/config.xsd"
            },
            nodes=[
                Xmlnode('type',
                        attributes={'name': classname},
                        nodes=[
                            Xmlnode('plugin',
                                    attributes={
                                        'name':
                                        plugin.class_namespace.replace(
                                            '\\', '_'),
                                        'type':
                                        plugin.class_namespace,
                                        'sortOrder':
                                        sortorder,
                                        'disabled':
                                        'true' if disabled else 'false'
                                    })
                        ])
            ])

        self.add_xml('etc/di.xml', config)
Beispiel #5
0
    def add(self, name='', description='', extra_params=None):
        if not name:
            name = self._module.name
        cache_id = '{}_cache_tag'.format(name.lower())

        # Add cache class
        cache_class = Phpclass(
            'Model\\Cache\\{}'.format(name),
            extends=
            '\\Magento\\Framework\\Cache\\Frontend\\Decorator\\TagScope',
            attributes=[
                "const TYPE_IDENTIFIER = '{}';".format(cache_id),
                "const CACHE_TAG = '{}';".format(cache_id.upper())
            ])

        cache_class.add_method(
            Phpmethod(
                '__construct',
                params=[
                    '\Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool'
                ],
                body=
                "parent::__construct($cacheFrontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG);",
                docstring=[
                    '@param \\Magento\\Framework\\App\\Cache\\Type\\FrontendPool $cacheFrontendPool'
                ]))

        self.add_class(cache_class)

        # Cache XML
        cache_xml = Xmlnode('config',
                            attributes={
                                'xsi:noNamespaceSchemaLocation':
                                "urn:magento:framework:Cache/etc/cache.xsd"
                            },
                            nodes=[
                                Xmlnode('type',
                                        attributes={
                                            'name': cache_id,
                                            'translate': 'label,description',
                                            'instance':
                                            cache_class.class_namespace
                                        },
                                        nodes=[
                                            Xmlnode('label', node_text=name),
                                            Xmlnode('description',
                                                    node_text=description)
                                        ])
                            ])

        self.add_xml('etc/cache.xml', cache_xml)
Beispiel #6
0
    def add(self, test_suite, test_name, extra_params=None):
        class_name = "\\Test\\Unit\\{}Test".format(test_suite)

        unittest_class = Phpclass(class_name,
                                  extends='\\PHPUnit_Framework_TestCase')

        # Adding class setup and teardown
        unittest_class.add_method(
            Phpmethod(
                'setUpBeforeClass',
                access='public static',
                body="//setup",
                docstring=['Is called once before running all test in class']))

        self.add_class(unittest_class)
Beispiel #7
0
	def add(self, cronjob_name, schedule='*/5 * * * *', extra_params=None):

		crontab_file = 'etc/crontab.xml'

		instance = "Magento\Sales\Cron\CleanExpiredQuotes"

		class_name_parts = []
		for cronjob_name_part in cronjob_name.split(' '):
			class_name_parts.append(cronjob_name_part.capitalize())

		class_name = ''.join(class_name_parts)

		method= "execute"

		crontab_class = Phpclass('Cron\\'+class_name)
		crontab_class.attributes.append('protected $logger;')
		crontab_class.add_method(Phpmethod(
            '__construct',
            params=[
                '\Psr\Log\LoggerInterface $logger',
            ],
            body="$this->logger = $logger;"
        ))
		crontab_class.add_method(Phpmethod('execute',body='$this->logger->addInfo("Cronjob '+cronjob_name+' is executed.");'))
	
		self.add_class(crontab_class)

		cronjob_name = (self.module_name + '_' + cronjob_name).lower().replace(' ','_')

		crontab_xml = Xmlnode('config',attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Cron:etc/crontab.xsd"},nodes=[
			Xmlnode('group',attributes={'id':'default'},nodes=[
				Xmlnode(
					'job',
					attributes={
						'name':cronjob_name,
						'instance': crontab_class.class_namespace,
						'method': method,
					}, 
					nodes=[
						Xmlnode('schedule',node_text=schedule)
					]
				)	
			])
		]);

		self.add_xml(crontab_file, crontab_xml)
Beispiel #8
0
    def add(self, cronjob_name, schedule='*/5 * * * *', extra_params=None):

        crontab_file = 'etc/crontab.xml'

        instance = "Magento\Sales\Cron\CleanExpiredQuotes"

        class_name_parts = []
        for cronjob_name_part in cronjob_name.split(' '):
            class_name_parts.append(cronjob_name_part.capitalize())

        class_name = ''.join(class_name_parts)

        method = "execute"

        crontab_class = Phpclass('Cron\\' + class_name)
        crontab_class.attributes.append('protected $logger;')
        crontab_class.add_method(
            Phpmethod('__construct',
                      params=[
                          '\Psr\Log\LoggerInterface $logger',
                      ],
                      body="$this->logger = $logger;"))
        crontab_class.add_method(
            Phpmethod('execute',
                      body='$this->logger->addInfo("Cronjob ' + cronjob_name +
                      ' is executed.");'))

        self.add_class(crontab_class)

        cronjob_name = (self.module_name + '_' + cronjob_name).lower().replace(
            ' ', '_')

        crontab_xml = Xmlnode(
            'config',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Cron:etc/crontab.xsd"
            },
            nodes=[
                Xmlnode('group',
                        attributes={'id': 'default'},
                        nodes=[
                            Xmlnode('job',
                                    attributes={
                                        'name': cronjob_name,
                                        'instance':
                                        crontab_class.class_namespace,
                                        'method': method,
                                    },
                                    nodes=[
                                        Xmlnode('schedule', node_text=schedule)
                                    ])
                        ])
            ])

        self.add_xml(crontab_file, crontab_xml)
Beispiel #9
0
    def add(self,attribute_label,frontend_input='text',required=False,scope=1,options=None,extra_params=None):
        extra_params = extra_params if extra_params else {}
        attribute_code = attribute_label.lower().replace(' ','_');
        value_type = self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input,'int');
        user_defined = 'true'
        options = options.split(',') if options else []
        options_php_array = '"'+'","'.join(x.strip() for x in options) + '"'
        options_php_array_string = "array('values' => array("+options_php_array+"))"
        methodName = 'install' + attribute_label + 'ProductAttribute'

        templatePath = os.path.join(os.path.dirname(__file__), '../templates/attributes/productattribute.tmpl')

        with open(templatePath, 'rb') as tmpl:
            template = tmpl.read().decode('utf-8')

        methodBody = template.format(
            attribute_code=attribute_code,
            attribute_label=attribute_label,
            value_type=value_type,
            frontend_input=frontend_input,
            user_defined = user_defined,
            scope = scope,
            required = required,
            options = options_php_array_string,
            searchable = extra_params.get('searchable','false'),
            filterable = extra_params.get('filterable','false'),
            visible_on_front = extra_params.get('visible_on_front','false'),
            comparable = extra_params.get('comparable','false'),
            used_in_product_listing = extra_params.get('used_in_product_listing','false'),
            unique = extra_params.get('unique','false'),
            default = extra_params.get('default','0'),
            is_visible_in_advanced_search = extra_params.get('is_visible_in_advanced_search','0')
        )

        install_data = Phpclass('Setup\\InstallData',implements=['InstallDataInterface'],dependencies=['Magento\\Framework\\Setup\\InstallDataInterface','Magento\\Framework\\Setup\\ModuleContextInterface','Magento\\Framework\\Setup\\ModuleDataSetupInterface','Magento\\Eav\\Setup\\EavSetup','Magento\\Eav\\Setup\\EavSetupFactory'])
        install_data.attributes.append('private $eavSetupFactory;')
        install_data.add_method(Phpmethod(
            '__construct',
            params=[
                'EavSetupFactory $eavSetupFactory',
            ],
            body="$this->eavSetupFactory = $eavSetupFactory;"
        )) 
        install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body="$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);"))
        install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body=methodBody))
    
        self.add_class(install_data)
Beispiel #10
0
	def add(self, cronjob_class, schedule='*/5 * * * *', extra_params=None):

		crontab_class = Phpclass('Cron\\{}'.format(upperfirst(cronjob_class)), attributes=[
			'protected $logger;'
		])

		crontab_class.add_method(Phpmethod(
            '__construct',
            params=[
                '\Psr\Log\LoggerInterface $logger',
            ],
            body="$this->logger = $logger;",
            docstring=[
            	'Constructor',
            	'',
            	'@param \\Psr\\Log\\LoggerInterface $logger',
            ]
        ))
		crontab_class.add_method(Phpmethod('execute',
			body='$this->logger->addInfo("Cronjob '+cronjob_class+' is executed.");',
			docstring=[
            	'Execute the cron',
            	'',
            	'@return void',
            ]
		))
	
		self.add_class(crontab_class)

		crontab_xml = Xmlnode('config',attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Cron:etc/crontab.xsd"},nodes=[
			Xmlnode('group',attributes={'id':'default'},nodes=[
				Xmlnode(
					'job',
					attributes={
						'name': "{}_{}".format(self.module_name, cronjob_class).lower(),
						'instance': crontab_class.class_namespace,
						'method': "execute",
					}, 
					nodes=[
						Xmlnode('schedule',node_text=schedule)
					]
				)	
			])
		]);

		self.add_xml('etc/crontab.xml', crontab_xml)
Beispiel #11
0
    def add(self,
            tab,
            section,
            group,
            field,
            field_type='text',
            new_tab=False,
            extra_params=None,
            source_model=False,
            source_model_options=False):
        resource_id = self.module_name + '::config_' + self.module_name.lower()
        extra_params = extra_params if extra_params else {}

        tab_code = tab.lower().replace(' ', '_')
        section_code = section.lower().replace(' ', '_')
        group_code = group.lower().replace(' ', '_')
        field_code = field.lower().replace(' ', '_')

        # customer source model
        if source_model == 'custom' and source_model_options and field_type == 'select' or field_type == 'multiselect':

            source_model_class = Phpclass(
                'Model\\Config\\Source\\' + field_code.capitalize(),
                implements=['\Magento\Framework\Option\ArrayInterface'])
            source_model_options = source_model_options.split(',')
            to_option_array = "[{}]".format(','.join(
                "['value' => '{0}', 'label' => __('{0}')]".format(o.strip())
                for o in source_model_options))
            to_array = "[{}]".format(','.join(
                "'{0}' => __('{0}')".format(o.strip())
                for o in source_model_options))

            source_model_class.add_method(
                Phpmethod('toOptionArray',
                          body="return {};".format(to_option_array)))
            source_model_class.add_method(
                Phpmethod('toArray', body="return {};".format(to_array)))

            self.add_class(source_model_class)

            source_model = source_model_class.class_namespace

        # system xml
        file = 'etc/adminhtml/system.xml'

        if new_tab:
            tabxml = Xmlnode(
                'tab',
                attributes={
                    'id': tab,
                    'translate': 'label',
                    'sortOrder': extra_params.get('tab_sortOrder', 999) or 999
                },
                nodes=[
                    Xmlnode('label',
                            node_text=extra_params.get('tab_label', tab)
                            or tab)
                ])
        else:
            tabxml = False

        if field_type == 'select' or field_type == 'multiselect':
            source_model_xml = Xmlnode('source_model', node_text=source_model)
        else:
            source_model_xml = False

        if extra_params.get('field_backend_model'):
            backend_model_xml = Xmlnode(
                'backend_model',
                node_text=extra_params.get('field_backend_model'))
        else:
            backend_model_xml = False

        config = Xmlnode(
            'config',
            attributes={
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Config:etc/system_file.xsd"
            },
            nodes=[
                Xmlnode(
                    'system',
                    nodes=[
                        tabxml,
                        Xmlnode(
                            'section',
                            attributes={
                                'id':
                                section,
                                'sortOrder':
                                extra_params.get('section_sortorder', 10)
                                or 10,
                                'showInWebsite':
                                1 if extra_params.get(
                                    'section_show_in_website', True) else 0,
                                'showInStore':
                                1 if extra_params.get('section_show_in_store',
                                                      True) else 0,
                                'showInDefault':
                                1 if extra_params.get(
                                    'section_show_in_default', True) else 0,
                                'translate':
                                'label'
                            },
                            match_attributes={'id'},
                            nodes=[
                                Xmlnode('label',
                                        node_text=extra_params.get(
                                            'section_label', section)
                                        or section),
                                Xmlnode('tab', node_text=tab),
                                Xmlnode('resource', node_text=resource_id),
                                Xmlnode(
                                    'group',
                                    attributes={
                                        'id':
                                        group,
                                        'sortOrder':
                                        extra_params.get(
                                            'group_sortorder', 10) or 10,
                                        'showInWebsite':
                                        1 if extra_params.get(
                                            'group_show_in_website', True) else
                                        0,
                                        'showInStore':
                                        1 if extra_params.get(
                                            'group_show_in_store',
                                            True) else 0,
                                        'showInDefault':
                                        1 if extra_params.get(
                                            'group_show_in_default',
                                            True) else 0,
                                        'translate':
                                        'label'
                                    },
                                    match_attributes={'id'
                                                      },
                                    nodes=[
                                        Xmlnode(
                                            'label',
                                            node_text=extra_params.get(
                                                'group_label', group)
                                            or group),
                                        Xmlnode(
                                            'field',
                                            attributes={
                                                'id':
                                                field,
                                                'type':
                                                field_type,
                                                'sortOrder':
                                                extra_params.get(
                                                    'field_sortorder', 10)
                                                or 10,
                                                'showInWebsite':
                                                1 if extra_params.get(
                                                    'field_show_in_website',
                                                    True) else 0,
                                                'showInStore':
                                                1 if extra_params.get(
                                                    'field_show_in_store',
                                                    True) else 0,
                                                'showInDefault':
                                                1 if extra_params.get(
                                                    'field_show_in_default',
                                                    True) else 0,
                                                'translate':
                                                'label'
                                            },
                                            match_attributes={'id'},
                                            nodes=[
                                                Xmlnode(
                                                    'label',
                                                    node_text=extra_params.get(
                                                        'field_label', field)
                                                    or field),
                                                Xmlnode(
                                                    'comment',
                                                    node_text=extra_params.get(
                                                        'field_comment')),
                                                source_model_xml,
                                                backend_model_xml
                                            ])
                                    ])
                            ])
                    ])
            ])

        self.add_xml(file, config)

        # acl xml
        aclfile = 'etc/acl.xml'

        acl = Xmlnode(
            'config',
            attributes={
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:framework:Acl/etc/acl.xsd"
            },
            nodes=[
                Xmlnode(
                    'acl',
                    nodes=[
                        Xmlnode(
                            'resources',
                            nodes=[
                                Xmlnode(
                                    'resource',
                                    attributes={
                                        'id': 'Magento_Backend::admin'
                                    },
                                    match_attributes={'id'},
                                    nodes=[
                                        Xmlnode(
                                            'resource',
                                            attributes={
                                                'id': 'Magento_Backend::stores'
                                            },
                                            nodes=[
                                                Xmlnode(
                                                    'resource',
                                                    attributes={
                                                        'id':
                                                        'Magento_Backend::stores_settings'
                                                    },
                                                    match_attributes={'id'},
                                                    nodes=[
                                                        Xmlnode(
                                                            'resource',
                                                            attributes={
                                                                'id':
                                                                'Magento_Config::config'
                                                            },
                                                            match_attributes={
                                                                'id'
                                                            },
                                                            nodes=[
                                                                Xmlnode(
                                                                    'resource',
                                                                    attributes={
                                                                        'id':
                                                                        resource_id,
                                                                        'title':
                                                                        section
                                                                    },
                                                                    match_attributes
                                                                    ={'id'})
                                                            ])
                                                    ])
                                            ])
                                    ])
                            ])
                    ])
            ])

        self.add_xml(aclfile, acl)

        # default config values xml
        config_file = 'etc/config.xml'

        default_config = Xmlnode(
            'config',
            attributes={
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Store:etc/config.xsd"
            },
            nodes=[
                Xmlnode('default',
                        nodes=[
                            Xmlnode(section,
                                    nodes=[
                                        Xmlnode(
                                            group,
                                            nodes=[
                                                Xmlnode(
                                                    field,
                                                    node_text=extra_params.get(
                                                        'field_default'))
                                            ])
                                    ])
                        ])
            ])

        self.add_xml(config_file, default_config)
Beispiel #12
0
    def add(self,
            frontname='',
            section='index',
            action='index',
            adminhtml=False,
            ajax=False,
            extra_params=None):
        if not frontname:
            frontname = self._module.name.lower()
        file = 'etc/{}/routes.xml'.format(
            'adminhtml' if adminhtml else 'frontend')

        # Create config router
        module = Xmlnode('module', attributes={'name': self.module_name})
        if adminhtml:
            module.attributes['before'] = 'Magento_Backend'

        config = Xmlnode('config',
                         attributes={
                             'xsi:noNamespaceSchemaLocation':
                             "urn:magento:framework:App/etc/routes.xsd"
                         },
                         nodes=[
                             Xmlnode('router',
                                     attributes={
                                         'id':
                                         'admin' if adminhtml else 'standard'
                                     },
                                     nodes=[
                                         Xmlnode('route',
                                                 attributes={
                                                     'id': frontname,
                                                     'frontName': frontname
                                                 },
                                                 nodes=[module])
                                     ])
                         ])
        self.add_xml(file, config)

        # Create controller
        controller_class = ['Controller']
        if adminhtml:
            controller_class.append('Adminhtml')
        controller_class.append(section)
        controller_class.append(action)

        controller_extend = '\Magento\Backend\App\Action' if adminhtml else '\Magento\Framework\App\Action\Action'
        controller = Phpclass('\\'.join(controller_class), controller_extend)
        controller.attributes.append('protected $resultPageFactory;')

        if ajax:
            controller.attributes.append('protected $jsonHelper;')

        # generate construct
        if ajax:
            controller.add_method(
                Phpmethod(
                    '__construct',
                    params=[
                        '\Magento\Framework\App\Action\Context $context',
                        '\Magento\Framework\View\Result\PageFactory $resultPageFactory',
                        '\Magento\Framework\Json\Helper\Data $jsonHelper',
                    ],
                    body="""$this->resultPageFactory = $resultPageFactory;
					$this->jsonHelper = $jsonHelper;
					parent::__construct($context);
				"""))
        else:
            controller.add_method(
                Phpmethod(
                    '__construct',
                    params=[
                        '\Magento\Framework\App\Action\Context $context',
                        '\Magento\Framework\View\Result\PageFactory $resultPageFactory'
                    ],
                    body="""$this->resultPageFactory = $resultPageFactory;
					parent::__construct($context);
				"""))

        # generate execute method
        if ajax:
            execute_body = """try {
			    return $this->jsonResponse('your response');
			} catch (\Magento\Framework\Exception\LocalizedException $e) {
			    return $this->jsonResponse($e->getMessage());
			} catch (\Exception $e) {
			    $this->logger->critical($e);
			    return $this->jsonResponse($e->getMessage());
			}
        	"""
        else:
            execute_body = 'return $this->resultPageFactory->create();'

        controller.add_method(Phpmethod('execute', body=execute_body))

        # generate jsonResponse method
        if ajax:
            controller.add_method(
                Phpmethod('jsonResponse',
                          params=["$response = ''"],
                          body="""return $this->getResponse()->representJson(
						$this->jsonHelper->jsonEncode($response)
					);"""))

        self.add_class(controller)

        if ajax:
            return
        else:
            # create block
            block_class = ['Block']
            if adminhtml:
                block_class.append('Adminhtml')
            block_class.append(section)
            block_class.append(action)

            block = Phpclass('\\'.join(block_class),
                             '\Magento\Framework\View\Element\Template')
            self.add_class(block)

            # Add layout xml
            layout_xml = Xmlnode(
                'page',
                attributes={
                    'layout':
                    "admin-1column" if adminhtml else "1column",
                    'xsi:noNamespaceSchemaLocation':
                    "urn:magento:framework:View/Layout/etc/page_configuration.xsd"
                },
                nodes=[
                    Xmlnode('body',
                            nodes=[
                                Xmlnode('referenceContainer',
                                        attributes={'name': 'content'},
                                        nodes=[
                                            Xmlnode(
                                                'block',
                                                attributes={
                                                    'name':
                                                    "{}.{}".format(
                                                        section, action),
                                                    'class':
                                                    block.class_namespace,
                                                    'template':
                                                    "{}::{}/{}.phtml".format(
                                                        self.module_name,
                                                        section, action)
                                                })
                                        ])
                            ])
                ])
            path = os.path.join(
                'view', 'adminhtml' if adminhtml else 'frontend', 'layout',
                "{}_{}_{}.xml".format(frontname, section, action))
            self.add_xml(path, layout_xml)

            # add template file
            path = os.path.join('view',
                                'adminhtml' if adminhtml else 'frontend',
                                'templates')
            self.add_static_file(
                path,
                StaticFile("{}/{}.phtml".format(section, action),
                           body="Hello {}/{}.phtml".format(section, action)))
Beispiel #13
0
    def add(self, method_name, extra_params=None):

        payment_code = method_name.lower().replace(' ', '_')
        payment_class_name = method_name

        payment_class = Phpclass(
            'Model\\Payment\\' + payment_class_name,
            extends='\Magento\Payment\Model\Method\AbstractMethod',
            attributes=[
                'protected $_code = "' + payment_code + '";',
                'protected $_isOffline = true;'
            ])

        payment_class.add_method(
            Phpmethod(
                'isAvailable',
                params=[
                    '\\Magento\\Quote\\Api\\Data\\CartInterface $quote = null'
                ],
                body="return parent::isAvailable($quote);"))

        self.add_class(payment_class)

        payment_file = 'etc/payment.xml'

        payment_xml = Xmlnode(
            'payment',
            attributes={
                'xmlns:xsi':
                "http://www.w3.org/2001/XMLSchema-instance",
                "xsi:noNamespaceSchemaLocation":
                "urn:magento:module:Magento_Payment:etc/payment.xsd"
            },
            nodes=[
                Xmlnode('groups',
                        nodes=[
                            Xmlnode(
                                'group',
                                attributes={'id': 'offline'},
                                nodes=[
                                    Xmlnode(
                                        'label',
                                        node_text='Offline Payment Methods')
                                ])
                        ]),
                Xmlnode('methods',
                        nodes=[
                            Xmlnode('method',
                                    attributes={'name': payment_code},
                                    nodes=[
                                        Xmlnode('allow_multiple_address',
                                                node_text='1'),
                                    ])
                        ])
            ])

        self.add_xml(payment_file, payment_xml)

        config_file = 'etc/config.xml'

        config = Xmlnode(
            'config',
            attributes={
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Store:etc/config.xsd"
            },
            nodes=[
                Xmlnode('default',
                        nodes=[
                            Xmlnode(
                                'payment',
                                nodes=[
                                    Xmlnode(
                                        payment_code,
                                        nodes=[
                                            Xmlnode('active', node_text='1'),
                                            Xmlnode('model',
                                                    node_text=payment_class.
                                                    class_namespace),
                                            Xmlnode('order_status',
                                                    node_text='pending'),
                                            Xmlnode('title',
                                                    node_text=method_name),
                                            Xmlnode('allowspecific',
                                                    node_text='0'),
                                            Xmlnode('group',
                                                    node_text='Offline'),
                                        ])
                                ])
                        ])
            ])

        self.add_xml(config_file, config)

        system_file = 'etc/adminhtml/system.xml'

        system = Xmlnode(
            'config',
            attributes={
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Config:etc/system_file.xsd"
            },
            nodes=[
                Xmlnode(
                    'system',
                    nodes=[
                        Xmlnode(
                            'section',
                            attributes={
                                'id': 'payment',
                                'sortOrder': 1000,
                                'showInWebsite': 1,
                                'showInStore': 1,
                                'showInDefault': 1,
                                'translate': 'label'
                            },
                            match_attributes={'id'},
                            nodes=[
                                Xmlnode(
                                    'group',
                                    attributes={
                                        'id': payment_code,
                                        'sortOrder': 10,
                                        'showInWebsite': 1,
                                        'showInStore': 1,
                                        'showInDefault': 1,
                                        'translate': 'label'
                                    },
                                    match_attributes={'id'},
                                    nodes=[
                                        Xmlnode('label',
                                                node_text=method_name),
                                        Xmlnode(
                                            'field',
                                            attributes={
                                                'id': 'active',
                                                'type': 'select',
                                                'sortOrder': 10,
                                                'showInWebsite': 1,
                                                'showInStore': 1,
                                                'showInDefault': 1,
                                                'translate': 'label'
                                            },
                                            match_attributes={'id'},
                                            nodes=[
                                                Xmlnode('label',
                                                        node_text='Enabled'),
                                                Xmlnode(
                                                    'source_model',
                                                    node_text=
                                                    'Magento\\Config\\Model\\Config\\Source\\Yesno'
                                                ),
                                            ]),
                                        Xmlnode('field',
                                                attributes={
                                                    'id': 'title',
                                                    'type': 'text',
                                                    'sortOrder': 20,
                                                    'showInWebsite': 1,
                                                    'showInStore': 1,
                                                    'showInDefault': 1,
                                                    'translate': 'label'
                                                },
                                                match_attributes={'id'},
                                                nodes=[
                                                    Xmlnode('label',
                                                            node_text='Title'),
                                                ]),
                                        Xmlnode(
                                            'field',
                                            attributes={
                                                'id': 'order_status',
                                                'type': 'select',
                                                'sortOrder': 30,
                                                'showInWebsite': 1,
                                                'showInStore': 1,
                                                'showInDefault': 1,
                                                'translate': 'label'
                                            },
                                            match_attributes={'id'
                                                              },
                                            nodes=[
                                                Xmlnode(
                                                    'label',
                                                    node_text='New Order Status'
                                                ),
                                                Xmlnode(
                                                    'source_model',
                                                    node_text=
                                                    'Magento\\Sales\\Model\\Config\\Source\\Order\\Status\\NewStatus'
                                                ),
                                            ]),
                                        Xmlnode(
                                            'field',
                                            attributes={
                                                'id': 'allowspecific',
                                                'type': 'allowspecific',
                                                'sortOrder': 40,
                                                'showInWebsite': 1,
                                                'showInStore': 1,
                                                'showInDefault': 1,
                                                'translate': 'label'
                                            },
                                            match_attributes={'id'
                                                              },
                                            nodes=[
                                                Xmlnode(
                                                    'label',
                                                    node_text=
                                                    'Payment from Applicable Countries'
                                                ),
                                                Xmlnode(
                                                    'source_model',
                                                    node_text=
                                                    'Magento\\Payment\\Model\Config\\Source\\Allspecificcountries'
                                                ),
                                            ]),
                                        Xmlnode(
                                            'field',
                                            attributes={
                                                'id': 'specificcountry',
                                                'type': 'multiselect',
                                                'sortOrder': 50,
                                                'showInWebsite': 1,
                                                'showInStore': 1,
                                                'showInDefault': 1,
                                                'translate': 'label'
                                            },
                                            match_attributes={'id'
                                                              },
                                            nodes=[
                                                Xmlnode(
                                                    'label',
                                                    node_text=
                                                    'Payment from Applicable Countries'
                                                ),
                                                Xmlnode(
                                                    'source_model',
                                                    node_text=
                                                    'Magento\\Directory\\Model\\Config\\Source\\Country'
                                                ),
                                                Xmlnode('can_be_empty',
                                                        node_text='1'),
                                            ]),
                                        Xmlnode(
                                            'field',
                                            attributes={
                                                'id': 'sort_order',
                                                'type': 'text',
                                                'sortOrder': 60,
                                                'showInWebsite': 1,
                                                'showInStore': 1,
                                                'showInDefault': 1,
                                                'translate': 'label'
                                            },
                                            match_attributes={'id'
                                                              },
                                            nodes=[
                                                Xmlnode(
                                                    'label',
                                                    node_text='Sort Order'),
                                            ]),
                                        Xmlnode(
                                            'field',
                                            attributes={
                                                'id': 'instructions',
                                                'type': 'textarea',
                                                'sortOrder': 70,
                                                'showInWebsite': 1,
                                                'showInStore': 1,
                                                'showInDefault': 1,
                                                'translate': 'label'
                                            },
                                            match_attributes={'id'
                                                              },
                                            nodes=[
                                                Xmlnode(
                                                    'label',
                                                    node_text='Instructions'),
                                            ]),
                                    ])
                            ])
                    ])
            ])

        self.add_xml(system_file, system)

        layout_file = 'view/frontend/layout/checkout_index_index.xml'

        layout_payment = Xmlnode(
            'item',
            attributes={
                'name': payment_code,
                'xsi:type': 'array'
            },
            nodes=[
                Xmlnode('item',
                        attributes={
                            'name': 'component',
                            'xsi:type': 'string'
                        },
                        node_text='{}/js/view/payment/{}'.format(
                            self.module_name, payment_code)),
                Xmlnode('item',
                        attributes={
                            'name': 'methods',
                            'xsi:type': 'array'
                        },
                        nodes=[
                            Xmlnode('item',
                                    attributes={
                                        'name': payment_code,
                                        'xsi:type': 'array'
                                    },
                                    nodes=[
                                        Xmlnode('item',
                                                attributes={
                                                    'name':
                                                    'isBillingAddressRequired',
                                                    'xsi:type': 'boolean'
                                                },
                                                node_text='true')
                                    ])
                        ])
            ])

        layout_item = Xmlnode(
            'item',
            attributes={
                'name': 'components',
                'xsi:type': 'array'
            },
            nodes=[
                Xmlnode(
                    'item',
                    attributes={
                        'name': 'checkout',
                        'xsi:type': 'array'
                    },
                    nodes=[
                        Xmlnode(
                            'item',
                            attributes={
                                'name': 'children',
                                'xsi:type': 'array'
                            },
                            nodes=[
                                Xmlnode(
                                    'item',
                                    attributes={
                                        'name': 'steps',
                                        'xsi:type': 'array'
                                    },
                                    nodes=[
                                        Xmlnode(
                                            'item',
                                            attributes={
                                                'name': 'children',
                                                'xsi:type': 'array'
                                            },
                                            nodes=[
                                                Xmlnode(
                                                    'item',
                                                    attributes={
                                                        'name': 'billing-step',
                                                        'xsi:type': 'array'
                                                    },
                                                    nodes=[
                                                        Xmlnode(
                                                            'item',
                                                            attributes={
                                                                'name':
                                                                'children',
                                                                'xsi:type':
                                                                'array'
                                                            },
                                                            nodes=[
                                                                Xmlnode(
                                                                    'item',
                                                                    attributes={
                                                                        'name':
                                                                        'payment',
                                                                        'xsi:type':
                                                                        'array'
                                                                    },
                                                                    nodes=[
                                                                        Xmlnode(
                                                                            'item',
                                                                            attributes
                                                                            ={
                                                                                'name':
                                                                                'children',
                                                                                'xsi:type':
                                                                                'array'
                                                                            },
                                                                            nodes
                                                                            =[
                                                                                Xmlnode(
                                                                                    'item',
                                                                                    attributes
                                                                                    ={
                                                                                        'name':
                                                                                        'renders',
                                                                                        'xsi:type':
                                                                                        'array'
                                                                                    },
                                                                                    nodes
                                                                                    =[
                                                                                        Xmlnode(
                                                                                            'item',
                                                                                            attributes
                                                                                            ={
                                                                                                'name':
                                                                                                'children',
                                                                                                'xsi:type':
                                                                                                'array'
                                                                                            },
                                                                                            nodes
                                                                                            =[
                                                                                                layout_payment
                                                                                            ]
                                                                                        )
                                                                                    ]
                                                                                )
                                                                            ])
                                                                    ])
                                                            ])
                                                    ])
                                            ])
                                    ])
                            ])
                    ])
            ])

        layout_base = Xmlnode(
            'page',
            attributes={
                'xmlns:xsi':
                "http://www.w3.org/2001/XMLSchema-instance",
                'layout':
                '1column',
                'xsi:noNamespaceSchemaLocation':
                'urn:magento:framework:View/Layout/etc/page_configuration.xsd'
            },
            nodes=[
                Xmlnode('body',
                        nodes=[
                            Xmlnode('referenceBlock',
                                    attributes={'name': 'checkout.root'},
                                    nodes=[
                                        Xmlnode('arguments',
                                                nodes=[
                                                    Xmlnode(
                                                        'argument',
                                                        attributes={
                                                            'name': 'jsLayout',
                                                            'xsi:type': 'array'
                                                        },
                                                        nodes=[layout_item])
                                                ])
                                    ])
                        ])
            ])

        self.add_xml(layout_file, layout_base)

        self.add_static_file(
            'view/frontend/web/template/payment',
            StaticFile(payment_code + '.html',
                       template_file='payment/payment.tmpl',
                       context_data={
                           'module_name': self.module_name,
                           'payment_code': payment_code
                       }))
        self.add_static_file(
            'view/frontend/web/js/view/payment',
            StaticFile(payment_code + '.js',
                       template_file='payment/payment-js.tmpl',
                       context_data={
                           'module_name': self.module_name,
                           'payment_code': payment_code
                       }))
        self.add_static_file(
            'view/frontend/web/js/view/payment/method-renderer',
            StaticFile(payment_code + '-method.js',
                       template_file='payment/payment-method-js.tmpl',
                       context_data={
                           'module_name': self.module_name,
                           'payment_code': payment_code
                       }))
	def add(self,attribute_label, frontend_input='text', scope=1, required=False, source_model=False, source_model_options=False, extra_params=None):
		extra_params = extra_params if extra_params else {}
		
		value_type = self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input,'int')
		value_type = value_type if value_type != 'date' else 'datetime'

		form_element = self.FRONTEND_FORM_ELEMENT.get(frontend_input,'input')

		user_defined = 'false'
		backend_model = ''

		attribute_code = extra_params.get('attribute_code', None)
		if not attribute_code:
			attribute_code = attribute_label.lower().replace(' ','_')[:30]
		if frontend_input == 'select' and not source_model:
			source_model = "Magento\Eav\Model\Entity\Attribute\Source\Boolean"
		elif frontend_input == 'multiselect':
			backend_model = "Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend"
			if not source_model:    
				source_model = "Magento\Catalog\Model\Category\Attribute\Source\Page"
		elif frontend_input == "image":
			source_model = ''
			backend_model = "Magento\Catalog\Model\Category\Attribute\Backend\Image"
		elif frontend_input != 'multiselect' and frontend_input != 'select':
			source_model = ''
			backend_model = ''

		# customer source model
		if source_model == 'custom' and source_model_options and frontend_input == 'select' or frontend_input == 'multiselect':
			source_model_class = Phpclass(
				'Model\\Category\\Attribute\\Source\\' + ''.join(n.capitalize() for n in attribute_code.split('_')),
				extends='\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource',
				attributes=[
					'protected $_optionsData;'
				]   
			)

			source_model_class.add_method(Phpmethod('__construct',
				params=['array $options'],
				body="$this->_optionsData = $options;",
				docstring=[
					'Constructor',
					'',
					'@param array $options',
				]
			))

			if frontend_input == 'select':
				to_option_array = "[\n        {}\n    ]".format(',\n        '.join(
					"['value' => '{1}', 'label' => __('{0}')]".format(value.strip(),index + 1) for index, value in enumerate(source_model_options.split(',')))
				)
			else:
				to_option_array = "[\n        {}\n    ]".format(',\n        '.join(
					"['value' => (string) '{0}', 'label' => __('{0}')]".format(value.strip()) for value in source_model_options.split(','))
				)
			

			source_model_class.add_method(Phpmethod('getAllOptions',
				body="""
				if ($this->_options === null) {{
				    $this->_options = {options};
				}}
				return $this->_options;
				""".format(options=to_option_array),
				docstring=[
					'getAllOptions',
					'',
					'@return array',
				]
			))
			self.add_class(source_model_class)

			source_model = source_model_class.class_namespace

		sort_order = extra_params.get('sort_order','333') if extra_params.get('sort_order','333') else '333'

		templatePath = os.path.join(os.path.dirname(__file__), '../templates/attributes/categoryattribute.tmpl')

		with open(templatePath, 'rb') as tmpl:
			template = tmpl.read().decode('utf-8')

		methodBody = template.format(
			attribute_code=attribute_code,
			attribute_label=attribute_label,
			value_type=value_type,
			frontend_input=frontend_input,
			user_defined = user_defined,
			scope = scope,
			required = str(required).lower(),
			default = 'null',
			sort_order = sort_order,
			source_model = source_model,
			backend_model = backend_model
		)

		install_data = Phpclass('Setup\\InstallData',
			implements=['InstallDataInterface'],
			dependencies=[
				'Magento\\Framework\\Setup\\InstallDataInterface',
				'Magento\\Framework\\Setup\\ModuleContextInterface',
				'Magento\\Framework\\Setup\\ModuleDataSetupInterface',
				'Magento\\Eav\\Setup\\EavSetup',
				'Magento\\Eav\\Setup\\EavSetupFactory'],
			attributes=[
				'private $eavSetupFactory;'
			])

		install_data.add_method(Phpmethod(
			'__construct',
			params=['EavSetupFactory $eavSetupFactory'],
			body="$this->eavSetupFactory = $eavSetupFactory;",
			docstring=[
				'Constructor',
				'',
				'@param \\Magento\\Eav\\Setup\\EavSetupFactory $eavSetupFactory'
			]
		)) 
		
		install_data.add_method(Phpmethod('install',
			params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],
			body="$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);",
			docstring=['{@inheritdoc}']))
		install_data.add_method(Phpmethod('install',
			params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],
			body=methodBody))
	
		self.add_class(install_data)

		category_form_file = 'view/adminhtml/ui_component/category_form.xml'

		if frontend_input=='select' or frontend_input == 'multiselect':
			options_xml = Xmlnode('item',attributes={'name':'options','xsi:type':'object'},node_text=source_model)
		else:
			options_xml = False

		if frontend_input == 'image' :
			image_xml = [
							Xmlnode('item',attributes={'name':'uploaderConfig','xsi:type':'array'},nodes=[Xmlnode('item',attributes={'name':'url','xsi:type':'url','path':'catalog/category_image/upload'})]),
							Xmlnode('item',attributes={'name':'elementTmpl','xsi:type':'string'},node_text='ui/form/element/uploader/uploader'),
							Xmlnode('item',attributes={'name':'previewTmpl','xsi:type':'string'},node_text='Magento_Catalog/image-preview')
						]
		
		else:
			image_xml = []    

		required_value = 'true' if required else 'false'
		required_xml = Xmlnode('item',attributes={'name':'required','xsi:type':'boolean'},node_text=required_value)
		required_entry_xml = Xmlnode('item',attributes={'name':'validation','xsi:type':'array'},nodes=[Xmlnode('item',attributes={'name':'required-entry','xsi:type':'boolean'},node_text=required_value)])

		item_xml = [
					required_xml,
					required_entry_xml,
					Xmlnode('item',attributes={'name':'sortOrder','xsi:type':'number',},node_text=sort_order),
					Xmlnode('item',attributes={'name':'dataType','xsi:type':'string'},node_text='string'),
					Xmlnode('item',attributes={'name':'formElement','xsi:type':'string'},node_text=form_element),
					Xmlnode('item',attributes={'name':'label','xsi:type':'string','translate':'true'},node_text=attribute_label)
				]

		item_xml.extend(image_xml)        

		category_form_xml = Xmlnode('form',attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"},nodes=[
			Xmlnode('fieldset',attributes={'name':'general'},nodes=[
				# Xmlnode('argument',attributes={'name':'data','xsi:type':'array'},nodes=[
				#     Xmlnode('item',attributes={'name':'config','xsi:type':'array'},nodes=[
				#         Xmlnode('item',attributes={'name':'label','xsi:type':'string','translate':'true'},node_text='test'),
				#         Xmlnode('item',attributes={'name':'collapsible','xsi:type':'boolean'},node_text='true'),
				#         Xmlnode('item',attributes={'name':'sortOrder','xsi:type':'number'},node_text='100'),
				#     ])
				# ]),
				Xmlnode('field',attributes={'name':attribute_code},nodes=[
					Xmlnode('argument',attributes={'name':'data','xsi:type':'array'},nodes=[
						options_xml,                  
						Xmlnode('item',attributes={'name':'config','xsi:type':'array'},nodes=item_xml)
					])
				])
			])
		])

		self.add_xml(category_form_file, category_form_xml)
Beispiel #15
0
	def add(self, frontname='', section='index', action='index', adminhtml=False, ajax=False, extra_params=None):
		if not frontname:
			frontname = self._module.name.lower()
		file = 'etc/{}/routes.xml'.format('adminhtml' if adminhtml else 'frontend')

		# Create config router
		module = Xmlnode('module', attributes={'name': self.module_name})
		if adminhtml:
			module.attributes['before'] = 'Magento_Backend'

		config = Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation':"urn:magento:framework:App/etc/routes.xsd"}, nodes=[
			Xmlnode('router', attributes={'id': 'admin' if adminhtml else 'standard'}, nodes=[
				Xmlnode('route', attributes={'id': frontname, 'frontName': frontname}, nodes=[
					module
				])
			])
		])
		self.add_xml(file, config)

		# Create controller
		controller_class = ['Controller']
		if adminhtml:
			controller_class.append('Adminhtml')
		controller_class.append(section)
		controller_class.append(action)

		controller_extend = '\Magento\Backend\App\Action' if  adminhtml else '\Magento\Framework\App\Action\Action' 
		controller = Phpclass('\\'.join(controller_class), controller_extend, attributes=[
			'protected $resultPageFactory;'
		])

		if ajax:
			controller.attributes.extend([
			'protected $jsonHelper;'
		])

		# generate construct
		context_class = '\Magento\\' + ('Backend' if adminhtml else 'Framework') +'\App\Action\Context'
		if ajax:
			controller.add_method(Phpmethod(
				'__construct',
				params=[
					context_class + ' $context',
					'\Magento\Framework\View\Result\PageFactory $resultPageFactory',
					'\Magento\Framework\Json\Helper\Data $jsonHelper',
				],
				body="""$this->resultPageFactory = $resultPageFactory;
					$this->jsonHelper = $jsonHelper;
					parent::__construct($context);
				""",
				docstring=[
					'Constructor',
					'',
					'@param ' + context_class + '  $context',
					'@param \\Magento\\Framework\\Json\\Helper\\Data $jsonHelper',
				]
			))	
		else: 
			controller.add_method(Phpmethod(
				'__construct',
				params=[
					context_class + ' $context',
					'\Magento\Framework\View\Result\PageFactory $resultPageFactory'
				],
				body="""$this->resultPageFactory = $resultPageFactory;
					parent::__construct($context);
				""",
				docstring=[
					'Constructor',
					'',
					'@param ' + context_class + '  $context',
					'@param \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory',
				]
			))

		# generate execute method
		if ajax:
			execute_body = """try {
			    return $this->jsonResponse('your response');
			} catch (\Magento\Framework\Exception\LocalizedException $e) {
			    return $this->jsonResponse($e->getMessage());
			} catch (\Exception $e) {
			    $this->logger->critical($e);
			    return $this->jsonResponse($e->getMessage());
			}
        	"""
		else:
			execute_body = 'return $this->resultPageFactory->create();'

		controller.add_method(Phpmethod(
			'execute',
			body=execute_body,
			docstring=[
				'Execute view action',
				'',
				'@return \Magento\Framework\Controller\ResultInterface',
			]
		))

		# generate jsonResponse method
		if ajax:
			controller.add_method(Phpmethod(
				'jsonResponse',
				params=["$response = ''"],
				body="""
				return $this->getResponse()->representJson(
				    $this->jsonHelper->jsonEncode($response)
				);""",
				docstring=[
					'Create json response',
					'',
					'@return \Magento\Framework\Controller\ResultInterface',
				]
				)
			)

		self.add_class(controller)

		if ajax: 
			return
		else:
			# create block
			block_class = ['Block']
			if adminhtml:
				block_class.append('Adminhtml')
			block_class.append(section)
			block_class.append(action)

			block = Phpclass('\\'.join(block_class), '\Magento\Framework\View\Element\Template')
			self.add_class(block)

			# Add layout xml
			layout_xml = Xmlnode('page', attributes={'layout':"admin-1column" if adminhtml else "1column", 'xsi:noNamespaceSchemaLocation':"urn:magento:framework:View/Layout/etc/page_configuration.xsd"}, nodes=[
				Xmlnode('body', nodes=[
					Xmlnode('referenceContainer', attributes={'name': 'content'}, nodes=[
						Xmlnode('block', attributes={
							'name': "{}.{}".format(section, action), 
							'class': block.class_namespace,
							'template': "{}::{}/{}.phtml".format(self.module_name, section, action)
						})
					])
				])
			])
			path = os.path.join('view', 'adminhtml' if adminhtml else 'frontend', 'layout', "{}_{}_{}.xml".format(frontname, section, action))
			self.add_xml(path, layout_xml)

			# add template file
			path = os.path.join('view', 'adminhtml' if adminhtml else 'frontend', 'templates')
			self.add_static_file(path, StaticFile("{}/{}.phtml".format(section, action),body="Hello {}/{}.phtml".format(section, action)))
Beispiel #16
0
    def add(self,
            classname,
            methodname,
            scope=SCOPE_FRONTEND,
            layout_handle=None,
            reference_type=REFERENCE_CONTAINER,
            reference_name='content',
            extra_params=None):
        # Add class
        block = Phpclass('Block\\{}'.format(classname))
        type = 'frontend'
        if scope == self.SCOPE_ADMINHTML:
            block = Phpclass('Block\\Adminhtml\\{}'.format(classname))
            type = 'adminhtml'

        function_name = methodname[0] + methodname[1:]
        block.add_method(
            Phpmethod(function_name,
                      body="""//Your block code
			return 'Hello World!;""",
                      params=[],
                      docstring=['@return string']))

        # Add plug first will add the module namespace to PhpClass
        self.add_class(block)

        block_template = '{}.phtml'.format(
            classname.replace('\\', '/').lower())
        if layout_handle:
            # Layout Block XML
            xml_path = os.path.join('view', type, 'layout')
            page = Xmlnode(
                'page',
                attributes={
                    'xmlns:xsi':
                    'http://www.w3.org/2001/XMLSchema-instance',
                    'xsi:noNamespaceSchemaLocation':
                    "urn:magento:framework:View/Layout/etc/page_configuration.xsd"
                },
                nodes=[
                    Xmlnode('body',
                            attributes={},
                            nodes=[
                                Xmlnode('referenceContainer' if reference_type
                                        == self.REFERENCE_CONTAINER else
                                        'referenceBlock',
                                        attributes={
                                            'name':
                                            reference_name
                                            if reference_name else 'content'
                                        },
                                        nodes=[
                                            Xmlnode('block',
                                                    attributes={
                                                        'class':
                                                        block.class_namespace,
                                                        'name':
                                                        classname.replace(
                                                            '\\', '.').lower(),
                                                        'as':
                                                        classname.replace(
                                                            '\\', '_').lower(),
                                                        'template':
                                                        '{}::{}'.format(
                                                            self.module_name,
                                                            block_template),
                                                    })
                                        ])
                            ])
                ])
            xml_path = '{}/{}.xml'.format(xml_path, layout_handle.lower())
            self.add_xml(xml_path, page)

        # add template file
        path = os.path.join('view', type, 'templates')
        self.add_static_file(
            path,
            StaticFile(block_template,
                       body="""<?php
/**
 * @var $block \{classname}
 */
?>
<div>
	<?= $block->{function_name}() ?>
	<?= __('Hello {module_name}::{block_template}') ?>
</div>""".format(classname=block.class_namespace,
                 function_name=function_name,
                 module_name=self.module_name,
                 block_template=block_template)))
Beispiel #17
0
    def add(self, test_suite, test_name, extra_params=None):
        class_name = "\\Test\\Unit\\{}Test".format(test_suite)

        unittest_class = Phpclass(class_name,
                                  extends='\\PHPUnit_Framework_TestCase')

        # Adding class setup and teardown
        unittest_class.add_method(
            Phpmethod(
                'setUpBeforeClass',
                access='static',
                body='# Is called once before running all test in class'))

        unittest_class.add_method(
            Phpmethod('tearDownAfterClass',
                      access='static',
                      body='# Is called once after running all test in class'))

        # Adding test setup and teardown
        unittest_class.add_method(
            Phpmethod('setUp',
                      access='protected',
                      body='# Is called before running a test'))

        unittest_class.add_method(
            Phpmethod('tearDown',
                      access='protected',
                      body='# Is called after running a test'))

        # Adding test
        unittest_class.add_method(
            Phpmethod(
                'test{}'.format(upperfirst(test_name)),
                access='public',
                body=
                "# The test itself, every test function must start with 'test'\n$this->assertTrue(false);"
            ))

        self.add_class(unittest_class)
Beispiel #18
0
    def add(self, config_name, node_name, field_name, extra_params=None):
        config_class_name = ''.join(
            utils.upperfirst(w) for w in config_name.split('_'))

        # Create XSD
        config_xsd = Xmlnode(
            'xs:schema',
            xsd=True,
            attributes={
                'attributeFormDefault': "unqualified",
                "elementFormDefault": "qualified",
                "xmlns:xs": "http://www.w3.org/2001/XMLSchema"
            },
            nodes=[
                Xmlnode('xs:element',
                        attributes={'name': 'config'},
                        nodes=[
                            Xmlnode(
                                'xs:complexType',
                                nodes=[
                                    Xmlnode(
                                        'xs:choice',
                                        attributes={'maxOccurs': 'unbounded'},
                                        nodes=[
                                            Xmlnode(
                                                'xs:element',
                                                attributes={
                                                    'name':
                                                    node_name,
                                                    'type':
                                                    '{}Type'.format(node_name),
                                                    'maxOccurs':
                                                    'unbounded',
                                                    'minOccurs':
                                                    '0'
                                                })
                                        ])
                                ])
                        ]),
                Xmlnode('xs:complexType',
                        attributes={'type': '{}Type'.format(node_name)},
                        nodes=[
                            Xmlnode('xs:sequence',
                                    nodes=[
                                        Xmlnode('xs:element',
                                                attributes={
                                                    'name': field_name,
                                                    'type': 'xs:string'
                                                })
                                    ])
                        ])
            ])
        self.add_xml('etc/{}.xsd'.format(config_name), config_xsd)

        # create merge XSD
        config_merged_xsd = Xmlnode(
            'xs:schema',
            attributes={'xmlns:xs': 'http://www.w3.org/2001/XMLSchema'},
            nodes=[
                Xmlnode('xs:include',
                        attributes={
                            'schemaLocation':
                            'urn:magento:module:{}:etc/{}.xsd'.format(
                                self.module_name, config_name)
                        })
            ])
        self.add_xml('etc/{}_merged.xsd'.format(config_name),
                     config_merged_xsd)

        # Create SchemaLocator
        schema_locator_class = Phpclass(
            'Config\\{}\\SchemaLocator'.format(config_class_name),
            implements=[
                '\\Magento\\Framework\\Config\\SchemaLocatorInterface'
            ],
            attributes=[
                'protected $_schema = null;',
                'protected $_perFileSchema = null;'
            ],
            dependencies=['Magento\\Framework\\Module\\Dir'])

        schema_locator_class.add_method(
            Phpmethod(
                '__construct',
                params=[
                    '\\Magento\\Framework\\Module\\Dir\\Reader $moduleReader'
                ],
                body="""
			$etcDir = $moduleReader->getModuleDir(Dir::MODULE_ETC_DIR, '{module_name}');
			$this->_schema = $etcDir . '/{config_name}_merged.xsd';
			$this->_perFileSchema = $etcDir . '/{config_name}.xsd';
			""".format(module_name=self.module_name, config_name=config_name),
                docstring=[
                    '@param \Magento\Framework\Module\Dir\Reader $moduleReader'
                ]))

        schema_locator_class.add_method(
            Phpmethod('getSchema',
                      body="return $this->_schema;",
                      docstring=[
                          'Get path to merged config schema', '',
                          '@return string|null'
                      ]))
        schema_locator_class.add_method(
            Phpmethod('getPerFileSchema',
                      body="return $this->_perFileSchema;",
                      docstring=[
                          'Get path to pre file validation schema', '',
                          '@return string|null'
                      ]))

        self.add_class(schema_locator_class)

        # Create Converter
        converter_class = Phpclass(
            'Config\\{}\\Converter'.format(config_class_name),
            implements=['\\Magento\\Framework\\Config\\ConverterInterface'])

        converter_class.add_method(
            Phpmethod('convert',
                      params=['$source'],
                      docstring=[
                          'Convert dom node tree to array',
                          '',
                          '@param \DOMDocument $source',
                          '@return array',
                      ],
                      body="""
			$output = [];
			$xpath = new \DOMXPath($source);
			$nodes = $xpath->evaluate('/config/{node_name}');

			/** @var $node \DOMNode */
			foreach ($nodes as $node) {{
			    $nodeId = $node->attributes->getNamedItem('id');

			    $data = [];
			    $data['id'] = $nodeId;
			    foreach ($node->childNodes as $childNode) {{
			        if ($childNode->nodeType != XML_ELEMENT_NODE) {{
			            continue;
			        }}

			        $data[$childNode->nodeName] = $childNode->nodeValue;
			    }}
			    $output['{node_name}'][$nodeId] = $data;
			}}

			return $output;
			""".format(node_name=node_name)))

        self.add_class(converter_class)

        # Create Reader
        reader_class = Phpclass(
            'Config\\{}\\Reader'.format(config_class_name),
            extends='\\Magento\\Framework\\Config\\Reader\\Filesystem',
            attributes=[
                "protected $_idAttributes = [\n        '/config/{}' => 'id',\n    ];"
                .format(node_name)
            ])

        reader_class.add_method(
            Phpmethod(
                '__construct',
                params=[
                    '\\Magento\\Framework\\Config\\FileResolverInterface $fileResolver',
                    'Converter $converter',
                    'SchemaLocator $schemaLocator',
                    '\\Magento\\Framework\\Config\\ValidationStateInterface $validationState',
                    "$fileName = '{}.xml'".format(config_name),
                    '$idAttributes = []',
                    "$domDocumentClass = 'Magento\\Framework\\Config\\Dom'",
                    "$defaultScope = 'global'",
                ],
                body="""
			parent::__construct(
			    $fileResolver,
			    $converter,
			    $schemaLocator,
			    $validationState,
			    $fileName,
			    $idAttributes,
			    $domDocumentClass,
			    $defaultScope
			);
			"""))

        self.add_class(reader_class)
Beispiel #19
0
	def add(self,from_version='1.0.0', extra_params=None):

		install_schema = Phpclass('Setup\\InstallSchema',implements=['InstallSchemaInterface'],dependencies=[
			'Magento\\Framework\\Setup\\InstallSchemaInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\SchemaSetupInterface'])
		install_schema.add_method(Phpmethod('install',params=['SchemaSetupInterface $setup','ModuleContextInterface $context'],
			body='$installer = $setup;\n$installer->startSetup();',
			body_return='$setup->endSetup();'))
	
		self.add_class(install_schema)

		install_data = Phpclass('Setup\\InstallData',implements=['InstallDataInterface'],dependencies=[
			'Magento\\Framework\\Setup\\InstallDataInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\ModuleDataSetupInterface'])
		install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context']))
	
		self.add_class(install_data)

		update_schema = Phpclass('Setup\\UpgradeSchema',implements=['UpgradeSchemaInterface'],dependencies=[
			'Magento\\Framework\\Setup\\UpgradeSchemaInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\SchemaSetupInterface'])
		update_schema.add_method(Phpmethod('upgrade',params=['SchemaSetupInterface $setup','ModuleContextInterface $context'],
			body='$setup->startSetup();\nif(version_compare($context->getVersion(), "'+from_version+'", "<")){\n//Your upgrade script\n}\n$setup->endSetup();\n'))
	
		self.add_class(update_schema)

		update_data = Phpclass('Setup\\UpgradeData',implements=['UpgradeDataInterface'],dependencies=[
			'Magento\\Framework\\Setup\\UpgradeDataInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\ModuleDataSetupInterface'])
		update_data.add_method(Phpmethod('upgrade',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],
			body='$setup->startSetup();\nif(version_compare($context->getVersion(), "'+from_version+'", "<")){\n//Your upgrade script\n}\n$setup->endSetup();\n'))
		
		self.add_class(update_data)		
Beispiel #20
0
    def add(self, api_name, api_method='GET', extra_params=None):

        methodname = api_name
        url = '/V1/' + self._module.package.lower(
        ) + '-' + self._module.name.lower() + '/' + api_name.lower()
        resource = 'anonymous'
        description = api_method + ' for ' + api_name + ' api'

        management_interface = InterfaceClass('Api\\' + methodname +
                                              'ManagementInterface')
        management_interface.add_method(
            InterfaceMethod(api_method.lower() + upperfirst(api_name),
                            params=['$param'],
                            docstring=[
                                description, '@param string $param',
                                '@return string'
                            ]))

        self.add_class(management_interface)
        api_classname = management_interface.class_namespace

        model = Phpclass('\\'.join(['Model', methodname + 'Management']))
        model.add_method(
            Phpmethod(api_method.lower() + upperfirst(api_name),
                      params=['$param'],
                      docstring=['{@inheritdoc}'],
                      body="return 'hello api " + api_method +
                      " return the $param ' . $param;"))

        self.add_class(model)
        model_classname = model.class_namespace

        di_xml = Xmlnode(
            'config',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:framework:ObjectManager/etc/config.xsd"
            },
            nodes=[
                Xmlnode('preference',
                        attributes={
                            'for': api_classname,
                            'type': model_classname
                        })
            ])

        self.add_xml('etc/di.xml', di_xml)

        webapi_xml = Xmlnode(
            'routes',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Webapi:etc/webapi.xsd"
            },
            nodes=[
                Xmlnode('route',
                        attributes={
                            'url': url,
                            'method': api_method
                        },
                        match_attributes={'url', 'method'},
                        nodes=[
                            Xmlnode('service',
                                    attributes={
                                        'class':
                                        api_classname,
                                        'method':
                                        api_method.lower() +
                                        upperfirst(api_name)
                                    }),
                            Xmlnode('resources',
                                    nodes=[
                                        Xmlnode('resource',
                                                attributes={'ref': resource})
                                    ])
                        ])
            ])

        self.add_xml('etc/webapi.xml', webapi_xml)
Beispiel #21
0
    def add(self,
            attribute_label,
            frontend_input='text',
            scope=1,
            required=False,
            source_model=False,
            source_model_options=False,
            extra_params=None):
        extra_params = extra_params if extra_params else {}

        value_type = self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input, 'int')
        value_type = value_type if value_type != 'date' else 'datetime'

        form_element = self.FRONTEND_FORM_ELEMENT.get(frontend_input, 'input')

        user_defined = 'false'
        backend_model = ''

        attribute_code = extra_params.get('attribute_code', None)
        if not attribute_code:
            attribute_code = attribute_label.lower().replace(' ', '_')[:30]
        if frontend_input == 'select' and not source_model:
            source_model = "Magento\Eav\Model\Entity\Attribute\Source\Boolean"
        elif frontend_input == 'multiselect':
            backend_model = "Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend"
            if not source_model:
                source_model = "Magento\Catalog\Model\Category\Attribute\Source\Page"
        elif frontend_input == "image":
            source_model = ''
            backend_model = "Magento\Catalog\Model\Category\Attribute\Backend\Image"
        elif frontend_input != 'multiselect' and frontend_input != 'select':
            source_model = ''
            backend_model = ''

        # customer source model
        if source_model == 'custom' and source_model_options and frontend_input == 'select' or frontend_input == 'multiselect':
            source_model_class = Phpclass(
                'Model\\Category\\Attribute\\Source\\' +
                ''.join(n.capitalize() for n in attribute_code.split('_')),
                extends=
                '\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource',
                attributes=['protected $_optionsData;'])

            source_model_class.add_method(
                Phpmethod('__construct',
                          params=['array $options'],
                          body="$this->_optionsData = $options;",
                          docstring=[
                              'Constructor',
                              '',
                              '@param array $options',
                          ]))

            if frontend_input == 'select':
                to_option_array = "[\n        {}\n    ]".format(
                    ',\n        '.join(
                        "['value' => '{1}', 'label' => __('{0}')]".format(
                            value.strip(), index + 1)
                        for index, value in enumerate(
                            source_model_options.split(','))))
            else:
                to_option_array = "[\n        {}\n    ]".format(
                    ',\n        '.join(
                        "['value' => (string) '{0}', 'label' => __('{0}')]".
                        format(value.strip())
                        for value in source_model_options.split(',')))

            source_model_class.add_method(
                Phpmethod('getAllOptions',
                          body="""
				if ($this->_options === null) {{
				    $this->_options = {options};
				}}
				return $this->_options;
				""".format(options=to_option_array),
                          docstring=[
                              'getAllOptions',
                              '',
                              '@return array',
                          ]))
            self.add_class(source_model_class)

            source_model = source_model_class.class_namespace

        sort_order = extra_params.get('sort_order', '333') if extra_params.get(
            'sort_order', '333') else '333'

        templatePath = os.path.join(
            os.path.dirname(__file__),
            '../templates/attributes/categoryattribute.tmpl')

        with open(templatePath, 'rb') as tmpl:
            template = tmpl.read().decode('utf-8')

        methodBody = template.format(attribute_code=attribute_code,
                                     attribute_label=attribute_label,
                                     value_type=value_type,
                                     frontend_input=frontend_input,
                                     user_defined=user_defined,
                                     scope=scope,
                                     required=str(required).lower(),
                                     default='null',
                                     sort_order=sort_order,
                                     source_model=source_model,
                                     backend_model=backend_model)

        install_data = Phpclass(
            'Setup\\InstallData',
            implements=['InstallDataInterface'],
            dependencies=[
                'Magento\\Framework\\Setup\\InstallDataInterface',
                'Magento\\Framework\\Setup\\ModuleContextInterface',
                'Magento\\Framework\\Setup\\ModuleDataSetupInterface',
                'Magento\\Eav\\Setup\\EavSetup',
                'Magento\\Eav\\Setup\\EavSetupFactory'
            ],
            attributes=['private $eavSetupFactory;'])

        install_data.add_method(
            Phpmethod(
                '__construct',
                params=['EavSetupFactory $eavSetupFactory'],
                body="$this->eavSetupFactory = $eavSetupFactory;",
                docstring=[
                    'Constructor', '',
                    '@param \\Magento\\Eav\\Setup\\EavSetupFactory $eavSetupFactory'
                ]))

        install_data.add_method(
            Phpmethod(
                'install',
                params=[
                    'ModuleDataSetupInterface $setup',
                    'ModuleContextInterface $context'
                ],
                body=
                "$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);",
                docstring=['{@inheritdoc}']))
        install_data.add_method(
            Phpmethod('install',
                      params=[
                          'ModuleDataSetupInterface $setup',
                          'ModuleContextInterface $context'
                      ],
                      body=methodBody))

        self.add_class(install_data)

        category_form_file = 'view/adminhtml/ui_component/category_form.xml'

        if frontend_input == 'select' or frontend_input == 'multiselect':
            options_xml = Xmlnode('item',
                                  attributes={
                                      'name': 'options',
                                      'xsi:type': 'object'
                                  },
                                  node_text=source_model)
        else:
            options_xml = False

        if frontend_input == 'image':
            image_xml = [
                Xmlnode('item',
                        attributes={
                            'name': 'uploaderConfig',
                            'xsi:type': 'array'
                        },
                        nodes=[
                            Xmlnode('item',
                                    attributes={
                                        'name': 'url',
                                        'xsi:type': 'url',
                                        'path': 'catalog/category_image/upload'
                                    })
                        ]),
                Xmlnode('item',
                        attributes={
                            'name': 'elementTmpl',
                            'xsi:type': 'string'
                        },
                        node_text='ui/form/element/uploader/uploader'),
                Xmlnode('item',
                        attributes={
                            'name': 'previewTmpl',
                            'xsi:type': 'string'
                        },
                        node_text='Magento_Catalog/image-preview')
            ]

        else:
            image_xml = []

        required_value = 'true' if required else 'false'
        required_xml = Xmlnode('item',
                               attributes={
                                   'name': 'required',
                                   'xsi:type': 'boolean'
                               },
                               node_text=required_value)
        required_entry_xml = Xmlnode('item',
                                     attributes={
                                         'name': 'validation',
                                         'xsi:type': 'array'
                                     },
                                     nodes=[
                                         Xmlnode('item',
                                                 attributes={
                                                     'name': 'required-entry',
                                                     'xsi:type': 'boolean'
                                                 },
                                                 node_text=required_value)
                                     ])

        item_xml = [
            required_xml, required_entry_xml,
            Xmlnode('item',
                    attributes={
                        'name': 'sortOrder',
                        'xsi:type': 'number',
                    },
                    node_text=sort_order),
            Xmlnode('item',
                    attributes={
                        'name': 'dataType',
                        'xsi:type': 'string'
                    },
                    node_text='string'),
            Xmlnode('item',
                    attributes={
                        'name': 'formElement',
                        'xsi:type': 'string'
                    },
                    node_text=form_element),
            Xmlnode('item',
                    attributes={
                        'name': 'label',
                        'xsi:type': 'string',
                        'translate': 'true'
                    },
                    node_text=attribute_label)
        ]

        item_xml.extend(image_xml)

        category_form_xml = Xmlnode(
            'form',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"
            },
            nodes=[
                Xmlnode(
                    'fieldset',
                    attributes={'name': 'general'},
                    nodes=[
                        # Xmlnode('argument',attributes={'name':'data','xsi:type':'array'},nodes=[
                        #     Xmlnode('item',attributes={'name':'config','xsi:type':'array'},nodes=[
                        #         Xmlnode('item',attributes={'name':'label','xsi:type':'string','translate':'true'},node_text='test'),
                        #         Xmlnode('item',attributes={'name':'collapsible','xsi:type':'boolean'},node_text='true'),
                        #         Xmlnode('item',attributes={'name':'sortOrder','xsi:type':'number'},node_text='100'),
                        #     ])
                        # ]),
                        Xmlnode('field',
                                attributes={'name': attribute_code},
                                nodes=[
                                    Xmlnode('argument',
                                            attributes={
                                                'name': 'data',
                                                'xsi:type': 'array'
                                            },
                                            nodes=[
                                                options_xml,
                                                Xmlnode('item',
                                                        attributes={
                                                            'name': 'config',
                                                            'xsi:type': 'array'
                                                        },
                                                        nodes=item_xml)
                                            ])
                                ])
                    ])
            ])

        self.add_xml(category_form_file, category_form_xml)
Beispiel #22
0
    def add(self,
            attribute_label,
            frontend_input='text',
            scope=1,
            required=False,
            options=None,
            extra_params=None):
        extra_params = extra_params if extra_params else {}
        apply_to = extra_params.get('apply_to', [])
        try:
            apply_to = ','.join(x for x in apply_to if x != '-1')
        except:
            apply_to = ''

        value_type = self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input, 'int')
        value_type = value_type if value_type != 'date' else 'datetime'
        user_defined = 'true'
        options = options.split(',') if options else []
        options_php_array = '"' + '","'.join(x.strip() for x in options) + '"'
        options_php_array_string = "array('values' => array(" + options_php_array + "))"

        attribute_code = extra_params.get('attribute_code', None)
        if not attribute_code:
            attribute_code = attribute_label.lower().replace(' ', '_')[:30]

        templatePath = os.path.join(
            os.path.dirname(__file__),
            '../templates/attributes/productattribute.tmpl')

        with open(templatePath, 'rb') as tmpl:
            template = tmpl.read().decode('utf-8')

        methodBody = template.format(
            attribute_code=attribute_code,
            attribute_label=attribute_label,
            value_type=value_type,
            frontend_input=frontend_input,
            user_defined=user_defined,
            scope=scope,
            required=str(required).lower(),
            options=options_php_array_string,
            searchable='true'
            if extra_params.get('searchable', False) else 'false',
            filterable='true'
            if extra_params.get('filterable', False) else 'false',
            visible_on_front='true' if extra_params.get(
                'visible_on_front', False) else 'false',
            comparable='true'
            if extra_params.get('comparable', False) else 'false',
            used_in_product_listing='true' if extra_params.get(
                'used_in_product_listing', False) else 'false',
            unique='true' if extra_params.get('unique', False) else 'false',
            default='null',
            is_visible_in_advanced_search=extra_params.get(
                'is_visible_in_advanced_search', '0'),
            apply_to=apply_to,
            backend='Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend'
            if frontend_input == 'multiselect' else '')

        install_data = Phpclass(
            'Setup\\InstallData',
            implements=['InstallDataInterface'],
            dependencies=[
                'Magento\\Framework\\Setup\\InstallDataInterface',
                'Magento\\Framework\\Setup\\ModuleContextInterface',
                'Magento\\Framework\\Setup\\ModuleDataSetupInterface',
                'Magento\\Eav\\Setup\\EavSetup',
                'Magento\\Eav\\Setup\\EavSetupFactory'
            ],
            attributes=['private $eavSetupFactory;'])

        install_data.add_method(
            Phpmethod(
                '__construct',
                params=[
                    'EavSetupFactory $eavSetupFactory',
                ],
                body="$this->eavSetupFactory = $eavSetupFactory;",
                docstring=[
                    'Constructor', '',
                    '@param \\Magento\\Eav\\Setup\\EavSetupFactory $eavSetupFactory'
                ]))
        install_data.add_method(
            Phpmethod(
                'install',
                params=[
                    'ModuleDataSetupInterface $setup',
                    'ModuleContextInterface $context'
                ],
                body=
                "$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);",
                docstring=['{@inheritdoc}']))
        install_data.add_method(
            Phpmethod('install',
                      params=[
                          'ModuleDataSetupInterface $setup',
                          'ModuleContextInterface $context'
                      ],
                      body=methodBody))

        # Catalog Attributes XML | Transport Attribute to Quote Item Product
        transport_to_quote_item = extra_params.get('transport_to_quote_item',
                                                   False)
        if transport_to_quote_item:
            config = Xmlnode(
                'config',
                attributes={
                    'xmlns:xsi':
                    'http://www.w3.org/2001/XMLSchema-instance',
                    'xsi:noNamespaceSchemaLocation':
                    "urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd"
                },
                nodes=[
                    Xmlnode('group',
                            attributes={'name': 'quote_item'},
                            nodes=[
                                Xmlnode('attribute',
                                        attributes={'name': attribute_code})
                            ])
                ])
            self.add_xml('etc/catalog_attributes.xml', config)

        self.add_class(install_data)
	def add(self, attribute_label, frontend_input='text', scope=1, required=False, options=None, extra_params=None):
		extra_params = extra_params if extra_params else {}
		apply_to = extra_params.get('apply_to', [])
		try:
			apply_to = ','.join(x for x in apply_to if x != '-1')
		except:
			apply_to = ''
		
		value_type = self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input,'int')
		value_type = value_type if value_type != 'date' else 'datetime'
		user_defined = 'true'
		options = options.split(',') if options else []
		options_php_array = '"'+'","'.join(x.strip() for x in options) + '"'
		options_php_array_string = "array('values' => array("+options_php_array+"))"

		attribute_code = extra_params.get('attribute_code', None)
		if not attribute_code:
			attribute_code = attribute_label.lower().replace(' ','_')[:30]

		templatePath = os.path.join(os.path.dirname(__file__), '../templates/attributes/productattribute.tmpl')

		with open(templatePath, 'rb') as tmpl:
			template = tmpl.read().decode('utf-8')

		methodBody = template.format(
			attribute_code=attribute_code,
			attribute_label=attribute_label,
			value_type=value_type,
			frontend_input=frontend_input,
			user_defined = user_defined,
			scope = scope,
			required = str(required).lower(),
			options = options_php_array_string,
			searchable = 'true' if extra_params.get('searchable', False) else 'false',
			filterable = 'true' if extra_params.get('filterable', False) else 'false',
			visible_on_front = 'true' if extra_params.get('visible_on_front', False) else 'false',
			comparable = 'true' if extra_params.get('comparable', False) else 'false',
			used_in_product_listing = 'true' if extra_params.get('used_in_product_listing', False) else 'false',
			unique = 'true' if extra_params.get('unique', False) else 'false',
			default = 'null',
			is_visible_in_advanced_search = extra_params.get('is_visible_in_advanced_search','0'),
			apply_to = apply_to,
			backend = 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend' if frontend_input == 'multiselect' else ''
		)

		install_data = Phpclass('Setup\\InstallData',
			implements=['InstallDataInterface'],
			dependencies=[
				'Magento\\Framework\\Setup\\InstallDataInterface',
				'Magento\\Framework\\Setup\\ModuleContextInterface',
				'Magento\\Framework\\Setup\\ModuleDataSetupInterface',
				'Magento\\Eav\\Setup\\EavSetup',
				'Magento\\Eav\\Setup\\EavSetupFactory'],
			attributes=['private $eavSetupFactory;'])

		install_data.add_method(Phpmethod(
			'__construct',
			params=[
				'EavSetupFactory $eavSetupFactory',
			],
			body="$this->eavSetupFactory = $eavSetupFactory;",
			docstring=[
				'Constructor',
				'',
				'@param \\Magento\\Eav\\Setup\\EavSetupFactory $eavSetupFactory'
			]
		)) 
		install_data.add_method(Phpmethod('install',
			params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],
			body="$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);",
			docstring=['{@inheritdoc}']))
		install_data.add_method(Phpmethod('install',
			params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],
			body=methodBody))
	
		self.add_class(install_data)
Beispiel #24
0
	def add(self, tab, section, group, field, field_type='text', new_tab=False, extra_params=None, source_model=False, source_model_options=False):
		resource_id = self.module_name+'::config_'+self.module_name.lower()
		extra_params = extra_params if extra_params else {}

		tab_code = tab.lower().replace(' ', '_')
		section_code = section.lower().replace(' ', '_')
		group_code = group.lower().replace(' ', '_')
		field_code = field.lower().replace(' ', '_')

		# customer source model
		if source_model == 'custom' and source_model_options and field_type == 'select' or field_type == 'multiselect':

			source_model_class = Phpclass(
				'Model\\Config\\Source\\'+ field_code.capitalize(),
				implements=['\Magento\Framework\Option\ArrayInterface']
			)
			source_model_options = source_model_options.split(',')
			to_option_array = "[{}]".format(','.join("['value' => '{0}', 'label' => __('{0}')]".format(o.strip()) for o in source_model_options))
			to_array = "[{}]".format(','.join("'{0}' => __('{0}')".format(o.strip()) for o in source_model_options))

			source_model_class.add_method(Phpmethod('toOptionArray',body="return {};".format(to_option_array)))
			source_model_class.add_method(Phpmethod('toArray',body="return {};".format(to_array)))

			self.add_class(source_model_class)

			source_model = source_model_class.class_namespace


		# system xml
		file = 'etc/adminhtml/system.xml'	

		if new_tab :
			tabxml = Xmlnode('tab',attributes={
					'id':tab,
					'translate':'label',
					'sortOrder':extra_params.get('tab_sortOrder',999) or 999},nodes=[
				Xmlnode('label',node_text=extra_params.get('tab_label',tab) or tab)	
			 ])
		else:
			tabxml = False

		if field_type =='select' or field_type == 'multiselect' :
			source_model_xml = Xmlnode('source_model',node_text=source_model)
		else:
			source_model_xml = False

		if extra_params.get('field_backend_model'):
			backend_model_xml = Xmlnode('backend_model',node_text=extra_params.get('field_backend_model'))
		else:
			backend_model_xml = False			

		config = Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Config:etc/system_file.xsd"}, nodes=[
				Xmlnode('system',  nodes=[
					tabxml,
					Xmlnode('section',attributes={
							'id':section,
							'sortOrder': extra_params.get('section_sortorder',10) or 10,
							'showInWebsite':1 if extra_params.get('section_show_in_website',True) else 0,
							'showInStore':1 if extra_params.get('section_show_in_store',True) else 0,
							'showInDefault': 1 if extra_params.get('section_show_in_default',True) else 0,
							'translate':'label'},match_attributes={'id'},nodes=[
						Xmlnode('label',node_text=extra_params.get('section_label',section) or section),
						Xmlnode('tab',node_text=tab),
						Xmlnode('resource',node_text=resource_id),
						Xmlnode('group', attributes={
								'id':group,'sortOrder':extra_params.get('group_sortorder',10) or 10,
								'showInWebsite': 1 if extra_params.get('group_show_in_website',True) else 0,
								'showInStore': 1 if extra_params.get('group_show_in_store',True) else 0,
								'showInDefault': 1 if extra_params.get('group_show_in_default',True) else 0,
								'translate':'label'},match_attributes={'id'},nodes=[
							Xmlnode('label',node_text=extra_params.get('group_label',group) or group),
							Xmlnode('field', attributes={
									'id':field,
									'type':field_type,
									'sortOrder':extra_params.get('field_sortorder',10) or 10,
									'showInWebsite': 1 if extra_params.get('field_show_in_website',True) else 0,
									'showInStore': 1 if extra_params.get('field_show_in_store',True) else 0,
									'showInDefault': 1 if extra_params.get('field_show_in_default',True) else 0,
									'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text=extra_params.get('field_label',field) or field),
								Xmlnode('comment',node_text=extra_params.get('field_comment')),
								source_model_xml,
								backend_model_xml
							])
						])	
					])
				])
		])

		self.add_xml(file, config)

		# acl xml
		aclfile = 'etc/acl.xml'
		
		acl = Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation':"urn:magento:framework:Acl/etc/acl.xsd"}, nodes=[
			Xmlnode('acl',nodes=[
				Xmlnode('resources',nodes=[
					Xmlnode('resource',attributes={'id':'Magento_Backend::admin'},match_attributes={'id'},nodes=[
						Xmlnode('resource',attributes={'id':'Magento_Backend::stores'},nodes=[
							Xmlnode('resource',attributes={'id':'Magento_Backend::stores_settings'},match_attributes={'id'},nodes=[
								Xmlnode('resource',attributes={'id':'Magento_Config::config'},match_attributes={'id'},nodes=[
									Xmlnode('resource',attributes={'id':resource_id,'title':section},match_attributes={'id'})
								])
							])
						])
					])
				])
			])
		]);

		self.add_xml(aclfile, acl)

		# default config values xml
		config_file = 'etc/config.xml'
		
		default_config = Xmlnode('config',attributes={'xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Store:etc/config.xsd"},nodes=[
			Xmlnode('default',nodes=[
				Xmlnode(section,nodes=[
					Xmlnode(group,nodes=[
						Xmlnode(field,node_text=extra_params.get('field_default'))
					])
				])
			])
		]);
		
		self.add_xml(config_file, default_config)
Beispiel #25
0
	def add(self, model_name, field_name, field_type, extra_params=False):
		model_id = '{}_id'.format(model_name.lower())
		install_class = Phpclass('Setup\\InstallSchema',implements=['InstallSchemaInterface'],dependencies=[
			'Magento\\Framework\\Setup\\InstallSchemaInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\SchemaSetupInterface'])

		# Start setup
		install_method = Phpmethod('install', params=['SchemaSetupInterface $setup','ModuleContextInterface $context'],
			body='$installer = $setup;\n$installer->startSetup();',
			body_return='$setup->endSetup();')
		
		# Create table
		install_method.body.append("$table{0} = $setup->getConnection()->newTable($setup->getTable('{0}'));".format(model_name))
		
		# add model id field
		install_method.body.append("$table{table}->addColumn(\n  '{field}',\n  {type},\n  {size},\n  {options},\n  '{comment}'\n);".format(
			table=model_name,
			field=model_id,
			type='\\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER',
			size='null',
			options="array('identity' => true,'nullable' => false,'primary' => true,'unsigned' => true,)",
			comment='Entity ID'	
		))

		# Add field
		install_method.body.append("$table{table}->addColumn(\n  '{field}',\n  {type},\n  {size},\n  {options},\n  '{comment}'\n);".format(
			table=model_name,
			field=field_name,
			type='\\Magento\\Framework\\DB\\Ddl\\Table::TYPE_{}'.format(field_type.upper()),
			size=extra_params.get('field_size') or 'null',
			options='[]',
			comment=extra_params.get('comment') or field_name	
		))
		
		# End setup + create table 
		install_method.end_body.append('$setup->getConnection()->createTable($table{});'.format(model_name))

		install_class.add_method(install_method)
		self.add_class(install_class)
		
		# Create resource class
		resource_model_class = Phpclass('Model\\ResourceModel\\' + model_name.replace('_', '\\'), extends='\\Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb')
		resource_model_class.add_method(Phpmethod('_construct', access=Phpmethod.PROTECTED, body="$this->_init('{}', '{}');".format(model_name, model_id)))
		self.add_class(resource_model_class)

		# Create model class
		model_class = Phpclass('Model\\' + model_name.replace('_', '\\'), extends='\\Magento\\Framework\\Model\\AbstractModel')
		model_class.add_method(Phpmethod('_construct', access=Phpmethod.PROTECTED, body="$this->_init('{}');".format(resource_model_class.class_namespace)))
		self.add_class(model_class)

		# Create collection
		collection_model_class = Phpclass('Model\\ResourceModel\\' + model_name.replace('_', '\\') + '\\Collection', extends='\\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection')
		collection_model_class.add_method(Phpmethod('_construct', access=Phpmethod.PROTECTED, body="$this->_init(\n  '{}',\n  '{}');".format(
			model_class.class_namespace ,resource_model_class.class_namespace)))
		self.add_class(collection_model_class)
Beispiel #26
0
	def add(self, test_suite, test_name, extra_params=None):
		class_name = "\\Test\\Unit\\{}Test".format(test_suite)

		unittest_class = Phpclass(class_name,extends='\\PHPUnit_Framework_TestCase')

		# Adding class setup and teardown
		unittest_class.add_method(
			Phpmethod(
				'setUpBeforeClass',
				access='public static',
				body="//setup",
				docstring=['Is called once before running all test in class']
			)
		)

		unittest_class.add_method(
			Phpmethod(
				'tearDownAfterClass',
				access='public static',
				body="//teardown",
				docstring=['Is called once after running all test in class']
			)
		)


		# Adding test setup and teardown
		unittest_class.add_method(
			Phpmethod(
				'setUp',
				access='protected',
				body="//setup",
				docstring=['Is called before running a test']
			)
		)

		unittest_class.add_method(
			Phpmethod(
				'tearDown',
				access='protected',
				body="//teardown",
				docstring=['Is called after running a test']
			)
		)

		# Adding test
		unittest_class.add_method(
			Phpmethod(
				'test{}'.format(upperfirst(test_name)),
				access='public',
				body='$this->assertTrue(false);',
				docstring=["The test itself, every test function must start with 'test'"]
			)
		)

		self.add_class(unittest_class)
Beispiel #27
0
    def add(self,
            name,
            field,
            field_type='text',
            sortorder=10,
            extra_params=None):

        widget_block = Phpclass(
            '\\'.join(['Block', 'Widget', name]),
            implements=['BlockInterface'],
            dependencies=[
                'Magento\Framework\View\Element\Template',
                'Magento\Widget\Block\BlockInterface'
            ],
            extends='Template',
            attributes=[
                'protected $_template = "widget/{}.phtml";'.format(
                    name.lower())
            ])

        self.add_class(widget_block)

        parameter_attributes = {
            'name': field.lower(),
            'xsi:type': field_type,
            'visible': 'true',
            'sort_order': sortorder
        }

        if field_type == 'select' or field_type == 'multiselect':
            parameter_attributes[
                "source_model"] = "Magento\\Config\\Model\\Config\\Source\\Yesno"

        widget_file = 'etc/widget.xml'

        widget_xml = Xmlnode(
            'widgets',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:module:Magento_Widget:etc/widget.xsd"
            },
            nodes=[
                Xmlnode('widget',
                        attributes={
                            'id':
                            '{}_{}_{}'.format(self._module.package.lower(),
                                              self._module.name.lower(),
                                              name.lower()),
                            'class':
                            widget_block.class_namespace
                        },
                        nodes=[
                            Xmlnode('label', node_text=name),
                            Xmlnode('description', node_text=name),
                            Xmlnode('parameters',
                                    nodes=[
                                        Xmlnode(
                                            'parameter',
                                            attributes=parameter_attributes,
                                            nodes=[
                                                Xmlnode('label',
                                                        node_text=field)
                                            ])
                                    ])
                        ])
            ])

        self.add_xml(widget_file, widget_xml)

        path = os.path.join('view', 'frontend', 'templates')
        self.add_static_file(
            path,
            StaticFile(
                "{}/{}.phtml".format('widget', name),
                body=
                "<?php if($block->getData('{name}')): ?>\n\t<h2 class='{name}'><?php echo $block->getData('{name}'); ?></h2>\n<?php endif; ?>"
                .format(name=field.lower(),
                        classname=widget_block.class_namespace)))
Beispiel #28
0
    def add(self, action_name, short_description, extra_params=None):

        console = Phpclass(
            'Console\\Command\\' + action_name,
            extends='Command',
            dependencies=[
                'Symfony\Component\Console\Command\Command',
                'Symfony\Component\Console\Input\InputArgument',
                'Symfony\Component\Console\Input\InputOption',
                'Symfony\Component\Console\Input\InputInterface',
                'Symfony\Component\Console\Output\OutputInterface'
            ],
            attributes=[
                'const NAME_ARGUMENT = "name";',
                'const NAME_OPTION = "option";'
            ])

        console.add_method(
            Phpmethod(
                'execute',
                access='protected',
                params=['InputInterface $input', 'OutputInterface $output'],
                body="""
			$name = $input->getArgument(self::NAME_ARGUMENT);
			$option = $input->getOption(self::NAME_OPTION);
			$output->writeln("Hello " . $name);
			""",
                docstring=['{@inheritdoc}']))

        console.add_method(
            Phpmethod('configure',
                      access='protected',
                      body=""" 
				$this->setName("{module_name}:{action_name}");
				$this->setDescription("{short_description}");
				$this->setDefinition([
				    new InputArgument(self::NAME_ARGUMENT, InputArgument::OPTIONAL, "Name"),
				    new InputOption(self::NAME_OPTION, "-a", InputOption::VALUE_NONE, "Option functionality")
				]);
				parent::configure();
				""".format(module_name=self.module_name.lower(),
               action_name=action_name.lower(),
               short_description=short_description),
                      docstring=['{@inheritdoc}']))

        self.add_class(console)

        config = Xmlnode(
            'config',
            attributes={
                'xmlns:xsi':
                'http://www.w3.org/2001/XMLSchema-instance',
                'xsi:noNamespaceSchemaLocation':
                "urn:magento:framework:ObjectManager/etc/config.xsd"
            },
            nodes=[
                Xmlnode(
                    'type',
                    attributes={
                        'name': 'Magento\Framework\Console\CommandList'
                    },
                    nodes=[
                        Xmlnode(
                            'arguments',
                            nodes=[
                                Xmlnode(
                                    'argument',
                                    attributes={
                                        'name': 'commands',
                                        'xsi:type': 'array',
                                    },
                                    nodes=[
                                        Xmlnode(
                                            'item',
                                            attributes={
                                                'name': action_name,
                                                'xsi:type': 'object'
                                            },
                                            node_text=console.class_namespace)
                                    ])
                            ])
                    ])
            ])

        self.add_xml('etc/di.xml', config)
Beispiel #29
0
	def add(self, frontname='', section='index', action='index', adminhtml=False, extra_params=None):
		if not frontname:
			frontname = self._module.name.lower()
		file = 'etc/{}/routes.xml'.format('adminhtml' if adminhtml else 'frontend')

		# Create config router
		module = Xmlnode('module', attributes={'name': self.module_name})
		if adminhtml:
			module.attributes['before'] = 'Magento_Backend'

		config = Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation':"urn:magento:framework:App/etc/routes.xsd"}, nodes=[
			Xmlnode('router', attributes={'id': 'admin' if adminhtml else 'standard'}, nodes=[
				Xmlnode('route', attributes={'id': frontname, 'frontName': frontname}, nodes=[
					module
				])
			])
		])
		self.add_xml(file, config)

		# Create controller
		controller_class = ['Controller']
		if adminhtml:
			controller_class.append('Adminhtml')
		controller_class.append(section)
		controller_class.append(action)

		controller = Phpclass('\\'.join(controller_class), '\Magento\Framework\App\Action\Action')
		controller.attributes.append('protected $resultPageFactory;')
		controller.add_method(Phpmethod(
			'__construct',
			params=[
				'\Magento\Framework\App\Action\Context $context',
				'\Magento\Framework\View\Result\PageFactory $resultPageFactory'
			],
			body="""$this->resultPageFactory = $resultPageFactory;
				parent::__construct($context);
			"""
		))
		controller.add_method(Phpmethod(
			'execute',
			body='return $this->resultPageFactory->create();'
		))

		self.add_class(controller)

		# create block
		block_class = ['Block']
		if adminhtml:
			block_class.append('Adminhtml')
		block_class.append(section)
		block_class.append(action)

		block = Phpclass('\\'.join(block_class), '\Magento\Framework\View\Element\Template')
		self.add_class(block)

		# Add layout xml
		layout_xml = Xmlnode('page', attributes={'layout':"admin-1column" if adminhtml else "1column", 'xsi:noNamespaceSchemaLocation':"urn:magento:framework:View/Layout/etc/page_configuration.xsd"}, nodes=[
			Xmlnode('body', nodes=[
				Xmlnode('referenceContainer', attributes={'name': 'content'}, nodes=[
					Xmlnode('block', attributes={
						'name': "{}.{}".format(section, action), 
						'class': block.class_namespace,
						'template': "{}::{}/{}.phtml".format(self.module_name, section, action)
					})
				])
			])
		])
		path = os.path.join('view', 'adminhtml' if adminhtml else 'frontend', 'layout', "{}_{}_{}.xml".format(frontname, section, action))
		self.add_xml(path, layout_xml)

		# add template file
		path = os.path.join('view', 'adminhtml' if adminhtml else 'frontend', 'templates')
		self.add_static_file(path, StaticFile("{}/{}.phtml".format(section, action),body="Hello {}/{}.phtml".format(section, action)))
Beispiel #30
0
    def add(self,
            model_name,
            field_name,
            field_type='text',
            adminhtml_grid=False,
            extra_params=False):
        extra_params = extra_params if extra_params else {}

        model_table = '{}_{}'.format(self._module.package.lower(),
                                     model_name.lower())
        model_id = '{}_id'.format(model_name.lower())

        install_class = Phpclass(
            'Setup\\InstallSchema',
            implements=['InstallSchemaInterface'],
            dependencies=[
                'Magento\\Framework\\Setup\\InstallSchemaInterface',
                'Magento\\Framework\\Setup\\ModuleContextInterface',
                'Magento\\Framework\\Setup\\SchemaSetupInterface'
            ])

        # Start setup
        install_method = Phpmethod(
            'install',
            params=[
                'SchemaSetupInterface $setup',
                'ModuleContextInterface $context'
            ],
            body='$installer = $setup;\n$installer->startSetup();',
            body_return='$setup->endSetup();')

        # Create table
        install_method.body.append(
            "$table_{0} = $setup->getConnection()->newTable($setup->getTable('{0}'));"
            .format(model_table))

        # add model id field
        install_method.body.append(
            "$table_{table}->addColumn(\n  '{field}',\n  {type},\n  {size},\n  {options},\n  '{comment}'\n);"
            .format(
                table=model_table,
                field=model_id,
                type='\\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER',
                size='null',
                options=
                "array('identity' => true,'nullable' => false,'primary' => true,'unsigned' => true,)",
                comment='Entity ID'))

        # create options
        options = OrderedDict()
        if extra_params.get('default'):
            options['default'] = "'{}'".format(extra_params.get('default'))
        if not extra_params.get('nullable'):
            options['nullable'] = extra_params.get('nullable')
        if extra_params.get('identity'):
            options['identity'] = True
        if extra_params.get('auto_increment'):
            options['auto_increment'] = True
        if extra_params.get('unsigned'):
            options['unsigned'] = True
        if extra_params.get('precision'):
            options['precision'] = extra_params.get('precision')
        if extra_params.get('scale'):
            options['scale'] = extra_params.get('scale')

        options = "[{}]".format(','.join("'{}' => {}".format(key, value)
                                         for key, value in options.items()))

        # Add field
        install_method.body.append(
            "$table_{table}->addColumn(\n  '{field}',\n  {type},\n  {size},\n  {options},\n  '{comment}'\n);"
            .format(
                table=model_table,
                field=field_name,
                type='\\Magento\\Framework\\DB\\Ddl\\Table::TYPE_{}'.format(
                    field_type.upper()),
                size=extra_params.get('field_size') or 'null',
                options=options,
                comment=extra_params.get('comment') or field_name))

        # End setup + create table
        install_method.end_body.append(
            '$setup->getConnection()->createTable($table_{});'.format(
                model_table))

        install_class.add_method(install_method)
        self.add_class(install_class)

        # Create resource class
        resource_model_class = Phpclass(
            'Model\\ResourceModel\\' + model_name.replace('_', '\\'),
            extends='\\Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb'
        )
        resource_model_class.add_method(
            Phpmethod('_construct',
                      access=Phpmethod.PROTECTED,
                      body="$this->_init('{}', '{}');".format(
                          model_table, model_id)))
        self.add_class(resource_model_class)

        # Create model class
        model_class = Phpclass(
            'Model\\' + model_name.replace('_', '\\'),
            extends='\\Magento\\Framework\\Model\\AbstractModel')
        model_class.add_method(
            Phpmethod('_construct',
                      access=Phpmethod.PROTECTED,
                      body="$this->_init('{}');".format(
                          resource_model_class.class_namespace)))
        self.add_class(model_class)

        # Create collection
        collection_model_class = Phpclass(
            'Model\\ResourceModel\\' + model_name.replace('_', '\\') +
            '\\Collection',
            extends=
            '\\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection'
        )
        collection_model_class.add_method(
            Phpmethod('_construct',
                      access=Phpmethod.PROTECTED,
                      body="$this->_init(\n  '{}',\n  '{}');".format(
                          model_class.class_namespace,
                          resource_model_class.class_namespace)))
        self.add_class(collection_model_class)

        # add grid
        if adminhtml_grid:
            frontname = self.module_name.lower()
            data_source_id = '{}_grid_data_source'.format(model_table)

            # create controller
            index_controller_class = Phpclass(
                'Controller\\Adminhtml\\' + model_name.replace('_', '\\') +
                '\\Index',
                extends='\\Magento\\Framework\\App\\Action\\Action',
                attributes=['protected $resultPageFactory;'])

            index_controller_class.add_method(
                Phpmethod(
                    '__construct',
                    params=[
                        '\\Magento\\Framework\\App\\Action\\Context $context',
                        '\\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory'
                    ],
                    body=
                    '$this->resultPageFactory = $resultPageFactory;\nparent::__construct($context);'
                ))

            index_controller_class.add_method(
                Phpmethod(
                    'execute',
                    body_return='return $this->resultPageFactory->create();'))

            self.add_class(index_controller_class)

            # create menu.xml
            self.add_xml(
                'etc/adminhtml/menu.xml',
                Xmlnode('config',
                        attributes={
                            'xsi:noNamespaceSchemaLocation':
                            "urn:magento:module:Magento_Backend:etc/menu.xsd"
                        },
                        nodes=[
                            Xmlnode('menu',
                                    nodes=[
                                        Xmlnode('add',
                                                attributes={
                                                    'id':
                                                    "{}::top_level".format(
                                                        self.module_name),
                                                    'title':
                                                    self._module.package,
                                                    'module':
                                                    self.module_name,
                                                    'sortOrder':
                                                    9999,
                                                    'resource':
                                                    'Magento_Backend::content',
                                                }),
                                        Xmlnode(
                                            'add',
                                            attributes={
                                                'id':
                                                "{}::{}".format(
                                                    self.module_name,
                                                    model_table),
                                                'title':
                                                model_name.replace('_', ' '),
                                                'module':
                                                self.module_name,
                                                'sortOrder':
                                                9999,
                                                'resource':
                                                'Magento_Backend::content',
                                                'parent':
                                                '{}::top_level'.format(
                                                    self.module_name),
                                                'action':
                                                '{}/{}/index'.format(
                                                    frontname,
                                                    model_name.lower().replace(
                                                        '_', '\\'))
                                            })
                                    ])
                        ]))

            # Create routes.xml
            self.add_xml(
                'etc/adminhtml/routes.xml',
                Xmlnode('config',
                        attributes={
                            'xsi:noNamespaceSchemaLocation':
                            'urn:magento:framework:App/etc/routes.xsd'
                        },
                        nodes=[
                            Xmlnode('router',
                                    attributes={'id': 'admin'},
                                    nodes=[
                                        Xmlnode('route',
                                                attributes={
                                                    'frontName': frontname,
                                                    'id': frontname
                                                },
                                                nodes=[
                                                    Xmlnode(
                                                        'module',
                                                        attributes={
                                                            'before':
                                                            'Magento_Backend',
                                                            'name':
                                                            self.module_name
                                                        })
                                                ])
                                    ])
                        ]))

            # di.xml
            self.add_xml(
                'etc/di.xml',
                Xmlnode(
                    'config',
                    attributes={
                        'xsi:noNamespaceSchemaLocation':
                        "urn:magento:framework:ObjectManager/etc/config.xsd"
                    },
                    nodes=[
                        Xmlnode(
                            'virtualType',
                            attributes={
                                'name':
                                collection_model_class.class_namespace.replace(
                                    'Collection', 'Grid\\Collection'),
                                'type':
                                'Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult',
                            },
                            nodes=[
                                Xmlnode(
                                    'arguments',
                                    nodes=[
                                        Xmlnode(
                                            'argument',
                                            attributes={
                                                'name':
                                                'mainTable',
                                                'xsi:type': 'string'
                                            },
                                            node_text=model_table),
                                        Xmlnode(
                                            'argument',
                                            attributes={
                                                'name':
                                                'resourceModel',
                                                'xsi:type': 'string'
                                            },
                                            node_text=collection_model_class.
                                            class_namespace),
                                    ])
                            ]),
                        Xmlnode(
                            'type',
                            attributes={
                                'name':
                                'Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\CollectionFactory'
                            },
                            nodes=[
                                Xmlnode(
                                    'arguments',
                                    nodes=[
                                        Xmlnode(
                                            'argument',
                                            attributes={
                                                'name':
                                                'collections',
                                                'xsi:type': 'array'
                                            },
                                            nodes=[
                                                Xmlnode(
                                                    'item',
                                                    attributes={
                                                        'name':
                                                        data_source_id,
                                                        'xsi:type': 'string'
                                                    },
                                                    node_text=
                                                    collection_model_class.
                                                    class_namespace.replace(
                                                        'Collection',
                                                        'Grid\\Collection'))
                                            ])
                                    ])
                            ])
                    ]))

            # create layout.xml
            self.add_xml(
                'view/adminhtml/layout/{}_{}_index.xml'.format(
                    frontname, model_name.lower()),
                Xmlnode(
                    'page',
                    attributes={
                        'xsi:noNamespaceSchemaLocation':
                        "urn:magento:framework:View/Layout/etc/page_configuration.xsd"
                    },
                    nodes=[
                        Xmlnode('update', attributes={'handle': 'styles'}),
                        Xmlnode(
                            'body',
                            nodes=[
                                Xmlnode(
                                    'referenceContainer',
                                    attributes={'name': 'content'},
                                    nodes=[
                                        Xmlnode(
                                            'uiComponent',
                                            attributes={
                                                'name':
                                                '{}_index'.format(model_table)
                                            })
                                    ])
                            ])
                    ]))

            # create components.xml
            data_source_xml = Xmlnode(
                'dataSource',
                attributes={'name': data_source_id},
                nodes=[
                    Xmlnode(
                        'argument',
                        attributes={
                            'name': 'dataProvider',
                            'xsi:type': 'configurableObject'
                        },
                        nodes=[
                            Xmlnode(
                                'argument',
                                attributes={
                                    'name': 'class',
                                    'xsi:type': 'string'
                                },
                                node_text=
                                'Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\DataProvider'
                            ),
                            Xmlnode('argument',
                                    attributes={
                                        'name': 'name',
                                        'xsi:type': 'string'
                                    },
                                    node_text=data_source_id),
                            Xmlnode('argument',
                                    attributes={
                                        'name': 'primaryFieldName',
                                        'xsi:type': 'string'
                                    },
                                    node_text=model_id),
                            Xmlnode('argument',
                                    attributes={
                                        'name': 'requestFieldName',
                                        'xsi:type': 'string'
                                    },
                                    node_text='id'),
                            Xmlnode(
                                'argument',
                                attributes={
                                    'name': 'data',
                                    'xsi:type': 'array'
                                },
                                nodes=[
                                    Xmlnode(
                                        'item',
                                        attributes={
                                            'name':
                                            'config',
                                            'xsi:type': 'array'
                                        },
                                        nodes=[
                                            Xmlnode(
                                                'item',
                                                attributes={
                                                    'name':
                                                    'component',
                                                    'xsi:type':
                                                    'string'
                                                },
                                                node_text=
                                                'Magento_Ui/js/grid/provider'),
                                            Xmlnode('item',
                                                    attributes={
                                                        'name': 'update_url',
                                                        'xsi:type': 'url',
                                                        'path':
                                                        'mui/index/render'
                                                    }),
                                            Xmlnode(
                                                'item',
                                                attributes={
                                                    'name': 'storageConfig',
                                                    'xsi:type': 'array'
                                                },
                                                nodes=[
                                                    Xmlnode('item',
                                                            attributes={
                                                                'name':
                                                                'indexField',
                                                                'xsi:type':
                                                                'string'
                                                            },
                                                            node_text=model_id)
                                                ]),
                                        ])
                                ]),
                        ])
                ])

            columns_xml = Xmlnode(
                'columns',
                attributes={'name': '{}_columns'.format(model_table)},
                nodes=[
                    Xmlnode('selectionsColumn',
                            attributes={'name': 'ids'},
                            nodes=[
                                Xmlnode('argument',
                                        attributes={
                                            'name': 'data',
                                            'xsi:type': 'array'
                                        },
                                        nodes=[
                                            Xmlnode('item',
                                                    attributes={
                                                        'name': 'config',
                                                        'xsi:type': 'array'
                                                    },
                                                    nodes=[
                                                        Xmlnode(
                                                            'item',
                                                            attributes={
                                                                'name':
                                                                'indexField',
                                                                'xsi:type':
                                                                'string'
                                                            },
                                                            node_text=model_id)
                                                    ])
                                        ])
                            ]),
                    Xmlnode('column',
                            attributes={'name': model_id},
                            nodes=[
                                Xmlnode('argument',
                                        attributes={
                                            'name': 'data',
                                            'xsi:type': 'array'
                                        },
                                        nodes=[
                                            Xmlnode(
                                                'item',
                                                attributes={
                                                    'name': 'config',
                                                    'xsi:type': 'array'
                                                },
                                                nodes=[
                                                    Xmlnode('item',
                                                            attributes={
                                                                'name':
                                                                'filter',
                                                                'xsi:type':
                                                                'string'
                                                            },
                                                            node_text='text'),
                                                    Xmlnode('item',
                                                            attributes={
                                                                'name':
                                                                'sorting',
                                                                'xsi:type':
                                                                'string'
                                                            },
                                                            node_text='asc'),
                                                    Xmlnode('item',
                                                            attributes={
                                                                'name':
                                                                'label',
                                                                'xsi:type':
                                                                'string',
                                                                'translate':
                                                                'true'
                                                            },
                                                            node_text='ID'),
                                                ])
                                        ])
                            ]),
                    Xmlnode('column',
                            attributes={'name': field_name},
                            nodes=[
                                Xmlnode('argument',
                                        attributes={
                                            'name': 'data',
                                            'xsi:type': 'array'
                                        },
                                        nodes=[
                                            Xmlnode(
                                                'item',
                                                attributes={
                                                    'name': 'config',
                                                    'xsi:type': 'array'
                                                },
                                                nodes=[
                                                    Xmlnode('item',
                                                            attributes={
                                                                'name':
                                                                'filter',
                                                                'xsi:type':
                                                                'string'
                                                            },
                                                            node_text='text'),
                                                    Xmlnode('item',
                                                            attributes={
                                                                'name':
                                                                'sorting',
                                                                'xsi:type':
                                                                'string'
                                                            },
                                                            node_text='asc'),
                                                    Xmlnode(
                                                        'item',
                                                        attributes={
                                                            'name': 'label',
                                                            'xsi:type':
                                                            'string',
                                                            'translate': 'true'
                                                        },
                                                        node_text=field_name),
                                                ])
                                        ])
                            ]),
                ])

            self.add_xml(
                'view/adminhtml/ui_component/{}_index.xml'.format(model_table),
                Xmlnode(
                    'listing',
                    attributes={
                        'xsi:noNamespaceSchemaLocation':
                        "urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"
                    },
                    nodes=[
                        Xmlnode(
                            'argument',
                            attributes={
                                'name': 'context',
                                'xsi:type': 'configurableObject'
                            },
                            nodes=[
                                Xmlnode(
                                    'argument',
                                    attributes={
                                        'name': 'class',
                                        'xsi:type': 'string'
                                    },
                                    node_text=
                                    'Magento\\Framework\\View\\Element\\UiComponent\\Context'
                                ),
                                Xmlnode(
                                    'argument',
                                    attributes={
                                        'name': 'namespace',
                                        'xsi:type': 'string'
                                    },
                                    node_text='{}_index'.format(model_table)),
                            ]),
                        Xmlnode('argument',
                                attributes={
                                    'name': 'data',
                                    'xsi:type': 'array'
                                },
                                nodes=[
                                    Xmlnode(
                                        'item',
                                        attributes={
                                            'name': 'js_config',
                                            'xsi:type': 'array'
                                        },
                                        nodes=[
                                            Xmlnode(
                                                'item',
                                                attributes={
                                                    'name':
                                                    'provider',
                                                    'xsi:type': 'string'
                                                },
                                                node_text='{}_index.{}'.format(
                                                    model_table,
                                                    data_source_id)),
                                            Xmlnode(
                                                'item',
                                                attributes={
                                                    'name': 'deps',
                                                    'xsi:type': 'string'
                                                },
                                                node_text='{}_index.{}'.format(
                                                    model_table,
                                                    data_source_id)),
                                        ]),
                                    Xmlnode('item',
                                            attributes={
                                                'name': 'spinner',
                                                'xsi:type': 'string'
                                            },
                                            node_text='{}_columns'.format(
                                                model_table)),
                                ]),
                        data_source_xml,
                        columns_xml,
                    ]))
Beispiel #31
0
	def add(self,attribute_label, customer_forms=False, customer_address_forms=False, customer_entity='customer', frontend_input='text',
		static_field_type='varchar', required=False, source_model=False, source_model_options=False, extra_params=None):

		extra_params = extra_params if extra_params else {}
		attribute_code = extra_params.get('attribute_code', None)
		backend_model = ''
		
		if not attribute_code:
			attribute_code = attribute_label.lower().replace(' ','_')
		if frontend_input == 'select' and not source_model:
			source_model = "Magento\Customer\Model\ResourceModel\Address\Attribute\Source\Country"
		elif frontend_input == 'multiselect':
			backend_model = "Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend"
			if not source_model:    
				source_model = "Magento\Customer\Model\ResourceModel\Address\Attribute\Source\Country"
		elif frontend_input != 'multiselect' and frontend_input != 'select':
			source_model = ''
			backend_model = ''

		# customer source model
		if source_model == 'custom' and source_model_options and frontend_input == 'select' or frontend_input == 'multiselect':
			source_model_folder = 'Customer' if customer_entity =='customer' else 'Customer\\Address'
			source_model_class = Phpclass(
				'Model\\'+source_model_folder+'\\Attribute\\Source\\'+ attribute_code.capitalize(),
				extends='\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource'
			)
			source_model_options = source_model_options.split(',')

			if frontend_input == 'select':
				to_option_array = "[\n{}\n]".format(',\n'.join("['value' => '{1}', 'label' => __('{0}')]".format(o.strip(),source_model_options.index(o)+1) for o in source_model_options))
			else:
				to_option_array = "[\n{}\n]".format(',\n'.join("['value' => (string) '{0}', 'label' => __('{0}')]".format(o.strip()) for o in source_model_options))

			source_model_class.attributes.append('protected $_optionsData;')
			source_model_class.add_method(Phpmethod('__construct',params=['array $options'],body="$this->_optionsData = $options;")) 

			get_all_options_array = "\t$this->_options = {};".format(to_option_array)

			source_model_class.add_method(Phpmethod('getAllOptions',body="if ($this->_options === null) { \n " + get_all_options_array + "\n}\nreturn $this->_options;"))

			self.add_class(source_model_class)

			source_model = source_model_class.class_namespace

		value_type = static_field_type if frontend_input=='static' else self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input,'int');

		forms_array = customer_forms if customer_entity == 'customer' else customer_address_forms
		forms_array = forms_array if forms_array else []
		forms_array = forms_array if isinstance(forms_array, list) else [forms_array]

		if forms_array:
			forms_php_array = "'" + "','".join(forms_array) + "'"
		elif customer_entity=='customer' and customer_forms==False:
			forms_php_array = "'adminhtml_customer','adminhtml_checkout','customer_account_create','customer_account_edit'"
		else :
			forms_php_array = None

		template = 'customerattribute.tmpl' if customer_entity=='customer' else 'customeraddressattribute.tmpl' 
		templatePath = os.path.join(os.path.dirname(__file__), '../templates/attributes/'+template)

		with open(templatePath, 'rb') as tmpl:
			template = tmpl.read().decode('utf-8')

		methodBody = template.format(
			attribute_code=attribute_code,
			attribute_label=attribute_label,
			value_type=value_type,
			frontend_input=frontend_input,
			required = required,
			sort_order = extra_params.get('sort_order','333') if extra_params.get('sort_order','333') else '333',
			visible =  extra_params.get('visible','true'),
			source_model = source_model,
			backend_model = backend_model
		)

		install_data = Phpclass(
			'Setup\\InstallData',
			implements=['InstallDataInterface'],
			dependencies=[
				'Magento\\Framework\\Setup\\InstallDataInterface',
				'Magento\\Framework\\Setup\\ModuleContextInterface',
				'Magento\\Framework\\Setup\\ModuleDataSetupInterface',
				'Magento\\Customer\\Model\\Customer',
				'Magento\\Customer\\Setup\\CustomerSetupFactory'
				]
		)

		install_data.attributes.append('private $customerSetupFactory;')
		
		install_data.add_method(Phpmethod(
			'__construct',
			params=[
				'CustomerSetupFactory $customerSetupFactory'
			],
			body="$this->customerSetupFactory = $customerSetupFactory;"
		))

		install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body="$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);"))
		install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body=methodBody))

		if forms_php_array:
			attribute_form_data = "$attribute = $customerSetup->getEavConfig()->getAttribute('"+customer_entity+"', '"+attribute_code+"')->addData(['used_in_forms' => ["+forms_php_array+"]]);\n$attribute->save();"
			install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body=attribute_form_data))

		self.add_class(install_data)	

		extension_attributes_file = 'etc/extension_attributes.xml'

		api_class = "Magento\Customer\Api\Data\CustomerInterface"  if customer_entity=='customer' else 'Magento\Customer\Api\Data\AddressInterface'
	
		extension_attributes_xml = Xmlnode('config',attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:framework:Api/etc/extension_attributes.xsd"},nodes=[
			Xmlnode('extension_attributes',attributes={'for':api_class},match_attributes={'for'},nodes=[
				Xmlnode('attribute',attributes={
					'code':attribute_code,
					'type':'string'
				})
			])
		])

		self.add_xml(extension_attributes_file, extension_attributes_xml)
Beispiel #32
0
    def add(self,
            attribute_label,
            frontend_input='text',
            scope=1,
            required=False,
            options=None,
            extra_params=None):
        extra_params = extra_params if extra_params else {}
        apply_to = extra_params.get('apply_to', [])
        try:
            apply_to = ','.join(x for x in apply_to if x != '-1')
        except:
            apply_to = ''

        value_type = self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input, 'int')
        value_type = value_type if value_type != 'date' else 'datetime'
        user_defined = 'true'
        options = options.split(',') if options else []
        options_php_array = '"' + '","'.join(x.strip() for x in options) + '"'
        options_php_array_string = "array('values' => array(" + options_php_array + "))"

        attribute_code = extra_params.get('attribute_code', None)
        if not attribute_code:
            attribute_code = attribute_label.lower().replace(' ', '_')[:30]

        templatePath = os.path.join(
            os.path.dirname(__file__),
            '../templates/attributes/productattribute.tmpl')

        with open(templatePath, 'rb') as tmpl:
            template = tmpl.read().decode('utf-8')

        methodBody = template.format(
            attribute_code=attribute_code,
            attribute_label=attribute_label,
            value_type=value_type,
            frontend_input=frontend_input,
            user_defined=user_defined,
            scope=scope,
            required=required,
            options=options_php_array_string,
            searchable=extra_params.get('searchable', 'false'),
            filterable=extra_params.get('filterable', 'false'),
            visible_on_front=extra_params.get('visible_on_front', 'false'),
            comparable=extra_params.get('comparable', 'false'),
            used_in_product_listing=extra_params.get('used_in_product_listing',
                                                     'false'),
            unique=extra_params.get('unique', 'false'),
            default='null',
            is_visible_in_advanced_search=extra_params.get(
                'is_visible_in_advanced_search', '0'),
            apply_to=apply_to,
            backend='Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend'
            if frontend_input == 'multiselect' else '')

        install_data = Phpclass(
            'Setup\\InstallData',
            implements=['InstallDataInterface'],
            dependencies=[
                'Magento\\Framework\\Setup\\InstallDataInterface',
                'Magento\\Framework\\Setup\\ModuleContextInterface',
                'Magento\\Framework\\Setup\\ModuleDataSetupInterface',
                'Magento\\Eav\\Setup\\EavSetup',
                'Magento\\Eav\\Setup\\EavSetupFactory'
            ])
        install_data.attributes.append('private $eavSetupFactory;')
        install_data.add_method(
            Phpmethod('__construct',
                      params=[
                          'EavSetupFactory $eavSetupFactory',
                      ],
                      body="$this->eavSetupFactory = $eavSetupFactory;"))
        install_data.add_method(
            Phpmethod(
                'install',
                params=[
                    'ModuleDataSetupInterface $setup',
                    'ModuleContextInterface $context'
                ],
                body=
                "$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);"
            ))
        install_data.add_method(
            Phpmethod('install',
                      params=[
                          'ModuleDataSetupInterface $setup',
                          'ModuleContextInterface $context'
                      ],
                      body=methodBody))

        self.add_class(install_data)
Beispiel #33
0
	def add(self,method_name, extra_params=None):

		payment_code = method_name.lower().replace(' ', '_')
		payment_class_name = method_name

		payment_class = Phpclass('Model\\Payment\\'+payment_class_name,
			extends='\Magento\Payment\Model\Method\AbstractMethod',
			attributes=[
				'protected $_code = "'+payment_code+'";',
				'protected $_isOffline = true;'
			])

		payment_class.add_method(Phpmethod(
			'isAvailable',
			params=[
				'\\Magento\\Quote\\Api\\Data\\CartInterface $quote = null'
			],
			body="return parent::isAvailable($quote);" 
		))
	
		self.add_class(payment_class)

		payment_file = 'etc/payment.xml'

		payment_xml = Xmlnode('payment',attributes={'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance","xsi:noNamespaceSchemaLocation":"urn:magento:module:Magento_Payment:etc/payment.xsd"},nodes=[
			Xmlnode('groups',nodes=[
				Xmlnode('group',attributes={'id':'offline'}, nodes=[
					Xmlnode('label',node_text='Offline Payment Methods')
				])
			]),
			Xmlnode('methods',nodes=[
				Xmlnode('method',attributes={'name':payment_code},nodes=[
					Xmlnode('allow_multiple_address',node_text='1'),
				])
			])
		]);

		self.add_xml(payment_file, payment_xml)

		config_file = 'etc/config.xml'

		config = Xmlnode('config',attributes={'xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Store:etc/config.xsd"},nodes=[
			Xmlnode('default',nodes=[
				Xmlnode('payment',nodes=[
					Xmlnode(payment_code,nodes=[
						Xmlnode('active',node_text='1'),
						Xmlnode('model',node_text= payment_class.class_namespace),
						Xmlnode('order_status',node_text='pending'),
						Xmlnode('title',node_text=method_name),
						Xmlnode('allowspecific',node_text='0'),
						Xmlnode('group',node_text='Offline'),
					])
				])
			])
		]);

		self.add_xml(config_file, config)

		system_file = 'etc/adminhtml/system.xml'

		system = Xmlnode('config', attributes={'xsi:noNamespaceSchemaLocation':"urn:magento:module:Magento_Config:etc/system_file.xsd"}, nodes=[
				Xmlnode('system',  nodes=[
					Xmlnode('section',attributes={'id':'payment','sortOrder':1000,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
						Xmlnode('group', attributes={'id':payment_code,'sortOrder':10,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
							Xmlnode('label',node_text=method_name),
							Xmlnode('field', attributes={'id':'active','type':'select','sortOrder':10,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text='Enabled'),
								Xmlnode('source_model',node_text='Magento\\Config\\Model\\Config\\Source\\Yesno'),
							]),
							Xmlnode('field', attributes={'id':'title','type':'text','sortOrder':20,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text='Title'),
							]),
							Xmlnode('field', attributes={'id':'order_status','type':'select','sortOrder':30,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text='New Order Status'),
								Xmlnode('source_model',node_text='Magento\\Sales\\Model\\Config\\Source\\Order\\Status\\NewStatus'),
							]),
							Xmlnode('field', attributes={'id':'allowspecific','type':'allowspecific','sortOrder':40,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text='Payment from Applicable Countries'),
								Xmlnode('source_model',node_text='Magento\\Payment\\Model\Config\\Source\\Allspecificcountries'),
							]),
							Xmlnode('field', attributes={'id':'specificcountry','type':'multiselect','sortOrder':50,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text='Payment from Applicable Countries'),
								Xmlnode('source_model',node_text='Magento\\Directory\\Model\\Config\\Source\\Country'),
								Xmlnode('can_be_empty',node_text='1'),
							]),
							Xmlnode('field', attributes={'id':'sort_order','type':'text','sortOrder':60,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text='Sort Order'),
							]),
							Xmlnode('field', attributes={'id':'instructions','type':'textarea','sortOrder':70,'showInWebsite':1,'showInStore':1,'showInDefault':1,'translate':'label'},match_attributes={'id'},nodes=[
								Xmlnode('label',node_text='Instructions'),
							]),
						])	
					])
				])
		])

		self.add_xml(system_file,system)

		layout_file = 'view/frontend/layout/checkout_index_index.xml'

		layout_payment = Xmlnode('item',attributes={'name':'offline-payments','xsi:type':'array'},nodes=[
			Xmlnode('item',attributes={'name':'component','xsi:type':'string'},node_text='Magento_OfflinePayments/js/view/payment/offline-payments'),
			Xmlnode('item',attributes={'name':'methods','xsi:type':'array'},nodes=[
				Xmlnode('item',attributes={'name':payment_code,'xsi:type':'array'},nodes=[
					Xmlnode('item',attributes={'name':'isBillingAddressRequired','xsi:type':'boolean'},node_text='true')
				])
			])
		])

		layout_item = Xmlnode('item',attributes={'name':'components','xsi:type':'array'},nodes=[
			Xmlnode('item',attributes={'name':'checkout','xsi:type':'array'},nodes=[
				Xmlnode('item',attributes={'name':'children','xsi:type':'array'},nodes=[
					Xmlnode('item',attributes={'name':'steps','xsi:type':'array'},nodes=[
						Xmlnode('item',attributes={'name':'children','xsi:type':'array'},nodes=[
							Xmlnode('item',attributes={'name':'billing-step','xsi:type':'array'},nodes=[
								Xmlnode('item',attributes={'name':'children','xsi:type':'array'},nodes=[
									Xmlnode('item',attributes={'name':'payment','xsi:type':'array'},nodes=[
										Xmlnode('item',attributes={'name':'children','xsi:type':'array'},nodes=[
											Xmlnode('item',attributes={'name':'renders','xsi:type':'array'},nodes=[
												Xmlnode('item',attributes={'name':'children','xsi:type':'array'},nodes=[layout_payment])
											])
										])
									])
								])
							])
						])
					])
				])
			])
		])

		layout_base = Xmlnode('pagepage', attributes={'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",'layout':'1column', 'xsi:noNamespaceSchemaLocation':'urn:magento:framework:View/Layout/etc/page_configuration.xsd'}, nodes=[
			Xmlnode('body',nodes=[
				Xmlnode('referenceBlock',attributes={'name':'checkout.root'},nodes=[
					Xmlnode('arguments',nodes=[
						Xmlnode('argument',attributes={'name':'jsLayout','xsi:type':'array'},nodes=[layout_item])
					])
				])
			])
		])


		self.add_xml(layout_file,layout_base)

		self.add_static_file('view/frontend/web/template/payment', StaticFile(payment_code + '.html', template_file='payment/payment.tmpl',context_data={'module_name':self.module_name,'payment_code':payment_code}))
		self.add_static_file('view/frontend/web/js/view/payment', StaticFile(payment_code + '.js', template_file='payment/payment-js.tmpl',context_data={'module_name':self.module_name,'payment_code':payment_code}))
		self.add_static_file('view/frontend/web/js/view/payment/method-renderer', StaticFile(payment_code + '-method.js', template_file='payment/payment-method-js.tmpl',context_data={'module_name':self.module_name,'payment_code':payment_code}))
Beispiel #34
0
	def add(self,from_version='1.0.0', extra_params=None):

		install_schema = Phpclass('Setup\\InstallSchema',implements=['InstallSchemaInterface'],dependencies=[
			'Magento\\Framework\\Setup\\InstallSchemaInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\SchemaSetupInterface'])
		install_schema.add_method(Phpmethod('install',params=['SchemaSetupInterface $setup','ModuleContextInterface $context'],
			body='$installer = $setup;\n$installer->startSetup();',
			body_return='$setup->endSetup();',
			docstring=['{@inheritdoc}']))
	
		self.add_class(install_schema)

		install_data = Phpclass('Setup\\InstallData',implements=['InstallDataInterface'],dependencies=[
			'Magento\\Framework\\Setup\\InstallDataInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\ModuleDataSetupInterface'])
		install_data.add_method(Phpmethod('install',
			params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],
			body='//Your install script',
			docstring=['{@inheritdoc}']))
	
		self.add_class(install_data)

		update_schema = Phpclass('Setup\\UpgradeSchema',implements=['UpgradeSchemaInterface'],dependencies=[
			'Magento\\Framework\\Setup\\UpgradeSchemaInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\SchemaSetupInterface'])
		update_schema.add_method(Phpmethod('upgrade',params=['SchemaSetupInterface $setup','ModuleContextInterface $context'],
			body='$setup->startSetup();\nif (version_compare($context->getVersion(), "'+from_version+'", "<")) {\n//Your upgrade script\n}\n$setup->endSetup();\n',
			docstring=['{@inheritdoc}']))
	
		self.add_class(update_schema)

		update_data = Phpclass('Setup\\UpgradeData',implements=['UpgradeDataInterface'],dependencies=[
			'Magento\\Framework\\Setup\\UpgradeDataInterface',
			'Magento\\Framework\\Setup\\ModuleContextInterface',
			'Magento\\Framework\\Setup\\ModuleDataSetupInterface'])
		update_data.add_method(Phpmethod('upgrade',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],
			body='$setup->startSetup();\nif (version_compare($context->getVersion(), "'+from_version+'", "<")) {\n//Your upgrade script\n}\n$setup->endSetup();\n',
			docstring=['{@inheritdoc}']))
		
		self.add_class(update_data)		
Beispiel #35
0
	def add(self,attribute_label, customer_forms=False, customer_address_forms=False, customer_entity='customer', frontend_input='text',
		static_field_type='varchar', required=False, extra_params=None):

		extra_params = extra_params if extra_params else {}
		attribute_code = extra_params.get('attribute_code', None)
		if not attribute_code:
			attribute_code = attribute_label.lower().replace(' ','_')

		value_type = static_field_type if frontend_input=='static' else self.FRONTEND_INPUT_VALUE_TYPE.get(frontend_input,'int');
		source_model = "Magento\Customer\Model\ResourceModel\Address\Attribute\Source\Country" if frontend_input=='select' or frontend_input == 'multiselect' else 'Null'

		forms_array = customer_forms if customer_entity == 'customer' else customer_address_forms
		forms_array = forms_array if forms_array else []
		forms_array = forms_array if isinstance(forms_array, list) else [forms_array]

		if forms_array:
			forms_php_array = "'" + "','".join(forms_array) + "'"
		elif customer_entity=='customer' and customer_forms==False:
			forms_php_array = "'adminhtml_customer','adminhtml_checkout','customer_account_create','customer_account_edit'"
		else :
			forms_php_array = None

		template = 'customerattribute.tmpl' if customer_entity=='customer' else 'customeraddressattribute.tmpl' 
		templatePath = os.path.join(os.path.dirname(__file__), '../templates/attributes/'+template)

		with open(templatePath, 'rb') as tmpl:
			template = tmpl.read().decode('utf-8')

		methodBody = template.format(
			attribute_code=attribute_code,
			attribute_label=attribute_label,
			value_type=value_type,
			frontend_input=frontend_input,
			required = required,
			sort_order = extra_params.get('sort_order','333') if extra_params.get('sort_order','333') else '333',
			visible =  extra_params.get('visible','true'),
			source_model = source_model
		)

		install_data = Phpclass(
			'Setup\\InstallData',
			implements=['InstallDataInterface'],
			dependencies=[
				'Magento\\Framework\\Setup\\InstallDataInterface',
				'Magento\\Framework\\Setup\\ModuleContextInterface',
				'Magento\\Framework\\Setup\\ModuleDataSetupInterface',
				'Magento\\Customer\\Model\\Customer',
				'Magento\\Customer\\Setup\\CustomerSetupFactory'
				]
		)

		install_data.attributes.append('private $customerSetupFactory;')
		
		install_data.add_method(Phpmethod(
			'__construct',
			params=[
				'CustomerSetupFactory $customerSetupFactory'
			],
			body="$this->customerSetupFactory = $customerSetupFactory; \n$this->attributeSetFactory = $attributeSetFactory;"
		))

		install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body="$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);"))
		install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body=methodBody))

		if forms_php_array:
			attribute_form_data = "$attribute = $customerSetup->getEavConfig()->getAttribute('"+customer_entity+"', '"+attribute_code+"')->addData(['used_in_forms' => ["+forms_php_array+"]]);\n$attribute->save();"
			install_data.add_method(Phpmethod('install',params=['ModuleDataSetupInterface $setup','ModuleContextInterface $context'],body=attribute_form_data))

		self.add_class(install_data)	

		extension_attributes_file = 'etc/extension_attributes.xml'

		api_class = "Magento\Customer\Api\Data\CustomerInterface"  if customer_entity=='customer' else 'Magento\Customer\Api\Data\AddressInterface'
	
		extension_attributes_xml = Xmlnode('config',attributes={'xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','xsi:noNamespaceSchemaLocation':"urn:magento:framework:Api/etc/extension_attributes.xsd"},nodes=[
			Xmlnode('extension_attributes',attributes={'for':api_class},match_attributes={'for'},nodes=[
				Xmlnode('attribute',attributes={
					'code':attribute_code,
					'type':'string'
				})
			])
		])

		self.add_xml(extension_attributes_file, extension_attributes_xml)