Skip to content

Instantly share code, notes, and snippets.

@tomislacker
Created August 11, 2016 20:44
Show Gist options
  • Select an option

  • Save tomislacker/0a45ce8489943194b58688a623e046d2 to your computer and use it in GitHub Desktop.

Select an option

Save tomislacker/0a45ce8489943194b58688a623e046d2 to your computer and use it in GitHub Desktop.
Ansible PHP Associative Array Filter

Ansible PHP Associative Array Filter

php_aarray.py

"""
Custom filter to take a hash and output a PHP associative array
"""
from __future__ import print_function
import json
from ansible import errors

SPACES_PER_NEST_LEVEL = 4
''' Define how many spaces should be involved in nesting '''


def _var_to_array(contents, nested=0):
    ''' Takes a variable `contents` & converts to PHP content

    :param contents: Variable contents
    :type contents: dict|str
    '''
    whitespace1 = " " * (nested * SPACES_PER_NEST_LEVEL)
    whitespace2 = " " * ((1 + nested) * SPACES_PER_NEST_LEVEL)
    if type(contents) is dict:
        return "array(\n{ws2}{array}\n{ws1})".format(
            array=",\n{}".format(whitespace2).join([
                "'{k}' => {v}".format(
                    k=k,
                    v=_var_to_array(v, nested+1))
                for k, v in contents.iteritems()
            ]),
            ws1=whitespace1,
            ws2=whitespace2)

    elif type(contents) is list:
        return "array(\n{ws2}{array}\n{ws1})".format(
            array=",\n{}".format(whitespace2).join([
                _var_to_array(c, nested+1) for c in contents
            ]),
            ws1=whitespace1,
            ws2=whitespace2)

    else:
        return str(contents)


def to_php_array(contents, var_name='conf'):
    ''' Takes the hash `contents` & converts to PHP associative array

    :param contents: Variable contents
    :type contents: dict
    :param var_name: Variable name
    :type var_name: str
    '''
    return "${var_name} = {contents};".format(
        var_name=var_name,
        contents=_var_to_array(contents))


class FilterModule(object):
    ''' A filter to output a hash to PHP code '''
    def filters(self):
        return {
            'to_php_array': to_php_array,
        }

if __name__ == '__main__':
    print(to_php_array({
            'error_level': 'ERROR_REPORTING_HIDE',
            'redis_client_host': "'1.2.3.4'",
            'cache_prefix': {
                'default': "'prod'",
            },
            'siblings': [
                "'john'",
                "'paul'",
                "'ringo'",
            ],
        },
        'conf'))

Example Usage

Vars

drupal_conf:
    siblings:
        - john
        - paul
        - ringo
    error_level: "ERROR_REPORTING_HIDE"
    redis_client_host: "'1.2.3.4'"
    cache_prefix:
        default:
            "'prod'"

Template (settings.php.j2)

<?php

{{ drupal_conf | to_php_array("conf") }}

Output

<?php

$conf = array(
    'siblings' => array(
        'john',
        'paul',
        'ringo'
    ),
    'error_level' => ERROR_REPORTING_HIDE,
    'redis_client_host' => '1.2.3.4',
    'cache_prefix' => array(
        'default' => 'prod'
    )
);
@tomislacker
Copy link
Copy Markdown
Author

Stephen: a hunk of python to generate a hunk of php, based off a hunk of ...yaml?
Me: lol yup
Stephen: kill yourself :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment