├── VERSION ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ └── run-tests.yml ├── .gitignore ├── tests ├── bootstrap.php └── FixerTest.php ├── .editorconfig ├── .travis.yml ├── CHANGELOG.md ├── phpunit.xml.dist ├── LICENSE ├── composer.json ├── src ├── PadsJson.php └── Fixer.php └── readme.md /VERSION: -------------------------------------------------------------------------------- 1 | v1.0.0 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: adhocore 2 | custom: ['https://paypal.me/ji10'] 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # standards 2 | /.cache/ 3 | /.env 4 | /.idea/ 5 | /vendor/ 6 | composer.lock 7 | coverage.xml 8 | clover.xml 9 | *.local.* 10 | .phpunit.result.cache -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: composer 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "22:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /tests/bootstrap.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * 9 | * Licensed under MIT license. 10 | */ 11 | 12 | require_once __DIR__ . '/../vendor/autoload.php'; 13 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | ; http://editorconfig.org 2 | ; 3 | ; Sublime: https://github.com/sindresorhus/editorconfig-sublime 4 | ; Phpstorm: https://plugins.jetbrains.com/plugin/7294-editorconfig 5 | 6 | root = true 7 | 8 | [*] 9 | indent_style = space 10 | indent_size = 4 11 | end_of_line = lf 12 | charset = utf-8 13 | trim_trailing_whitespace = true 14 | insert_final_newline = true 15 | 16 | [{*.js,*.css,*.scss,*.html}] 17 | indent_size = 2 18 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | php: 4 | - 5.6 5 | - 7.0 6 | - 7.1 7 | - 7.2 8 | - 7.3 9 | - 7.4 10 | - nightly 11 | 12 | matrix: 13 | allow_failures: 14 | - php: nightly 15 | 16 | install: 17 | - composer install --prefer-dist 18 | 19 | before_script: 20 | - for P in src tests; do find $P -type f -name '*.php' -exec php -l {} \;; done 21 | 22 | script: 23 | - vendor/bin/phpunit --coverage-text --coverage-clover=coverage.xml 24 | 25 | after_success: 26 | - bash <(curl -s https://codecov.io/bash) 27 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [v0.0.4](https://github.com/adhocore/php-json-fixer/releases/tag/v0.0.4) (2022-04-13) 2 | 3 | ### Bug Fixes 4 | - Regular expression (ockstadt) [_e168d9a_](https://github.com/adhocore/php-json-fixer/commit/e168d9a) 5 | 6 | 7 | ## [v0.0.3](https://github.com/adhocore/php-json-fixer/releases/tag/v0.0.3) (2020-12-30) 8 | 9 | ### Builds 10 | - **Travis**: Add php 7.4 (Jitendra Adhikari) [_bbeab27_](https://github.com/adhocore/php-json-fixer/commit/bbeab27) 11 | - **Travis**: Retire PHP pre 5.6 (Jitendra Adhikari) [_e92c1bb_](https://github.com/adhocore/php-json-fixer/commit/e92c1bb) 12 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 14 | 15 | 16 | ./tests/ 17 | 18 | 19 | 20 | 21 | ./src 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Jitendra Adhikari 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "adhocore/json-fixer", 3 | "description": "Fix/repair truncated JSON data", 4 | "type": "library", 5 | "keywords": ["php","php-json-fixer","json","truncated-json","json-fixer","truncation-fixer","rectify-json","fix-json"], 6 | "license": "MIT", 7 | "authors": [ 8 | { 9 | "name": "Jitendra Adhikari", 10 | "email": "jiten.adhikary@gmail.com" 11 | } 12 | ], 13 | "autoload": { 14 | "psr-4": { 15 | "Ahc\\Json\\": "src/" 16 | }, 17 | "files": [] 18 | }, 19 | "autoload-dev": { 20 | "psr-4": { 21 | "Ahc\\Test\\Json\\": "tests/" 22 | } 23 | }, 24 | "require": { 25 | "php": ">=5.4.0", 26 | "ext-json": "*" 27 | }, 28 | "require-dev": { 29 | "phpunit/phpunit": "^4.8 || ^5.7 || ^6.5 || ^7.0 || ^8.0 || ^9.0" 30 | }, 31 | "config": { 32 | "optimize-autoloader": true, 33 | "preferred-install": { 34 | "*": "dist" 35 | } 36 | }, 37 | "scripts": { 38 | "post-root-package-install": [ 39 | ], 40 | "lint": "for P in src tests; do find $P -type f -name '*.php' -exec php -l {} \\;; done", 41 | "test": "vendor/bin/phpunit --coverage-text --coverage-clover coverage.xml" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: [ push, pull_request ] 4 | 5 | jobs: 6 | test: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | fail-fast: true 10 | matrix: 11 | os: [ ubuntu-latest ] 12 | php: [ 5.6, 7.0, 7.1, 7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3 ] 13 | dependency-version: [ prefer-stable ] 14 | 15 | name: P${{ matrix.php }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} 16 | 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v3 20 | 21 | - name: Cache dependencies 22 | uses: actions/cache@v3 23 | with: 24 | path: ~/.composer/cache/files 25 | key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} 26 | 27 | - name: Setup PHP 28 | uses: shivammathur/setup-php@v2 29 | with: 30 | php-version: ${{ matrix.php }} 31 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick 32 | coverage: xdebug 33 | 34 | - name: Install dependencies 35 | run: composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction 36 | 37 | - name: Lint 38 | run: composer lint 39 | 40 | - name: Execute tests 41 | run: composer test 42 | 43 | - name: Upload coverage to Codecov 44 | uses: codecov/codecov-action@v3 45 | with: 46 | token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos 47 | fail_ci_if_error: false # optional (default = false) 48 | verbose: true # optional (default = false) 49 | -------------------------------------------------------------------------------- /src/PadsJson.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * 9 | * Licensed under MIT license. 10 | */ 11 | 12 | namespace Ahc\Json; 13 | 14 | /** 15 | * Attempts to fix truncated JSON by padding contextual counterparts at the end. 16 | * 17 | * @author Jitendra Adhikari 18 | * @license MIT 19 | * 20 | * @internal 21 | * 22 | * @link https://github.com/adhocore/php-json-fixer 23 | */ 24 | trait PadsJson 25 | { 26 | public function pad($tmpJson) 27 | { 28 | if (!$this->inStr) { 29 | $tmpJson = \rtrim($tmpJson, ','); 30 | while ($this->lastToken() === ',') { 31 | $this->popToken(); 32 | } 33 | } 34 | 35 | $tmpJson = $this->padLiteral($tmpJson); 36 | $tmpJson = $this->padObject($tmpJson); 37 | 38 | return $this->padStack($tmpJson); 39 | } 40 | 41 | protected function padLiteral($tmpJson) 42 | { 43 | if ($this->inStr) { 44 | return $tmpJson; 45 | } 46 | 47 | $match = \preg_match('/(tr?u?e?|fa?l?s?e?|nu?l?l?)$/', $tmpJson, $matches); 48 | 49 | if (!$match || null === $literal = $this->maybeLiteral($matches[1])) { 50 | return $tmpJson; 51 | } 52 | 53 | return \substr($tmpJson, 0, 0 - \strlen($matches[1])) . $literal; 54 | } 55 | 56 | protected function padStack($tmpJson) 57 | { 58 | foreach (\array_reverse($this->stack, true) as $token) { 59 | if (isset($this->pairs[$token])) { 60 | $tmpJson .= $this->pairs[$token]; 61 | } 62 | } 63 | 64 | return $tmpJson; 65 | } 66 | 67 | protected function padObject($tmpJson) 68 | { 69 | if (!$this->objectNeedsPadding($tmpJson)) { 70 | return $tmpJson; 71 | } 72 | 73 | $part = \substr($tmpJson, $this->objectPos + 1); 74 | if (\preg_match('/(\s*\"[^"]+\"\s*:\s*([^,]+|\"(?:.(?!(?inStr) { 79 | $tmpJson .= '"'; 80 | } 81 | 82 | $tmpJson = $this->padIf($tmpJson, ':'); 83 | $tmpJson = $tmpJson . $this->missingValue; 84 | 85 | if ($this->lastToken() === '"') { 86 | $this->popToken(); 87 | } 88 | 89 | return $tmpJson; 90 | } 91 | 92 | protected function objectNeedsPadding($tmpJson) 93 | { 94 | $last = \substr($tmpJson, -1); 95 | $empty = $last === '{' && !$this->inStr; 96 | 97 | return !$empty && $this->arrayPos < $this->objectPos; 98 | } 99 | 100 | protected function padString($string) 101 | { 102 | $last = \substr($string, -1); 103 | $last2 = \substr($string, -2); 104 | 105 | if ($last2 === '\"' || $last !== '"') { 106 | return $string . '"'; 107 | } 108 | 109 | // @codeCoverageIgnoreStart 110 | return null; 111 | // @codeCoverageIgnoreEnd 112 | } 113 | 114 | protected function padIf($string, $substr) 115 | { 116 | if (\substr($string, 0 - \strlen($substr)) !== $substr) { 117 | return $string . $substr; 118 | } 119 | 120 | return $string; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## adhocore/json-fixer 2 | 3 | PHP library to fix Truncated JSON data by padding contextual counterpart to the end. Works with PHP5.4 or above. 4 | 5 | [![Latest Version](https://img.shields.io/github/release/adhocore/php-json-fixer.svg?style=flat-square)](https://github.com/adhocore/php-json-fixer/releases) 6 | [![Travis Build](https://travis-ci.com/adhocore/php-json-fixer.svg?branch=master)](https://travis-ci.com/adhocore/php-json-fixer?branch=master) 7 | [![Scrutinizer CI](https://img.shields.io/scrutinizer/g/adhocore/php-json-fixer.svg?style=flat-square)](https://scrutinizer-ci.com/g/adhocore/php-json-fixer/?branch=master) 8 | [![Codecov branch](https://img.shields.io/codecov/c/github/adhocore/php-json-fixer/master.svg?style=flat-square)](https://codecov.io/gh/adhocore/php-json-fixer) 9 | [![StyleCI](https://styleci.io/repos/141589074/shield)](https://styleci.io/repos/141589074) 10 | [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) 11 | [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Rescue+and+fix+truncated+JSON+data+in+PHP&url=https://github.com/adhocore/php-json-fixer&hashtags=php,json,jsonfixer,fixjson) 12 | [![Support](https://img.shields.io/static/v1?label=Support&message=%E2%9D%A4&logo=GitHub)](https://github.com/sponsors/adhocore) 13 | 16 | 17 | 18 | - Zero dependency (no vendor bloat). 19 | 20 | **It is a work in progress and might not cover all edge cases.** It would be great if you try it out, open some issues or contribute. 21 | 22 | ## Installation 23 | ```bash 24 | composer require adhocore/json-fixer 25 | ``` 26 | 27 | ## Usage 28 | ```php 29 | use Ahc\Json\Fixer; 30 | 31 | $json = (new Fixer)->fix('{"a":1,"b":2'); 32 | // {"a":1,"b":2} 33 | 34 | $json = (new Fixer)->fix('{"a":1,"b":true,'); 35 | // {"a":1,"b":true} 36 | 37 | $json = (new Fixer)->fix('{"b":[1,[{"b":1,"c"'); 38 | // {"b":[1,[{"b":1,"c":null}]]} 39 | 40 | // For batch fixing, you can just reuse same fixer instance: 41 | $fixer = new Fixer; 42 | 43 | $fixer->fix('...'); 44 | $fixer->fix('...'); 45 | // ... 46 | ``` 47 | 48 | ## Error 49 | 50 | If there's error and fixer cant fix the JSON for some reason, it will throw a `RuntimeException`. 51 | You can disable this behavior by passing silent flag (2nd param) to `fix()` in which case original input is returned: 52 | 53 | ```php 54 | (new Fixer)->silent()->fix('invalid'); 55 | // 'invalid' 56 | 57 | (new Fixer)->silent(true)->fix('invalid'); 58 | // 'invalid' 59 | 60 | (new Fixer)->silent(false)->fix('invalid'); 61 | // RuntimeException 62 | ``` 63 | 64 | ## Missing Value 65 | 66 | By default missing values are padded with `null`. You can change it passing desired value to `missingValue()`: 67 | 68 | ```php 69 | // key b is missing value and is padded with `null` 70 | $json = (new Fixer)->fix('{"a":1,"b":'); 71 | // {"a":1,"b":null} 72 | 73 | // key b is missing value and is padded with `true` 74 | $json = (new Fixer)->missingValue(true)->fix('{"a":1,"b":'); 75 | // {"a":1,"b":true} 76 | 77 | // key b is missing value and is padded with `"truncated"` 78 | // Note that you can actually inject a whole new JSON subset as 3rd param 79 | // but that should be a valid JSON segment and is not checked by fixer. 80 | $json = (new Fixer)->missingValue('"truncated"')->fix('{"a":1,"b":'); 81 | // {"a":1,"b":"truncated"} 82 | ``` 83 | 84 | ## Todo 85 | 86 | - [ ] Configurable missing value as per context (options) 87 | -------------------------------------------------------------------------------- /tests/FixerTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * 9 | * Licensed under MIT license. 10 | */ 11 | 12 | namespace Ahc\Test\Json; 13 | 14 | use Ahc\Json\Fixer; 15 | 16 | class FixerTest extends \PHPUnit\Framework\TestCase 17 | { 18 | /** @dataProvider theTests */ 19 | public function test($json, $expect, $msg = '') 20 | { 21 | $this->assertSame($expect, (new Fixer())->fix($json), $msg); 22 | } 23 | 24 | public function test_invalid_literal() 25 | { 26 | $fixer = (new Fixer())->silent(true); 27 | 28 | $this->assertSame('{"a" : invalid', $fixer->fix('{"a" : invalid')); 29 | $this->assertSame(' hmm ', $fixer->fix(' hmm ')); 30 | } 31 | 32 | public function test_ws() 33 | { 34 | $this->assertSame('{ "a" :null}', (new Fixer())->missingValue(null)->fix('{ "a" :')); 35 | $this->assertSame("\n [{}]", (new Fixer())->fix("\n [{,")); 36 | } 37 | 38 | public function test_custom_missing() 39 | { 40 | $fixer = new Fixer(); 41 | $this->assertSame('{"a":false}', $fixer->missingValue(false)->fix('{"a')); 42 | $this->assertSame('{"a":true}', $fixer->missingValue('true')->fix('{"a":')); 43 | $this->assertSame('{"a":1,"b":"missing"}', $fixer->missingValue('"missing"')->fix('{"a":1,"b"')); 44 | } 45 | 46 | public function test_fail_silent() 47 | { 48 | $this->assertSame('{"a"}', (new Fixer())->silent(true)->fix('{"a"}')); 49 | } 50 | 51 | public function test_fail_throws() 52 | { 53 | $this->expectException('\RuntimeException'); 54 | $this->expectExceptionMessage('Could not fix JSON'); 55 | 56 | (new Fixer())->silent(false)->fix('{,"a'); 57 | } 58 | 59 | public function theTests() 60 | { 61 | return [[ 62 | 'json' => '', 63 | 'expect' => '', 64 | ], [ 65 | 'json' => '"', 66 | 'expect' => '""', 67 | ], [ 68 | 'json' => '"a"', 69 | 'expect' => '"a"', 70 | ], [ 71 | 'json' => 'true', 72 | 'expect' => 'true', 73 | ], [ 74 | 'json' => 'false', 75 | 'expect' => 'false', 76 | ], [ 77 | 'json' => 'null', 78 | 'expect' => 'null', 79 | ], [ 80 | 'json' => 'fal', 81 | 'expect' => 'false', 82 | ], [ 83 | 'json' => 't', 84 | 'expect' => 'true', 85 | ], [ 86 | 'json' => 'nu', 87 | 'expect' => 'null', 88 | ], [ 89 | 'json' => '{', 90 | 'expect' => '{}', 91 | ], [ 92 | 'json' => '[', 93 | 'expect' => '[]', 94 | ], [ 95 | 'json' => '12.34', 96 | 'expect' => '12.34', 97 | ], [ 98 | 'json' => '"str', 99 | 'expect' => '"str"', 100 | ], [ 101 | 'json' => '[{', 102 | 'expect' => '[{}]', 103 | ], [ 104 | 'json' => '[1', 105 | 'expect' => '[1]', 106 | ], [ 107 | 'json' => '["', 108 | 'expect' => '[""]', 109 | ], [ 110 | 'json' => '[1,', 111 | 'expect' => '[1]', 112 | ], [ 113 | 'json' => '[1,{', 114 | 'expect' => '[1,{}]', 115 | ], [ 116 | 'json' => '["a', 117 | 'expect' => '["a"]', 118 | ], [ 119 | 'json' => '["b,', 120 | 'expect' => '["b,"]', 121 | ], [ 122 | 'json' => '["b",{"', 123 | 'expect' => '["b",{"":null}]', 124 | ], [ 125 | 'json' => '["b",{"a', 126 | 'expect' => '["b",{"a":null}]', 127 | ], [ 128 | 'json' => '["b",{"a":', 129 | 'expect' => '["b",{"a":null}]', 130 | ], [ 131 | 'json' => '["b",{"a":[t', 132 | 'expect' => '["b",{"a":[true]}]', 133 | ], [ 134 | 'json' => '{"a":2', 135 | 'expect' => '{"a":2}', 136 | ], [ 137 | 'json' => '{"a":', 138 | 'expect' => '{"a":null}', 139 | ], [ 140 | 'json' => '{"a"', 141 | 'expect' => '{"a":null}', 142 | ], [ 143 | 'json' => '{"', 144 | 'expect' => '{"":null}', 145 | ], [ 146 | 'json' => '{"a":1.2,', 147 | 'expect' => '{"a":1.2}', 148 | ], [ 149 | 'json' => '{"a":"', 150 | 'expect' => '{"a":""}', 151 | ], [ 152 | 'json' => '{"a":[', 153 | 'expect' => '{"a":[]}', 154 | ], [ 155 | 'json' => '{"a":{', 156 | 'expect' => '{"a":{}}', 157 | ], [ 158 | 'json' => '{"a":{"b":"a"}', 159 | 'expect' => '{"a":{"b":"a"}}', 160 | ], [ 161 | 'json' => '{"a":{"b":"a"', 162 | 'expect' => '{"a":{"b":"a"}}', 163 | ], [ 164 | 'json' => '{"a":{"b":1', 165 | 'expect' => '{"a":{"b":1}}', 166 | ], [ 167 | 'json' => '{"a":{"b":1}', 168 | 'expect' => '{"a":{"b":1}}', 169 | ], [ 170 | 'json' => '{"a":"b","b":["', 171 | 'expect' => '{"a":"b","b":[""]}', 172 | ], [ 173 | 'json' => '{"a":"b","b":[t', 174 | 'expect' => '{"a":"b","b":[true]}', 175 | ], [ 176 | 'json' => '[ {"id":1, "data": []}, {"id":2, "data": [', 177 | 'expect' => '[ {"id":1, "data": []}, {"id":2, "data": []}]', 178 | ], [ 179 | 'json' => '[ {"id":1, "data": []}, {"id":2, "data": "bla,', 180 | 'expect' => '[ {"id":1, "data": []}, {"id":2, "data": "bla,"}]', 181 | ], 182 | ]; 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/Fixer.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * 9 | * Licensed under MIT license. 10 | */ 11 | 12 | namespace Ahc\Json; 13 | 14 | /** 15 | * Attempts to fix truncated JSON by padding contextual counterparts at the end. 16 | * 17 | * @author Jitendra Adhikari 18 | * @license MIT 19 | * 20 | * @link https://github.com/adhocore/php-json-fixer 21 | */ 22 | class Fixer 23 | { 24 | use PadsJson; 25 | 26 | /** @var array Current token stack indexed by position */ 27 | protected $stack = []; 28 | 29 | /** @var bool If current char is within a string */ 30 | protected $inStr = false; 31 | 32 | /** @var bool Whether to throw Exception on failure */ 33 | protected $silent = false; 34 | 35 | /** @var array The complementary pairs */ 36 | protected $pairs = [ 37 | '{' => '}', 38 | '[' => ']', 39 | '"' => '"', 40 | ]; 41 | 42 | /** @var int The last seen object `{` type position */ 43 | protected $objectPos = -1; 44 | 45 | /** @var int The last seen array `[` type position */ 46 | protected $arrayPos = -1; 47 | 48 | /** @var string Missing value. (Options: true, false, null) */ 49 | protected $missingValue = 'null'; 50 | 51 | /** 52 | * Set/unset silent mode. 53 | * 54 | * @param bool $silent 55 | * 56 | * @return $this 57 | */ 58 | public function silent($silent = true) 59 | { 60 | $this->silent = (bool) $silent; 61 | 62 | return $this; 63 | } 64 | 65 | /** 66 | * Set missing value. 67 | * 68 | * @param mixed $value 69 | * 70 | * @return $this 71 | */ 72 | public function missingValue($value) 73 | { 74 | if ($value === null) { 75 | $value = 'null'; 76 | } elseif (\is_bool($value)) { 77 | $value = $value ? 'true' : 'false'; 78 | } 79 | 80 | $this->missingValue = $value; 81 | 82 | return $this; 83 | } 84 | 85 | /** 86 | * Fix the truncated JSON. 87 | * 88 | * @param string $json The JSON string to fix. 89 | * 90 | * @throws \RuntimeException When fixing fails. 91 | * 92 | * @return string Fixed JSON. If failed with silent then original JSON. 93 | */ 94 | public function fix($json) 95 | { 96 | list($head, $json, $tail) = $this->trim($json); 97 | 98 | if (empty($json) || $this->isValid($json)) { 99 | return $json; 100 | } 101 | 102 | if (null !== $tmpJson = $this->quickFix($json)) { 103 | return $tmpJson; 104 | } 105 | 106 | $this->reset(); 107 | 108 | return $head . $this->doFix($json) . $tail; 109 | } 110 | 111 | protected function trim($json) 112 | { 113 | \preg_match('/^(\s*)([^\s]+)(\s*)$/', $json, $match); 114 | 115 | $match += ['', '', '', '']; 116 | $match[2] = \trim($json); 117 | 118 | \array_shift($match); 119 | 120 | return $match; 121 | } 122 | 123 | protected function isValid($json) 124 | { 125 | \json_decode($json); 126 | 127 | return \JSON_ERROR_NONE === \json_last_error(); 128 | } 129 | 130 | protected function quickFix($json) 131 | { 132 | if (\strlen($json) === 1 && isset($this->pairs[$json])) { 133 | return $json . $this->pairs[$json]; 134 | } 135 | 136 | if ($json[0] !== '"') { 137 | return $this->maybeLiteral($json); 138 | } 139 | 140 | return $this->padString($json); 141 | } 142 | 143 | protected function reset() 144 | { 145 | $this->stack = []; 146 | $this->inStr = false; 147 | $this->objectPos = -1; 148 | $this->arrayPos = -1; 149 | } 150 | 151 | protected function maybeLiteral($json) 152 | { 153 | if (!\in_array($json[0], ['t', 'f', 'n'])) { 154 | return null; 155 | } 156 | 157 | foreach (['true', 'false', 'null'] as $literal) { 158 | if (\strpos($literal, $json) === 0) { 159 | return $literal; 160 | } 161 | } 162 | 163 | // @codeCoverageIgnoreStart 164 | return null; 165 | // @codeCoverageIgnoreEnd 166 | } 167 | 168 | protected function doFix($json) 169 | { 170 | list($index, $char) = [-1, '']; 171 | 172 | while (isset($json[++$index])) { 173 | list($prev, $char) = [$char, $json[$index]]; 174 | 175 | $next = isset($json[$index + 1]) ? $json[$index + 1] : ''; 176 | 177 | if (!\in_array($char, [' ', "\n", "\r"])) { 178 | $this->stack($prev, $char, $index, $next); 179 | } 180 | } 181 | 182 | return $this->fixOrFail($json); 183 | } 184 | 185 | protected function stack($prev, $char, $index, $next) 186 | { 187 | if ($this->maybeStr($prev, $char, $index)) { 188 | return; 189 | } 190 | 191 | $last = $this->lastToken(); 192 | 193 | if (\in_array($last, [',', ':', '"']) && \preg_match('/\"|\d|\{|\[|t|f|n/', $char)) { 194 | $this->popToken(); 195 | } 196 | 197 | if (\in_array($char, [',', ':', '[', '{'])) { 198 | $this->stack[$index] = $char; 199 | } 200 | 201 | $this->updatePos($char, $index); 202 | } 203 | 204 | protected function lastToken() 205 | { 206 | return \end($this->stack); 207 | } 208 | 209 | protected function popToken($token = null) 210 | { 211 | // Last one 212 | if (null === $token) { 213 | return \array_pop($this->stack); 214 | } 215 | 216 | $keys = \array_reverse(\array_keys($this->stack)); 217 | foreach ($keys as $key) { 218 | if ($this->stack[$key] === $token) { 219 | unset($this->stack[$key]); 220 | break; 221 | } 222 | } 223 | } 224 | 225 | protected function maybeStr($prev, $char, $index) 226 | { 227 | if ($prev !== '\\' && $char === '"') { 228 | $this->inStr = !$this->inStr; 229 | } 230 | 231 | if ($this->inStr && $this->lastToken() !== '"') { 232 | $this->stack[$index] = '"'; 233 | } 234 | 235 | return $this->inStr; 236 | } 237 | 238 | protected function updatePos($char, $index) 239 | { 240 | if ($char === '{') { 241 | $this->objectPos = $index; 242 | } elseif ($char === '}') { 243 | $this->popToken('{'); 244 | $this->objectPos = -1; 245 | } elseif ($char === '[') { 246 | $this->arrayPos = $index; 247 | } elseif ($char === ']') { 248 | $this->popToken('['); 249 | $this->arrayPos = -1; 250 | } 251 | } 252 | 253 | protected function fixOrFail($json) 254 | { 255 | $length = \strlen($json); 256 | $tmpJson = $this->pad($json); 257 | 258 | if ($this->isValid($tmpJson)) { 259 | return $tmpJson; 260 | } 261 | 262 | if ($this->silent) { 263 | return $json; 264 | } 265 | 266 | throw new \RuntimeException( 267 | \sprintf('Could not fix JSON (tried padding `%s`)', \substr($tmpJson, $length)) 268 | ); 269 | } 270 | } 271 | --------------------------------------------------------------------------------