Created
March 18, 2019 13:26
-
-
Save kolomiec-valeriy/37b53bf90ddf1932e4b06ce4bf502e4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Service; | |
use Psr\Log\LoggerInterface; | |
use Symfony\Bundle\FrameworkBundle\Console\Application; | |
use Symfony\Component\Console\Input\ArrayInput; | |
use Symfony\Component\Filesystem\Filesystem; | |
use Symfony\Component\HttpKernel\KernelInterface; | |
class PdfCreatorService | |
{ | |
/** | |
* @var KernelInterface | |
*/ | |
private $kernel; | |
/** | |
* @var Filesystem | |
*/ | |
private $filesystem; | |
/** | |
* @var LoggerInterface | |
*/ | |
private $logger; | |
private $cacheDir; | |
public function __construct( | |
KernelInterface $kernel, | |
Filesystem $filesystem, | |
LoggerInterface $logger, | |
string $cacheDir | |
) | |
{ | |
$this->kernel = $kernel; | |
$this->filesystem = $filesystem; | |
$this->logger = $logger; | |
$this->cacheDir = $cacheDir; | |
} | |
public function create(string $sourcePageUrl) | |
{ | |
$application = new Application($this->kernel); | |
$application->setAutoExit(false); | |
$fileName = $this->cacheDir.'/'.md5(rand(0, 1000)).'.pdf'; | |
$input = new ArrayInput(array( | |
'command' => 'pdf:create', | |
'fileName' => $fileName, | |
'url' => $sourcePageUrl, | |
)); | |
try { | |
$application->run($input); | |
} catch (\Exception $e) { | |
$this->logger->error( | |
'error creating pdf file', | |
[ | |
'message' => $e->getMessage(), | |
] | |
); | |
return false; | |
} | |
return $this->changeFilePermission($fileName); | |
} | |
private function changeFilePermission(string $file) | |
{ | |
if (!$this->filesystem->exists($file)) { | |
return false; | |
} | |
try { | |
$this->filesystem->chmod($file, 0777); | |
} catch (\Exception $e) { | |
$this->logger->error( | |
'error change mod for file - '.$file, | |
[ | |
'message' => $e->getMessage(), | |
] | |
); | |
return false; | |
} | |
return $file; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment