Skip to content

Instantly share code, notes, and snippets.

@treetop1500
Created March 24, 2017 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treetop1500/842e29d572880a613c6a04d3c9bbf752 to your computer and use it in GitHub Desktop.
Save treetop1500/842e29d572880a613c6a04d3c9bbf752 to your computer and use it in GitHub Desktop.
DataTransformer for Markdown Syntax and custom Markdown input field
<?php
namespace Common\ContentBundle\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
/**
* Class MarkdownTransformer
* @package Common\ContentBundle\DataTransformer
*/
class MarkdownTransformer implements DataTransformerInterface
{
/**
* Transforms the HTML string back to markdown.
*
* @param string $val
* @return string
*/
public function transform($val)
{
// strong to double asterisks:
$val = preg_replace("/\<strong\>(.+?)\<\/strong\>/i", "**$1**", $val);
// italic to double underscores:
$val = preg_replace("/\<em\>(.+?)\<\/em\>/i", "__$1__", $val);
return $val;
}
/**
* Transforms the markdown string to html.
* @param string $val
* @return string
*/
public function reverseTransform($val)
{
// double asterisks to strong:
$val = preg_replace("/\*\*(.+?)\*\*/i", "<strong>$1</strong>", $val);
// double underscores to italic:
$val = preg_replace("/\_\_(.+?)\_\_/i", "<em>$1</em>", $val);
return $val;
}
}
<?php
namespace Common\Form;
use Common\ContentBundle\DataTransformer\MarkdownTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class MarkDownType
* @package Common\Form
*/
class MarkDownType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new MarkdownTransformer();
$builder->addModelTransformer($transformer);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'attr' => array(
'help' => 'To bold words, surround them with double asterisks. e.g.: This is <strong>**bold**</strong> now. To emphasize words surround the with double underscores.',
),
));
}
/**
* @return mixed
*/
public function getParent()
{
return TextType::class;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment