public static createFromFile ( string $filename ) : |
||
$filename | string | eg: __DIR__ . '/../../configuration.json' |
return | an instance of JSON with the data read from the file |
public static function createFromFile($filename)
{
if (!file_exists($filename)) {
throw new Exception(sprintf('Failed to load json from file %s. The file does not exist', $filename), Exception::BAD_LOADERDATA);
}
//suppres warning with @ operator. we are explicitely testing the return value.
$json = @file_get_contents($filename);
if (false === $json) {
throw new Exception(sprintf('Failed to read json data from file %s. Unknown error (permissions?)', $filename), Exception::BAD_LOADERDATA);
}
return new static($json);
}
/** * @test */ public function shouldThrowExceptionForNoMachineData() { $machine = new StateMachine(new Context(new Identifier('json-test', 'json-machine'))); $loader = JSON::createFromFile(__DIR__ . '/fixture-no-machines.json'); try { $loader->load($machine); $this->fail('should not come here'); } catch (Exception $e) { $this->assertEquals(Exception::BAD_LOADERDATA, $e->getCode()); $this->assertContains('no machine data', $e->getMessage()); } }