{"record":{"id":"88da3c295ec947b7","repo":"getgrav/grav","slug":"encoding-yaml-failed-message","errorCode":null,"errorMessage":"Encoding YAML failed: {message}","messagePattern":"Encoding YAML failed: (.+?)","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"system/src/Grav/Framework/File/Formatter/YamlFormatter.php","lineNumber":94,"sourceCode":"\n    /**\n     * @param array $data\n     * @param int|null $inline\n     * @param int|null $indent\n     * @return string\n     * @see FileFormatterInterface::encode()\n     */\n    public function encode($data, $inline = null, $indent = null): string\n    {\n        try {\n            return YamlParser::dump(\n                $data,\n                $inline ? (int) $inline : $this->getInlineOption(),\n                $indent ? (int) $indent : $this->getIndentOption(),\n                YamlParser::DUMP_EXCEPTION_ON_INVALID_TYPE\n            );\n        } catch (DumpException $e) {\n            throw new RuntimeException('Encoding YAML failed: ' . $e->getMessage(), 0, $e);\n        }\n    }\n\n    /**\n     * {@inheritdoc}\n     * @see FileFormatterInterface::decode()\n     */\n    public function decode($data): array\n    {\n        // Try native PECL YAML PHP extension first if available.\n        if (function_exists('yaml_parse') && $this->useNativeDecoder()) {\n            // Safely decode YAML.\n            $saved = @ini_get('yaml.decode_php');\n            @ini_set('yaml.decode_php', '0');\n            $decoded = @yaml_parse($data);\n            if ($saved !== false) {\n                @ini_set('yaml.decode_php', $saved);\n            }","sourceCodeStart":76,"sourceCodeEnd":112,"githubUrl":"https://github.com/getgrav/grav/blob/6040efed04efa69b8209448ed81308e7c24147c2/system/src/Grav/Framework/File/Formatter/YamlFormatter.php#L76-L112","documentation":"YamlFormatter::encode() dumps data with Symfony Yaml using the DUMP_EXCEPTION_ON_INVALID_TYPE flag, so any value YAML cannot represent (PHP resources, closures/anonymous objects, NAN/INF) raises a DumpException that Grav rethrows as 'Encoding YAML failed'. The data structure you passed contains a type that has no YAML representation. This is almost always a bug in the data being saved, not in the YAML layer itself.","triggerScenarios":"Saving frontmatter/config whose array contains a resource (e.g. a file handle or GdImage), a closure, or a non-serializable object; passing a Doctrine/Grav object where an array was expected to $formatter->encode() or CompiledYamlFile::save(); third-party code injecting INF/NAN floats into header data.","commonSituations":"A plugin builds page header data from an ORM/resource result and saves it with YamlFormatter; custom code calls $page->header() with an object then saves to YAML storage; upgrading Symfony YAML versions where previously silently-coerced values now throw.","solutions":["Inspect the $data structure right before encode and replace objects/resources with scalar/array representations (e.g. call ->toArray()/jsonSerialize() first).","Remove the offending values (unset($data['field'])) or convert them (cast resources away, replace closures with their result).","If the value is legitimately unrepresentable, use a different formatter (JsonFormatter/SerializeFormatter) for that file.","Catch RuntimeException at the save boundary and report which file failed instead of aborting the whole save loop."],"exampleFix":"// before\n$file->save(['image' => $gdResource]); // Encoding YAML failed\n\n// after\n$file->save(['image' => [\n    'width' => imagesx($gdResource),\n    'height' => imagesy($gdResource),\n]]);","handlingStrategy":"validation","validationCode":"// Recursively verify every value is YAML-representable before encode\nfunction isYamlSafe($v): bool {\n    if (is_array($v)) { return array_reduce($v, fn($ok, $x) => $ok && isYamlSafe($x), true); }\n    return $v === null || is_scalar($v) || (is_object($v) && method_exists($v, '__toString'));\n}\nif (!isYamlSafe($data)) { /* convert ->toArray()/jsonSerialize() or reject */ }","typeGuard":null,"tryCatchPattern":"try {\n    $yaml = $formatter->encode($data);\n} catch (\\Grav\\Framework\\File\\Formatter\\Exception\\RuntimeException $e) {\n    // message embeds the underlying DumpException cause (e.g. \"Dumping a resource is not supported\")\n    throw new \\RuntimeException('Cannot save ' . $filename . ': ' . $e->getMessage(), 0, $e);\n}","preventionTips":["Normalize data to arrays/scalars (->toArray(), jsonSerialize()) before handing it to YamlFormatter.","Never store resources, closures, or floating INF/NAN in persisted page headers.","Unit-test encode() for any new data shape your plugin saves."],"tags":["yaml","grav","serialization","symfony-yaml","dump"],"backgroundTag":"yaml-encode-invalid-type","analyzedSha":"6040efed04efa69b8209448ed81308e7c24147c2","analyzedAt":"2026-08-17T05:07:31.593Z","schemaVersion":2},"datasetVersion":"2026-08-17T09:17:11.063Z"}