Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Last active July 14, 2023 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jehoshua02/61dc9c72db7ce8bee70d to your computer and use it in GitHub Desktop.
Save jehoshua02/61dc9c72db7ce8bee70d to your computer and use it in GitHub Desktop.
JsonFileDataProviderIterator class for use with PHPUnit @dataProvider annotation.

JsonFileDataProviderIterator

First in the test use @dataProvider annotation and instantiate JsonFileDataProviderIterator in the data provider method, passing in the test file (__FILE__) and some namespace (something):

<?php

use \JsonFileDataProviderIterator;

class MyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider someDataProvider
     */
    public function testSomething($data)
    {
        // ...
    }

    public function someDataProvider()
    {
        return new JsonFileDataProviderIterator(__FILE__, 'something');
    }
}

Then setup a directory next to the test file with the same name replacing .php with .data, organize json data files into subdirectories matching the namespace used in the test (something).

+ MyTest.php
+ MyTest.data/
|--+ something/
|  |--+ some_simple_scenario.json
|  |--+ some_crazy_scenario.json
<?php
class JsonDataProviderIterator implements Iterator
{
protected $position = 0;
protected $array;
public function __construct($test, $namespace)
{
$path = preg_replace('/.php$/', '.data', $test) . '/' . $namespace;
$files = array_filter(scandir($path), function ($file) {
return preg_match('/.json$/', $file);
});
$files = array_map(function ($file) use ($path) {
return $path . '/' . $file;
}, $files);
sort($files);
$this->array = $files;
}
public function current()
{
$file = $this->array[$this->position];
$content = file_get_contents($file);
return [json_decode($content, true)];
}
public function key()
{
return $this->position;
}
public function next()
{
++$this->position;
}
public function rewind()
{
$this->position = 0;
}
public function valid()
{
return isset($this->array[$this->position]);
}
}
@openbrian
Copy link

-class JsonDataProviderIterator implements Iterator
+class JsonFileDataProviderIterator implements Iterator

@henryruhs
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment