opnform/app/Service/OpenAi/Utils/PadsJson.php

114 lines
2.6 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Service\OpenAi\Utils;
/**
* Attempts to fix truncated JSON by padding contextual counterparts at the end.
*
* @author Jitendra Adhikari <jiten.adhikary@gmail.com>
* @license MIT
*
* @internal
*
* @link https://github.com/adhocore/php-json-fixer
*/
trait PadsJson
{
public function pad($tmpJson)
{
2024-02-23 10:54:12 +00:00
if (! $this->inStr) {
$tmpJson = \rtrim($tmpJson, ',');
while ($this->lastToken() === ',') {
$this->popToken();
}
}
$tmpJson = $this->padLiteral($tmpJson);
$tmpJson = $this->padObject($tmpJson);
return $this->padStack($tmpJson);
}
protected function padLiteral($tmpJson)
{
if ($this->inStr) {
return $tmpJson;
}
$match = \preg_match('/(tr?u?e?|fa?l?s?e?|nu?l?l?)$/', $tmpJson, $matches);
2024-02-23 10:54:12 +00:00
if (! $match || null === $literal = $this->maybeLiteral($matches[1])) {
return $tmpJson;
}
2024-02-23 10:54:12 +00:00
return \substr($tmpJson, 0, 0 - \strlen($matches[1])).$literal;
}
protected function padStack($tmpJson)
{
foreach (\array_reverse($this->stack, true) as $token) {
if (isset($this->pairs[$token])) {
$tmpJson .= $this->pairs[$token];
}
}
return $tmpJson;
}
protected function padObject($tmpJson)
{
2024-02-23 10:54:12 +00:00
if (! $this->objectNeedsPadding($tmpJson)) {
return $tmpJson;
}
$part = \substr($tmpJson, $this->objectPos + 1);
if (\preg_match('/(\s*\"[^"]+\"\s*:\s*[^,]+,?)+$/', $part, $matches)) {
return $tmpJson;
}
if ($this->inStr) {
$tmpJson .= '"';
}
$tmpJson = $this->padIf($tmpJson, ':');
2024-02-23 10:54:12 +00:00
$tmpJson = $tmpJson.$this->missingValue;
if ($this->lastToken() === '"') {
$this->popToken();
}
return $tmpJson;
}
protected function objectNeedsPadding($tmpJson)
{
2024-02-23 10:54:12 +00:00
$last = \substr($tmpJson, -1);
$empty = $last === '{' && ! $this->inStr;
2024-02-23 10:54:12 +00:00
return ! $empty && $this->arrayPos < $this->objectPos;
}
protected function padString($string)
{
2024-02-23 10:54:12 +00:00
$last = \substr($string, -1);
$last2 = \substr($string, -2);
if ($last2 === '\"' || $last !== '"') {
2024-02-23 10:54:12 +00:00
return $string.'"';
}
// @codeCoverageIgnoreStart
return null;
// @codeCoverageIgnoreEnd
}
protected function padIf($string, $substr)
{
if (\substr($string, 0 - \strlen($substr)) !== $substr) {
2024-02-23 10:54:12 +00:00
return $string.$substr;
}
return $string;
}
}