Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
Sync
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
3 / 3
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 replace
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 remove
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\References;
6
7use Celema\Quma\Database;
8
9/**
10 * Keeps the derived reference indexes (`asset_references`,
11 * `node_references`) in step with an owner's content: full replace per
12 * owner, no diffing. Inserts join against the target tables, so
13 * dangling uids are skipped instead of tripping the FK.
14 */
15final class Sync
16{
17    public function __construct(
18        private readonly Database $db,
19    ) {}
20
21    /** @param array{assets: list<string>, nodes: list<string>} $refs */
22    public function replace(string $ownerType, string $ownerUid, array $refs): void
23    {
24        $this->remove($ownerType, $ownerUid);
25        $owner = ['ownerType' => $ownerType, 'ownerUid' => $ownerUid];
26
27        if ($refs['assets'] !== []) {
28            $this->db->references->insertAssets([
29                ...$owner,
30                'uids' => json_encode($refs['assets']),
31            ])->run();
32        }
33
34        if ($refs['nodes'] !== []) {
35            $this->db->references->insertNodes([
36                ...$owner,
37                'uids' => json_encode($refs['nodes']),
38            ])->run();
39        }
40    }
41
42    public function remove(string $ownerType, string $ownerUid): void
43    {
44        $this->db->references->deleteOwner([
45            'ownerType' => $ownerType,
46            'ownerUid' => $ownerUid,
47        ])->run();
48    }
49}