GenerateDocxJob.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Jobs;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldBeUnique;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. use Illuminate\Support\Facades\Log;
  10. use PhpOffice\PhpWord\TemplateProcessor;
  11. class GenerateDocxJob implements ShouldQueue
  12. {
  13. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  14. protected $vars;
  15. protected $prod_count;
  16. protected $filename;
  17. /**
  18. * Create a new job instance.
  19. *
  20. * @return void
  21. */
  22. public function __construct($vars, $count_products, $filename)
  23. {
  24. $this->vars =$vars;
  25. $this->prod_count = $count_products;
  26. $this->filename = $filename;
  27. }
  28. /**
  29. * Execute the job.
  30. *
  31. * @return void
  32. */
  33. public function handle()
  34. {
  35. $tmpfile = public_path('exported/docx/' . $this->filename . '.txt');
  36. $my_template = new TemplateProcessor(storage_path('templates/template_maf.docx'));
  37. $my_template->cloneBlock('product_block', $this->prod_count, true, true, $this->vars);
  38. $i = 0;
  39. $total = count($this->vars);
  40. foreach ($this->vars as $k => $v){
  41. $file = public_path() . '/' . env('IMAGES_PATH') . '/' . $v;
  42. if(str_starts_with($k, 'image') && file_exists($file) && $v !== ''){
  43. $my_template->setImageValue($k, ['path' => $file, 'width' => 270, 'height' => 180]);
  44. } else {
  45. $my_template->setValue($k, $v);
  46. }
  47. if(($i++ % 50) == 0) {
  48. $f = fopen($tmpfile, 'w+');
  49. $percent = round($i / ($total / 100), 0);
  50. fwrite($f, $percent);
  51. fclose($f);
  52. }
  53. }
  54. $my_template->saveAs(public_path('exported/docx/') . $this->filename);
  55. unlink($tmpfile);
  56. Log::notice('Generation finished: ' . $i . ' / ' . $total . ' Execution time: ' . microtime(true) - LARAVEL_START);
  57. }
  58. }