1<?php
2/**
3 * Zend Framework (http://framework.zend.com/)
4 *
5 * @link      http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license   http://framework.zend.com/license/new-bsd New BSD License
8 */
9
10namespace Zend\Log\Filter;
11
12use Traversable;
13use Zend\Log\Exception;
14use Zend\Stdlib\ErrorHandler;
15
16class Regex implements FilterInterface
17{
18    /**
19     * Regex to match
20     *
21     * @var string
22     */
23    protected $regex;
24
25    /**
26     * Filter out any log messages not matching the pattern
27     *
28     * @param string|array|Traversable $regex Regular expression to test the log message
29     * @return Regex
30     * @throws Exception\InvalidArgumentException
31     */
32    public function __construct($regex)
33    {
34        if ($regex instanceof Traversable) {
35            $regex = iterator_to_array($regex);
36        }
37        if (is_array($regex)) {
38            $regex = isset($regex['regex']) ? $regex['regex'] : null;
39        }
40        ErrorHandler::start(E_WARNING);
41        $result = preg_match($regex, '');
42        $error  = ErrorHandler::stop();
43        if ($result === false) {
44            throw new Exception\InvalidArgumentException(sprintf(
45                'Invalid regular expression "%s"',
46                $regex
47            ), 0, $error);
48        }
49        $this->regex = $regex;
50    }
51
52    /**
53     * Returns TRUE to accept the message, FALSE to block it.
54     *
55     * @param array $event event data
56     * @return bool accepted?
57     */
58    public function filter(array $event)
59    {
60        $message = $event['message'];
61        if (is_array($event['message'])) {
62            $message = var_export($message, true);
63        }
64        return preg_match($this->regex, $message) > 0;
65    }
66}
67