Parameters in JOB Laravel class 5.8

Asked

Viewed 202 times

0

Error passing variable as parameter in constructor of an Laravel job

Too few arguments to function App\Jobs\ImportDocumentJob::__construct  
  (), 0 passed in /Applications/MAMP/htdocs/maximus-rev/app/Console/Ker  
  nel.php on line 57 and exactly 1 expected  

Layer Services


    /**
     * Owner Services
     *
     * @var OwnerServices
     */
    protected $ownerServices;

    /**
     * Product Services
     *
     * @var OwnerServices
     */
    protected $productServices;

    /**
     * Document Services
     *
     * @var DocumentServices
     */
    protected $documentServices;

    /**
     * Product Services
     *
     * @var DocumentProductServices
     */
    protected $documentProductServices;



    public function __construct(OwnerServices $ownerServices, ProductServices $productServices, DocumentServices $documentServices, DocumentProductServices $documentProductServices) {
        $this->ownerServices = $ownerServices;
        $this->productServices = $productServices;
        $this->documentServices = $documentServices;
        $this->documentProductServices = $documentProductServices;
    }

    /**
     * Funcao responsavel por importar os dados no sistema
     *
     * @param [type] $request Array que deverá conter a seguinte estrutura: 
     *               $request = [
     *                  'owner' => [
     *                      'code'          => (string 30)      'Código de Identificacao'        (* Obrigatório),
     *                      'name'          => (string 100)     'Nome'                          (* Obrigatório),
     *                      'complement',   => (string 255)     'Complemento'                   (Opcional),
     *                      'document',     => (string 14)      'CNPJ'                           (* Obrigatório)
     *                  ], 
     *                  'document' => [
     *                      'code'              => (string 44)      'Chave Eletronica/Numero Tíquete'   (* Obrigatório)
     *                      'serie'             => (string 20)      'Serie NFe'                         (* Ogriatorio somente para produtos FERRO GUSA)
     *                      'document_number'   => (string 20)      'Numero NFe / Número Tíquete'       (* Obrigatório)
     *                      'observation'       => (string MAX)     'Detalhes Adicionais'               (Opcional)
     *                      'content_file'       => (string MAX)     'Conteudo do Arquivo Importado'     (Opcional)    
     *                  ],
     *                  'product' => [
     *                      'code'          => (string 30)      'Código de Identificacao'        (* Obrigatório),
     *                      'name'          => (string 100)     'Nome'                          (* Obrigatório),
     *                      'complement'    => (string 255)     'Complemento'                   (Opcional),
     *                      'amount'        => (decimal 5,2)    'Quantidade'                   (Opcional)
     *                      'unit_price'    => (decimal 10,2)   'Preco Unitario'                (Opcional) 
     *                      'gross_weight'  => (decimal 5,2)    'Peso Bruto'                   (Opcional),
     *                      'net_weight'    => (decimal 5,2)    'Peso Liquido'                 (* Obrigatório),
     *                      'lot'           => (string 20)      'Lote'                           (* Obrigatorio somente para produtos FERRO GUSA)
     *                  ]
     *                      
     *               ];
     * @return void
     */
    public  function updateOrCreate($request) {

        \Illuminate\Support\Facades\Log::info('Services chamado');

        $lstPrincipal=null;

        try {



            // verifica se existe a tag 'owner'
            if(Arr::has($request, 'owner')){

                // envia para cadastro
                $result = $this->ownerServices->updateOrCreate($request['owner']);

                // verificar se cadastrou corretamente
                if($result['success']){
                    // adiciona ao array principal
                    $lstPrincipal = Arr::add($lstPrincipal, 'owner_id', $result['data']['id']);
                }
            }

            // verifica se existe a tag 'document' 
            if(Arr::has($request, 'document')){

                // adiciona a tag 'owner_id' ao array
                $temp = Arr::add($request['document'], 'owner_id', $lstPrincipal['owner_id']);

                // envia para cadastro
                $result = $this->documentServices->updateOrCreate($temp);

                // verificar se cadastrou corretamente
                if($result['success']){
                    // adiciona ao array principal
                    $lstPrincipal = Arr::add($lstPrincipal, 'document_id', $result['data']['id']);
                }
            }


            // verifica se existe a 'product'
            // adiciona os valores dos produtos da NF 
            if(Arr::has($request, 'product')){

                // envia para cadastro
                $result = $this->productServices->updateOrCreate($request['product']);

                // verificar se cadastrou corretamente.
                if($result['success']){
                    // adiciona ao array principal
                    $lstPrincipal = Arr::add($lstPrincipal, 'product_id', $result['data']['id']);
                }

                // adiciona a tag 'document_id' e 'product_id' ao array
                $temp = Arr::add($request['product'], 'product_id', $lstPrincipal['product_id']);
                $temp = Arr::add($temp, 'document_id', $lstPrincipal['document_id']);

                // cadastra os produtos na tabela de produtos da NFe
                $dados = $this->documentProductServices->updateOrCreate($temp);

            }

            // retorna resultado da gravacao
            return [
                'success'   => true,
                'message'   => 'record created/updated successfully',
                'total'     => null,
                'data'      => null,
            ];
        } catch (\Throwable $th) {

            return [
                'success'   => false,
                'message'   => $th,
                'total'     => null,
                'data'      => null,
            ];
        }
    }
}

My job

class ImportDocumentJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $services;
    public function __construct(ImportDocumentsServices $services)
    {
        $this->services = $services;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {


        $lst = \Illuminate\Support\Facades\File::allFiles(storage_path('app/xml/'));

        $dados=null;
        foreach ($lst as $key => $value) {

            $fullPath = (string)$value;

            // verifica somente arquivos com extensao xml
            if(\File::extension($fullPath) == 'xml') {
                // carrega o arquivo xml
                $xml = \simplexml_load_file($fullPath);

                // verifica se o documento é um XMl de NFE
                if(isset($xml->NFe)) {

                    // montagem do array para cadastro
                    $request = [
                        'owner' => [
                            'code'              => (string)$xml->NFe->infNFe->emit->CNPJ,
                            'name'              => (string)$xml->NFe->infNFe->emit->xNome,
                            'complement'        => (string)$xml->NFe->infNFe->emit->xFant,
                            'document'          => (string)$xml->NFe->infNFe->emit->CNPJ                          
                        ], 
                        'document' => [
                            'code'              => str_replace("NFe","",(string)$xml->NFe->infNFe->attributes()->Id),
                            'serie'             => (string)$xml->NFe->infNFe->ide->serie,
                            'document_number'   => (string)$xml->NFe->infNFe->ide->cNF,
                            'observation'       => (string)$xml->NFe->infNFe->infAdic->infCpl,
                            'content_file'      => \file_get_contents($fullPath),
                        ],
                        'product' => [
                            'code'              => (string)$xml->NFe->infNFe->det->prod->cProd,
                            'name'              => (string)$xml->NFe->infNFe->det->prod->xProd,
                            'complement'        => null,
                            'amount'            => null,
                            'unit_price'        => null,
                            'gross_weight'      => null,
                            'net_weight'        => (floatval((string)$xml->NFe->infNFe->det->prod->qCom)*1000),
                            'lot'               => (string)$xml->NFe->infNFe->transp->vol->marca                       
                        ]    
                    ];

                    $this->services->updateOrCreate($request);

                } 
            }
        }
    }
}

Kernel class for Job call

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {





        // Importacao automatica de arquivos XML 
        $schedule->job(new \App\Jobs\ImportDocumentJob)->everyMinute();

        // $schedule->command('inspire')
        //          ->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

2 answers

0


Solution:

Instead of passing the service class in the constructor parameter, simply pass as parameter in the Handle function

class ImportDocumentJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $services;

    public function __construct()
    {

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(ImportDocumentsServices $services)
    {
        $this->services = $services;

        $lst = \Illuminate\Support\Facades\File::allFiles(storage_path('app/xml/'));

        $dados=null;
        foreach ($lst as $key => $value) {

            $fullPath = (string)$value;

            // verifica somente arquivos com extensao xml
            if(\File::extension($fullPath) == 'xml') {
                // carrega o arquivo xml
                $xml = \simplexml_load_file($fullPath);

                // verifica se o documento é um XMl de NFE
                if(isset($xml->NFe)) {

                    // montagem do array para cadastro
                    $request = [
                        'owner' => [
                            'code'              => (string)$xml->NFe->infNFe->emit->CNPJ,
                            'name'              => (string)$xml->NFe->infNFe->emit->xNome,
                            'complement'        => (string)$xml->NFe->infNFe->emit->xFant,
                            'document'          => (string)$xml->NFe->infNFe->emit->CNPJ                          
                        ], 
                        'document' => [
                            'code'              => str_replace("NFe","",(string)$xml->NFe->infNFe->attributes()->Id),
                            'serie'             => (string)$xml->NFe->infNFe->ide->serie,
                            'document_number'   => (string)$xml->NFe->infNFe->ide->cNF,
                            'observation'       => (string)$xml->NFe->infNFe->infAdic->infCpl,
                            'content_file'      => \file_get_contents($fullPath),
                        ],
                        'product' => [
                            'code'              => (string)$xml->NFe->infNFe->det->prod->cProd,
                            'name'              => (string)$xml->NFe->infNFe->det->prod->xProd,
                            'complement'        => null,
                            'amount'            => null,
                            'unit_price'        => null,
                            'gross_weight'      => null,
                            'net_weight'        => (floatval((string)$xml->NFe->infNFe->det->prod->qCom)*1000),
                            'lot'               => (string)$xml->NFe->infNFe->transp->vol->marca                       
                        ]    
                    ];

                    $this->services->updateOrCreate($request);

                } 
            }
        }
    }
}
```

0

Hello! I noticed that the Importdocumentjob class has a constructor that waits as parameter:

ImportDocumentsServices $services

Thus, the instantiation of the object referred to this class should be:

new \App\Jobs\ImportDocumentJob($services)

I hope I’ve helped!

Browser other questions tagged

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