从同一 yaml 文件解析自定义标签 (!tag) 和常量 (!php/const)

Parsing custom tag (!tag) and constant (!php/const) from the same yaml file

Yaml 文件:

- name: hero-block
  title: Hero Block
  description: A Hero Block Section block
  category: landing-pages
  icon: welcome-view-site
  example:
    attributes:
      mode: preview
      data:
        headline: !php/const LIPSUM
        subheadline: !php/const LIPSUM
        custom: !my_tag echo 1

Php 文件

function yaml_parse($relname) {
  return Yaml::parse(
    file_get_contents(get_template_directory() . '/flat_data/' .$relname. '.yaml'),
    Yaml::PARSE_CONSTANT); // PARSE_CUSTOM_TAGS
}

用于解析的标志是 Int 类型。 想不出任何方法来实现所需的输出。 非常感谢任何提示。

TLDR:使用Yaml::PARSE_CONSTANT + Yaml::PARSE_CUSTOM_TAGS

此函数对 $flags 参数值使用按位 & 运算符。

更多信息在这里:

https://www.php.net/manual/en/language.operators.bitwise.php https://www.w3resource.com/php/operators/bitwise-operators.php

所以这段代码:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Yaml\Yaml;

class DemoController extends AbstractController
{
    public const LIPSUM = 'Lorem';

    #[Route('/')]
    public function index()
    {
        $yaml   = <<<EOF
- name: hero-block
  title: Hero Block
  description: A Hero Block Section block
  category: landing-pages
  icon: welcome-view-site
  example:
    attributes:
      mode: preview
      data:
        headline: !php/const App\Controller\DemoController::LIPSUM
        subheadline: !php/const App\Controller\DemoController::LIPSUM
        custom: !my_tag echo 1
EOF;
        $parsed = Yaml::parse($yaml, Yaml::PARSE_CONSTANT + Yaml::PARSE_CUSTOM_TAGS);

        $tagName  = $parsed[0]['example']['attributes']['data']['custom']->getTag();
        $tagValue = $parsed[0]['example']['attributes']['data']['custom']->getValue();

        return $this->json(['tagName' => $tagName, 'tagValue' => $tagValue, 'parsedYaml' => $parsed]);
    }
}

将return这个:

{
    "tagName": "my_tag",
    "tagValue": "echo 1",
    "parsedYaml": [
        {
            "name": "hero-block",
            "title": "Hero Block",
            "description": "A Hero Block Section block",
            "category": "landing-pages",
            "icon": "welcome-view-site",
            "example": {
                "attributes": {
                    "mode": "preview",
                    "data": {
                        "headline": "Lorem",
                        "subheadline": "Lorem",
                        "custom": {
                            "tag": "my_tag",
                            "value": "echo 1"
                        }
                    }
                }
            }
        }
    ]
}