How to create an instance of a Prestashop module within a controller?

Asked

Viewed 259 times

0

I would like to create an instance inside the control of a particular module to be able to validate it in the Prestashop authenticator pattern:

I am using Prestashop for the version: 1.6.1.3

Path to Authentication Control: project/override/controllers/front/AuthController.php

protected function processSubmitAccount()
    {
        Hook::exec('actionBeforeSubmitAccount');
        $this->create_account = true;
        $citizen = trim(Tools::getValue('citizen'));

        $type_citizen = ($citizen == 1) ? trim(Tools::getValue('cnpj')) : trim(Tools::getValue('cpf'));

        if ($citizen == '1') {
            $data = array(
                'cnpj' => $type_citizen
            );
        } else {
            $data = array(
                'cpf' => $type_citizen
            );
        }
        /* gostaria de instanciar o módulo aqui para 
           pegar os métodos internos dele e validar
           o formulário de autenticação, com CPF e CNPJ.
      /*  $cpfmodule = $this->context->link->getModuleLink('cpfmodule', 'AuthController', array('process' => $data)); */
//
        if ($citizen == 1) {
            if (!$cpfmodule->cnpjValidate($data['cnpj'])) {
                $this->errors[] = Tools::displayError('CNPJ Inválido.');
            }
        } else {
            if (!$cpfmodule->cpfValidation($data['cpf'])) {
                $this->errors[] = Tools::displayError('CPF Inválido.');
            }
        }
... (resumido)

This is the CPF module class:

<?php
/**
  * Customer's Registration
  * @category Tools
  *
  * @author Ehinarr Elkader/ PrestashopBr
  * @copyright Ehinarr Elhader
  * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
  * @version 1.3
  */

class cpfmodule extends Module
{
    private $_html = '';
    private $_postErrors = array();

    private $required;
    private $webservice;
    private $byjgPwd;
    private $byjgUser;
    private $bcKey;
    private $autoCepKey;
    private $autoCepUser;

    public function __construct()
    {
        $this->name    = 'cpfmodule';
        $this->tab     = 'Ehinarr Solutions';
        $this->version = '1.3';
        $this->path    = $this->_path;

        if (Configuration::get('CPFMODULE_REQUIRED'))
            $this->required = Configuration::get('CPFMODULE_REQUIRED');
        if (Configuration::get('CPFMODULE_WEBSERVICE'))
            $this->webservice = Configuration::get('CPFMODULE_WEBSERVICE');
        if (Configuration::get('CPFMODULE_BYJGPWD'))
            $this->byjgPwd = Configuration::get('CPFMODULE_BYJGPWD');
        if (Configuration::get('CPFMODULE_BYJGUSER'))
            $this->byjgUser = Configuration::get('CPFMODULE_BYJGUSER');
        if (Configuration::get('CPFMODULE_BCKEY'))
            $this->bcKey = Configuration::get('CPFMODULE_BCKEY');
        if (Configuration::get('CPFMODULE_AUTOCEPUSER'))
            $this->autoCepUser = Configuration::get('CPFMODULE_AUTOCEPUSER');
        if (Configuration::get('CPFMODULE_AUTOCEPKEY'))
            $this->autoCepKey = Configuration::get('CPFMODULE_AUTOCEPKEY');

        parent::__construct();

        $this->page             = basename(__FILE__, '.php');
        $this->displayName      = $this->l('CPF Module');
        $this->description      = $this->l('Adds CPF and CNPJ fields in customer\'s registration form.');

    }

    public function install()
    {
        if (!parent::install()
            OR !$this->registerHook('createAccountTop')
            OR !$this->registerHook('createAccount')
            OR !$this->registerHook('authentication')
            OR !$this->registerHook('adminCustomers')
            OR !$this->installDB()
            OR !$this->installModuleTab()
            OR !Configuration::updateValue('CPFMODULE_REQUIRED', '1')
            OR !Configuration::updateValue('CPFMODULE_WEBSERVICE', 'RV')
            OR !Configuration::updateValue('CPFMODULE_BYJGPWD', '')
            OR !Configuration::updateValue('CPFMODULE_BYJGUSER', '')
            OR !Configuration::updateValue('CPFMODULE_BCKEY', '')
            OR !Configuration::updateValue('CPFMODULE_AUTOCEPUSER', '')
            OR !Configuration::updateValue('CPFMODULE_AUTOCEPKEY', '')
            )
            return false;
            return true;
    }

    public function uninstall()
    {
       if (!parent::uninstall()
       OR !Configuration::deleteByName('CPFMODULE_REQUIRED')
       OR !Configuration::deleteByName('CPFMODULE_WEBSERVICE')
       OR !Configuration::deleteByName('CPFMODULE_BYJGPWD')
       OR !Configuration::deleteByName('CPFMODULE_BYJGUSER')
       OR !Configuration::deleteByName('CPFMODULE_BCKEY')
       OR !Configuration::deleteByName('CPFMODULE_AUTOCEPUSER')
       OR !Configuration::deleteByName('CPFMODULE_AUTOCEPKEY')
       OR !$this->uninstallModuleTab()
           //OR !$this->uninstallDB()
           )
          return false;
          return true;
    }

    private function installDB()
    {
        Db::getInstance()->Execute('
        CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'cpfmodule_data` (
            `id_record` INT NOT NULL AUTO_INCREMENT,
            `doc` VARCHAR (14),
            `type`  VARCHAR (4),
            `idt` VARCHAR (15),
            `id_customer` INT NOT NULL,
            PRIMARY KEY (`id_record`)
         ) ENGINE = MYISAM;');
           return true;
    }

    private function uninstallDB()
    {
        Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'cpfmodule_data`;');
        return true;
    }

    private function _postValidation()
    {
        if (Tools::isSubmit('btnSubmit'))
        {
            if (Tools::isEmpty($_POST['required']))
            $this->_postErrors[] = $this->l('Please choose if required or not.');
            if(Tools::getValue('webservice') == 'BYJG')
            {
                if(Tools::isEmpty($_POST['byjgUser']))
                $this->_postErrors[] = $this->l('Please ByJG User is required.');
                if(Tools::isEmpty($_POST['byjgPwd']))
                $this->_postErrors[] = $this->l('Please ByJG Passwordr is required.');
            }
            if(Tools::getValue('webservice') == 'BC')
            {
                if(Tools::isEmpty($_POST['bcKey']))
                $this->_postErrors[] = $this->l('Please Buscar CEP key is required.');
            }
            if(Tools::getValue('webservice') == 'AC')
            {
                if(Tools::isEmpty($_POST['autoCepUser']))
                $this->_postErrors[] = $this->l('Please AutoCep User is required.');
                if(Tools::isEmpty($_POST['autoCepKey']))
                $this->_postErrors[] = $this->l('Please AutoCep Key is required.');
            }

        }
    }

    private function _postProcess()
    {
       if (Tools::isSubmit('btnSubmit'))
       {
           Configuration::updateValue('CPFMODULE_REQUIRED',Tools::getValue('required'));
           Configuration::updateValue('CPFMODULE_WEBSERVICE',Tools::getValue('webservice'));
           Configuration::updateValue('CPFMODULE_BYJGPWD',Tools::getValue('byjgPwd'));
           Configuration::updateValue('CPFMODULE_BYJGUSER',Tools::getValue('byjgUser'));
           Configuration::updateValue('CPFMODULE_BCKEY',Tools::getValue('bcKey'));
           Configuration::updateValue('CPFMODULE_AUTOCEPUSER',Tools::getValue('autoCepUser'));
           Configuration::updateValue('CPFMODULE_AUTOCEPKEY',Tools::getValue('autoCepKey'));
       }

        $this->_html .= Module::displayConfirmation($this->l('Settings updated'));
    }



    public function hookCreateAccount($params)
    {
        if (!$this->active)
        return ;

        $newCustomer = $params['newCustomer'];

        if (!Validate::isLoadedObject($newCustomer))
        return false;

        $postVars = $params['_POST'];

        if (empty($postVars))
        return false;

        if($postVars['citizen'] == '2')
        {
            $doc = (!Tools::isEmpty($postVars['cpf']) ? preg_replace("/[^0-9]/", "", $postVars['cpf']) : 0);
            $type = 'cpf';
            $idt  = (!Tools::isEmpty($postVars['rg']) ? preg_replace("/[^0-9]/", "", $postVars['rg']) : 0);
        }
        elseif($postVars['citizen'] == '1')
        {
            $doc = (!Tools::isEmpty($postVars['cnpj']) ? preg_replace("/[^0-9]/", "", $postVars['cnpj']) : 0);
            $type = 'cnpj';
            $idt  = (!Tools::isEmpty($postVars['ie']) ? preg_replace("/[^0-9]/", "", $postVars['ie']) : 0);
        }

        $data = array('doc' => pSQL($doc), 'type' => pSQL($type), 'idt' => pSQL($idt), 'id_customer' => pSQL($newCustomer->id));
        Db::getInstance()->autoExecute(_DB_PREFIX_.'cpfmodule_data',$data , 'INSERT');

        global $cookie;

        $cookie->__set('number',$doc);
        $cookie->__set('type',$type);
        $cookie->__set('idt',$idt);

        return true;
    }

    public function cpfValidation($item)
    {
        $nulos = array("12345678909","11111111111","22222222222","33333333333","44444444444","55555555555", "66666666666", "77777777777",
            "88888888888", "99999999999", "00000000000");
        /* Retira todos os caracteres que nao sejam 0-9 */
        $cpf = preg_replace("/[^0-9]/", "", $item);

        if (strlen($cpf) <> 11)
        {
             $err =  $this->l('O numero deve conter 11 dígitos!');
             return $err;
         }
        if (!is_numeric($cpf))
        {
            $err =  $this->l('Apenas numeros são aceitos!');
            return $err;
        }
        /*Retorna falso se houver letras no cpf */

        if (!(preg_match("/[0-9]/", $cpf)))
        {
            $err =  $this->l('Apenas numeros são aceitos!');
            return $err;
        }

        /* Retorna falso se o cpf for nulo*/
        if (in_array($cpf, $nulos)) {
             $err =  $this->l('Número nulo. Verifique por favor!');
             return $err;
        }

        if($this->checkDuplicate('doc',$cpf) == true) {
             $err =  $this->l('Este número já está cadastrado!');
             return $err;
        }

        /* Calcula o penúltimo dígito verificador */
        $acum = 0;
        for ($i = 0; $i < 9; $i++) {
            $acum += $cpf[$i] * (10 - $i);
        }

        $x = $acum % 11;
        $acum = ($x > 1) ? (11 - $x) : 0;
        /* Retorna falso se o digito calculado eh diferente do passado na string */
        if ($acum != $cpf[9]) {
             $err =  $this->l('Número inválido. Verifique por favor!');
             return $err;
        }
        /*Calcula o último dígito verificador*/
        $acum = 0;
        for ($i = 0; $i < 10; $i++) {
            $acum += $cpf[$i] * (11 - $i);
        }

        $x = $acum % 11;
        $acum = ($x > 1) ? (11 - $x) : 0;
        /* Retorna falso se o digito calculado eh diferente do passado na string */
        if ($acum != $cpf[10]) {
             $err =  $this->l('Número inválido. Verifique por favor!');
             return $err;
        }

        /* Retorna verdadeiro se o cpf é valido */
        return '1';
    }

    function cnpjValidate($str) 
    {
        $nulos = array("12345678909123","11111111111111","111111111111111","22222222222222","222222222222222","33333333333333","333333333333333","44444444444444","444444444444444","55555555555555", "555555555555555","66666666666666", "666666666666666","77777777777777", "777777777777777",
            "88888888888888", "888888888888888", "99999999999999","999999999999999", "00000000000000", "000000000000000");

        if (!preg_match('|^(\d{2,3})\.?(\d{3})\.?(\d{3})\/?(\d{4})\-?(\d{2})$|', $str, $matches)) {
            $err =  $this->l('Numero inválido. Verifique por favor!');
            return $err;
        }
        if ($this->checkDuplicate('doc',$str) == true) {
             $err =  $this->l('Este numero já está cadastrado!');
             return $err;
        }
        if (in_array($str, $nulos)) {
             $err =  $this->l('Numero nulo. Verifique por favor!');
             return $err;
        }

        array_shift($matches);
        $str = implode('', $matches);
        if (strlen($str) > 14)
        $str = substr($str, 1);

        $sum1 = 0;
        $sum2 = 0;
        $sum3 = 0;
        $calc1 = 5;
        $calc2 = 6;

        for ($i=0; $i <= 12; $i++) {
            $calc1 = $calc1 < 2 ? 9 : $calc1;
            $calc2 = $calc2 < 2 ? 9 : $calc2;

            if ($i <= 11)
            $sum1 += $str[$i] * $calc1;

            $sum2 += $str[$i] * $calc2;
            $sum3 += $str[$i];
            $calc1--;
            $calc2--;
        }

        $sum1 %= 11;
        $sum2 %= 11;

        $result = ($sum3 && $str[12] == ($sum1 < 2 ? 0 : 11 - $sum1) && $str[13] == ($sum2 < 2 ? 0 : 11 - $sum2)) ? true : false;

        if (!$result) {
            $err =  $this->l('Número inválido. Verifique por favor!');
            return $err;
        }
        return '1';
    }
    /* ---- obs: removi os outros métodos para reduzir o código ---- */
}
?>

1 answer

0


I solved the problem by doing so:

require_once './modules/cpfmodule/cpfmodule.php';

$cpfmodule = new cpfmodule();

edited so far:

I further improved the code above, doing so:

 $cpfmodule = Module::getInstanceByName('cpfmodule');

  if ($cpfmodule  instanceof cpfmodule) {
     //aqui a utilização
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.