ringfinger/backend/classes/core/QrCode.php

90 lines
2.2 KiB
PHP
Raw Normal View History

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