Skip to content

Commit

Permalink
refactor: implement HIS subquery
Browse files Browse the repository at this point in the history
  • Loading branch information
zhyian committed May 30, 2024
1 parent 0003ae4 commit 5541fd2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
4 changes: 2 additions & 2 deletions src/Infrastructure/Repository/WpQueryArgs.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ public function withOrderBy(array $orderBy): self
return $this->withArg('orderby', $orderBy);
}

public function withTaxQueryItem(array $item, string $relation = 'AND'): self
public function withTaxQueryItem(array $item): self
{
$instance = clone $this;

$instance->args['tax_query'] = (array) ($instance->args['tax_query']
?? ['relation' => $relation]);
?? ['relation' => 'AND']);

$instance->args['tax_query'][] = $item;

Expand Down
37 changes: 22 additions & 15 deletions src/Infrastructure/Repository/WpQueryArgsBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,26 +88,31 @@ public function build(CollectionCriteria $criteria): WpQueryArgs
$queryArgs = $this->applyFilter($filter, $queryArgs, $criteria->languageCode());
}

foreach ($criteria->hisCodes() as $hisCode) {
$queryArgs = $this->applyHisCode($hisCode, $queryArgs);
if (count($criteria->hisCodes()) > 0) {
$queryArgs = $this->applyHisCodes($criteria->hisCodes(), $queryArgs);
}

return $queryArgs;
}

public function applyHisCode(string $hisCode, WpQueryArgs $queryArgs): WpQueryArgs
/**
* @param array<string> $hisCodes
*/
public function applyHisCodes(array $hisCodes, WpQueryArgs $queryArgs): WpQueryArgs
{
$taxQueryItem = [
'relation' => 'AND',
];
$hisCodesQuery = [];

foreach ($hisCodes as $hisCode) {
$taxQueryItem = [
'relation' => 'AND',
];

try {
$taxonomyToTermMapping = $this->campoKeysRepository->taxonomyToTermsMapFromCampoKeys(
CampoKeys::fromHisCode($hisCode)
);

if (count($taxonomyToTermMapping) === 0) {
return $queryArgs;
continue;
}

foreach ($taxonomyToTermMapping as $taxonomy => $termId) {
Expand All @@ -119,14 +124,16 @@ public function applyHisCode(string $hisCode, WpQueryArgs $queryArgs): WpQueryAr
];
}

return $queryArgs->withTaxQueryItem($taxQueryItem, 'OR');
} catch (RuntimeException) {
/*
* Return an empty result if one or more campo keys in HIS code are not matched to any terms.
* Otherwise invalid HIS codes would be matched to false results.
*/
return $queryArgs->withArg('post__in', [0]);
$hisCodesQuery[] = $taxQueryItem;
}

if (count($hisCodesQuery) === 0) {
return $queryArgs;
}

$hisCodesQuery['relation'] = 'OR';

return $queryArgs->withTaxQueryItem($hisCodesQuery);
}

private function applyOrderBy(
Expand Down

0 comments on commit 5541fd2

Please sign in to comment.