Home > Back-end >  Parsing custom tag (!tag) and constant (!php/const) from the same yaml file
Parsing custom tag (!tag) and constant (!php/const) from the same yaml file

Time:05-23

Yaml file:

- 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 file

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

Flag for parse is of type Int. Can't think of any way to achieve desired output. Any tip is much appreciated.

CodePudding user response:

TLDR: Use Yaml::PARSE_CONSTANT Yaml::PARSE_CUSTOM_TAGS

This function uses the bitwise & operator on the $flags parameter value.

More info here:

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

So this code:

<?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]);
    }
}

will return this:

{
    "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"
                        }
                    }
                }
            }
        }
    ]
}
  • Related