Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.00% covered (warning)
75.00%
9 / 12
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
UserCompanies
75.00% covered (warning)
75.00%
9 / 12
66.67% covered (warning)
66.67%
2 / 3
5.39
0.00% covered (danger)
0.00%
0 / 1
 forUser
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 forget
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 keyFor
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace App\Services;
4
5use App\Models\TblCompanyUsers;
6
7/**
8 * FIRE-1146: Cache the per-user `company_id` list so it isn't re-queried
9 * on every controller constructor across ~10 endpoints.
10 *
11 * Backed by the FIRE-1145 ResultCache (tagged Redis cache). TTL is 10 min,
12 * matching the existing list-cache TTL — the mutation surface that
13 * invalidates this key is admin-only and small (assigning / unassigning
14 * a user to a company), so a short TTL is safe.
15 *
16 * Domain tag: 'users' (shared with get_commercial_with_pendings etc.).
17 *
18 * Usage on the READ path:
19 *
20 *     $companyIds = UserCompanies::forUser($userId);
21 *
22 * Usage on the WRITE path (after assigning/unassigning a user):
23 *
24 *     UserCompanies::forget($userId);
25 */
26final class UserCompanies
27{
28    private const TTL_SECONDS = 600;
29
30    /**
31     * Return the list of company_ids the given user is assigned to.
32     * Cached for 10 minutes inside the 'users' domain.
33     */
34    public static function forUser(int $userId): array
35    {
36        if ($userId <= 0) {
37            return [];
38        }
39
40        return ResultCache::rememberKey(
41            'users',
42            self::keyFor($userId),
43            self::TTL_SECONDS,
44            fn () => TblCompanyUsers::where('user_id', $userId)->pluck('company_id')->all(),
45        );
46    }
47
48    /**
49     * Drop the cached list for one user. Call after any mutation on
50     * tbl_company_users that adds or removes a user/company link.
51     * (NOT needed for `is_selected` toggles — those don't change the list.)
52     */
53    public static function forget(int $userId): void
54    {
55        if ($userId <= 0) {
56            return;
57        }
58
59        ResultCache::forget('users', self::keyFor($userId));
60    }
61
62    private static function keyFor(int $userId): string
63    {
64        return "company_ids:{$userId}";
65    }
66}