3 namespace BookStack\References;
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Entity;
7 use Illuminate\Database\Eloquent\Collection;
11 public function __construct(
12 protected EntityProvider $entityProvider
17 * Update the outgoing references for the given entity.
19 public function updateForEntity(Entity $entity): void
21 $this->updateForEntities([$entity]);
25 * Update the outgoing references for all entities in the system.
27 public function updateForAll(): void
29 Reference::query()->delete();
31 foreach ($this->entityProvider->all() as $entity) {
32 $entity->newQuery()->select(['id', $entity->htmlField])->chunk(100, function (Collection $entities) {
33 $this->updateForEntities($entities->all());
39 * Update the outgoing references for the entities in the given array.
41 * @param Entity[] $entities
43 protected function updateForEntities(array $entities): void
45 if (count($entities) === 0) {
49 $parser = CrossLinkParser::createWithEntityResolvers();
52 $this->dropReferencesFromEntities($entities);
54 foreach ($entities as $entity) {
55 $models = $parser->extractLinkedModels($entity->getAttribute($entity->htmlField));
57 foreach ($models as $model) {
59 'from_id' => $entity->id,
60 'from_type' => $entity->getMorphClass(),
61 'to_id' => $model->id,
62 'to_type' => $model->getMorphClass(),
67 foreach (array_chunk($references, 1000) as $referenceDataChunk) {
68 Reference::query()->insert($referenceDataChunk);
73 * Delete all the existing references originating from the given entities.
74 * @param Entity[] $entities
76 protected function dropReferencesFromEntities(array $entities): void
80 foreach ($entities as $entity) {
81 $type = $entity->getMorphClass();
82 if (!isset($IdsByType[$type])) {
83 $IdsByType[$type] = [];
86 $IdsByType[$type][] = $entity->id;
89 foreach ($IdsByType as $type => $entityIds) {
91 ->where('from_type', '=', $type)
92 ->whereIn('from_id', $entityIds)