1<?php 2 3/* 4 * This file is part of the Symfony package. 5 * 6 * (c) Fabien Potencier <fabien@symfony.com> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Symfony\Component\Yaml; 13 14use Symfony\Component\Yaml\Exception\ParseException; 15 16/** 17 * Yaml offers convenience methods to load and dump YAML. 18 * 19 * @author Fabien Potencier <fabien@symfony.com> 20 * 21 * @final 22 */ 23class Yaml 24{ 25 public const DUMP_OBJECT = 1; 26 public const PARSE_EXCEPTION_ON_INVALID_TYPE = 2; 27 public const PARSE_OBJECT = 4; 28 public const PARSE_OBJECT_FOR_MAP = 8; 29 public const DUMP_EXCEPTION_ON_INVALID_TYPE = 16; 30 public const PARSE_DATETIME = 32; 31 public const DUMP_OBJECT_AS_MAP = 64; 32 public const DUMP_MULTI_LINE_LITERAL_BLOCK = 128; 33 public const PARSE_CONSTANT = 256; 34 public const PARSE_CUSTOM_TAGS = 512; 35 public const DUMP_EMPTY_ARRAY_AS_SEQUENCE = 1024; 36 public const DUMP_NULL_AS_TILDE = 2048; 37 38 /** 39 * Parses a YAML file into a PHP value. 40 * 41 * Usage: 42 * 43 * $array = Yaml::parseFile('config.yml'); 44 * print_r($array); 45 * 46 * @param string $filename The path to the YAML file to be parsed 47 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior 48 * 49 * @return mixed 50 * 51 * @throws ParseException If the file could not be read or the YAML is not valid 52 */ 53 public static function parseFile(string $filename, int $flags = 0) 54 { 55 $yaml = new Parser(); 56 57 return $yaml->parseFile($filename, $flags); 58 } 59 60 /** 61 * Parses YAML into a PHP value. 62 * 63 * Usage: 64 * <code> 65 * $array = Yaml::parse(file_get_contents('config.yml')); 66 * print_r($array); 67 * </code> 68 * 69 * @param string $input A string containing YAML 70 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior 71 * 72 * @return mixed 73 * 74 * @throws ParseException If the YAML is not valid 75 */ 76 public static function parse(string $input, int $flags = 0) 77 { 78 $yaml = new Parser(); 79 80 return $yaml->parse($input, $flags); 81 } 82 83 /** 84 * Dumps a PHP value to a YAML string. 85 * 86 * The dump method, when supplied with an array, will do its best 87 * to convert the array into friendly YAML. 88 * 89 * @param mixed $input The PHP value 90 * @param int $inline The level where you switch to inline YAML 91 * @param int $indent The amount of spaces to use for indentation of nested nodes 92 * @param int $flags A bit field of DUMP_* constants to customize the dumped YAML string 93 */ 94 public static function dump($input, int $inline = 2, int $indent = 4, int $flags = 0): string 95 { 96 $yaml = new Dumper($indent); 97 98 return $yaml->dump($input, $inline, 0, $flags); 99 } 100} 101