Skip to content

Commit

Permalink
Merge pull request #21 from pavog/multi-pattern-detector
Browse files Browse the repository at this point in the history
Add MultiPatternDetector
  • Loading branch information
matthi4s authored Sep 11, 2024
2 parents 2eec8ff + 9f0380d commit 8f7615e
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/Detective/MultiPatternDetector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Aternos\Codex\Detective;

/**
* MultiPatternDetector can detect multiple patterns in a log and return true if all patterns are found
*/
class MultiPatternDetector extends Detector
{
protected array $patterns = [];

/**
* Add a pattern to the list of patterns to detect
*
* @param string $pattern
* @return $this
*/
public function addPattern(string $pattern): static
{
$this->patterns[] = $pattern;
return $this;
}

/**
* Detects if the log matches all patterns
*
* Returns true if all patterns are found, false otherwise
*
* @return bool|float
*/
public function detect(): bool|float
{
foreach ($this->patterns as $pattern) {
if (preg_match($pattern, $this->getLogContent()) !== 1) {
return false;
}
}

return true;
}
}
40 changes: 40 additions & 0 deletions test/tests/Detector/MultiPatternDetectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Aternos\Codex\Test\Tests\Detector;

use Aternos\Codex\Detective\MultiPatternDetector;
use Aternos\Codex\Log\File\StringLogFile;
use PHPUnit\Framework\TestCase;

class MultiPatternDetectorTest extends TestCase
{
public function testDetectSinglePattern(): void
{
$this->assertTrue((new MultiPatternDetector())
->setLogFile(new StringLogFile("You can detect this."))
->addPattern('/detect/')
->detect()
);
}

public function testDetectMultiplePatterns(): void
{
$this->assertTrue((new MultiPatternDetector())
->setLogFile(new StringLogFile("You can detect this and this."))
->addPattern('/detect/')
->addPattern('/and this/')
->detect()
);
}

public function testNotDetectMissingFromMultiplePatterns(): void
{
$this->assertFalse((new MultiPatternDetector())
->setLogFile(new StringLogFile("You can detect this and this."))
->addPattern('/detect/')
->addPattern('/and this/')
->addPattern('/but not this/')
->detect()
);
}
}

0 comments on commit 8f7615e

Please sign in to comment.