2022-01-07 15:04:11 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace common\services;
|
|
|
|
|
|
|
|
|
2022-01-10 15:22:51 +03:00
|
|
|
use common\models\Document;
|
2022-01-07 15:04:11 +03:00
|
|
|
use PhpOffice\PhpWord\Exception\CopyFileException;
|
|
|
|
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
|
|
|
|
use PhpOffice\PhpWord\TemplateProcessor;
|
|
|
|
use Yii;
|
|
|
|
|
|
|
|
class DocumentService
|
|
|
|
{
|
2022-01-10 15:22:51 +03:00
|
|
|
private $model;
|
2022-01-07 15:04:11 +03:00
|
|
|
private $document;
|
2022-01-10 15:22:51 +03:00
|
|
|
private $file_title;
|
|
|
|
private $documentFieldValuesArr;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @throws CopyFileException
|
|
|
|
* @throws CreateTemporaryFileException
|
|
|
|
*/
|
|
|
|
public function __construct($modelID)
|
|
|
|
{
|
|
|
|
$this->model = Document::findOne($modelID);
|
2022-01-07 15:04:11 +03:00
|
|
|
|
2022-01-10 15:22:51 +03:00
|
|
|
$this->initDocument();
|
|
|
|
}
|
2022-01-07 15:04:11 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @throws CopyFileException
|
|
|
|
* @throws CreateTemporaryFileException
|
|
|
|
*/
|
2022-01-10 15:22:51 +03:00
|
|
|
private function initDocument()
|
2022-01-07 15:04:11 +03:00
|
|
|
{
|
2022-01-10 15:22:51 +03:00
|
|
|
$this->file_title = $this->model->title . '.docx';
|
|
|
|
|
|
|
|
$template_title = $this->model->template->template_file_name;
|
|
|
|
$this->document = new TemplateProcessor(
|
|
|
|
Yii::getAlias('@templates') . "/$template_title");
|
|
|
|
|
|
|
|
$this->documentFieldValuesArr = $this->model->documentFieldValues;
|
2022-01-07 15:04:11 +03:00
|
|
|
}
|
|
|
|
|
2022-01-10 15:22:51 +03:00
|
|
|
public function setFields()
|
2022-01-07 15:04:11 +03:00
|
|
|
{
|
2022-01-10 15:22:51 +03:00
|
|
|
foreach ($this->documentFieldValuesArr as $docFieldValue) {
|
|
|
|
$this->document->setValue(
|
|
|
|
$docFieldValue->field->field_template,
|
|
|
|
$docFieldValue->value
|
|
|
|
);
|
2022-01-07 15:04:11 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-10 15:22:51 +03:00
|
|
|
public function downloadDocument()
|
2022-01-07 15:04:11 +03:00
|
|
|
{
|
|
|
|
$this->document->saveAs($this->file_title);
|
|
|
|
|
2022-01-10 15:22:51 +03:00
|
|
|
// Имя скачиваемого файла
|
|
|
|
$downloadFile = $this->file_title;
|
|
|
|
// Контент-тип означающий скачивание
|
|
|
|
header("Content-Type: application/octet-stream");
|
|
|
|
// Размер в байтах
|
|
|
|
header("Accept-Ranges: bytes");
|
|
|
|
// Размер файла
|
|
|
|
header("Content-Length: ".filesize($downloadFile));
|
|
|
|
// Расположение скачиваемого файла
|
|
|
|
header("Content-Disposition: attachment; filename=".$downloadFile);
|
|
|
|
|
2022-01-11 00:20:54 +03:00
|
|
|
// Прочитать файл
|
2022-01-10 15:22:51 +03:00
|
|
|
readfile($downloadFile);
|
2022-01-11 00:20:54 +03:00
|
|
|
unlink($this->file_title);
|
2022-01-10 15:22:51 +03:00
|
|
|
}
|
2022-01-07 15:04:11 +03:00
|
|
|
}
|