ringfinger/backend/classes/core/QrCode.php

90 lines
1.9 KiB
PHP
Raw Permalink Normal View History

2020-08-17 23:46:58 +02:00
<?php
declare(strict_types=1);
final class QrCode
{
2020-08-23 12:37:39 +02:00
private int $fingerprintId;
private string $fingerprint;
private string $temporaryFilename;
public function __construct(int $fingerprintId, string $fingerprint)
{
$this->fingerprintId = $fingerprintId;
$this->fingerprint = $fingerprint;
}
public function save(): void
{
if (!is_file($this->temporaryFilename)) {
throw new QrCodeException(
sprintf('Temporary QR file %s couldn\'t be found!', $this->temporaryFilename)
);
}
$returnCode = 0;
2020-08-17 23:46:58 +02:00
$filename = $this->getFilePath();
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
passthru(
sprintf('mv %s %s', $this->temporaryFilename, $filename),
$returnCode
);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
if ($returnCode !== 0 || !is_file($filename)) {
throw new QrCodeException(
sprintf('QR code for fingerprint %d couldn\'t be created!', $this->fingerprintId)
);
}
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function delete(): void
{
$filepath = $this->getFilePath();
if (!is_file($filepath)) {
throw new QrCodeException(sprintf('Qr code file %s not found!', $filepath));
}
if (!unlink($filepath)) {
throw new QrCodeException('Couldn\'t delete %s!', $filepath);
}
}
2020-08-23 12:37:39 +02:00
public function generate(): bool
{
$returnCode = 0;
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$path = substr(Setting::PATH_TMP, -1) === '/' ? Setting::PATH_TMP : Setting::PATH_TMP . '/';
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
$this->temporaryFilename = $path . $this->generateTemporaryFilename() . '.svg';
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
passthru(
sprintf('qrencode -o %s -t SVG "%s"', $this->temporaryFilename, $this->fingerprint),
$returnCode
);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
return !(bool)$returnCode;
}
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
public function hasFile(): bool
{
return is_file($this->getFilePath());
}
2020-08-23 12:37:39 +02:00
private function generateTemporaryFilename(): string
{
$hash = hash('md5', (new DateTime())->format('U') . $this->fingerprint);
2020-08-17 23:46:58 +02:00
2020-08-23 12:37:39 +02:00
return sprintf('%s.svg', $hash);
}
2020-08-23 12:37:39 +02:00
private function getFilePath(): string
{
$path = substr(Setting::PATH_QR_CODES, -1) === '/'
? Setting::PATH_QR_CODES
: Setting::PATH_QR_CODES . '/';
return $path . $this->fingerprintId . '.svg';
}
2020-08-17 23:46:58 +02:00
}