<?php

/**
 * Build HTML tag attributes string with a given array.
 *
 * Usage Example:
 *     echo '<img ' . http_build_attributes([
 *         'src' => 'some-image-url',
 *         'class' => ['img-responsive', 'decorative'],
 *     ]);
 *
 * Result:
 *     <img src="some-image-url" class="img-responsive decorative" />
 *
 * @author Koala Yeung <https://github.com/yookoala>dd
 * @link https://gist.github.com/yookoala/9f647e87df42cc7a918ecb75db738c32
 * #design_ref: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_attributes/7.x
 *
 * @param array $attr
 *   An assoc array of attributes with key as attribute name
 *   and value as attribute value(s).
 *
 *   The value can be either an array of string or a string.
 *   If an object is given, it will be cast as string.
 *
 * @return string
 */
function http_build_attributes(array $attr): string
{
    return implode(' ', array_map(function ($key) use ($attr) {
        $value = is_object($attr[$key]) ? (string) $attr[$key] : $attr[$key];
        $value = is_array($value) ? implode(' ', array_map(function ($item) {
            return (string) $item; // cast all second level array value to string.
        }, $value)) : (string) $value;
        return sprintf('%s="%s"', htmlspecialchars($key), htmlspecialchars($value));
    }, array_keys($attr)));
}