v1.2.1
This commit is contained in:
parent
7d3fc1969d
commit
3a25585090
30 changed files with 1124 additions and 711 deletions
68
vendor/league/commonmark/CHANGELOG.md
vendored
68
vendor/league/commonmark/CHANGELOG.md
vendored
|
|
@ -6,6 +6,69 @@ Updates should follow the [Keep a CHANGELOG](https://keepachangelog.com/) princi
|
|||
|
||||
## [Unreleased][unreleased]
|
||||
|
||||
## [2.10.0] - 2026-08-11
|
||||
|
||||
This is a **security release** to address a denial of service vulnerability in the `AttributesExtension`.
|
||||
|
||||
### Added
|
||||
- Added a new `table_of_contents/max_placeholder_entries` option to limit how many table of contents entries a document may render across all of its placeholders (#1134)
|
||||
- Added `Cursor::matchInPlace()`, which matches a regular expression at the cursor's position within the line using PCRE's native offset semantics instead of copying the remainder (#1145)
|
||||
- `\G` anchors at the cursor, `^` anchors at the start of the line, and lookbehinds and `\b` see the characters actually preceding the cursor; this keeps scanning loops linear and enables left-context assertions that `match()` cannot express
|
||||
- Added `RegexHelper::PARTIAL_LINK_TITLE_UNANCHORED` and `RegexHelper::PARTIAL_LINK_DESTINATION_BRACES`, unanchored fragments so each call site can supply its own anchor
|
||||
- Added a `default_attributes` configuration format which pairs the node attribute map with a new `strict_callables` option: `['default_attributes' => ['attributes' => [...], 'strict_callables' => true]]`. With `strict_callables` enabled, only closures and invokable objects are treated as callbacks, so strings and arrays are always used as literal attribute values. Callbacks written as string or array callables can be wrapped with `Closure::fromCallable()`. The original format - passing the node map directly - is still accepted, and defaults `strict_callables` to `false`.
|
||||
- Added a new `slug_normalizer/reserved` option which treats the given slugs as already-used, so colliding headings receive an incremental numeric suffix just like duplicate headings do (#1080)
|
||||
|
||||
### Changed
|
||||
- Changed the `TableOfContents` extension to render the table of contents once and share it across all placeholders instead of cloning it into each one (#1134)
|
||||
- A custom renderer registered for the `TableOfContents` node is no longer called once per placeholder, so it must return the same markup each time it is called for a given document (#1134)
|
||||
- The first placeholder receives the table of contents itself, so a document still contains a `TableOfContents` node for listeners which locate and reposition it (#1143)
|
||||
- `$environment->getConfiguration()->get('default_attributes')` now returns the normalized structure with `attributes` and `strict_callables` keys instead of the node map; read `default_attributes/attributes` to get the map. Configuration written in either format continues to work unchanged.
|
||||
|
||||
### Deprecated
|
||||
- Deprecated `RegexHelper::PARTIAL_LINK_TITLE` and `RegexHelper::REGEX_LINK_DESTINATION_BRACES`; use the unanchored variants with an explicit anchor instead
|
||||
- Deprecated the `default_attributes` `strict_callables` option, which will be removed in 3.0 when only closures and invokable objects will ever be treated as callbacks.
|
||||
|
||||
### Fixed
|
||||
- Fixed `default_attributes` values which happen to match the name of a PHP function - such as `'class' => 'link'`, `'header'`, `'key'`, `'range'`, or `'current'` - being invoked as callbacks, producing errors like `link() expects exactly 2 arguments, 1 given`. Enable `strict_callables` to treat strings and arrays as literal attribute values (#1123)
|
||||
- Fixed the `DefaultAttributesExtension` re-testing every configured value with `is_callable()` once per matching node, which asked the autoloader whether the first element of each array value named a real class every single time
|
||||
- Fixed a `default_attributes` value which PHP treats as callable reporting its failure from inside whichever function it collided with; the error now names the attribute and node class responsible, and keeps the original error as its previous exception
|
||||
- Fixed custom `UniqueSlugNormalizerInterface` implementations being wrapped by the built-in `UniqueSlugNormalizer` and never receiving the documented `clearHistory()` calls, which caused slug history to leak across documents when `slug_normalizer/unique` was set to `'document'` (#1080)
|
||||
- Custom implementations are now trusted to enforce uniqueness themselves, per the interface contract; the extra deduplication layer the wrapper used to provide is no longer applied on top of them
|
||||
- Fixed the `AttributesExtension` re-merging and re-filtering everything a node had already collected each time another attribute node was applied to it, causing long runs of distinctly-named attributes to be resolved in quadratic time, which could be abused to cause a denial of service - this completes the fix for GHSA-jjv6-8j6v-6j52, which covered only the `class` attribute (GHSA-8rr7-cvq3-gmfh)
|
||||
- Fixed the `AttributesExtension` re-merging everything an attribute block had already collected on each of its continuation lines, causing long runs of distinctly-named attributes on consecutive lines to be resolved in quadratic time, which could be abused to cause a denial of service (GHSA-8rr7-cvq3-gmfh)
|
||||
|
||||
## [2.9.2] - 2026-08-10
|
||||
|
||||
This release fixes a regression introduced in 2.9.0 which changed the behavior of `Cursor::match()` for certain regular expression patterns.
|
||||
|
||||
### Changed
|
||||
- Improved performance of reading single characters from multibyte lines
|
||||
- Improved performance of locating the next non-space character on lines without tabs
|
||||
- Optimized `Cursor::advanceToNextNonSpaceOrNewline()` to scan the line in place instead of copying everything left in the block on every call
|
||||
- Optimized inline link destination parsing to scan the line in place, so its cost follows the length of the destination rather than the length of everything left in the block
|
||||
|
||||
### Fixed
|
||||
- Fixed a regression introduced in 2.9.0 where `Cursor::match()` treated text before the cursor as part of the match subject (#1145). Patterns were matched against the whole line at an offset, which silently changed the meaning of `\b`, `\B`, `\A`, lookbehinds, a `^` anywhere other than the very start of the pattern, and a leading `^` combined with the `m` modifier. `match()` once again matches against the remainder, exactly as it did in 2.8; the core parsers keep the optimized in-place matching via a new internal method with PCRE's native offset semantics, anchoring their patterns at the cursor with `\G`
|
||||
- Fixed heading permalinks rendered with `aria-hidden="true"` remaining in the keyboard tab order; they are now also given `tabindex="-1"`, as a focusable element removed from the accessibility tree has no accessible name to announce when focused (WCAG 4.1.2)
|
||||
- Fixed cloning a node breaking the link from the original node's children back to their parent, silently corrupting the document that node belonged to; detaching or inserting around those children afterwards could drop nodes from the tree
|
||||
- Fixed cloned nodes sharing their `data` with the node they were cloned from, so that setting an attribute on either one also set it on the other
|
||||
|
||||
## [2.9.1] - 2026-08-09
|
||||
|
||||
This is a **security release** to address multiple denial of service vulnerabilities and one cross-site scripting (XSS) vulnerability.
|
||||
|
||||
### Changed
|
||||
- Shortcut and collapsed reference links (`[label]` and `[label][]`) now apply the spec's 999-character link label limit when resolving the label, matching the limit already enforced when parsing reference definitions and when resolving the `[text][label]` form. A label longer than 999 characters which collapsed to a shorter, defined label once whitespace was normalized will no longer resolve; this matches cmark's behavior.
|
||||
|
||||
### Fixed
|
||||
- Fixed attribute names prefixed with a form feed (such as `{<FF>onclick="..."}`) bypassing both the `on*` event handler filter and the `allow_unsafe_links` protection, as browsers treat that byte as whitespace and parse the name as a genuine `onclick` or `href` (GHSA-f8fg-pg57-v4j8)
|
||||
- Fixed catastrophic backtracking in the fenced code block start pattern, causing a single line of backticks to be scanned in quadratic time, which could be abused to cause a denial of service (GHSA-j8pm-gj4c-rq4x)
|
||||
- Fixed shortcut reference link lookups normalizing arbitrarily long labels once a single reference definition is present, causing nested brackets to be resolved in quadratic time, which could be abused to cause a denial of service (GHSA-j8pm-gj4c-rq4x)
|
||||
- Fixed delimiter processors keying the opener-search cache on the raw closer run length, leaving the cache key space unbounded and causing emphasis, strikethrough, and highlight runs to be processed in super-linear time, which could be abused to cause a denial of service (GHSA-j8pm-gj4c-rq4x)
|
||||
- Fixed the `SmartPunctExtension` recopying the whole preceding text node when replacing each unpaired quote, causing documents with many apostrophes to be processed in quadratic time, which could be abused to cause a denial of service (GHSA-jjv6-8j6v-6j52)
|
||||
- Fixed the `AttributesExtension` scanning the remaining siblings of every block-level attribute node, causing long runs of adjacent attribute blocks to be resolved in quadratic time, which could be abused to cause a denial of service - this completes the fix for GHSA-g2gp-3wwq-f4ph, which covered only inline attributes (GHSA-jjv6-8j6v-6j52)
|
||||
- Fixed the `AttributesExtension` rebuilding the accumulated class list on every merge, causing long runs of `.class` attributes to be resolved in quadratic time, which could be abused to cause a denial of service (GHSA-jjv6-8j6v-6j52)
|
||||
|
||||
## [2.9.0] - 2026-08-03
|
||||
|
||||
This is a **security release** to address five denial of service vulnerabilities and one cross-site scripting (XSS) vulnerability.
|
||||
|
|
@ -771,7 +834,10 @@ No changes were introduced since the previous release.
|
|||
- Alternative 1: Use `CommonMarkConverter` or `GithubFlavoredMarkdownConverter` if you don't need to customize the environment
|
||||
- Alternative 2: Instantiate a new `Environment` and add the necessary extensions yourself
|
||||
|
||||
[unreleased]: https://github.com/thephpleague/commonmark/compare/2.9.0...HEAD
|
||||
[unreleased]: https://github.com/thephpleague/commonmark/compare/2.10.0...HEAD
|
||||
[2.10.0]: https://github.com/thephpleague/commonmark/compare/2.9.2...2.10.0
|
||||
[2.9.2]: https://github.com/thephpleague/commonmark/compare/2.9.1...2.9.2
|
||||
[2.9.1]: https://github.com/thephpleague/commonmark/compare/2.9.0...2.9.1
|
||||
[2.9.0]: https://github.com/thephpleague/commonmark/compare/2.8.3...2.9.0
|
||||
[2.8.3]: https://github.com/thephpleague/commonmark/compare/2.8.2...2.8.3
|
||||
[2.8.2]: https://github.com/thephpleague/commonmark/compare/2.8.1...2.8.2
|
||||
|
|
|
|||
2
vendor/league/commonmark/composer.json
vendored
2
vendor/league/commonmark/composer.json
vendored
|
|
@ -116,7 +116,7 @@
|
|||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "2.10-dev"
|
||||
"dev-main": "2.11-dev"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
|
|
|
|||
|
|
@ -400,11 +400,13 @@ final class Environment implements EnvironmentInterface, EnvironmentBuilderInter
|
|||
\assert($normalizer instanceof TextNormalizerInterface);
|
||||
$this->injectEnvironmentAndConfigurationIfNeeded($normalizer);
|
||||
|
||||
if ($this->config->get('slug_normalizer/unique') !== UniqueSlugNormalizerInterface::DISABLED && ! $normalizer instanceof UniqueSlugNormalizer) {
|
||||
$normalizer = new UniqueSlugNormalizer($normalizer);
|
||||
if ($this->config->get('slug_normalizer/unique') !== UniqueSlugNormalizerInterface::DISABLED && ! $normalizer instanceof UniqueSlugNormalizerInterface) {
|
||||
/** @var string[] $reserved */
|
||||
$reserved = $this->config->get('slug_normalizer/reserved');
|
||||
$normalizer = new UniqueSlugNormalizer($normalizer, $reserved);
|
||||
}
|
||||
|
||||
if ($normalizer instanceof UniqueSlugNormalizer) {
|
||||
if ($normalizer instanceof UniqueSlugNormalizerInterface) {
|
||||
if ($this->config->get('slug_normalizer/unique') === UniqueSlugNormalizerInterface::PER_DOCUMENT) {
|
||||
$this->addEventListener(DocumentParsedEvent::class, [$normalizer, 'clearHistory'], -1000);
|
||||
}
|
||||
|
|
@ -445,6 +447,7 @@ final class Environment implements EnvironmentInterface, EnvironmentBuilderInter
|
|||
'instance' => Expect::type(TextNormalizerInterface::class)->default(new SlugNormalizer()),
|
||||
'max_length' => Expect::int()->min(0)->default(255),
|
||||
'unique' => Expect::anyOf(UniqueSlugNormalizerInterface::DISABLED, UniqueSlugNormalizerInterface::PER_ENVIRONMENT, UniqueSlugNormalizerInterface::PER_DOCUMENT)->default(UniqueSlugNormalizerInterface::PER_DOCUMENT),
|
||||
'reserved' => Expect::listOf('string')->default([]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,11 @@ use League\CommonMark\Extension\CommonMark\Node\Block\ListItem;
|
|||
use League\CommonMark\Node\Inline\AbstractInline;
|
||||
use League\CommonMark\Node\Node;
|
||||
|
||||
/**
|
||||
* @psalm-type PendingAttributes = array{node: Node, front: array<string, mixed>, back: array<string, mixed>, classFront: list<string>, classBack: list<string>, hasClass: bool, unfiltered: array<string, mixed>}
|
||||
*
|
||||
* @phpstan-type PendingAttributes = array{node: Node, front: array<string, mixed>, back: array<string, mixed>, classFront: list<string>, classBack: list<string>, hasClass: bool, unfiltered: array<string, mixed>}
|
||||
*/
|
||||
final class AttributesListener
|
||||
{
|
||||
private const DIRECTION_PREFIX = 'prefix';
|
||||
|
|
@ -44,12 +49,24 @@ final class AttributesListener
|
|||
|
||||
public function processDocument(DocumentParsedEvent $event): void
|
||||
{
|
||||
// Targets already worked out for attribute blocks we walked past; see findTargetAndDirection()
|
||||
/** @var \SplObjectStorage<Attributes|AttributesInline, array<Node|string|null>> $resolved */
|
||||
$resolved = new \SplObjectStorage();
|
||||
|
||||
/**
|
||||
* Attributes waiting to be written to their target, keyed by target object ID; see
|
||||
* newPendingEntry() for the shape and contribute() for how each node is folded in.
|
||||
*
|
||||
* @var array<int, PendingAttributes> $pending
|
||||
*/
|
||||
$pending = [];
|
||||
|
||||
foreach ($event->getDocument()->iterator() as $node) {
|
||||
if (! ($node instanceof Attributes || $node instanceof AttributesInline)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$target, $direction] = self::findTargetAndDirection($node);
|
||||
[$target, $direction] = self::findTargetAndDirection($node, $resolved);
|
||||
|
||||
if ($target instanceof Node) {
|
||||
$parent = $target->parent();
|
||||
|
|
@ -57,29 +74,239 @@ final class AttributesListener
|
|||
$target = $parent;
|
||||
}
|
||||
|
||||
if ($direction === self::DIRECTION_SUFFIX) {
|
||||
$attributes = AttributesHelper::mergeAttributes($target, $node->getAttributes());
|
||||
} else {
|
||||
$attributes = AttributesHelper::mergeAttributes($node->getAttributes(), $target);
|
||||
$id = \spl_object_id($target);
|
||||
if (! isset($pending[$id])) {
|
||||
$pending[$id] = self::newPendingEntry($target);
|
||||
}
|
||||
|
||||
$target->data->set('attributes', AttributesHelper::filterAttributes($attributes, $this->allowList, $this->allowUnsafeLinks));
|
||||
$this->contribute($pending[$id], $node->getAttributes(), $direction === self::DIRECTION_SUFFIX);
|
||||
}
|
||||
|
||||
$node->detach();
|
||||
}
|
||||
|
||||
foreach ($pending as $entry) {
|
||||
$entry['node']->data->set('attributes', self::assemble($entry));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Attributes|AttributesInline $node
|
||||
* Seed an accumulator from whatever the target already carries
|
||||
*
|
||||
* Anything another extension put there takes part in the merges, so it faces the filter too -
|
||||
* but only once the first node has had its say, since whatever that node overwrites never
|
||||
* reaches the filter at all.
|
||||
*
|
||||
* @return PendingAttributes
|
||||
*/
|
||||
private static function newPendingEntry(Node $target): array
|
||||
{
|
||||
/** @var array<string, mixed> $existing */
|
||||
$existing = (array) $target->data->get('attributes');
|
||||
|
||||
$entry = ['node' => $target, 'front' => [], 'back' => [], 'classFront' => [], 'classBack' => [], 'hasClass' => false, 'unfiltered' => $existing];
|
||||
|
||||
foreach ($existing as $name => $value) {
|
||||
if ($name === 'class') {
|
||||
// mergeAttributes() builds the class list by appending to it, so a value with no
|
||||
// classes in it - an empty string, or an empty array - never creates the key at
|
||||
// all, and leaves the target with no class rather than an empty one
|
||||
$classes = AttributesHelper::classList($value);
|
||||
if ($classes === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$entry['classBack'] = $classes;
|
||||
$entry['hasClass'] = true;
|
||||
}
|
||||
|
||||
$entry['back'][$name] = $value;
|
||||
}
|
||||
|
||||
return $entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold one node's attributes into the accumulator in time proportional to that node's own
|
||||
* size, reproducing what mergeAttributes() plus filterAttributes() would have produced had
|
||||
* they been handed the whole accumulated dict.
|
||||
*
|
||||
* Both of those are O(size of the accumulator), so calling them once per node - as this used
|
||||
* to - costs O(n^2) for a document that contributes a new key n times.
|
||||
*
|
||||
* @param PendingAttributes $entry
|
||||
* @param array<string, mixed> $attributes
|
||||
* @param bool $suffix Whether the node's attributes lose conflicts to what is already accumulated
|
||||
*/
|
||||
private function contribute(array &$entry, array $attributes, bool $suffix): void
|
||||
{
|
||||
$class = $attributes['class'] ?? null;
|
||||
unset($attributes['class']);
|
||||
|
||||
// Keys whose value this node decides, and which therefore have yet to face the filter
|
||||
$touched = [];
|
||||
|
||||
if ($suffix) {
|
||||
// mergeAttributes() rebuilds the class list before anything else, so merging over an
|
||||
// accumulator that already has one moves it back to the front
|
||||
if ($entry['hasClass']) {
|
||||
self::moveToFront($entry, 'class');
|
||||
} elseif ($class !== null) {
|
||||
$entry['back']['class'] = null;
|
||||
}
|
||||
|
||||
if ($class !== null) {
|
||||
foreach (AttributesHelper::classList($class) as $c) {
|
||||
$entry['classBack'][] = $c;
|
||||
}
|
||||
|
||||
$entry['hasClass'] = true;
|
||||
$touched['class'] = $class;
|
||||
}
|
||||
|
||||
foreach ($attributes as $name => $value) {
|
||||
// Overwriting leaves a key where it already sits, in front or behind
|
||||
if (\array_key_exists($name, $entry['front'])) {
|
||||
$entry['front'][$name] = $value;
|
||||
} else {
|
||||
$entry['back'][$name] = $value;
|
||||
}
|
||||
|
||||
$touched[$name] = $value;
|
||||
}
|
||||
|
||||
$this->filter($entry, $touched);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// This node goes in front of everything accumulated so far. 'front' is kept in reverse, so
|
||||
// the keys most recently moved there are the ones assemble() emits first.
|
||||
if ($class === null && $entry['hasClass']) {
|
||||
self::moveToFront($entry, 'class');
|
||||
}
|
||||
|
||||
foreach (\array_reverse(\array_keys($attributes)) as $name) {
|
||||
// A key this node shares with the accumulator takes its position from here, but keeps
|
||||
// the value it already had
|
||||
if (\array_key_exists($name, $entry['front']) || \array_key_exists($name, $entry['back'])) {
|
||||
self::moveToFront($entry, $name);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$entry['front'][$name] = $attributes[$name];
|
||||
$touched[$name] = $attributes[$name];
|
||||
}
|
||||
|
||||
if ($class !== null) {
|
||||
self::moveToFront($entry, 'class');
|
||||
foreach (\array_reverse(AttributesHelper::classList($class)) as $c) {
|
||||
$entry['classFront'][] = $c;
|
||||
}
|
||||
|
||||
$entry['hasClass'] = true;
|
||||
$touched['class'] = $class;
|
||||
}
|
||||
|
||||
$this->filter($entry, $touched);
|
||||
}
|
||||
|
||||
/**
|
||||
* Give a key the frontmost position, keeping whatever value it already had
|
||||
*
|
||||
* @param PendingAttributes $entry
|
||||
*/
|
||||
private static function moveToFront(array &$entry, string $name): void
|
||||
{
|
||||
$value = $entry['front'][$name] ?? $entry['back'][$name] ?? null;
|
||||
unset($entry['front'][$name], $entry['back'][$name]);
|
||||
|
||||
$entry['front'][$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop whichever of the just-decided keys the filter rejects
|
||||
*
|
||||
* Everything else in the accumulator survived this same filter when it was decided, and the
|
||||
* filter judges each name and value on its own, so re-examining any of it would be wasted.
|
||||
*
|
||||
* @param PendingAttributes $entry
|
||||
* @param array<string, mixed> $touched
|
||||
*/
|
||||
private function filter(array &$entry, array $touched): void
|
||||
{
|
||||
// Whatever the target arrived with has kept its value through this first merge, so it is
|
||||
// being decided now too
|
||||
foreach ($entry['unfiltered'] as $name => $value) {
|
||||
if (\array_key_exists($name, $touched)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$touched[$name] = $value;
|
||||
}
|
||||
|
||||
$entry['unfiltered'] = [];
|
||||
|
||||
if ($touched === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$kept = AttributesHelper::filterAttributes($touched, $this->allowList, $this->allowUnsafeLinks);
|
||||
|
||||
foreach (\array_keys($touched) as $name) {
|
||||
if (\array_key_exists($name, $kept)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($name === 'class') {
|
||||
$entry['classFront'] = $entry['classBack'] = [];
|
||||
$entry['hasClass'] = false;
|
||||
}
|
||||
|
||||
// Forget where it sat as well as what it held, so a later node contributing the same
|
||||
// name starts it over at the back
|
||||
unset($entry['front'][$name], $entry['back'][$name]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param PendingAttributes $entry
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function assemble(array $entry): array
|
||||
{
|
||||
$attributes = \array_merge(\array_reverse($entry['front'], true), $entry['back']);
|
||||
|
||||
if ($entry['hasClass']) {
|
||||
$attributes['class'] = \implode(' ', \array_merge(\array_reverse($entry['classFront']), $entry['classBack']));
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Attributes|AttributesInline $node
|
||||
* @param \SplObjectStorage<Attributes|AttributesInline, array<Node|string|null>> $resolved
|
||||
*
|
||||
* @return array<Node|string|null>
|
||||
*/
|
||||
private static function findTargetAndDirection($node): array
|
||||
private static function findTargetAndDirection($node, \SplObjectStorage $resolved): array
|
||||
{
|
||||
if (isset($resolved[$node])) {
|
||||
$result = $resolved[$node];
|
||||
// Each node is only ever resolved once, so don't keep it alive any longer
|
||||
unset($resolved[$node]);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
$target = null;
|
||||
$direction = null;
|
||||
$previous = $next = $node;
|
||||
/** @var list<Attributes> $shared */
|
||||
$shared = [];
|
||||
while (true) {
|
||||
$previous = self::getPrevious($previous);
|
||||
$next = self::getNext($next);
|
||||
|
|
@ -119,9 +346,27 @@ final class AttributesListener
|
|||
|
||||
break;
|
||||
}
|
||||
|
||||
// Only a TARGET_NEXT block can have a sibling block to walk past, so if that's what
|
||||
// we're looking at then we are one too, which means getPrevious() already returned
|
||||
// null for us and will keep doing so. Neither of us can therefore pick anything up on
|
||||
// the left, and what is left of this walk is the whole of that block's own walk: it
|
||||
// must end up with the same target we do. Remember that instead of re-scanning the
|
||||
// chain once per block.
|
||||
if (! ($next instanceof Attributes) || $next->getTarget() !== Attributes::TARGET_NEXT) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$shared[] = $next;
|
||||
}
|
||||
|
||||
return [$target, $direction];
|
||||
/** @var array<Node|string|null> $result */
|
||||
$result = [$target, $direction];
|
||||
foreach ($shared as $sharedNode) {
|
||||
$resolved[$sharedNode] = $result;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -30,6 +30,27 @@ final class AttributesBlockContinueParser extends AbstractBlockContinueParser
|
|||
|
||||
private bool $hasSubsequentLine = false;
|
||||
|
||||
/**
|
||||
* Every attribute merged so far except the class list, which is accumulated separately and
|
||||
* only takes the placeholder position recorded here. Re-merging the whole dict on every line
|
||||
* would cost O(size of the dict) per line, so a document adding a key per line would be
|
||||
* quadratic; folding each line in on its own is linear.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $attributes = [];
|
||||
|
||||
/** @var list<string> */
|
||||
private array $classes = [];
|
||||
|
||||
private bool $hasClass = false;
|
||||
|
||||
/**
|
||||
* mergeAttributes() rebuilds the class list before anything else, so any line merged over an
|
||||
* existing list moves it to the front of the result
|
||||
*/
|
||||
private bool $classFirst = false;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes The attributes identified by the block start parser
|
||||
* @param AbstractBlock $container The node we were in when these attributes were discovered
|
||||
|
|
@ -39,6 +60,8 @@ final class AttributesBlockContinueParser extends AbstractBlockContinueParser
|
|||
$this->block = new Attributes($attributes);
|
||||
|
||||
$this->container = $container;
|
||||
|
||||
$this->absorb($attributes);
|
||||
}
|
||||
|
||||
public function getBlock(): AbstractBlock
|
||||
|
|
@ -57,10 +80,9 @@ final class AttributesBlockContinueParser extends AbstractBlockContinueParser
|
|||
$cursor->advanceToNextNonSpaceOrTab();
|
||||
if ($cursor->isAtEnd() && $attributes !== []) {
|
||||
// It does! Merge them into what we parsed previously
|
||||
$this->block->setAttributes(AttributesHelper::mergeAttributes(
|
||||
$this->block->getAttributes(),
|
||||
$attributes
|
||||
));
|
||||
$this->classFirst = $this->classFirst || $this->hasClass;
|
||||
|
||||
$this->absorb($attributes);
|
||||
|
||||
// Tell the core parser we've consumed everything
|
||||
return BlockContinue::at($cursor);
|
||||
|
|
@ -75,8 +97,49 @@ final class AttributesBlockContinueParser extends AbstractBlockContinueParser
|
|||
return BlockContinue::none();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold one line's attributes into what we've accumulated, in time proportional to that line
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
private function absorb(array $attributes): void
|
||||
{
|
||||
foreach ($attributes as $name => $value) {
|
||||
if ($name !== 'class') {
|
||||
$this->attributes[$name] = $value;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (AttributesHelper::classList($value) as $class) {
|
||||
$this->classes[] = $class;
|
||||
}
|
||||
|
||||
if ($this->hasClass) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Hold the spot the joined list will occupy; closeBlock() writes the value
|
||||
$this->attributes['class'] = null;
|
||||
$this->hasClass = true;
|
||||
}
|
||||
}
|
||||
|
||||
public function closeBlock(): void
|
||||
{
|
||||
$attributes = $this->attributes;
|
||||
if ($this->hasClass) {
|
||||
$class = \implode(' ', $this->classes);
|
||||
if ($this->classFirst) {
|
||||
unset($attributes['class']);
|
||||
$attributes = \array_merge(['class' => $class], $attributes);
|
||||
} else {
|
||||
$attributes['class'] = $class;
|
||||
}
|
||||
}
|
||||
|
||||
$this->block->setAttributes($attributes);
|
||||
|
||||
// Attributes appearing at the very end of the document won't have any last lines to check
|
||||
// so we can make that determination here
|
||||
if (! $this->hasSubsequentLine) {
|
||||
|
|
|
|||
|
|
@ -24,7 +24,14 @@ use League\CommonMark\Util\RegexHelper;
|
|||
final class AttributesHelper
|
||||
{
|
||||
private const SINGLE_ATTRIBUTE = '\s*([.]-?[_a-z][^\s.}]*|[#][^\s}]+|' . RegexHelper::PARTIAL_ATTRIBUTENAME . RegexHelper::PARTIAL_ATTRIBUTEVALUESPEC . ')\s*';
|
||||
private const ATTRIBUTE_LIST = '/^{:?(' . self::SINGLE_ATTRIBUTE . ')+}/i';
|
||||
private const ATTRIBUTE_LIST = '/\G{:?(' . self::SINGLE_ATTRIBUTE . ')+}/i';
|
||||
|
||||
/**
|
||||
* PCRE's `\s` matches the form feed that PHP's default trim charlist omits, so the
|
||||
* separators SINGLE_ATTRIBUTE accepts must be trimmed with this list instead - otherwise
|
||||
* that byte survives inside an attribute name, where a browser reads it as a separator.
|
||||
*/
|
||||
private const WHITESPACE = " \t\n\r\0\x0B\x0C";
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
|
|
@ -46,7 +53,7 @@ final class AttributesHelper
|
|||
// matching individual attributes since they won't need to look ahead for the closing '}'
|
||||
// while dealing with the fact that attributes can technically contain curly braces.
|
||||
// So we'll just match the start and end braces up front.
|
||||
$attributeExpression = $cursor->match(self::ATTRIBUTE_LIST);
|
||||
$attributeExpression = $cursor->matchInPlace(self::ATTRIBUTE_LIST);
|
||||
if ($attributeExpression === null) {
|
||||
$cursor->restoreState($state);
|
||||
|
||||
|
|
@ -59,7 +66,7 @@ final class AttributesHelper
|
|||
|
||||
/** @var array<string, mixed> $attributes */
|
||||
$attributes = [];
|
||||
while ($attribute = \trim((string) $attributeCursor->match('/^' . self::SINGLE_ATTRIBUTE . '/i'))) {
|
||||
while ($attribute = \trim((string) $attributeCursor->matchInPlace('/\G' . self::SINGLE_ATTRIBUTE . '/i'), self::WHITESPACE)) {
|
||||
if ($attribute[0] === '#') {
|
||||
$attributes['id'] = \substr($attribute, 1);
|
||||
|
||||
|
|
@ -86,12 +93,12 @@ final class AttributesHelper
|
|||
$value = \substr($value, 1, -1);
|
||||
}
|
||||
|
||||
if (\strtolower(\trim($name)) === 'class') {
|
||||
foreach (\array_filter(\explode(' ', \trim($value))) as $class) {
|
||||
if (\strtolower(\trim($name, self::WHITESPACE)) === 'class') {
|
||||
foreach (\array_filter(\explode(' ', \trim($value, self::WHITESPACE))) as $class) {
|
||||
$attributes['class'][] = $class;
|
||||
}
|
||||
} else {
|
||||
$attributes[\trim($name)] = \trim($value);
|
||||
$attributes[\trim($name, self::WHITESPACE)] = \trim($value, self::WHITESPACE);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -119,11 +126,7 @@ final class AttributesHelper
|
|||
/** @var array<string, mixed> $arg */
|
||||
$arg = (array) $arg;
|
||||
if (isset($arg['class'])) {
|
||||
if (\is_string($arg['class'])) {
|
||||
$arg['class'] = \array_filter(\explode(' ', \trim($arg['class'])));
|
||||
}
|
||||
|
||||
foreach ($arg['class'] as $class) {
|
||||
foreach (self::classList($arg['class']) as $class) {
|
||||
$attributes['class'][] = $class;
|
||||
}
|
||||
|
||||
|
|
@ -140,6 +143,22 @@ final class AttributesHelper
|
|||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a `class` attribute value into the individual classes it contributes to a merge
|
||||
*
|
||||
* @param mixed $class
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function classList($class): array
|
||||
{
|
||||
if (\is_string($class)) {
|
||||
return \array_values(\array_filter(\explode(' ', \trim($class))));
|
||||
}
|
||||
|
||||
return \array_values((array) $class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
* @param list<string> $allowList
|
||||
|
|
@ -151,7 +170,15 @@ final class AttributesHelper
|
|||
$allowList = \array_fill_keys($allowList, true);
|
||||
|
||||
foreach ($attributes as $name => $value) {
|
||||
$attrNameLower = \strtolower($name);
|
||||
// The checks below compare against literal names, and the renderer emits names
|
||||
// without escaping them, so anything that isn't a well-formed attribute name
|
||||
// would slip past both
|
||||
if (\preg_match('/^' . RegexHelper::PARTIAL_ATTRIBUTENAME . '$/i', (string) $name) !== 1) {
|
||||
unset($attributes[$name]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$attrNameLower = \strtolower((string) $name);
|
||||
|
||||
// Remove any unsafe links
|
||||
if (! $allowUnsafeLinks && ($attrNameLower === 'href' || $attrNameLower === 'src') && \is_string($value) && RegexHelper::isLinkPotentiallyUnsafe($value)) {
|
||||
|
|
|
|||
|
|
@ -113,7 +113,10 @@ final class EmphasisDelimiterProcessor implements CacheableDelimiterProcessorInt
|
|||
$this->char,
|
||||
$closer->canOpen() ? 'canOpen' : 'cannotOpen',
|
||||
$closer->getOriginalLength() % 3,
|
||||
$closer->getLength(),
|
||||
// getDelimiterUse() only ever asks whether the closer's length is >= 2, so lengths
|
||||
// beyond that are interchangeable. Clamping keeps the key space bounded, which is
|
||||
// what makes the delimiter stack's lower-bound cache amortize.
|
||||
\min($closer->getLength(), 2),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ final class FencedCodeStartParser implements BlockStartParserInterface
|
|||
}
|
||||
|
||||
$indent = $cursor->getIndent();
|
||||
$fence = $cursor->match('/^[ \t]*(?:`{3,}(?!.*`)|~{3,})/');
|
||||
$fence = $cursor->matchInPlace('/\G[ \t]*(?:`{3,}+(?!.*`)|~{3,})/');
|
||||
if ($fence === null) {
|
||||
return BlockStart::none();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,13 +56,13 @@ final class BacktickParser implements InlineParserInterface
|
|||
if ($this->findMatchingTicks(\strlen($ticks), $cursor)) {
|
||||
$code = $cursor->getSubstring($currentPosition, $cursor->getPosition() - $currentPosition - \strlen($ticks));
|
||||
|
||||
$c = \preg_replace('/\n/m', ' ', $code) ?? '';
|
||||
$c = \str_replace("\n", ' ', $code);
|
||||
|
||||
if (
|
||||
$c !== '' &&
|
||||
$c[0] === ' ' &&
|
||||
\substr($c, -1, 1) === ' ' &&
|
||||
\preg_match('/[^ ]/', $c)
|
||||
\strspn($c, ' ') !== \strlen($c)
|
||||
) {
|
||||
$c = \substr($c, 1, -1);
|
||||
}
|
||||
|
|
@ -110,7 +110,7 @@ final class BacktickParser implements InlineParserInterface
|
|||
return false;
|
||||
}
|
||||
|
||||
while ($ticks = $cursor->match('/`{1,' . self::MAX_BACKTICKS . '}/m')) {
|
||||
while ($ticks = $cursor->matchInPlace('/`{1,' . self::MAX_BACKTICKS . '}/')) {
|
||||
$numTicks = \strlen($ticks);
|
||||
|
||||
// Did we find the closer?
|
||||
|
|
|
|||
|
|
@ -181,6 +181,16 @@ final class CloseBracketParser implements InlineParserInterface, EnvironmentAwar
|
|||
// The reference must not contain a bracket. If we know there's a bracket, we don't even bother checking it.
|
||||
$start = $opener->getPosition();
|
||||
$length = $startPos - $start;
|
||||
|
||||
// spec: A link label can have at most 999 characters inside the square brackets.
|
||||
// ReferenceParser::parseLabel() enforces that when storing definitions, so a longer
|
||||
// span here cannot possibly match one. Rejecting it up-front - before copying and
|
||||
// normalizing the span - is what keeps deeply-nested brackets from being quadratic.
|
||||
if ($length > 999) {
|
||||
$cursor->restoreState($savePos);
|
||||
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
$cursor->restoreState($savePos);
|
||||
|
||||
|
|
|
|||
|
|
@ -15,17 +15,29 @@ namespace League\CommonMark\Extension\DefaultAttributes;
|
|||
|
||||
use League\CommonMark\Event\DocumentParsedEvent;
|
||||
use League\CommonMark\Extension\Attributes\Util\AttributesHelper;
|
||||
use League\CommonMark\Node\Node;
|
||||
use League\Config\ConfigurationAwareInterface;
|
||||
use League\Config\ConfigurationInterface;
|
||||
use League\Config\Exception\InvalidConfigurationException;
|
||||
|
||||
final class ApplyDefaultAttributesProcessor implements ConfigurationAwareInterface
|
||||
{
|
||||
private ConfigurationInterface $config;
|
||||
|
||||
/**
|
||||
* Configured attributes with every callback already resolved to a `Closure`, keyed by node FQCN.
|
||||
*
|
||||
* @var array<string, array<string, mixed>>|null
|
||||
*/
|
||||
private ?array $resolved = null;
|
||||
|
||||
public function onDocumentParsed(DocumentParsedEvent $event): void
|
||||
{
|
||||
/** @var array<string, array<string, mixed>> $map */
|
||||
$map = $this->config->get('default_attributes');
|
||||
if ($this->resolved === null) {
|
||||
$this->resolved = $this->resolveConfiguredAttributes();
|
||||
}
|
||||
|
||||
$map = $this->resolved;
|
||||
|
||||
// Don't bother iterating if no default attributes are configured
|
||||
if (! $map) {
|
||||
|
|
@ -40,7 +52,7 @@ final class ApplyDefaultAttributesProcessor implements ConfigurationAwareInterfa
|
|||
|
||||
$newAttributes = [];
|
||||
foreach ($attributesToApply as $name => $value) {
|
||||
if (\is_callable($value)) {
|
||||
if ($value instanceof \Closure) {
|
||||
$value = $value($node);
|
||||
// Callables are allowed to return `null` indicating that no changes should be made
|
||||
if ($value !== null) {
|
||||
|
|
@ -62,4 +74,78 @@ final class ApplyDefaultAttributesProcessor implements ConfigurationAwareInterfa
|
|||
{
|
||||
$this->config = $configuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
private function resolveConfiguredAttributes(): array
|
||||
{
|
||||
/** @var array<string, array<string, mixed>> $map */
|
||||
$map = $this->config->get('default_attributes/attributes');
|
||||
$strict = (bool) $this->config->get('default_attributes/strict_callables');
|
||||
|
||||
$resolved = [];
|
||||
foreach ($map as $class => $attributes) {
|
||||
foreach ($attributes as $name => $value) {
|
||||
$resolved[$class][$name] = self::resolveValue($class, $name, $value, $strict);
|
||||
}
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return mixed A `Closure` if the value is a callback, otherwise the literal attribute value
|
||||
*/
|
||||
private static function resolveValue(string $class, string $name, $value, bool $strict)
|
||||
{
|
||||
if ($value instanceof \Closure) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (\is_string($value) || \is_array($value)) {
|
||||
// Strings and arrays are how literal attribute values are written, and plenty of them also
|
||||
// name a real function - PHP has a global `link()`, for example
|
||||
if ($strict) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (! \is_callable($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return self::wrapCallable($class, $name, $value, \Closure::fromCallable($value));
|
||||
}
|
||||
|
||||
return \is_callable($value) ? \Closure::fromCallable($value) : $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke the callable, replacing a failure with one which names the configuration responsible.
|
||||
*
|
||||
* A value like `'link'` is otherwise invoked and fails deep inside whichever function it collided
|
||||
* with, reporting an argument count the user never wrote.
|
||||
*
|
||||
* @param string|mixed[] $value The callable as it was written in the configuration
|
||||
*/
|
||||
private static function wrapCallable(string $class, string $name, $value, \Closure $callback): \Closure
|
||||
{
|
||||
return static function (Node $node) use ($callback, $class, $name, $value) {
|
||||
try {
|
||||
return $callback($node);
|
||||
} catch (\TypeError $e) {
|
||||
throw new InvalidConfigurationException(\sprintf(
|
||||
'The "%s" attribute configured for %s is %s, which PHP also treats as a callable, so it was '
|
||||
. 'called with the node and failed: %s. If it was meant to be a literal attribute value instead, '
|
||||
. 'set "default_attributes/strict_callables" to true.',
|
||||
$name,
|
||||
$class,
|
||||
\is_string($value) ? \sprintf('the string "%s"', $value) : 'an array',
|
||||
$e->getMessage()
|
||||
), 0, $e);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,15 +21,52 @@ use Nette\Schema\Expect;
|
|||
|
||||
final class DefaultAttributesExtension implements ConfigurableExtensionInterface
|
||||
{
|
||||
/**
|
||||
* Keys belonging to this extension's own settings rather than to a node class
|
||||
*/
|
||||
private const RESERVED_KEYS = ['attributes' => 0, 'strict_callables' => 0];
|
||||
|
||||
public function configureSchema(ConfigurationBuilderInterface $builder): void
|
||||
{
|
||||
$builder->addSchema('default_attributes', Expect::arrayOf(
|
||||
Expect::arrayOf(
|
||||
Expect::type('string|string[]|bool|callable'), // attribute value(s)
|
||||
'string' // attribute name
|
||||
),
|
||||
'string' // node FQCN
|
||||
)->default([]));
|
||||
$builder->addSchema('default_attributes', Expect::structure([
|
||||
'attributes' => Expect::arrayOf(
|
||||
Expect::arrayOf(
|
||||
Expect::type('string|string[]|bool|callable'), // attribute value(s)
|
||||
'string' // attribute name
|
||||
),
|
||||
'string' // node FQCN
|
||||
)->default([]),
|
||||
// @deprecated This option will be removed in 3.0, when only closures and invokable objects
|
||||
// will ever be treated as callbacks.
|
||||
'strict_callables' => Expect::bool()->default(true),
|
||||
])->before(static function ($value) {
|
||||
if (! \is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$canonical = \array_intersect_key($value, self::RESERVED_KEYS);
|
||||
$legacy = \array_diff_key($value, self::RESERVED_KEYS);
|
||||
|
||||
if ($legacy === []) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// Nothing can be merged into an `attributes` which isn't an array; hand it to the schema
|
||||
// as-is so it reports the same validation error it would without the node classes present
|
||||
if (isset($canonical['attributes']) && ! \is_array($canonical['attributes'])) {
|
||||
return $canonical;
|
||||
}
|
||||
|
||||
$canonical['attributes'] = \array_merge($legacy, $canonical['attributes'] ?? []);
|
||||
|
||||
// The flat shape predates this option, so it stays on the legacy callable handling
|
||||
// unless it opts in explicitly.
|
||||
if (! \array_key_exists('strict_callables', $canonical)) {
|
||||
$canonical['strict_callables'] = false;
|
||||
}
|
||||
|
||||
return $canonical;
|
||||
}));
|
||||
}
|
||||
|
||||
public function register(EnvironmentBuilderInterface $environment): void
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ final class DescriptionStartParser implements BlockStartParserInterface
|
|||
}
|
||||
|
||||
$cursor->advanceToNextNonSpaceOrTab();
|
||||
if ($cursor->match('/^:[ \t]+/') === null) {
|
||||
if ($cursor->matchInPlace('/\G:[ \t]+/') === null) {
|
||||
return BlockStart::none();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ final class FrontMatterParser implements FrontMatterParserInterface
|
|||
/** @psalm-readonly */
|
||||
private FrontMatterDataParserInterface $frontMatterParser;
|
||||
|
||||
private const REGEX_FRONT_MATTER = '/^---\\R.*?\\R---\\R/s';
|
||||
private const REGEX_FRONT_MATTER = '/\G---\\R.*?\\R---\\R/s';
|
||||
|
||||
public function __construct(FrontMatterDataParserInterface $frontMatterParser)
|
||||
{
|
||||
|
|
@ -38,7 +38,7 @@ final class FrontMatterParser implements FrontMatterParserInterface
|
|||
$cursor = new Cursor($markdownContent);
|
||||
|
||||
// Locate the front matter
|
||||
$frontMatter = $cursor->match(self::REGEX_FRONT_MATTER);
|
||||
$frontMatter = $cursor->matchInPlace(self::REGEX_FRONT_MATTER);
|
||||
if ($frontMatter === null) {
|
||||
return new MarkdownInputWithFrontMatter($markdownContent);
|
||||
}
|
||||
|
|
@ -53,7 +53,7 @@ final class FrontMatterParser implements FrontMatterParserInterface
|
|||
$data = $this->frontMatterParser->parse($frontMatter);
|
||||
|
||||
// Advance through any remaining newlines which separated the front matter from the Markdown text
|
||||
$trailingNewlines = $cursor->match('/^\R+/');
|
||||
$trailingNewlines = $cursor->matchInPlace('/\G\R+/');
|
||||
|
||||
// Calculate how many lines the Markdown is offset from the front matter by counting the number of newlines
|
||||
// Don't forget to add 1 because we stripped one out when trimming the trailing delims
|
||||
|
|
|
|||
|
|
@ -73,6 +73,9 @@ final class HeadingPermalinkRenderer implements NodeRendererInterface, XmlNodeRe
|
|||
$hidden = $this->config->get('heading_permalink/aria_hidden');
|
||||
if ($hidden) {
|
||||
$attrs->set('aria-hidden', 'true');
|
||||
// A focusable element removed from the accessibility tree is a WCAG 4.1.2 failure,
|
||||
// so the link must also be taken out of the tab order
|
||||
$attrs->set('tabindex', '-1');
|
||||
}
|
||||
|
||||
$attrs->set('title', $this->config->get('heading_permalink/title'));
|
||||
|
|
|
|||
|
|
@ -64,6 +64,10 @@ class MarkDelimiterProcessor implements CacheableDelimiterProcessorInterface
|
|||
|
||||
public function getCacheKey(DelimiterInterface $closer): string
|
||||
{
|
||||
return '=' . $closer->getLength();
|
||||
// getDelimiterUse() returns 0 for every possible opener once the closer exceeds 2
|
||||
// characters, so all longer closers behave identically and can share a bucket.
|
||||
// Clamping keeps the key space bounded, which is what makes the delimiter stack's
|
||||
// lower-bound cache amortize.
|
||||
return '=' . \min($closer->getLength(), 3);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,6 +64,10 @@ final class StrikethroughDelimiterProcessor implements CacheableDelimiterProcess
|
|||
|
||||
public function getCacheKey(DelimiterInterface $closer): string
|
||||
{
|
||||
return '~' . $closer->getLength();
|
||||
// getDelimiterUse() returns 0 for every possible opener once the closer exceeds 2
|
||||
// characters, so all longer closers behave identically and can share a bucket.
|
||||
// Clamping keeps the key space bounded, which is what makes the delimiter stack's
|
||||
// lower-bound cache amortize.
|
||||
return '~' . \min($closer->getLength(), 3);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ final class TableStartParser implements BlockStartParserInterface
|
|||
$cursor->advanceBy(1);
|
||||
}
|
||||
|
||||
if ($cursor->match('/^-+/') === null) {
|
||||
if ($cursor->matchInPlace('/\G-+/') === null) {
|
||||
// Need at least one dash
|
||||
return [];
|
||||
}
|
||||
|
|
|
|||
47
vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsReference.php
vendored
Normal file
47
vendor/league/commonmark/src/Extension/TableOfContents/Node/TableOfContentsReference.php
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of the league/commonmark package.
|
||||
*
|
||||
* (c) Colin O'Dell <colinodell@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace League\CommonMark\Extension\TableOfContents\Node;
|
||||
|
||||
use League\CommonMark\Extension\TableOfContents\TableOfContentsRenderCache;
|
||||
use League\CommonMark\Node\Block\AbstractBlock;
|
||||
|
||||
/**
|
||||
* Lightweight stand-in for a placeholder which references the shared table of contents instead of holding a full copy
|
||||
*/
|
||||
final class TableOfContentsReference extends AbstractBlock
|
||||
{
|
||||
/** @psalm-readonly */
|
||||
private TableOfContents $tableOfContents;
|
||||
|
||||
/** @psalm-readonly */
|
||||
private TableOfContentsRenderCache $renderCache;
|
||||
|
||||
public function __construct(TableOfContents $tableOfContents, TableOfContentsRenderCache $renderCache)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->tableOfContents = $tableOfContents;
|
||||
$this->renderCache = $renderCache;
|
||||
}
|
||||
|
||||
public function getTableOfContents(): TableOfContents
|
||||
{
|
||||
return $this->tableOfContents;
|
||||
}
|
||||
|
||||
public function getRenderCache(): TableOfContentsRenderCache
|
||||
{
|
||||
return $this->renderCache;
|
||||
}
|
||||
}
|
||||
|
|
@ -14,10 +14,13 @@ declare(strict_types=1);
|
|||
namespace League\CommonMark\Extension\TableOfContents;
|
||||
|
||||
use League\CommonMark\Event\DocumentParsedEvent;
|
||||
use League\CommonMark\Event\DocumentPreRenderEvent;
|
||||
use League\CommonMark\Extension\CommonMark\Node\Block\Heading;
|
||||
use League\CommonMark\Extension\CommonMark\Node\Block\ListItem;
|
||||
use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink;
|
||||
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
|
||||
use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder;
|
||||
use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsReference;
|
||||
use League\CommonMark\Node\Block\Document;
|
||||
use League\CommonMark\Node\NodeIterator;
|
||||
use League\Config\ConfigurationAwareInterface;
|
||||
|
|
@ -89,16 +92,66 @@ final class TableOfContentsBuilder implements ConfigurationAwareInterface
|
|||
|
||||
private function replacePlaceholders(Document $document, TableOfContents $toc): void
|
||||
{
|
||||
$maxEntries = $this->config->get('table_of_contents/max_placeholder_entries');
|
||||
\assert(\is_int($maxEntries) || $maxEntries === null);
|
||||
$perCopy = $maxEntries === null ? 0 : self::countEntries($toc);
|
||||
$cache = new TableOfContentsRenderCache();
|
||||
$entries = 0;
|
||||
$anchored = false;
|
||||
|
||||
foreach ($document->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) {
|
||||
// Add the block once we find a placeholder
|
||||
if (! $node instanceof TableOfContentsPlaceholder) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$node->replaceWith(clone $toc);
|
||||
// Leave any remaining placeholders as-is once the entry budget is spent
|
||||
if ($maxEntries !== null && $entries + $perCopy > $maxEntries) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The first placeholder receives the table of contents itself, so that it remains
|
||||
// part of the document; the rest share the single result of rendering it
|
||||
if ($anchored) {
|
||||
$node->replaceWith(new TableOfContentsReference($toc, $cache));
|
||||
} else {
|
||||
$node->replaceWith($toc);
|
||||
$anchored = true;
|
||||
}
|
||||
|
||||
$entries += $perCopy;
|
||||
}
|
||||
}
|
||||
|
||||
public function onDocumentPreRender(DocumentPreRenderEvent $event): void
|
||||
{
|
||||
// The shared references are an HTML rendering optimization; other formats
|
||||
// (like XML) walk the node tree directly and expect complete copies
|
||||
if ($event->getFormat() === 'html') {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) {
|
||||
if (! $node instanceof TableOfContentsReference) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$node->replaceWith(clone $node->getTableOfContents());
|
||||
}
|
||||
}
|
||||
|
||||
private static function countEntries(TableOfContents $toc): int
|
||||
{
|
||||
$count = 0;
|
||||
foreach ($toc->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $node) {
|
||||
if ($node instanceof ListItem) {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
public function setConfiguration(ConfigurationInterface $configuration): void
|
||||
{
|
||||
$this->config = $configuration;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue