| 1 |
<?php |
| 2 |
// phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure. |
| 3 |
namespace Yoast\WP\SEO\Schema_Aggregator\Application; |
| 4 |
|
| 5 |
use Yoast\WP\SEO\Schema_Aggregator\Domain\Schema_Piece_Collection; |
| 6 |
use Yoast\WP\SEO\Schema_Aggregator\Infrastructure\Filtering_Strategy_Factory; |
| 7 |
|
| 8 |
/** |
| 9 |
* This class is responsible for taking a Schema_Piece_Collection and return another filtered Schema_Piece_Collection. |
| 10 |
*/ |
| 11 |
class Schema_Pieces_Aggregator { |
| 12 |
|
| 13 |
/** |
| 14 |
* The filtering strategy factory. |
| 15 |
* |
| 16 |
* @var Filtering_Strategy_Factory |
| 17 |
*/ |
| 18 |
private $filtering_strategy_factory; |
| 19 |
|
| 20 |
/** |
| 21 |
* The properties merger. |
| 22 |
* |
| 23 |
* @var Properties_Merger |
| 24 |
*/ |
| 25 |
private $properties_merger; |
| 26 |
|
| 27 |
/** |
| 28 |
* Class constructor |
| 29 |
* |
| 30 |
* @param Filtering_Strategy_Factory $filtering_strategy_factory The filtering strategy factory. |
| 31 |
* @param Properties_Merger $properties_merger The properties merger. |
| 32 |
*/ |
| 33 |
public function __construct( Filtering_Strategy_Factory $filtering_strategy_factory, Properties_Merger $properties_merger ) { |
| 34 |
$this->filtering_strategy_factory = $filtering_strategy_factory; |
| 35 |
$this->properties_merger = $properties_merger; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Main orchestrator method: deduplicates, merges and filter properties. |
| 40 |
* |
| 41 |
* @param Schema_Piece_Collection $schema_pieces The schema pieces to aggregate. |
| 42 |
* |
| 43 |
* @return Schema_Piece_Collection The aggregated schema pieces. |
| 44 |
*/ |
| 45 |
public function aggregate( Schema_Piece_Collection $schema_pieces ): Schema_Piece_Collection { |
| 46 |
$aggregated_schema = []; |
| 47 |
|
| 48 |
$filtering_strategy = $this->filtering_strategy_factory->create(); |
| 49 |
$filtered_schema_pieces = $filtering_strategy->filter( $schema_pieces ); |
| 50 |
|
| 51 |
foreach ( $filtered_schema_pieces->to_array() as $piece ) { |
| 52 |
|
| 53 |
$id = $piece->get_id(); |
| 54 |
if ( \is_null( $id ) ) { |
| 55 |
continue; |
| 56 |
} |
| 57 |
|
| 58 |
if ( isset( $aggregated_schema[ $id ] ) ) { |
| 59 |
$aggregated_schema[ $id ] = $this->properties_merger->merge( $aggregated_schema[ $id ], $piece ); |
| 60 |
} |
| 61 |
else { |
| 62 |
// Add new piece. |
| 63 |
$aggregated_schema[ $id ] = $piece; |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
// Return only the values to get rid of the keys (which are @id) and wrap in a collection. |
| 68 |
return new Schema_Piece_Collection( \array_values( $aggregated_schema ) ); |
| 69 |
} |
| 70 |
} |
| 71 |
|