<?php

namespace AutoAdmin\Bundle\Seo\Renderer;

use AutoAdmin\Bundle\Seo\Model\SeoPage;
use Symfony\Component\HttpFoundation\Response;

abstract class AbstractSeoRenderer implements SeoRendererInterface
{
    // will replace "<!-- seo --> <!-- /seo -->" -like tags
    protected function replaceSeoTags(Response $response, string $output, string $tag): Response
    {

        $content = preg_replace_callback(
            '/(<!-- '.$tag.' -->)(.+?)(<!-- \/'.$tag.' -->)/msu',
            function ($matches) use ($output) {
                if (is_array($matches)) {
                    $matches[2] = $output;
                    $matches = implode('', array_slice($matches, 1));

                    return $matches;
                }

                return $matches;
            },
            $response->getContent()
        );
        $response->setContent($content);

        return $response;
    }


    protected function createTag($tag, array $attributes = [], $content = null)
    {
        $template = '<%s%s/>';
        if ($content !== null) {
            $template = '<%s%s>%s</%s>';
        }

        $arguments = [];
        $arguments[] = $template;
        $arguments[] = $tag;
        $attributeString = '';
        foreach ($attributes as $key => $value) {
            $attributeString .= ' ' . $key . '=' . sprintf("\"%s\"", str_replace("\"", "\\\"", $value));
        }

        $arguments[] = $attributeString;
        if ($content !== null) {
            $arguments[] = $content;
            $arguments[] = $tag;
        }

        return call_user_func_array('sprintf', $arguments);
    }
}