• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

luttje / laravel-user-custom-id / 45212254803

23 Nov 2026 03:59PM UTC coverage: 94.421% (+0.7%) from 93.719%
45212254803

push

github

luttje
Add upgrade guide for 0.5.0

440 of 466 relevant lines covered (94.42%)

438.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.61
/src/UserCustomIdManager.php
1
<?php
2

3
namespace Luttje\UserCustomId;
4

5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Model;
7
use Luttje\UserCustomId\Exceptions\InvalidFormatException;
8
use Luttje\UserCustomId\FormatChunks\FormatChunkCollection;
9
use Luttje\UserCustomId\FormatChunks\Literal;
10

11
class UserCustomIdManager
12
{
13
    /**
14
     * The longest format that fits in the database column.
15
     */
16
    public const MAX_FORMAT_LENGTH = 255;
17

18
    /**
19
     * How often generating an id is tried again when the database reports
20
     * a deadlock, which can happen when many ids are generated at once.
21
     */
22
    public const GENERATE_ATTEMPTS = 3;
23

24
    public function __construct(
1,308 ✔
25
        protected ?FormatChunkRepository $formatChunkRepository = null,
26
    ) {
27
        $this->formatChunkRepository = $formatChunkRepository ?? new FormatChunkRepository;
1,308 ✔
28
        $this->formatChunkRepository->registerDefaultChunkTypes();
1,308 ✔
29
    }
30

31
    public function getChunkType(string $id): ?string
756 ✔
32
    {
33
        return $this->formatChunkRepository->getChunkType($id);
756 ✔
34
    }
35

36
    public function registerChunkType(string $chunkType): void
72 ✔
37
    {
38
        $this->formatChunkRepository->registerChunkType($chunkType);
72 ✔
39
    }
40

41
    public function createFormat(string $targetClass, Model $owner, string $format, string $targetAttribute, ?FormatChunkCollection $lastValueChunks = null): UserCustomId
252 ✔
42
    {
43
        // Only the format is mass assignable, the rest is set explicitly.
44
        $customId = (new UserCustomId)->forceFill([
252 ✔
45
            'target_type' => $targetClass,
252 ✔
46
            'owner_id' => $owner->getKey(),
252 ✔
47
            'owner_type' => $owner->getMorphClass(),
252 ✔
48
            'format' => $format,
252 ✔
49
            'target_attribute' => $targetAttribute,
252 ✔
50
            'last_target_custom_id' => $lastValueChunks,
252 ✔
51
        ]);
252 ✔
52

53
        $customId->save();
252 ✔
54

55
        return $customId;
240 ✔
56
    }
57

58
    public function get(Model|string $targetOrClass, Model $owner): ?UserCustomId
×
59
    {
60
        $targetClass = $targetOrClass instanceof Model
×
61
            ? $targetOrClass->getMorphClass()
×
62
            : $targetOrClass;
×
63

64
        return $this->query($targetClass, $owner)->first();
×
65
    }
66

67
    /**
68
     * @return Builder<UserCustomId>
69
     */
70
    protected function query(string $targetClass, Model $owner): Builder
264 ✔
71
    {
72
        return UserCustomId::query()
264 ✔
73
            ->where('target_type', $targetClass)
264 ✔
74
            ->where('owner_id', $owner->getKey())
264 ✔
75
            ->where('owner_type', $owner->getMorphClass());
264 ✔
76
    }
77

78
    public function getId(Model $target, Model $owner): ?string
×
79
    {
80
        $customId = $this->get($target, $owner);
×
81

82
        if ($customId) {
×
83
            return $target->{$customId->target_attribute};
×
84
        }
85

86
        return null;
×
87
    }
88

89
    public function getFormat(Model|string $targetOrClass, Model $owner): ?string
×
90
    {
91
        $customId = $this->get($targetOrClass, $owner);
×
92

93
        if ($customId) {
×
94
            return $customId->format;
×
95
        }
96

97
        return null;
×
98
    }
99

100
    /**
101
     * Generates a whole new custom id for the given target.
102
     */
103
    public function generateFor(Model $target, Model $owner): ?string
264 ✔
104
    {
105
        // Reading the last value, working out the next one and storing it must
106
        // happen as one step. Otherwise two requests at the same time both
107
        // continue from the same last value and end up with the same id.
108
        //
109
        // The row is locked until the transaction ends. When called inside a
110
        // transaction of your own (e.g. together with saving the target) the
111
        // lock is kept until that one ends, and the counter is rolled back
112
        // with it.
113
        return (new UserCustomId)->getConnection()->transaction(function () use ($target, $owner) {
264 ✔
114
            $customId = $this->query($target->getMorphClass(), $owner)
264 ✔
115
                ->lockForUpdate()
264 ✔
116
                ->first();
264 ✔
117

118
            if (! $customId) {
264 ✔
119
                return null;
60 ✔
120
            }
121

122
            $chunks = $this->parseCustomId($customId);
204 ✔
123
            $nextCustomId = $this->generateNextCustomId($chunks, $target, $owner);
204 ✔
124

125
            $target->{$customId->target_attribute} = $nextCustomId;
204 ✔
126

127
            $customId->last_target_custom_id = $chunks;
204 ✔
128
            $customId->save();
204 ✔
129

130
            return $nextCustomId;
204 ✔
131
        }, static::GENERATE_ATTEMPTS);
264 ✔
132
    }
133

134
    /**
135
     * Generates a whole new custom id based on the given format.
136
     *
137
     * The target and owner models are passed to the chunk types so they
138
     * can use the values of the models to generate the next value.
139
     */
140
    public function generateNextCustomId(FormatChunkCollection $chunks, Model $target, Model $owner): string
204 ✔
141
    {
142
        $generated = '';
204 ✔
143

144
        foreach ($chunks as $chunk) {
204 ✔
145
            $generated .= $chunk->generateNextValue($target, $owner);
204 ✔
146
        }
147

148
        return $generated;
204 ✔
149
    }
150

151
    /**
152
     * Checks that the given format can be used to generate ids, without
153
     * generating one. Call this (or use the ValidFormat validation rule)
154
     * before storing a format that a user wrote.
155
     *
156
     * @throws InvalidFormatException with a message that can be shown to the user.
157
     */
158
    public function validateFormat(string $format): void
672 ✔
159
    {
160
        if ($format === '') {
672 ✔
161
            throw new InvalidFormatException('The format cannot be empty.');
12 ✔
162
        }
163

164
        if (strlen($format) > static::MAX_FORMAT_LENGTH) {
660 ✔
165
            throw new InvalidFormatException('The format cannot be longer than '.static::MAX_FORMAT_LENGTH.' characters.');
12 ✔
166
        }
167

168
        try {
169
            $this->parseFormat($format);
648 ✔
170
        } catch (\InvalidArgumentException $e) {
252 ✔
171
            if ($e instanceof InvalidFormatException) {
252 ✔
172
                throw $e;
48 ✔
173
            }
174

175
            // Thrown by the chunks when their parameters are wrong.
176
            throw new InvalidFormatException($e->getMessage(), previous: $e);
204 ✔
177
        }
178
    }
179

180
    public function isValidFormat(string $format): bool
396 ✔
181
    {
182
        try {
183
            $this->validateFormat($format);
396 ✔
184
        } catch (InvalidFormatException) {
240 ✔
185
            return false;
240 ✔
186
        }
187

188
        return true;
156 ✔
189
    }
190

191
    /**
192
     * Parses the format of the given custom id, continuing from the
193
     * last value that was generated for it.
194
     */
195
    protected function parseCustomId(UserCustomId $customId): FormatChunkCollection
204 ✔
196
    {
197
        return $this->parseFormat($customId->format, $customId->last_target_custom_id);
204 ✔
198
    }
199

200
    /**
201
     * Parses the given format and returns an collection of chunks.
202
     * Chunks are identified by the curly braces. If the curly braces
203
     * are prefixed with a backslash, they will be treated as a literal
204
     * curly brace and not as a chunk.
205
     *
206
     * For literal texts a Literal chunk will be used, for other chunks
207
     * the appropriate chunk type will be used from FormatChunkRepository.
208
     *
209
     * @param  FormatChunkCollection|null  $lastValueChunks  The last value that was generated for this format.
210
     *
211
     * @throws InvalidFormatException when the format refers to a chunk that isn't registered.
212
     * @throws \InvalidArgumentException when the parameters of a chunk are wrong.
213
     */
214
    public function parseFormat(string $format, ?FormatChunkCollection $lastValueChunks = null): FormatChunkCollection
648 ✔
215
    {
216
        $chunks = [];
648 ✔
217

218
        // How often each chunk type has been seen, so every chunk
219
        // continues from its own last value.
220
        $occurrences = [];
648 ✔
221

222
        $currentChunkString = '';
648 ✔
223

224
        $isEscaped = false;
648 ✔
225

226
        for ($i = 0; $i < strlen($format); $i++) {
648 ✔
227
            $char = $format[$i];
648 ✔
228

229
            if ($char === '\\') {
648 ✔
230
                $isEscaped = true;
12 ✔
231

232
                continue;
12 ✔
233
            }
234

235
            if ($char === '{' && ! $isEscaped) {
648 ✔
236
                if ($currentChunkString !== '') {
600 ✔
237
                    $literal = new Literal;
240 ✔
238
                    $literal->setValue($currentChunkString);
240 ✔
239

240
                    $chunks[] = $literal;
240 ✔
241
                    $currentChunkString = '';
240 ✔
242
                }
243

244
                $currentChunkString .= $char;
600 ✔
245

246
                continue;
600 ✔
247
            }
248

249
            if ($char === '}' && ! $isEscaped) {
648 ✔
250
                $currentChunkString .= $char;
612 ✔
251

252
                $id = explode(':', trim($currentChunkString, '{}'))[0];
612 ✔
253
                $occurrence = $occurrences[$id] ?? 0;
612 ✔
254

255
                // Literals are made from the text between chunks, they can't be asked for.
256
                $chunk = $id === Literal::getChunkId()
612 ✔
257
                    ? null
12 ✔
258
                    : $this->formatChunkRepository->getChunk($currentChunkString, $lastValueChunks, $occurrence);
600 ✔
259

260
                if (! $chunk) {
420 ✔
261
                    throw new InvalidFormatException("The chunk '{$currentChunkString}' is not registered.");
48 ✔
262
                }
263

264
                $occurrences[$id] = $occurrence + 1;
384 ✔
265
                $chunks[] = $chunk;
384 ✔
266

267
                $currentChunkString = '';
384 ✔
268

269
                continue;
384 ✔
270
            }
271

272
            $currentChunkString .= $char;
648 ✔
273
            $isEscaped = false;
648 ✔
274
        }
275

276
        if ($currentChunkString !== '') {
420 ✔
277
            $literal = new Literal;
144 ✔
278
            $literal->setValue($currentChunkString);
144 ✔
279

280
            $chunks[] = $literal;
144 ✔
281
        }
282

283
        return new FormatChunkCollection($chunks);
420 ✔
284
    }
285
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc