public function addMainKey($key, $content) { $decoded = JsonFile::parseJson($this->contents); $content = $this->format($content); // key exists already $regex = '{^(\\s*\\{\\s*(?:' . self::$JSON_STRING . '\\s*:\\s*' . self::$JSON_VALUE . '\\s*,\\s*)*?)' . '(' . preg_quote(JsonFile::encode($key)) . '\\s*:\\s*' . self::$JSON_VALUE . ')(.*)}s'; if (isset($decoded[$key]) && $this->pregMatch($regex, $this->contents, $matches)) { // invalid match due to un-regexable content, abort if (!@json_decode('{' . $matches[2] . '}')) { return false; } $this->contents = $matches[1] . JsonFile::encode($key) . ': ' . $content . $matches[3]; return true; } // append at the end of the file and keep whitespace if ($this->pregMatch('#[^{\\s](\\s*)\\}$#', $this->contents, $match)) { $this->contents = preg_replace('#' . $match[1] . '\\}$#', addcslashes(',' . $this->newline . $this->indent . JsonFile::encode($key) . ': ' . $content . $this->newline . '}', '\\'), $this->contents); return true; } // append at the end of the file $this->contents = preg_replace('#\\}$#', addcslashes($this->indent . JsonFile::encode($key) . ': ' . $content . $this->newline . '}', '\\'), $this->contents); return true; }
public function addMainKey($key, $content) { $decoded = JsonFile::parseJson($this->contents); $content = $this->format($content); $regex = '{^(\\s*\\{\\s*(?:' . self::$JSON_STRING . '\\s*:\\s*' . self::$JSON_VALUE . '\\s*,\\s*)*?)' . '(' . preg_quote(JsonFile::encode($key)) . '\\s*:\\s*' . self::$JSON_VALUE . ')(.*)}s'; if (isset($decoded[$key]) && $this->pregMatch($regex, $this->contents, $matches)) { if (!@json_decode('{' . $matches[2] . '}')) { return false; } $this->contents = $matches[1] . JsonFile::encode($key) . ': ' . $content . $matches[3]; return true; } if ($this->pregMatch('#[^{\\s](\\s*)\\}$#', $this->contents, $match)) { $this->contents = preg_replace('#' . $match[1] . '\\}$#', addcslashes(',' . $this->newline . $this->indent . JsonFile::encode($key) . ': ' . $content . $this->newline . '}', '\\'), $this->contents); return true; } $this->contents = preg_replace('#\\}$#', addcslashes($this->indent . JsonFile::encode($key) . ': ' . $content . $this->newline . '}', '\\'), $this->contents); return true; }