@@ -649,4 +649,40 @@ public function jsonSerialize() {
649
649
return $ this ->toArray ();
650
650
}
651
651
652
+ /**
653
+ * Iterates once all elements in this collection and executes all stacked
654
+ * operations of them, finally it returns a new collection with the result.
655
+ * This is useful for converting non-rewindable internal iterators into
656
+ * a collection that can be rewound and used multiple times.
657
+ *
658
+ * A common use case is to re-use the same variable for calculating different
659
+ * data. In those cases it may be helpful and more performant to first compile
660
+ * a collection and then apply more operations to it.
661
+ *
662
+ * ### Example:
663
+ *
664
+ * {{{
665
+ * $collection->map($mapper)->sortBy('age')->extract('name');
666
+ * $compiled = $collection->compile();
667
+ * $isJohnHere = $compiled->some($johnMatcher);
668
+ * $allButJohn = $compiled->filter($johnMatcher);
669
+ * }}}
670
+ *
671
+ * In the above example, had not the collection compiled before, the iterations
672
+ * for `map`, `sortBy` and `extract` would've been executed twice: once for
673
+ * getting `$isJohnHere` and once for `$allButJohn`
674
+ *
675
+ * You can think of this method as a way to create save points for complex
676
+ * calculations in a collection.
677
+ *
678
+ * @param boolean $preserveKeys whether to use the keys returned by this
679
+ * collection as the array keys. Keep in mind that it is valid for iterators
680
+ * to return the same key for different elements, setting this value to false
681
+ * can help getting all items if keys are not important in the result.
682
+ * @return \Cake\Collection\Collection
683
+ */
684
+ public function compile ($ preserveKeys = true ) {
685
+ return new Collection ($ this ->toArray ($ preserveKeys ));
686
+ }
687
+
652
688
}
0 commit comments