2016-03-04 19:23:02 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
class Bundler {
|
|
|
|
|
|
|
|
private function sort( &$array ) {
|
|
|
|
// We have to ignore the error here (use @usort)
|
|
|
|
// otherwise this code fails when executed by unit tests
|
|
|
|
// See: https://bugs.php.net/bug.php?id=50688
|
|
|
|
|
2021-03-26 23:54:59 +00:00
|
|
|
// phpcs:ignore Generic.PHP.NoSilencedErrors
|
2021-05-04 16:06:42 +00:00
|
|
|
@usort( $array, static function ( Bundleable $a, Bundleable $b ) {
|
2016-03-04 19:23:02 +00:00
|
|
|
return strcmp( $b->getSortingKey(), $a->getSortingKey() );
|
|
|
|
} );
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Bundle bundleable elements that can be bundled by their bundling keys
|
|
|
|
*
|
|
|
|
* @param Bundleable[] $bundleables
|
|
|
|
* @return Bundleable[] Grouped notifications sorted by timestamp DESC
|
|
|
|
*/
|
2019-10-23 10:44:35 +00:00
|
|
|
public function bundle( array $bundleables ) {
|
2016-12-05 18:51:07 +00:00
|
|
|
$groups = [];
|
|
|
|
$bundled = [];
|
2016-03-04 19:23:02 +00:00
|
|
|
|
|
|
|
/** @var Bundleable $element */
|
|
|
|
foreach ( $bundleables as $element ) {
|
|
|
|
if ( $element->canBeBundled() && $element->getBundlingKey() ) {
|
|
|
|
$groups[ $element->getBundlingKey() ][] = $element;
|
|
|
|
} else {
|
|
|
|
$bundled[] = $element;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach ( $groups as $bundlingKey => $group ) {
|
|
|
|
$this->sort( $group );
|
|
|
|
/** @var Bundleable $base */
|
|
|
|
$base = array_shift( $group );
|
|
|
|
$base->setBundledElements( $group );
|
|
|
|
$bundled[] = $base;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->sort( $bundled );
|
|
|
|
return $bundled;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|