Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add AtMostModifier selector modifier #286

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/Selector/Modifier/AtMostModifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php declare(strict_types=1);

namespace PHPat\Selector\Modifier;

use PHPat\Selector\SelectorInterface;
use PHPStan\Reflection\ClassReflection;

final class AtMostModifier implements SelectorInterface
{
private int $max;
private array $selectors;

public function __construct(int $max, SelectorInterface ...$selector)
{
$this->max = $max;
$this->selectors = array_values($selector);
}

public function matches(ClassReflection $classReflection): bool
{
$matches = 0;

foreach ($this->selectors as $selector) {
if ($selector->matches($classReflection)) {
++$matches;
}
}

return $matches <= $this->max;
}

public function getName(): string
{
return 'at-most-'.$this->max.'-of: '.implode(
', ',
array_map(static fn (SelectorInterface $selector) => $selector->getName(), $this->selectors),
);
}
}
6 changes: 6 additions & 0 deletions src/Selector/Selector.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PHPat\Selector;

use PHPat\Selector\Modifier\AndModifier;
use PHPat\Selector\Modifier\AtMostModifier;
use PHPat\Selector\Modifier\NotModifier;

final class Selector extends SelectorPrimitive
Expand All @@ -16,4 +17,9 @@ public static function NOT(SelectorInterface $selector): NotModifier
{
return new NotModifier($selector);
}

public static function MAX(int $max, SelectorInterface ...$selector): AtMostModifier
{
return new AtMostModifier($max, ...$selector);
}
}
Loading