-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGithubEmojiReplacer.php
More file actions
60 lines (44 loc) · 1.39 KB
/
GithubEmojiReplacer.php
File metadata and controls
60 lines (44 loc) · 1.39 KB
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
<?php
declare(strict_types=1);
namespace App\Extend;
use GuzzleHttp\Client;
use Illuminate\Support\Str;
class GithubEmojiReplacer
{
protected const EMOJI_CODE_REGEX = '/\:([a-zA-Z0-9-_+]+)\:/';
/** @var Client */
private $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function replace(string $content): string
{
$emojis = $this->getGithubEmojis();
return preg_replace_callback(
self::EMOJI_CODE_REGEX,
function (array $matches) use ($emojis) {
return $this->getEmojiHtml($emojis, $matches[1]) ?? $matches[0];
},
$content
);
}
private function getEmojiHtml(array $emojis, string $code): ?string
{
if (!isset($emojis[$code])) {
return null;
}
return sprintf('<img class="gh-emoji" src="%s">', $emojis[$code]);
}
private function getGithubEmojis(): array
{
$cachePath = __DIR__ . '/../cache/gh-emoji.json';
if (file_exists($cachePath)) {
return json_decode(file_get_contents($cachePath), true);
}
$response = $this->client->get('https://api.github.com/emojis');
$responseJson = (string) $response->getBody();
file_put_contents($cachePath, $responseJson);
return \GuzzleHttp\json_decode($responseJson, true);
}
}