<?php

namespace Ignite\Core\Models\Seeds;

class JsonSeederParser
{
    /**
     * Parse the json data.
     *
     * @param  string $path
     * @param  string $key
     * @return array
     * @throws \Exception
     */
    public function parse($path, $key = 'data')
    {
        if (! file_exists($path) || ! is_file($path)) {
            throw new \Exception("$path does not exist or is not a file.");
        }

        $json = file_get_contents($path);

        $data = json_decode($json, $associative = true);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new \Exception("$path does not contain valid JSON: " . json_last_error_msg());
        }

        if (! array_key_exists($key, $data)) {
            throw new \Exception("Unable to find key $key in the JSON data.");
        }

        return $data[$key];
    }
}
