Skip to content

Instantly share code, notes, and snippets.

@rseon
Created June 14, 2019 07:43
Show Gist options
  • Save rseon/b3f94e952327a4e86de05a9c48ceb8d6 to your computer and use it in GitHub Desktop.
Save rseon/b3f94e952327a4e86de05a9c48ceb8d6 to your computer and use it in GitHub Desktop.
Extends [Parsedown](https://github.com/erusev/parsedown) with checkboxes and (closing) tags replacement.
<?php
use Parsedown as ParsedownBase;
/**
* Extends [Parsedown](https://github.com/erusev/parsedown) with :
* - Replacement of [ ] by checkbox
* - Replacement of tags by other (only closing tags).
* Usage :
* $Parsedown = new Parsedown();
* $Parsedown->supportCheckboxes();
* $Parsedown->setReplaceTags([
* 'h3' => 'h4',
* 'h2' => 'h3',
* 'h1' => 'h2',
* ]);
* echo $Parsedown->text('CHANGELOG.md');
*/
class Parsedown extends ParsedownBase
{
protected $checkboxes = false;
protected $replace_tags = [];
/**
* Set that we want to replace [ ] with checkboxes
*
* @param bool $flag
*/
public function supportCheckboxes(bool $flag = true)
{
$this->checkboxes = $flag;
}
/**
* Set tags to replace
*
* @param array $tags
*/
public function setReplaceTags(array $tags = [])
{
$this->replace_tags = $tags;
}
/**
* Override for custom modifications
*
* @param string $text
* @return string
*/
public function text($text)
{
$markup = parent::text($text);
if($this->replace_tags) {
$markup = $this->replaceTags($markup);
}
if($this->checkboxes) {
$markup = $this->replaceCheckboxes($markup);
}
return $markup;
}
/**
* Replace tags by other.
* Warning : only with closing tags (titles, link, etc...), not inline tags (like br, hr...)
*
* @param string $markup
* @return string
*/
protected function replaceTags(string $markup): string
{
$open_before = array_map(function($v) {
return "<$v>";
}, array_keys($this->replace_tags));
$open_after = array_map(function($v) {
return "<$v>";
}, array_values($this->replace_tags));
$close_before = array_map(function($v) {
return "</$v>";
}, array_keys($this->replace_tags));
$close_after = array_map(function($v) {
return "</$v>";
}, array_values($this->replace_tags));
$markup = str_replace($open_before, $open_after, $markup);
$markup = str_replace($close_before, $close_after, $markup);
return $markup;
}
/**
* Replace checkboxes
*
* @param string $markup
* @return string
*/
public function replaceCheckboxes(string $markup): string
{
$markup = str_replace('[ ]', '<input type="checkbox" disabled>', $markup);
$markup = str_replace('[x]', '<input type="checkbox" disabled checked>', $markup);
return $markup;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment