55use BookStack \Entities \Models \Book ;
66use BookStack \Entities \Models \HasDescriptionInterface ;
77use BookStack \Entities \Models \Entity ;
8- use BookStack \Entities \Models \EntityContainerData ;
98use BookStack \Entities \Models \Page ;
109use BookStack \Entities \Repos \RevisionRepo ;
1110use BookStack \Util \HtmlDocument ;
@@ -30,12 +29,45 @@ public function updateEntityReferences(Entity $entity, string $oldLink): void
3029 }
3130 }
3231
32+ /**
33+ * Change existing references for a range of entities using the given context.
34+ */
3335 public function changeReferencesUsingContext (ReferenceChangeContext $ context ): void
3436 {
35- // TODO
37+ $ bindings = [];
38+ foreach ($ context ->getOldEntities () as $ old ) {
39+ $ bindings [] = $ old ->getMorphClass ();
40+ $ bindings [] = $ old ->id ;
41+ }
3642
37- // We should probably have references by this point, so we could use those for efficient
38- // discovery instead of scanning each item within the context.
43+ // No targets to update within the context, so no need to continue.
44+ if (count ($ bindings ) < 2 ) {
45+ return ;
46+ }
47+
48+ $ toReferenceQuery = '(to_type, to_id) IN ( ' . rtrim (str_repeat ('(?,?), ' , count ($ bindings ) / 2 ), ', ' ) . ') ' ;
49+
50+ // Cycle each new entity in the context
51+ foreach ($ context ->getNewEntities () as $ new ) {
52+ // For each, get all references from it which lead to other items within the context of the change
53+ $ newReferencesInContext = $ new ->referencesFrom ()->whereRaw ($ toReferenceQuery , $ bindings )->get ();
54+ // For each reference, update the URL and the reference entry
55+ foreach ($ newReferencesInContext as $ reference ) {
56+ $ oldToEntity = $ reference ->to ;
57+ $ newToEntity = $ context ->getNewForOld ($ oldToEntity );
58+ if ($ newToEntity === null ) {
59+ continue ;
60+ }
61+
62+ $ this ->updateReferencesWithinEntity ($ new , $ oldToEntity ->getUrl (), $ newToEntity ->getUrl ());
63+ if ($ newToEntity instanceof Page && $ oldToEntity instanceof Page) {
64+ $ this ->updateReferencesWithinPage ($ newToEntity , $ oldToEntity ->getPermalink (), $ newToEntity ->getPermalink ());
65+ }
66+ $ reference ->to_id = $ newToEntity ->id ;
67+ $ reference ->to_type = $ newToEntity ->getMorphClass ();
68+ $ reference ->save ();
69+ }
70+ }
3971 }
4072
4173 /**
0 commit comments