Creating Instances - machitgarha/JsonFile GitHub Wiki
Creating instances is the first step. As the very first step, you have to provide the path of the file you want to load:
// Loading composer.json in the current directory
$jsonFile = new JSONFile(__DIR__ . "/composer.json");
Default behavior
When you try to load a file, two things might happen:
- The file doesn't exist. In this case, the file will be created automatically. If the file cannot be created, it will throw an exception.
- The file contains a bad JSON data, e.g.
{""}
. This will lead to an exception, and you might want to handle it.
Overriding the defaults
You can use options to override the default behavior. There are two options available:
JSONFile::FILE_MUST_EXIST
: Forces the file to be exist, otherwise it will throw an exception.JSONFile::IGNORE_INVALID_FILE
: Ignore invalid JSON data in the file, and set data to an empty array.
You can use a combination of the options, using |
operator.
Examples
$filename = __DIR__ . "/composer.json";
// Throws an exception if the file doesn't exist
$jsonFile = new JSONFile($filename, JSONFile::FILE_MUST_EXIST);
// Doesn't throw an exception if the file contains invalid JSON
$jsonFile = new JSONFile($filename, JSONFile::IGNORE_INVALID_FILE);
// Use both options together
$jsonFile = new JSONFile($filename, JSONFile::FILE_MUST_EXIST | JSONFile::IGNORE_INVALID_FILE);