json_last_error example

try {
            $fileContent = file_get_contents($pathname);
            if ($fileContent === false) {
                throw new ThemeCompileException(
                    $name,
                    'Unable to read theme.json'
                );
            }

            /** @var array<string, mixed> $data */
            $data = json_decode($fileContent, true);
            if (json_last_error() !== \JSON_ERROR_NONE) {
                throw new ThemeCompileException(
                    $name,
                    'Unable to parse theme.json. Message: ' . json_last_error_msg()
                );
            }

            $config = $this->createFromThemeJson($name$data$path);
        } catch (ThemeCompileException $e) {
            throw $e;
        } catch (\Exception $e) {
            throw new ThemeCompileException(
                
if ($depth <= 0) {
            throw new \ValueError('json_validate(): Argument #2 ($depth) must be greater than 0');
        }

        if ($depth >= self::JSON_MAX_DEPTH) {
            throw new \ValueError(sprintf('json_validate(): Argument #2 ($depth) must be less than %d', self::JSON_MAX_DEPTH));
        }

        json_decode($json, null, $depth$flags);

        return \JSON_ERROR_NONE === json_last_error();
    }
}
use Shopware\Core\Framework\Log\Package;
use Shopware\Storefront\Storefront;
use Symfony\Component\Finder\Finder;

#[Package('system-settings')] class SnippetFileHandler
{
    public function openJsonFile(string $path): array
    {
        $json = json_decode(file_get_contents($path), true);

        $jsonError = json_last_error();
        if ($jsonError !== 0) {
            throw new \RuntimeException(sprintf('Invalid JSON in snippet file at path \'%s\' with code \'%d\'', $path$jsonError));
        }

        return $json;
    }

    public function writeJsonFile(string $path, array $content): void
    {
        $json = json_encode($content, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES);

        
private function buildNested(array $entities, ?string $parentId): array
    {
        $nested = [];
        foreach ($entities as $entity) {
            if ($entity['parent_id'] !== $parentId) {
                continue;
            }

            $parameters = $entity['parameters'];
            if ($parameters && \is_string($parameters)) {
                $decodedParameters = json_decode((string) $entity['parameters'], true);
                if (json_last_error() === \JSON_ERROR_NONE) {
                    $entity['parameters'] = $decodedParameters;
                }
            }

            if ($this->isMultiFilter($entity['type'])) {
                $entity['queries'] = $this->buildNested($entities$entity['id']);
            }

            if ($this->isIdFilter($entity['field'])) {
                $entity = $this->wrapIdFilter($entity);
            }

            

        return [
            KernelEvents::REQUEST => ['onRequest', 128],
        ];
    }

    public function onRequest(RequestEvent $event): void
    {
        if ($event->getRequest()->getContent() && mb_stripos($event->getRequest()->headers->get('Content-Type', ''), 'application/json') === 0) {
            $data = json_decode($event->getRequest()->getContent(), true);

            if (json_last_error() !== \JSON_ERROR_NONE) {
                throw new BadRequestHttpException('The JSON payload is malformed.');
            }

            $event->getRequest()->request->replace(\is_array($data) ? $data : []);
        }
    }
}

    public function decode_body($associative = true, $depth = 512, $options = 0) {
        $data = json_decode($this->body, $associative$depth$options);

        if (json_last_error() !== JSON_ERROR_NONE) {
            $last_error = json_last_error_msg();
            throw new Exception('Unable to parse JSON data: ' . $last_error, 'response.invalid', $this);
        }

        return $data;
    }
}
public function testEncodeNotUtf8WithPartialOnError()
    {
        $context = ['json_encode_options' => \JSON_PARTIAL_OUTPUT_ON_ERROR];

        $arr = [
            'utf8' => 'Hello World!',
            'notUtf8' => "\xb0\xd0\xb5\xd0",
        ];

        $result = $this->encoder->encode($arr, 'json', $context);
        $jsonLastError = json_last_error();

        $this->assertSame(\JSON_ERROR_UTF8, $jsonLastError);
        $this->assertEquals('{"utf8":"Hello World!","notUtf8":null}', $result);

        $this->assertEquals('0', $this->serializer->serialize(\NAN, 'json', $context));
    }

    public function testDecodeFalseString()
    {
        $result = $this->encoder->decode('false', 'json');
        $this->assertSame(\JSON_ERROR_NONE, json_last_error());
        
try {
            $encodedJson = json_encode($data$options);
        } catch (\JsonException $e) {
            throw new NotEncodableValueException($e->getMessage(), 0, $e);
        }

        if (\JSON_THROW_ON_ERROR & $options) {
            return $encodedJson;
        }

        if (\JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & \JSON_PARTIAL_OUTPUT_ON_ERROR))) {
            throw new NotEncodableValueException(json_last_error_msg());
        }

        return $encodedJson;
    }

    public function supportsEncoding(string $format): bool
    {
        return JsonEncoder::FORMAT === $format;
    }
}
/** * Returns if an error occurred during most recent JSON encode/decode. * * Strings to be translated will be in format like * "Encoding error: Maximum stack depth exceeded". * * @since 4.4.0 * * @return false|string Boolean false or string error message. */
    protected function get_json_last_error() {
        $last_error_code = json_last_error();

        if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) {
            return false;
        }

        return json_last_error_msg();
    }

    /** * Retrieves the site index. * * This endpoint describes the capabilities of the site. * * @since 4.4.0 * * @param array $request { * Request. * * @type string $context Context. * } * @return WP_REST_Response The API root index data. */
try {
            $decodedData = json_decode($data$associative$recursionDepth$options);
        } catch (\JsonException $e) {
            throw new NotEncodableValueException($e->getMessage(), 0, $e);
        }

        if (\JSON_THROW_ON_ERROR & $options) {
            return $decodedData;
        }

        if (\JSON_ERROR_NONE !== json_last_error()) {
            throw new NotEncodableValueException(json_last_error_msg());
        }

        return $decodedData;
    }

    public function supportsDecoding(string $format): bool
    {
        return JsonEncoder::FORMAT === $format;
    }
}
return base64_encode(base64_decode($str, true)) === $str;
    }

    /** * Valid JSON */
    public function valid_json(?string $str = null): bool
    {
        json_decode($str ?? '');

        return json_last_error() === JSON_ERROR_NONE;
    }

    /** * Checks for a correctly formatted email address */
    public function valid_email(?string $str = null): bool
    {
        // @see https://regex101.com/r/wlJG1t/1/         if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46') && preg_match('#\A([^@]+)@(.+)\z#', $str ?? '', $matches)) {
            $str = $matches[1] . '@' . idn_to_ascii($matches[2], 0, INTL_IDNA_VARIANT_UTS46);
        }

        

    public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
    {
        $data = \json_decode($json$assoc$depth$options);
        if (\JSON_ERROR_NONE !== \json_last_error()) {
            throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
        }

        return $data;
    }

    /** * Wrapper for JSON encoding that throws when an error occurs. * * @param mixed $value The value being encoded * @param int $options JSON encode option bitmask * @param int $depth Set the maximum depth. Must be greater than zero. * * @throws InvalidArgumentException if the JSON cannot be encoded. * * @see https://www.php.net/manual/en/function.json-encode.php */
return \constant($env);
        }

        if ('base64' === $prefix) {
            return base64_decode(strtr($env, '-_', '+/'));
        }

        if ('json' === $prefix) {
            $env = json_decode($env, true);

            if (\JSON_ERROR_NONE !== json_last_error()) {
                throw new RuntimeException(sprintf('Invalid JSON in env var "%s": ', $name).json_last_error_msg());
            }

            if (null !== $env && !\is_array($env)) {
                throw new RuntimeException(sprintf('Invalid JSON env var "%s": array or null expected, "%s" given.', $nameget_debug_type($env)));
            }

            return $env;
        }

        if ('url' === $prefix) {
            
try {
            $encodedJson = json_encode($data$options);
        } catch (\JsonException $e) {
            throw new NotEncodableValueException($e->getMessage(), 0, $e);
        }

        if (\JSON_THROW_ON_ERROR & $options) {
            return $encodedJson;
        }

        if (\JSON_ERROR_NONE !== json_last_error() && (false === $encodedJson || !($options & \JSON_PARTIAL_OUTPUT_ON_ERROR))) {
            throw new NotEncodableValueException(json_last_error_msg());
        }

        return $encodedJson;
    }

    public function supportsEncoding(string $format): bool
    {
        return JsonEncoder::FORMAT === $format;
    }
}
public function format($data)
    {
        $config = new Format();

        $options = $config->formatterOptions['application/json'] ?? JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
        $options = $options | JSON_PARTIAL_OUTPUT_ON_ERROR;

        $options = ENVIRONMENT === 'production' ? $options : $options | JSON_PRETTY_PRINT;

        $result = json_encode($data$options, 512);

        if (in_array(json_last_error()[JSON_ERROR_NONE, JSON_ERROR_RECURSION], true)) {
            throw FormatException::forInvalidJSON(json_last_error_msg());
        }

        return $result;
    }
}
Home | Imprint | This part of the site doesn't use cookies.