Skip to content

Commit

Permalink
Update PCRE pattern after LogParser::addPattern()
Browse files Browse the repository at this point in the history
  • Loading branch information
kassner committed Jul 18, 2023
1 parent 36c3c2f commit ba411a2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 11 deletions.
32 changes: 21 additions & 11 deletions src/LogParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ final class LogParser
{
public const DEFAULT_FORMAT = '%h %l %u %t "%r" %>s %b';

/** @var string */
private $format;

/** @var string */
private $pcreFormat;

Expand Down Expand Up @@ -48,28 +51,20 @@ final class LogParser

public function __construct(string $format = null, LogEntryFactoryInterface $factory = null)
{
$this->updateIpPatterns();
$this->setFormat($format ?: self::DEFAULT_FORMAT);
$this->factory = $factory ?: new SimpleLogEntryFactory();
}

public function addPattern(string $placeholder, string $pattern): void
{
$this->patterns[$placeholder] = $pattern;
$this->updateIpPatterns();
$this->updatePCREPattern();
}

public function setFormat(string $format): void
{
// strtr won't work for "complex" header patterns
// $this->pcreFormat = strtr("#^{$format}$#", $this->patterns);
$expr = "#^{$format}$#";

foreach ($this->patterns as $pattern => $replace) {
$expr = preg_replace("/{$pattern}/", $replace, $expr);
}

$this->pcreFormat = $expr;
$this->format = $format;
$this->updatePCREPattern();
}

/**
Expand All @@ -91,6 +86,21 @@ public function getPCRE(): string
return $this->pcreFormat;
}

private function updatePCREPattern(): void
{
$this->updateIpPatterns();

// strtr won't work for "complex" header patterns
// $this->pcreFormat = strtr("#^{$format}$#", $this->patterns);
$expr = "#^{$this->format}$#";

foreach ($this->patterns as $pattern => $replace) {
$expr = preg_replace("/{$pattern}/", $replace, $expr);
}

$this->pcreFormat = $expr;
}

/**
* Replaces {{PATTERN_IP_ALL}} with the IPV4/6 patterns.
*/
Expand Down
18 changes: 18 additions & 0 deletions tests/CustomPatternTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,22 @@ public function testCustomIpPattern()
$entry = $this->parser->parse('192.168.1.20 2001:aaaa:bbbb::cc00 "GET / HTTP/1.1"');
$this->assertEquals('2001:aaaa:bbbb::cc00', $entry->loadBalancer);
}

public function testAddPatternBeforeSetFormat()
{
$this->parser->addPattern('%Y', '(?P<test>[0-9]+)');
$this->parser->setFormat('%Y');

$entry = $this->parser->parse('123');
$this->assertEquals('123', $entry->test);
}

public function testAddPatternAfterSetFormat()
{
$this->parser->setFormat('%Y');
$this->parser->addPattern('%Y', '(?P<test>[0-9]+)');

$entry = $this->parser->parse('123');
$this->assertEquals('123', $entry->test);
}
}

0 comments on commit ba411a2

Please sign in to comment.