<?php

declare(strict_types=1);

namespace App\Plates;

use League\CommonMark\CommonMarkConverter;
use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;

class StringExtension implements ExtensionInterface
{
    /** @var CommonMarkConverter */
    private $converter;

    public function __construct(CommonMarkConverter $converter)
    {
        $this->converter = $converter;
    }

    /**
     * Register functions with the Plates engine.
     *
     * Registers:
     *
     * - mdtohtml(string $markdown) : string
     * - excerpt(string $text, int $length) : string
     *
     * @param Engine $engine
     */
    public function register(Engine $engine): void
    {
        $engine->registerFunction('mdtohtml', [$this, 'markdownToHtml']);
        $engine->registerFunction('excerpt', [$this, 'excerpt']);
    }

    public function markdownToHtml(string $markdown): string
    {
        return $this->converter->convertToHtml($markdown);
    }


    public function excerpt(string $text, int $length = 190): string
    {
        $length = abs((int)$length);
        if (strlen($text) > $length) {
            $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
        }
        return($text);
    }
}
