public function getSnippet(array $post, bool $after = false) : array
{
// First, let's try cutting it off by section...
if (empty($post['body'])) {
return $post;
}
$i = 0;
if ($post['format'] === 'Rich Text') {
$post['body'] = \str_replace('><', '>' . "\n" . '<', $post['body']);
}
// Just in case:
$post['body'] = \str_replace("\r\n", "\n", $post['body']);
$lines = \explode("\n", $post['body']);
// If we find <!--FOLD--> in the body, split on that instead:
$search = \array_search($this->defaultSeparator, $lines);
if ($search !== false) {
$post['snippet'] = \implode("\n", \array_slice($lines, 0, $search - 1));
if ($after) {
$post['after_fold'] = \implode("\n", \array_slice($lines, $search));
}
return $post;
}
// Short post? Just dump it as-is:
if (count($lines) < 4 || Binary::safeStrlen($post['body']) < 200) {
$post['snippet'] = $post['body'];
$post['after_fold'] = '';
return $post;
}
$cutoff = null;
$regex = '#^([' . \preg_quote('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', '#') . '])#';
foreach ($lines as $i => $line) {
if (empty($line)) {
continue;
}
if ($post['format'] === 'RST') {
if (\preg_match($regex, $line[0], $m)) {
if ($i > 2 && \trim($line) === \str_repeat($m[1], Binary::safeStrlen($line))) {
$cutoff = $i;
break;
}
}
} elseif ($post['format'] === 'Markdown') {
if (\preg_match('#^([' . \preg_quote('#', '#') . ']{1,})#', $line[0], $m)) {
$cutoff = $i;
break;
}
} elseif ($post['format'] === 'HTML' || $post['format'] === 'Rich Text') {
if (\preg_match('#^<' . 'h[1-7]>#', $line[0], $m)) {
$cutoff = $i;
break;
}
}
}
if ($cutoff !== null) {
$post['snippet'] = \implode("\n", \array_slice($lines, 0, $i - 1));
if ($after) {
$post['after_fold'] = \implode("\n", \array_slice($lines, $i - 1));
}
return $post;
}
// Next, let's find the 37% mark for breaks
$split = $post['format'] === 'Rich Text' || $post['format'] === 'HTML' ? "\n" : "\n\n";
$sects = \explode($split, $post['body']);
// 37% is approximately 1/e (the mathematical constant)
$cut = (int) \ceil(0.37 * \count($sects));
if ($sects < 2) {
$post['snippet'] = $post['body'];
$post['after_fold'] = '';
return $post;
}
if (\preg_match('#^\\.\\. #', $sects[$cut - 1])) {
--$cut;
}
$post['snippet'] = \implode("\n\n", \array_slice($sects, 0, $cut - 1)) . "\n";
if ($after) {
$post['after_fold'] = "\n" . \implode($split, \array_slice($sects, $cut - 1));
}
return $post;
}