Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save benglass/25049ba10cfd46cdf595 to your computer and use it in GitHub Desktop.
Save benglass/25049ba10cfd46cdf595 to your computer and use it in GitHub Desktop.
<?php
namespace Application\Search;
use Application\Model\Repository\BillRepositoryInterface;
use Application\Model\Repository\BillProfileRepositoryInterface;
class BillSearchResultBillProfileKeywordsDecorator implements BillSearchResultDecoratorInterface
{
protected $profileIds = [];
protected $keywordRepository;
/**
* This array has billIds as the keys and an array of keywords for $this->profileIds as values
*/
protected $billIdKeywordsMap = [];
public function __construct(KeywordRepositoryInterface $keywordRepository, array $profileIds = [])
{
$this->keywordRepository = $keywordRepository;
$this->profileIds = [];
}
/**
* Add keywords to a single search result
*
* @param BillSearchResult $result
* @param array $profileIds
* @return BillSearchResult
*/
public function decorate(BillSearchResult $result)
{
$billId = $result->getId();
if (!isset($this->billIdKeywordsMap[$billId])) {
$this->buildBillIdKeywordsMap([$billId]);
}
$result->setOptionalFieldCollection(
new BillProfileKeywordsOptionFieldDecorator(
$result->getOptionalFieldCollection(),
OptionalField::billProfileKeywords($this->billIdKeywordsMap[$billId])
)
);
return $result;
}
/**
* Add keywords to each search result in a collection
*
* @param BillSearchResultCollection $collection
* @param array $profileIds
* @return BillSearchResultCollection
*/
public function decorateAll(BillSearchResultCollection $collection)
{
// Collect all of the bill ids
$billIds = [];
$results = $collection->getResults();
foreach ($results as $i => $result) {
$billIds[] = $result->getId();
}
// Build the keywords map for them so decorate wont hit the database at all
$this->buildBillIdKeywordsMap($billIds);
// Decorate each result
foreach ($results as $i => $result) {
$this->decorate($result);
}
return $collection;
}
/**
* @param int $billId
* @param array $profileIds
*/
public function buildBillIdKeywordsMap($billIds, array $profileIds)
{
// You will need to add this method to KeywordRepositoryInterface and KeywordDoctrineRepository
// This method needs to return an array where the keys are billIds and the values are an array of keywords for the given profileIds
$this->billIdKeywordsMap = $this->keywordRepository->findKeywordsForBillsInProfiles($billIds, $profileIds);
}
}
<?php
class SomeController
{
public function someAction()
{
$results = $this->getBillSearcher()->findMatching(...); // passing in criteria, page, etc.
$profileIds = [1,2,3];
$keywordsDecorator = new BillSearchResultBillProfileKeywordsDecorator($this->get('keyword_repository'), $profileIds);
$keywordsDecorator->decorateAll($results);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment