-
Notifications
You must be signed in to change notification settings - Fork 1
/
PasteAccessor.php
64 lines (52 loc) · 1.67 KB
/
PasteAccessor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php declare(strict_types=1);
namespace DaveRandom\JsonPrettifier;
use ExceptionalJSON\DecodeErrorException;
use Shitwork\Exceptions\BadRequestException;
use Shitwork\Exceptions\InternalErrorException;
use Shitwork\Routing\Exceptions\NotFoundException;
final class PasteAccessor
{
private $storageDirectory;
public function __construct(string $storageDirectory)
{
$this->storageDirectory = $storageDirectory;
}
/**
* @throws BadRequestException
* @throws InternalErrorException
*/
public function save(string $data): string
{
try {
\ExceptionalJSON\decode($data, true);
} catch (DecodeErrorException $e) {
throw new BadRequestException('Invalid JSON input');
}
do {
try {
$id = base62_encode(\random_bytes(16));
} catch (\Throwable $e) {
throw new InternalErrorException('Failed to obtain random bytes: ' . $e->getMessage());
}
} while (\is_file($path = "{$this->storageDirectory}/{$id}.json"));
if (!\file_put_contents($path, $data)) {
throw new InternalErrorException('Saving file failed!');
}
return $id;
}
/**
* @throws InternalErrorException
* @throws NotFoundException
*/
public function load(string $id): string
{
$path = "{$this->storageDirectory}/{$id}.json";
if (!\is_file($path)) {
throw new NotFoundException('Paste not found');
}
if (false === $json = \file_get_contents($path)) {
throw new InternalErrorException('Reading file failed');
}
return $json;
}
}