<?php

namespace App\Markdown\Parser;

use Knp\Bundle\MarkdownBundle\Parser\MarkdownParser;

/**
 * class Comment.
 *
 * @author Simon Vieille <simon@deblan.fr>
 */
class Comment extends MarkdownParser
{
    /**
     * @var array Enabled features
     */
    protected $features = [
        'header' => true,
        'list' => true,
        'horizontal_rule' => false,
        'table' => false,
        'foot_note' => false,
        'fenced_code_block' => true,
        'abbreviation' => false,
        'definition_list' => false,
        'inline_link' => true, // [link text](url "optional title")
        'reference_link' => false, // [link text] [id]
        'shortcut_link' => false, // [link text]
        'images' => false,
        'html_block' => false,
        'block_quote' => true,
        'code_block' => true,
        'auto_link' => true,
        'auto_mailto' => false,
        'entities' => false,
        'no_html' => true,
    ];

    /**
     * Disable mailto unless auto_mailto.
     *
     * @param mixed $text
     */
    public function doAutoLinks($text)
    {
        if (!$this->features['auto_mailto']) {
            return preg_replace_callback('{((https?|ftp|dict):[^\'">\s]+)}i', [&$this, '_doAutoLinks_url_callback'], $text);
        }

        return parent::doAutoLinks($text);
    }

    /**
     * Callback for setext headers.
     *
     * @param array $matches
     *
     * @return string
     */
    protected function _doHeaders_callback_setext($matches)
    {
        if ('-' == $matches[3] && preg_match('{^- }', $matches[1])) {
            return $matches[0];
        }

        $level = '=' == $matches[3][0] ? 1 : 2;

        $level += 2;

        $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[1]) : null;

        $attr = $this->doExtraAttributes("h{$level}", $dummy = &$matches[2], $defaultId);
        $block = "<div class=\"h{$level}\" {$attr}>".$this->runSpanGamut($matches[1]).'</div>';

        return "\n".$this->hashBlock($block)."\n\n";
    }

    /**
     * Callback for atx headers.
     *
     * @param array $matches
     *
     * @return string
     */
    protected function _doHeaders_callback_atx($matches)
    {
        $level = strlen($matches[1]);

        $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[2]) : null;
        $attr = $this->doExtraAttributes("h{$level}", $dummy = &$matches[3], $defaultId);
        $level += 2;
        $block = "<div class=\"h{$level}\" {$attr}>".$this->runSpanGamut($matches[2]).'</div>';

        return "\n".$this->hashBlock($block)."\n\n";
    }
}
