<?php

namespace AutoAdmin\Bundle\Seo\Renderer;

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;

abstract class AbstractSeoRenderer implements SeoRendererInterface
{
    // will replace "<!-- seo --> <!-- /seo -->" -like tags
    protected function replaceSeoTags(Response $response, string $output, string $tag): Response
    {
        if (
            !$response instanceof BinaryFileResponse
            && !$response instanceof StreamedResponse
            && !$response instanceof RedirectResponse
        ) {
            $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);
    }
}
