1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* This file is part of Scout Extended. |
7
|
|
|
* |
8
|
|
|
* (c) Algolia Team <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Algolia\ScoutExtended\Repositories; |
15
|
|
|
|
16
|
|
|
use function is_string; |
17
|
|
|
use Algolia\AlgoliaSearch\SearchClient; |
18
|
|
|
use Illuminate\Contracts\Cache\Repository; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @internal |
22
|
|
|
*/ |
23
|
|
|
final class ApiKeysRepository |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* Holds the search key. |
27
|
|
|
*/ |
28
|
|
|
private const SEARCH_KEY = 'scout-extended.user-data.search-key'; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var \Illuminate\Contracts\Cache\Repository |
32
|
|
|
*/ |
33
|
|
|
private $cache; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var \Algolia\AlgoliaSearch\SearchClient |
37
|
|
|
*/ |
38
|
|
|
private $client; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* ApiKeysRepository constructor. |
42
|
|
|
* |
43
|
|
|
* @param \Illuminate\Contracts\Cache\Repository $cache |
44
|
|
|
* @param \Algolia\AlgoliaSearch\SearchClient $client |
45
|
|
|
* |
46
|
|
|
* @return void |
47
|
|
|
*/ |
48
|
2 |
|
public function __construct(Repository $cache, SearchClient $client) |
49
|
|
|
{ |
50
|
2 |
|
$this->cache = $cache; |
51
|
2 |
|
$this->client = $client; |
52
|
2 |
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param string|object $searchable |
56
|
|
|
* |
57
|
|
|
* @return string |
58
|
|
|
*/ |
59
|
2 |
|
public function getSearchKey($searchable): string |
60
|
|
|
{ |
61
|
2 |
|
$searchable = is_string($searchable) ? new $searchable : $searchable; |
62
|
|
|
|
63
|
2 |
|
$searchableAs = $searchable->searchableAs(); |
64
|
|
|
|
65
|
2 |
|
$searchKey = $this->cache->get(self::SEARCH_KEY); |
66
|
|
|
|
67
|
2 |
|
if ($searchKey === null) { |
68
|
2 |
|
$id = config('app.name').'::searchKey'; |
69
|
|
|
|
70
|
2 |
|
$keys = $this->client->listApiKeys()['keys']; |
71
|
2 |
|
$searchKey = null; |
72
|
|
|
|
73
|
2 |
|
foreach ($keys as $key) { |
74
|
1 |
|
if ($key['description'] === $id) { |
75
|
1 |
|
$searchKey = $key['value']; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
2 |
|
$searchKey = $searchKey ?? $this->client->addApiKey([ |
80
|
1 |
|
'acl' => ['search'], |
81
|
1 |
|
'description' => config('app.name').'::searchKey', |
82
|
2 |
|
])->getBody()['key']; |
83
|
|
|
|
84
|
2 |
|
$this->cache->put(self::SEARCH_KEY, $searchKey, 1440); |
85
|
|
|
} |
86
|
|
|
|
87
|
2 |
|
return $this->client::generateSecuredApiKey($searchKey, [ |
88
|
2 |
|
'restrictIndices' => $searchableAs, |
89
|
|
|
]); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|