Skip to content

Commit 29da61e

Browse files
committed
Add error types parser
This parser converts an error types expression from string to integer. e.g. E_ALL & ~E_DEPRECATED & ~E_NOTICE -> 24567
1 parent 1447190 commit 29da61e

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
3+
namespace Sentry\SentryBundle;
4+
5+
/**
6+
* Evaluate an error types expression.
7+
*/
8+
class ErrorTypesParser
9+
{
10+
private $expression = null;
11+
12+
/**
13+
* Initialize ErrorParser
14+
*
15+
* @param string $expression Error Types e.g. E_ALL & ~E_DEPRECATED & ~E_NOTICE
16+
*/
17+
public function __construct($expression)
18+
{
19+
$this->expression = $expression;
20+
}
21+
22+
/**
23+
* Parse and compute the error types expression
24+
*
25+
* @return int the parsed expression
26+
*/
27+
public function parse()
28+
{
29+
// convert constants to ints
30+
$this->expression = $this->convertErrorConstants($this->expression);
31+
$this->expression = str_replace([",", " "], [".", ""], $this->expression);
32+
// remove anything which could be a security issue
33+
$this->expression = preg_replace("/[^\d.+*%^|&~<>\/()-]/", "", $this->expression);
34+
35+
return $this->compute($this->expression);
36+
}
37+
38+
39+
/**
40+
* Converts error constants from string to int.
41+
*
42+
* @param string $expression e.g. E_ALL & ~E_DEPRECATED & ~E_NOTICE
43+
* @return string convertes expression e.g. 32767 & ~8192 & ~8
44+
*/
45+
private function convertErrorConstants($expression)
46+
{
47+
$output = preg_replace_callback("/(E_[a-zA-Z_]+)/", function ($errorConstant) {
48+
if (defined($errorConstant[1])) {
49+
return constant($errorConstant[1]);
50+
}
51+
return $errorConstant[0];
52+
}, $expression);
53+
54+
return $output;
55+
}
56+
57+
/**
58+
* Let PHP compute the prepared expression for us.
59+
*
60+
* @param string $expression prepared expression e.g. 32767&~8192&~8
61+
* @return int computed expression e.g. 24567
62+
*/
63+
private function compute($expression)
64+
{
65+
$compute = create_function("", "return " . $expression . ";");
66+
67+
return 0 + $compute();
68+
}
69+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
namespace Sentry\SentryBundle\Test;
4+
5+
use Sentry\SentryBundle\ErrorTypesParser;
6+
7+
class ErrorTypesParserTest extends \PHPUnit_Framework_TestCase
8+
{
9+
public function test_error_types_parser()
10+
{
11+
$ex = new ErrorTypesParser('E_ALL & ~E_DEPRECATED & ~E_NOTICE');
12+
$this->assertEquals($ex->parse(), E_ALL & ~E_DEPRECATED & ~E_NOTICE);
13+
}
14+
}

0 commit comments

Comments
 (0)