<?php

namespace Ignite\Core\Traits;

use Parsedown;

trait Markdownable
{
    /**
     * Markdown-ify the provided string.
     *
     * @param  string $text
     * @return string
     */
    protected function markdown($text)
    {
        $markdown = new Parsedown();
        $markdown->setSafeMode(false);
        $markdown->setMarkupEscaped(false);
        $markdown->setUrlsLinked(true);
        $markdown->setBreaksEnabled(true);

        $text = $this->getHyperlinkableText($text);

        return $markdown->text($text);
    }

    /**
     * Attempt to hyperlink anything that looks hyperlink-able.
     *
     * @param  string $text
     * @return string
     */
    protected function getHyperlinkableText($text)
    {
        $content = strip_tags($text, 'a');
        $pattern = '/((https?)\:\/\/)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';

        return  preg_replace_callback($pattern, function($matches) {
            $match = rtrim($matches[0], '.,()[]');
            $url = ! preg_match('/(https?\:\/\/)/', $match) ? 'http://' . strtolower($match) : $match;
            return sprintf('<a href="%s" target="_blank">%s</a>', $url, $match);
        }, $content);
    }
}
