Templater.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace app\components;
  3. use Yii;
  4. use yii\base\Component;
  5. use yii\helpers\FileHelper;
  6. class Templater extends Component
  7. {
  8. public $templatePath = '@app/templates/protocol.docx';
  9. private $content;
  10. public function process(array $data, $type = 'protocol', $filepath = false)
  11. {
  12. $filename = $this->createTempFile($filepath, $type);
  13. $file = new \ZipArchive();
  14. if ($file->open($filename) !== true) {
  15. throw new \Exception('Cannot open docx file');
  16. }
  17. $this->content = $file->getFromName('word/document.xml');
  18. $file->addFromString(
  19. 'word/document.xml',
  20. $this->replace($this->content, $data)
  21. );
  22. $file->close();
  23. return $filename;
  24. }
  25. private function replace($string, array $params = [])
  26. {
  27. foreach ($params as $index => $param) {
  28. $string = str_ireplace($index, $param, $string);
  29. }
  30. return $string;
  31. }
  32. private function createTempFile($filepath = false, $type)
  33. {
  34. $path = $filepath ?: Yii::getAlias('@runtime/tmp');
  35. FileHelper::createDirectory($path);
  36. $filename = "{$type}.docx";
  37. $newFilePath = $path . '/' . $filename;
  38. $tplPath = Yii::getAlias($this->templatePath);
  39. if (!file_exists($tplPath)) {
  40. throw new \Exception("Template not found: " . $tplPath);
  41. }
  42. copy($tplPath, $newFilePath);
  43. return $newFilePath;
  44. }
  45. }