File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed
Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace Aternos \Codex \Detective ;
4+
5+ /**
6+ * MultiPatternDetector can detect multiple patterns in a log and return true if all patterns are found
7+ */
8+ class MultiPatternDetector extends Detector
9+ {
10+ protected array $ patterns = [];
11+
12+ /**
13+ * Add a pattern to the list of patterns to detect
14+ *
15+ * @param string $pattern
16+ * @return $this
17+ */
18+ public function addPattern (string $ pattern ): static
19+ {
20+ $ this ->patterns [] = $ pattern ;
21+ return $ this ;
22+ }
23+
24+ /**
25+ * Detects if the log matches all patterns
26+ *
27+ * Returns true if all patterns are found, false otherwise
28+ *
29+ * @return bool|float
30+ */
31+ public function detect (): bool |float
32+ {
33+ foreach ($ this ->patterns as $ pattern ) {
34+ if (preg_match ($ pattern , $ this ->getLogContent ()) !== 1 ) {
35+ return false ;
36+ }
37+ }
38+
39+ return true ;
40+ }
41+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace Aternos \Codex \Test \Tests \Detector ;
4+
5+ use Aternos \Codex \Detective \MultiPatternDetector ;
6+ use Aternos \Codex \Log \File \StringLogFile ;
7+ use PHPUnit \Framework \TestCase ;
8+
9+ class MultiPatternDetectorTest extends TestCase
10+ {
11+ public function testDetectSinglePattern (): void
12+ {
13+ $ this ->assertTrue ((new MultiPatternDetector ())
14+ ->setLogFile (new StringLogFile ("You can detect this. " ))
15+ ->addPattern ('/detect/ ' )
16+ ->detect ()
17+ );
18+ }
19+
20+ public function testDetectMultiplePatterns (): void
21+ {
22+ $ this ->assertTrue ((new MultiPatternDetector ())
23+ ->setLogFile (new StringLogFile ("You can detect this and this. " ))
24+ ->addPattern ('/detect/ ' )
25+ ->addPattern ('/and this/ ' )
26+ ->detect ()
27+ );
28+ }
29+
30+ public function testNotDetectMissingFromMultiplePatterns (): void
31+ {
32+ $ this ->assertFalse ((new MultiPatternDetector ())
33+ ->setLogFile (new StringLogFile ("You can detect this and this. " ))
34+ ->addPattern ('/detect/ ' )
35+ ->addPattern ('/and this/ ' )
36+ ->addPattern ('/but not this/ ' )
37+ ->detect ()
38+ );
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments