Magento2 | PWA | GraphQL

Create Custom CLI command to create customers with supplied parameters Magento2


In this post we will check how to Create Custom CLI command in Magento2 and create customers with supplied parameters in that command arguments. 

You can find complete module on Github at Magelearn_CustomerCreateCommand



Let's start it by creating custom module.

Create folder inside app/code/Magelearn/CustomerCreateCommand

Add registration.php file in it:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magelearn_CustomerCreateCommand',
    __DIR__
);

Add composer.json file in it:

{
    "name": "magelearn/module-customer-create-command",
    "description": "Magento 2 Module which creates customer via command line interface with supplied parameters.",
    "type": "magento2-module",
    "require": {},
    "authors": [
        {
            "name": "vijay rami",
            "email": "vijaymrami@gmail.com"
        }
    ],
    "license": "proprietary",
    "minimum-stability": "dev",
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\CustomerCreateCommand\\": ""
        }
    }
}

Add etc/module.xml file in it:

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_CustomerCreateCommand" setup_version="1.0.0"/>
</config>

Now first we will add entry in di.xml file. To add command in Magento Command list.
Add file at etc/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Console\CommandList">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="create_customer_command" xsi:type="object">Magelearn\CustomerCreateCommand\Console\Command\Create</item>
            </argument>
        </arguments>
    </type>
</config>

Now as per highlighted code above we will add our command list object file.
Add file at Console/Command/Create.php

<?php

namespace Magelearn\CustomerCreateCommand\Console\Command;

use Magento\Framework\App\State;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Magelearn\CustomerCreateCommand\Helper\Customer;

/**
 * Create Command class
 */
class Create extends Command
{
    /**
     * @var Customer
     */
    private $customerHelper;

    /**
     * @var State
     */
    private $state;

    /**
     * Create constructor.
     * @param Customer $customerHelper
     * @param State $state
     */
    public function __construct(
        Customer $customerHelper,
        State $state
    ) {
        $this->customerHelper = $customerHelper;
        $this->state = $state;
        parent::__construct();
    }

    /**
     * magelearn:customer:create
     *   [-f|--customer-firstname CUSTOMER-FIRSTNAME][REQUIRED]
     *   [-l|--customer-lastname CUSTOMER-LASTNAME][REQUIRED]
     *   [-e|--customer-email CUSTOMER-EMAIL][REQUIRED]
     *   [-p|--customer-password CUSTOMER-PASSWORD][REQUIRED]
     *   [-w|--website WEBSITE][REQUIRED]
     *   [-s|--send-email [SEND-EMAIL]][OPTIONAL]
     *   [-ns|--newsletter-subscribe [NEWSLETTER-SUBSCRIBE]][OPTIONAL]
     *
     * php bin/magento magelearn:customer:create -f "Vijay" -l "Rami" -e "vijay.rami@gmail.com" -p "test123" -w 1
     * php bin/magento magelearn:customer:create -f "Vijay" -l "Rami" -e "vijay.rami@gmail.com" -p "test123" -w 1 -s 1 --newsletter-subscribe 1
     * @param InputInterface $input
     * @param OutputInterface $output
     * @throws \Magento\Framework\Exception\LocalizedException
     * @return int|void|null
     * 
     * Style the output text by using <error>, <info>, or <comment>
     * For More Info check at https://symfony.com/doc/current/console/coloring.html
     */
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ) {
        $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_GLOBAL);
        $output->writeln('<info>Creating new user</info>');
        $this->customerHelper->setData($input);

        $customer = $this->customerHelper->createCustomer();
        
        if ($customer && $customer->getId()) {
            $output->writeln("<info>Created new user</info>");
            $output->writeln((string) __("<comment>User ID: %1</comment>", $customer->getId()));
            $output->writeln((string) __("<comment>First name: %1</comment>", $customer->getFirstname()));
            $output->writeln((string) __("<comment>Last name: %1</comment>", $customer->getLastname()));
            $output->writeln((string) __("<comment>Email: %1</comment>", $customer->getEmail()));
            $output->writeln((string) __("<comment>Website Id: %1</comment>", $customer->getWebsiteId()));
            if ($input->getOption(Customer::KEY_NEWSLETTER_SUBSCRIBE)) {
                $output->writeln("<comment>Subscribed to Newsletter</comment>");
            }
            if ($input->getOption(Customer::KEY_SENDEMAIL)) {
                $output->writeln("<comment>Sending Email</comment>");
            }
        } else {
            $output->writeln("<error>Problem creating new user</error>");
            if ($e = $this->customerHelper->getException()) {
                $output->writeln((string) __("<error>%1</error>", $e->getMessage()));
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName("magelearn:customer:create");
        $this->setDescription("Create new customer with supplied arguments");
        $this->setDefinition([
            new InputOption(Customer::KEY_FIRSTNAME, '-f', InputOption::VALUE_REQUIRED, '(Required) First name'),
            new InputOption(Customer::KEY_LASTNAME, '-l', InputOption::VALUE_REQUIRED, '(Required) Last name'),
            new InputOption(Customer::KEY_EMAIL, '-e', InputOption::VALUE_REQUIRED, '(Required) Email'),
            new InputOption(Customer::KEY_PASSWORD, '-p', InputOption::VALUE_REQUIRED, '(Required) Password'),
            new InputOption(Customer::KEY_WEBSITE, '-w', InputOption::VALUE_REQUIRED, '(Required) Website ID'),
            new InputOption(Customer::KEY_SENDEMAIL, '-s', InputOption::VALUE_OPTIONAL, '(Optional)(1/0) Send email (default 0)'),
            new InputOption(Customer::KEY_NEWSLETTER_SUBSCRIBE, '-ns', InputOption::VALUE_OPTIONAL, '(Optional)(1/0) Subscribe to Newsletter (default 0)')
        ]);
        parent::configure();
    }
}

Add Helper file at Helper/Customer.php

<?php

namespace Magelearn\CustomerCreateCommand\Helper;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Model\AccountConfirmation;
use Magento\Customer\Model\EmailNotificationInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\MailException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Input\Input;

/**
 * Customer Helper class
 */
class Customer extends AbstractHelper
{
    const KEY_EMAIL = 'customer-email';
    const KEY_FIRSTNAME = 'customer-firstname';
    const KEY_LASTNAME = 'customer-lastname';
    const KEY_PASSWORD = 'customer-password';
    const KEY_WEBSITE = 'website';
    const KEY_SENDEMAIL = 'send-email';
    const KEY_NEWSLETTER_SUBSCRIBE = 'newsletter-subscribe';

    /**
     * @var CustomerInterfaceFactory
     */
    private $customerInterfaceFactory;

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepositoryInterface;

    /**
     * @var EncryptorInterface
     */
    private $encryptorInterface;

    /**
     * @var Symfony\Component\Console\Input\InputInterface
     */
    private $data;

    /**
     * @var Exception
     */
    private $exception;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var EmailNotificationInterface
     */
    private $emailNotification;

    /**
     * @var AccountConfirmation
     */
    private $accountConfirmation;

    /**
     * @var EmailNotificationInterface
     */
    private $emailNotificationInterface;

    /**
     * Customer constructor.
     * @param Context $context
     * @param CustomerInterfaceFactory $customerInterfaceFactory
     * @param CustomerRepositoryInterface $customerRepositoryInterface
     * @param EncryptorInterface $encryptorInterface
     * @param LoggerInterface $logger
     * @param AccountConfirmation $accountConfirmation
     */
    public function __construct(
        Context $context,
        CustomerInterfaceFactory $customerInterfaceFactory,
        CustomerRepositoryInterface $customerRepositoryInterface,
        EncryptorInterface $encryptorInterface,
        LoggerInterface $logger,
        AccountConfirmation $accountConfirmation,
        EmailNotificationInterface $emailNotificationInterface
    ) {
        $this->customerInterfaceFactory = $customerInterfaceFactory;
        $this->customerRepositoryInterface = $customerRepositoryInterface;
        $this->encryptorInterface = $encryptorInterface;
        $this->logger = $logger;
        $this->accountConfirmation = $accountConfirmation;
        $this->emailNotificationInterface = $emailNotificationInterface;
        parent::__construct($context);
    }

    /**
     * @param Input $input
     */
    public function setData(Input $input)
    {
        $this->data = $input;
    }

    /**
     * Create Customer record
     * @return bool|\Magento\Customer\Api\Data\CustomerInterface
     */
    public function createCustomer()
    {
        $websiteId = $this->data->getOption(self::KEY_WEBSITE);
        $email = $this->data->getOption(self::KEY_EMAIL);
        $firstname = $this->data->getOption(self::KEY_FIRSTNAME);
        $lastname = $this->data->getOption(self::KEY_LASTNAME);
        
        try {
            if (!$websiteId || !$email || !$firstname || !$lastname) {
                throw new LocalizedException(__("One or more parameters missing"));
            }

            if (!\Zend_Validate::is(trim($firstname), 'NotEmpty')) {
                throw new LocalizedException(__("Invalid first name"));
            }
            
            if (!\Zend_Validate::is(trim($lastname), 'NotEmpty')) {
                throw new LocalizedException(__("Invalid last name"));
            }

            if (!\Zend_Validate::is(trim($email), 'EmailAddress')) {
                throw new LocalizedException(__("Invalid email address"));
            }

            if (!is_numeric($websiteId)) {
                throw new LocalizedException(__("Invalid website ID"));
            }

            $customer = $this->customerInterfaceFactory
                ->create()
                ->setWebsiteId((int) $websiteId)
                ->setEmail($email)
                ->setFirstname($firstname)
                ->setLastname($lastname);
        
            $hashedPassword = $this->encryptorInterface->getHash($this->data->getOption(self::KEY_PASSWORD), true);
            
            if ($this->data->getOption(self::KEY_NEWSLETTER_SUBSCRIBE)) {
                $extensionAttributes = $customer->getExtensionAttributes();
                $extensionAttributes->setIsSubscribed(true);
                $customer->setExtensionAttributes($extensionAttributes);
            }
            
            $customer = $this->customerRepositoryInterface->save($customer, $hashedPassword);
            if ($this->data->getOption(self::KEY_SENDEMAIL)) {
                $this->sendEmailConfirmation($customer, null, $hashedPassword);
            }
            $this->exception = false;
            return $customer;
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->exception = $e;
            return false;
        }
    }

    /**
     * Send Email Confirmation
     * @param CustomerInterface $customer
     * @param string $redirectUrl
     * @param string $hash
     */
    protected function sendEmailConfirmation(CustomerInterface $customer, $redirectUrl = '', $hash = '')
    {
        try {
            $templateType = EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED;
            if ($this->isConfirmationRequired($customer) && $hash != '') {
                $templateType = EmailNotificationInterface::NEW_ACCOUNT_EMAIL_CONFIRMATION;
            } elseif ($hash == '') {
                $templateType = EmailNotificationInterface::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD;
            }
            $this->emailNotificationInterface->newAccount(
                $customer,
                $templateType,
                $redirectUrl,
                $customer->getStoreId()
            );
        } catch (MailException $e) {
            // If we are not able to send a new account email, this should be ignored
            $this->logger->critical($e);
        } catch (\UnexpectedValueException $e) {
            $this->logger->error($e);
        }
    }

    /**
     * Is confirmation required
     * @param $customer
     * @return bool
     */
    protected function isConfirmationRequired($customer)
    {
        return $this->accountConfirmation->isConfirmationRequired(
            $customer->getWebsiteId(),
            $customer->getId(),
            $customer->getEmail()
        );
    }

    /**
     * Get exception
     * @return Exception
     */
    public function getException()
    {
        return $this->exception;
    }
}
0 Comments On "Create Custom CLI command to create customers with supplied parameters Magento2 "

Back To Top