Last active
October 30, 2023 20:07
-
-
Save sstok/188390db4c12190b50a2 to your computer and use it in GitHub Desktop.
Domain helper stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Assert\Assertion; | |
trait DiffObjectCollections | |
{ | |
/** | |
* @var object[] | |
*/ | |
protected $items; | |
/** | |
* Returns the difference between the collections. | |
* | |
* @param object $other | |
* | |
* @return array[] | |
*/ | |
public function diff($other) | |
{ | |
$removed = []; | |
$added = []; | |
Assertion::isInstanceOf($other, get_class($this)); | |
// This is a two stage process, first check for items present in $this->items | |
// but not present in $other. They are removed. | |
// Then loop trough $other and add none-matched items to $this->items | |
// Look for removed items. | |
foreach ($this->items as $item) { | |
foreach ($other->toArray() as $item2) { | |
if ($item->equals($item2)) { | |
// Unchanged, continue with the next item in the main loop. | |
// Else the item is none-matched and removed. | |
continue 2; | |
} | |
} | |
// None of the existing items matched the $item, so the item is removed. | |
$removed[] = $item; | |
} | |
// Look for newly added items. | |
foreach ($other->toArray() as $item) { | |
foreach ($this->items as $item2) { | |
if ($item->equals($item2)) { | |
// Unchanged, continue with the next item in the main loop. | |
// Else the item is none-matched and added. | |
continue 2; | |
} | |
} | |
// None of the existing items matched so its a new one (added). | |
$added[] = $item; | |
} | |
return ['removed' => $removed, 'added' => $added]; | |
} | |
/** | |
* @return object[] | |
*/ | |
public function toArray() | |
{ | |
return $this->items; | |
} | |
/** | |
* Retrieve an external iterator. | |
* | |
* @return \ArrayIterator | |
*/ | |
public function getIterator() | |
{ | |
return new \ArrayIterator($this->items); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment