<?php

namespace App\ImportedDocument\EntityMatch;

/**
 * Most Entity matches entities for imported orders have the possibility to search by 'ordersExtSys'
 * criterion. The filtering of matching results (keeping only this match if any) is done for all
 * entities of this type.
 * @author Gabriel Grosu
 */
trait ExtSysCleanMatchesTrait
{

	/**
	 * If the matching is done by orderExtSys, that criterion is the most important, all other matches
	 * are eliminated. Searches for matches by ordersExtSys criteria; if found, all other criteria
	 * are eliminated (a separate bulk matches is constructed by eliminating all other criteria - different than ordersExtSys).
	 */
	protected function cleanMatches()
	{

		$foundExtSysMatch = false;
		$bulkMatchesExact = $this->bulkMatches;
		foreach($this->bulkMatches as $idx=>$matchesList) {
			foreach($matchesList as $id=>$details) {
				if ($details['_matchedField']=='documentExtSys') {
					$foundExtSysMatch = true;
				} else {
					unset($bulkMatchesExact[$idx][$id]);
				}
			}
		}
		if ($foundExtSysMatch) {
			$this->bulkMatches = array_filter($bulkMatchesExact);
		}

		parent::cleanMatches();

	}

}