Alex Alex - 3 months ago 7
YAML Question

Symfony YAML format conversion

I have some service definition that looks like this:

MyService:
class: Some\Class\Here
factory:
- SomeFactoryHere
- method
calls:
- [add, ["@=service('AnotherService1').create(service('AnotherService2'), service('AnotherService3'), service('AnotherService3'))"]]


IMHO, this can be more readable if converted to something like this:

MyService:
class: Some\Class\Here
factory:
- SomeFactoryHere
- method
calls:
-
add,
"@=service('AnotherService1').create(
service('AnotherService2'),
service('AnotherService3'),
service('AnotherService3')
)"


But, this is not valid YAML (Symfony parser fails), and my question is how this config can be converted to something like above?

Answer

The best way to break up your string

"@=service('AnotherService1').create(service('AnotherService2'), service('AnotherService3'), service('AnotherService3'))"

is by using a stripped folded block scalar. The limitation for this is that you cannot escape any special characters with backslashes, but those are not in your example (the reason you need "" around your scalar is because it starts with an @ which is a reserved character).

Then you also have to correctly re-represent the structure that you have, as @flyx already indicated: the value for calls is a sequence, the first element of which is a list of the scalar add and sequence consisting of the aforementioned long scalar that you want to break up for readability:

import yaml

yaml_str = """\
MyService:
    class: Some\Class\Here
    factory:
        - SomeFactoryHere
        - method
    calls:
        - - add
          - - >-
              @=service('AnotherService1').create(
              service('AnotherService2'),
              service('AnotherService3'),
              service('AnotherService3'))
"""

data = yaml.safe_load(yaml_str)
print(data)

gives:

"@=service('AnotherService1').create( service('AnotherService2'), service('AnotherService3'), service('AnotherService3'))"

Please note that this gives an extra space between .create( and service(.

The YAML parser that Symphony uses seems not to be able to parse the above (although it is correct). You can alternatively try:

MyService:
    class: Some\Class\Here
    factory:
        - SomeFactoryHere
        - method
    calls:
        - 
          - add
          - 
            - >-
              @=service('AnotherService1').create(
              service('AnotherService2'),
              service('AnotherService3'),
              service('AnotherService3'))
Comments