<?php

namespace Mnv\Core\JSONParser\Parser;

use Mnv\Core\JSONParser\Exception\FileException;

/**
 * SimpleExcel class for parsing JSON table
 *
 * @package JSONParser
 */
class JSONParser extends BaseParser implements IParser
{
    /**
     * Defines valid file extension
     *
     * @access   protected
     * @var      string
     */
    protected string $file_extension = 'json';

    /**
     * Load the JSONLANG file to be parsed
     *
     * @param  string  $file_path  Path to JSON file
     */
    public function loadFile($file_path)
    {
        if (!$this->isFileReady($file_path)) {
            return;
        }

        $handle = fopen($file_path, 'r');
        if (filesize($file_path) > 0) {
            $contents = fread($handle, filesize($file_path));
            $this->loadString($contents);
        }
        fclose($handle);
    }

    /**
     * Load the string to be parsed
     *
     * @param    string  $str    String with JSONLANG format
     * @throws   Exception       If JSONLANG format is invalid (or too deep)
     */
    public function loadString($str)
    {
        $field = array();
        if (($table = json_decode($str, true, 4)) === NULL) {
            throw new \Exception('Invalid JSON format: '.$str, FileException::MALFORMED_JSON);
        } else {
            foreach ($table as $rows) {
                array_push($field, $rows);
            }
        }
        $this->table_arr = $field;


    }
}
