2020-08-17 23:46:58 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
final class FingerprintPostController extends AbstractController
|
|
|
|
{
|
|
|
|
protected string $route = '/api/v1/fingerprint';
|
|
|
|
protected array $mandatoryAttributes = [
|
|
|
|
'fingerprint',
|
|
|
|
'userId',
|
|
|
|
];
|
|
|
|
|
|
|
|
public function handle(): void
|
|
|
|
{
|
2020-08-23 11:44:12 +02:00
|
|
|
if (!$this->isUserLoggedIn()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-08-17 23:46:58 +02:00
|
|
|
parent::handle();
|
|
|
|
|
2020-08-18 11:46:03 +02:00
|
|
|
$db = new MySqlDatabase();
|
2020-08-17 23:46:58 +02:00
|
|
|
$json = json_decode($this->requestBody);
|
2020-08-18 11:46:03 +02:00
|
|
|
$fingerprint = new Fingerprint(null, $db);
|
2020-08-20 23:08:20 +02:00
|
|
|
$this->response = new ApiJsonResponse();
|
2020-08-17 23:46:58 +02:00
|
|
|
|
|
|
|
try {
|
2020-08-23 11:44:12 +02:00
|
|
|
if (!$this->hasUserPermission((int)$json->userId)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
$fingerprint->setFingerprint((string)$json->fingerprint);
|
|
|
|
$fingerprint->setUserId((int)$json->userId);
|
2020-08-18 11:46:03 +02:00
|
|
|
|
|
|
|
if (!$db->hasTransaction()) {
|
|
|
|
$db->startTransaction();
|
|
|
|
}
|
|
|
|
|
2020-08-17 23:46:58 +02:00
|
|
|
$fingerprint->Save();
|
|
|
|
|
|
|
|
$qrCode = new QrCode($fingerprint->getFingerprintId(), $fingerprint->getFingerprint());
|
|
|
|
$qrCode->generate();
|
|
|
|
$qrCode->save();
|
|
|
|
|
2020-08-18 11:46:03 +02:00
|
|
|
$db->commit();
|
|
|
|
|
2020-08-17 23:46:58 +02:00
|
|
|
$this->response->setParameter('fingerprintId', $fingerprint->getFingerprintId());
|
|
|
|
} catch (QrCodeException $e) {
|
2020-08-20 23:08:20 +02:00
|
|
|
$this->response->setStatus(ServerStatus::INTERNAL_ERROR);
|
2020-08-17 23:46:58 +02:00
|
|
|
$this->response->setParameter('success', false);
|
2020-08-20 23:08:20 +02:00
|
|
|
$this->response->setMessage('An error occured during QR code creation!');
|
2020-08-17 23:46:58 +02:00
|
|
|
} catch (Throwable $e) {
|
|
|
|
$this->catchDatabaseException($e->getMessage(), $json);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private function catchDatabaseException(string $message, object $json): void
|
|
|
|
{
|
|
|
|
$this->response->setParameter('success', false);
|
|
|
|
|
|
|
|
if (substr_count($message, 'foreign key constraint fails') > 0) {
|
|
|
|
$this->response->setMessage(sprintf('User with id %d doesn\'t exist!', $json->userId));
|
|
|
|
$this->response->setStatus(ServerStatus::NOT_FOUND);
|
|
|
|
} elseif (substr_count($message, 'Duplicate entry') > 0) {
|
|
|
|
$this->response->setMessage(sprintf('Fingerprint %s already exists!', $json->fingerprint));
|
|
|
|
$this->response->setStatus(ServerStatus::BAD_REQUEST);
|
|
|
|
} else {
|
|
|
|
$this->response->setMessage($message);
|
|
|
|
$this->response->setStatus(ServerStatus::INTERNAL_ERROR);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|