diff --git a/src/Traits/FilterByDimensionTrait.php b/src/Traits/FilterByDimensionTrait.php index fb1ab14..d27eae9 100644 --- a/src/Traits/FilterByDimensionTrait.php +++ b/src/Traits/FilterByDimensionTrait.php @@ -6,10 +6,11 @@ use Google\Analytics\Data\V1beta\Filter\InListFilter; use Google\Analytics\Data\V1beta\Filter\StringFilter; use Google\Analytics\Data\V1beta\FilterExpression; +use Google\Analytics\Data\V1beta\FilterExpressionList; trait FilterByDimensionTrait { - public ?FilterExpression $dimensionFilter = null; + public $dimensionFilter = null; /** * Apply where dimension filter. @@ -56,4 +57,63 @@ public function whereDimensionIn(string $name, array $values, bool $caseSensitiv return $this; } + + /** + * Apply where dimension filter using 'and_group'. + * + * @param array $dimensions + * @return $this + */ + public function whereAndGroupDimensions($dimensions): self + { + $this->dimensionFilter = (new FilterExpression())->setAndGroup( + (new FilterExpressionList) + ->setExpressions( + $this->createDimensionGroup($dimensions) + ) + ); + + return $this; + } + + /** + * Apply where dimension filter using 'or_group'. + * + * @param array $dimensions + * @return $this + */ + public function whereOrGroupDimensions($dimensions): self + { + $this->dimensionFilter = (new FilterExpression())->setOrGroup( + (new FilterExpressionList) + ->setExpressions( + $this->createDimensionGroup($dimensions) + ) + ); + + return $this; + } + + /** + * Create an array of dimension filters. + * + * @param array $dimensions + * @return void + */ + protected function createDimensionGroup($dimensions): array + { + $filterExpressionList = []; + + foreach ($dimensions as $dimension) { + $stringFilter = (new StringFilter())->setCaseSensitive($dimension[3] ?? false) + ->setMatchType($dimension[1]) + ->setValue($dimension[2]); + + $filter = (new Filter())->setStringFilter($stringFilter)->setFieldName($dimension[0]); + + $filterExpressionList[] = (new FilterExpression())->setFilter($filter); + } + + return $filterExpressionList; + } }