Issues (18)

src/Searchable/ObjectIdEncrypter.php (1 issue)

Severity
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\Searchable;
15
16
use Algolia\ScoutExtended\Exceptions\ShouldReimportSearchableException;
17
use function count;
18
use function get_class;
19
20
/**
21
 * @internal
22
 */
23
final class ObjectIdEncrypter
24
{
25
    /**
26
     * Holds the metadata separator.
27
     *
28
     * @var string
29
     */
30
    private static $separator = '::';
31
32
    /**
33
     * Encrypt the given searchable.
34
     *
35
     * @param  mixed $searchable
36
     * @param int|null $part
37
     *
38
     * @return string
39
     */
40 20
    public static function encrypt($searchable, int $part = null): string
41
    {
42 20
        $scoutKey = method_exists($searchable, 'getScoutKey') ? $searchable->getScoutKey() : $searchable->getKey();
43
44 20
        $meta = [get_class($searchable->getModel()), $scoutKey];
45
46 20
        if ($part !== null) {
47 5
            $meta[] = $part;
48
        }
49
50 20
        return implode(self::$separator, $meta);
51
    }
52
53
    /**
54
     * @param  string $objectId
55
     *
56
     * @return string
57
     */
58 5
    public static function withoutPart(string $objectId): string
59
    {
60 5
        return implode(self::$separator, [self::decryptSearchable($objectId), self::decryptSearchableKey($objectId)]);
61
    }
62
63
    /**
64
     * @param  string $objectId
65
     *
66
     * @return string
67
     */
68 6
    public static function decryptSearchable(string $objectId): string
69
    {
70 6
        return (string) self::getSearchableExploded($objectId)[0];
71
    }
72
73
    /**
74
     * @param  string $objectId
75
     *
76
     * @return string
77
     */
78 5
    public static function decryptSearchableKey(string $objectId): string
79
    {
80 5
        return (string) self::getSearchableExploded($objectId)[1];
81
    }
82
83
    /**
84
     * @param  string $objectId
85
     *
86
     * @return string[]
87
     */
88 6
    private static function getSearchableExploded(string $objectId): array
89
    {
90 6
        $parts = explode(self::$separator, $objectId);
91
92 6
        if (! is_array($parts) || count($parts) < 2) {
0 ignored issues
show
The condition is_array($parts) is always true.
Loading history...
93 1
            throw new ShouldReimportSearchableException('ObjectID seems invalid. You may need to
94
                re-import your data using the `scout-reimport` Artisan command.');
95
        }
96
97 5
        return $parts;
98
    }
99
}
100