View source
<?php
namespace Drupal\markdown\Traits;
use Drupal\Core\Language\LanguageInterface;
use Drupal\markdown\MarkdownBenchmark;
use Drupal\markdown\MarkdownBenchmarkAverages;
use Drupal\markdown\ParsedMarkdown;
trait MarkdownParserBenchmarkTrait {
protected static $benchmark = FALSE;
public function benchmark($markdown, $format = NULL) {
$parsed = $this
->benchmarkParse($markdown);
$rendered = $this
->benchmarkRender($markdown, $format);
$total = MarkdownBenchmark::create('total', $parsed
->getStart(), $rendered
->getEnd(), $rendered
->getResult());
static::$benchmark = FALSE;
return [
$parsed,
$rendered,
$total,
];
}
public function benchmarkAverages($markdown, $format = NULL, $iterations = 10) {
return MarkdownBenchmarkAverages::create($iterations)
->iterate([
$this,
'benchmark',
], [
$markdown,
$format,
]);
}
public function benchmarkParse($markdown) {
$start = microtime(TRUE);
$result = $this
->convertToHtml($markdown);
$end = microtime(TRUE);
return MarkdownBenchmark::create('parsed', $start, $end, static::$benchmark = $result);
}
public function benchmarkRender($markdown, $format = NULL) {
if ($format === NULL) {
$renderer = \Drupal::service('renderer');
$start = microtime(TRUE);
$build = [
'#markup' => $this
->parse($markdown),
];
$result = $renderer
->renderPlain($build);
$end = microtime(TRUE);
}
else {
$start = microtime(TRUE);
$result = check_markup($markdown, $format);
$end = microtime(TRUE);
}
return MarkdownBenchmark::create('rendered', $start, $end, $result);
}
public function parse($markdown, LanguageInterface $language = NULL) {
return ParsedMarkdown::create($markdown, static::$benchmark ?: $this
->convertToHtml($markdown, $language), $language);
}
}