From 1fcb833902d9924543eac6904fe6c0680a422dae Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 1 Oct 2011 15:32:03 +0300 Subject: [PATCH] added Json parsing abstraction --- src/Composer/Json/JsonFile.php | 93 ++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 src/Composer/Json/JsonFile.php diff --git a/src/Composer/Json/JsonFile.php b/src/Composer/Json/JsonFile.php new file mode 100644 index 000000000..719e8ba5c --- /dev/null +++ b/src/Composer/Json/JsonFile.php @@ -0,0 +1,93 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Json; + +use Composer\Repository\RepositoryManager; + +/** + * Reads/writes json files. + * + * @author Konstantin Kudryashiv + */ +class JsonFile +{ + private $path; + + /** + * Initializes json file reader/parser. + * + * @param string $lockFile path to a lockfile + */ + public function __construct($path) + { + $this->path = $path; + } + + /** + * Checks whether json file exists. + * + * @return Boolean + */ + public function exists() + { + return is_file($this->path); + } + + /** + * Reads json file. + * + * @param string $json path or json string + * + * @return array + */ + public function read() + { + $json = file_get_contents($this->path); + $config = json_decode($json, true); + if (!$config) { + switch (json_last_error()) { + case JSON_ERROR_NONE: + $msg = 'No error has occurred, is your composer.json file empty?'; + break; + case JSON_ERROR_DEPTH: + $msg = 'The maximum stack depth has been exceeded'; + break; + case JSON_ERROR_STATE_MISMATCH: + $msg = 'Invalid or malformed JSON'; + break; + case JSON_ERROR_CTRL_CHAR: + $msg = 'Control character error, possibly incorrectly encoded'; + break; + case JSON_ERROR_SYNTAX: + $msg = 'Syntax error'; + break; + case JSON_ERROR_UTF8: + $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; + break; + } + throw new \UnexpectedValueException('Incorrect composer.json file: '.$msg); + } + + return $config; + } + + /** + * Writes json file. + * + * @param array $hash writes hash into json file + */ + public function write(array $hash) + { + file_put_contents($this->path, json_encode($hash)); + } +}