GenerateDocxJob.php 2.1 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. protected $template;
  18. /**
  19. * Create a new job instance.
  20. *
  21. * @return void
  22. */
  23. public function __construct($vars, $count_products, $filename, $template)
  24. {
  25. $this->vars =$vars;
  26. $this->prod_count = $count_products;
  27. $this->filename = $filename;
  28. $this->template = $template;
  29. }
  30. /**
  31. * Execute the job.
  32. *
  33. * @return void
  34. */
  35. public function handle()
  36. {
  37. $tmpfile = public_path('exported/docx/' . $this->filename . '.txt');
  38. $my_template = new TemplateProcessor(storage_path('templates/' . $this->template));
  39. $my_template->cloneBlock('product_block', $this->prod_count, true, true, $this->vars);
  40. $i = 0;
  41. $total = count($this->vars);
  42. foreach ($this->vars as $k => $v){
  43. $file = public_path() . '/' . env('IMAGES_PATH') . '/' . $v;
  44. if(str_starts_with($k, 'image') && file_exists($file) && $v !== ''){
  45. $my_template->setImageValue($k, ['path' => $file, 'width' => 270, 'height' => 180]);
  46. } else {
  47. $my_template->setValue($k, $v);
  48. }
  49. if(($i++ % 50) == 0) {
  50. $f = fopen($tmpfile, 'w+');
  51. $percent = round($i / ($total / 100), 0);
  52. fwrite($f, $percent);
  53. fclose($f);
  54. }
  55. }
  56. $my_template->saveAs(public_path('exported/docx/') . $this->filename);
  57. unlink($tmpfile);
  58. Log::notice('Generation finished: ' . $i . ' / ' . $total . ' Execution time: ' . microtime(true) - LARAVEL_START);
  59. }
  60. }