Skip to content

Commit cf9ddc0

Browse files
committed
Add new static function for parsing simple strings
1 parent 3e73949 commit cf9ddc0

File tree

3 files changed

+41
-5
lines changed

3 files changed

+41
-5
lines changed

README.md

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,14 @@ A small library to parse text representations of a PHP array and return an actua
55

66
Run `composer install` to run this script (and tests) in a standalone way. Alternatively, this can be used as a dependency in another project by running `composer require battye/php-array-parser "~1.0"`.
77

8-
If you notice any bugs, please feel free to raise an issue or pull request.
8+
Reference the namespace at the top of your PHP files to utilise the included classes:
9+
10+
```php
11+
use battye\array_parser\parser;
12+
use battye\array_parser\tokens;
13+
```
14+
15+
If you notice any bugs, please raise an issue or pull request.
916

1017
## Example
1118

@@ -16,10 +23,8 @@ In both of the following examples, `$result` would contain a PHP array containin
1623
To parse a simple array is very easy:
1724

1825
```php
19-
$string = "array(0 => array('one' => 1, 'two' => 'two'));";
20-
$tokens = new tokens($string);
21-
$parser = new parser($tokens);
22-
$result = $parser->parse_array();
26+
$value = "array(0 => array('one' => 1, 'two' => 'two'));";
27+
$result = parser::parse_simple($value);
2328
```
2429

2530
In this case, `$result` would produce the following:

src/parser.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,21 @@ public function __construct(tokens $tokens)
2424
$this->tokens = $tokens;
2525
}
2626

27+
/**
28+
* Simple parser to convert a simple string to an array
29+
* @param $value
30+
* @return array
31+
* @throws \Exception
32+
*/
33+
public static function parse_simple($value)
34+
{
35+
$tokens = new tokens($value);
36+
$parser = new parser($tokens);
37+
$result = $parser->parse_array();
38+
39+
return $result;
40+
}
41+
2742
/**
2843
* Simple and generic regex parser, made with phpBB in mind.
2944
* @param $regex

tests/ArrayParserTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,22 @@
99

1010
class ArrayParserTest extends \PHPUnit\Framework\TestCase
1111
{
12+
/**
13+
* Test a simple multi-dimensional array using the static function
14+
*/
15+
public function testParseSimple()
16+
{
17+
$string = "array('test' => [1, 2, 3, 4 => ['a', 'b', 'c']], 'value' => 'text');";
18+
$result = parser::parse_simple($string);
19+
20+
$expected = [
21+
'test' => [1, 2, 3, 4 => ['a', 'b', 'c']],
22+
'value' => 'text',
23+
];
24+
25+
$this->assertArraySubset($expected, $result);
26+
}
27+
1228
/**
1329
* Test that a simple string is parsed correctly
1430
*/

0 commit comments

Comments
 (0)