1
0
mirror of https://github.com/erusev/parsedown.git synced 2023-08-10 21:13:06 +03:00

Compare commits

...

83 Commits

Author SHA1 Message Date
Aidan Woods
32278afaf3 Fix title 2022-05-21 22:40:24 +01:00
Aidan Woods
b3f0ae4a7e Merge pull request #821 from erusev/documentation-v2.0
Documentation 2.0
2022-05-21 22:37:26 +01:00
Aidan Woods
7c7d581601 Error level 1 instead of totallyTyped
Seems this is now the equivalent and sanctioned way to do this.
2022-05-21 22:31:09 +01:00
Aidan Woods
5cc84366cb Test on 8.1 2022-05-21 22:31:00 +01:00
Aidan Woods
6be43664fd Add additional explaination for the State object
Adds a small non-technical introduction to help with intuition, after
the object appears for the first time.
2022-05-21 22:26:39 +01:00
Aidan Woods
bf6cfe8af0 Show importing of Parsedown and State in example 2021-12-08 20:38:35 +00:00
Aidan Woods
6fdcfaa14a Add initial documentation
This isn't yet complete, but is a decent start
2021-12-08 20:38:35 +00:00
Aidan Woods
79effc4ae2 Ignore invalid docblock in tests 2021-12-08 20:35:46 +00:00
Aidan Woods
f77cb47528 Remove unnecessary cast 2021-12-08 20:32:09 +00:00
Aidan Woods
95c9cce7de Update php-cs-fixer 2021-10-16 00:45:18 +01:00
Aidan Woods
9749ef7a8e Slightly nicer to allow construction from StateBearer 2021-10-15 23:23:14 +01:00
Aidan Woods
638079a3da Slightly nicer method name
Normally this name might be too vague for an interface, but implementing
this interface is a fairly special use case. We can expect dedicated
types here (so method name unlikely to be an issue).
2021-10-15 23:20:20 +01:00
Aidan Woods
421a2393d0 StateBearer must be constructable from State 2021-10-15 23:18:08 +01:00
Aidan Woods
4af22ec41a Allow substitution of blocks and inlines 2021-10-15 19:25:47 +01:00
Aidan Woods
4553515e8e Relax mutation tolerance 2021-10-13 22:12:06 +01:00
Aidan Woods
8ce88c1b36 Off by 1 2021-10-13 19:55:23 +01:00
Aidan Woods
b73fe2e9ec Apply correct state 2021-10-13 19:52:27 +01:00
Aidan Woods
7b0a9cda04 Transformations must return transformable renderables 2021-10-13 19:46:53 +01:00
Aidan Woods
05a47e7083 Complete docblock 2021-10-13 19:35:21 +01:00
Aidan Woods
e9dec33dc6 Replacing all function to TransformableRenderable 2021-10-13 19:26:07 +01:00
Aidan Woods
a9f41548d3 adding method for Container 2021-10-13 19:02:52 +01:00
Aidan Woods
71d9263664 Pass State to render stack closure 2021-10-13 18:50:04 +01:00
Aidan Woods
8fc49f6b0a Add TransformableRenderable capability 2021-10-12 21:58:24 +01:00
Aidan Woods
a48c451d6c Restrict autolinks to https 2021-10-12 18:21:17 +01:00
Aidan Woods
2ea4bece92 Return statebearer instead of state 2021-10-12 18:12:00 +01:00
Aidan Woods
efaf20d005 Minor refactor to use type hints 2021-10-12 18:05:58 +01:00
Aidan Woods
0f27f2e842 Add initState to tests 2021-10-12 18:04:36 +01:00
Aidan Woods
c773305bc1 Add RenderStack
This is a special configurable that can be used to alter the
Renderable[] AST before output.
2021-10-12 00:06:51 +01:00
Aidan Woods
7c2681be19 Remove travis 2021-10-11 23:12:06 +01:00
Aidan Woods
9d5af12971 Run both commonmark tests 2021-10-11 20:49:58 +01:00
Aidan Woods
58bb815870 Dev flag 2021-10-11 20:48:31 +01:00
Aidan Woods
de06199f4e Support old phpunit, remove lock file 2021-10-11 20:47:21 +01:00
Aidan Woods
f396d49a4c Use static analysis plugin for infection 2021-10-11 20:43:25 +01:00
Aidan Woods
7f11869f65 Remove infection for unit tests 2021-10-11 20:33:25 +01:00
Aidan Woods
3472b9bd3f GitHub Actions 2021-10-11 20:26:42 +01:00
Aidan Woods
7d1b9ca562 Better autolinks
This doesn't follow gfm spec yet, work lifted from my code over
at
8505e2737e/src/Parsers/GitHubFlavor/Inlines/AutoLink.php

Fixes #505
Fixes #717
2021-10-11 20:09:57 +01:00
Aidan Woods
cc5614bc5c Test 8.0 in travis 2021-10-11 19:25:58 +01:00
Aidan Woods
ca16d7573d Fix psalm errors 2021-10-11 19:23:44 +01:00
Aidan Woods
98aab22002 Update dependencies 2021-10-11 19:22:23 +01:00
Aidan Woods
9f6112e70a Ignore phpunit result cache 2021-10-11 19:21:21 +01:00
Aidan Woods
0c5e8c152e Merge pull request #767 from aidantwoods/enhancement/header-slug
Create ID's for Header elements so they can be referenced in anchor tags
2020-05-10 14:41:15 +01:00
Aidan Woods
8764512c23 Add SlugRegister so IDs are not duplicated 2020-05-10 14:32:01 +01:00
Aidan Woods
4e99e29d28 Trim leading and trailing hyphens from slug 2020-05-10 14:32:00 +01:00
Aidan Woods
d8bf07535c Strip superscripts and divisions from eventual slug
As suggested by @Ayesh

Co-authored-by: Ayesh Karunaratne <ayesh@ayesh.me>
2020-05-10 14:32:00 +01:00
Aidan Woods
e332b4710a Add HeaderSlug configurable
Adds HeaderSlug configurable, with the option for the slug function
to be customised.

Co-authored-by: netniV <netniv@hotmail.com>
2020-05-10 14:31:55 +01:00
Aidan Woods
74df602863 Merge pull request #768 from aidantwoods/feature/mutable-configurable
Add mutable configurable
2020-05-10 14:30:15 +01:00
Aidan Woods
c835535176 Implement DefinitionBook as MutableConfigurable
This is a slightly more correct implementation, but perhaps not worth
the headache.
2020-05-10 14:19:05 +01:00
Aidan Woods
0ef406e6d2 Add MutableConfigurable
Hopefully I do not regret this...
2020-05-10 14:18:51 +01:00
Aidan Woods
8e8d1dac21 Resolve dependencies when running unit tests 2020-05-05 22:20:11 +01:00
Aidan Woods
bc018e1d00 Remove 'matrix' key 2020-05-05 22:19:56 +01:00
Aidan Woods
dbb929fff7 Commit lock file so static analysis results are stable 2020-05-05 22:19:14 +01:00
Aidan Woods
836c028aa0 Add flag to get type-coverage 2020-01-26 13:09:19 +00:00
Aidan Woods
bded7a6ff3 PHP 7.4 is now released 2020-01-19 18:14:37 +00:00
Aidan Woods
2235e36a2c Use verb imperative to indicate method is non-mutating 2020-01-19 18:06:22 +00:00
Aidan Woods
a6c17f449e previousEmptyLines -> precedingEmptyLines 2020-01-19 17:15:02 +00:00
Aidan Woods
7610eacbf9 Fix uppercase typo 2020-01-19 15:36:53 +00:00
Aidan Woods
525b72349b Expensive operation last 2020-01-19 15:34:04 +00:00
Aidan Woods
39b8b04d33 Clarify sequential lines being tracked are empty 2020-01-19 15:32:51 +00:00
Aidan Woods
8d09320009 Compute on read optimisation for previousEmptyLines 2020-01-19 15:31:33 +00:00
Aidan Woods
a72455c78a Use ->toHtml over ->text 2020-01-19 15:26:48 +00:00
Aidan Woods
a2ea704a43 Use list type over int array 2020-01-19 15:23:58 +00:00
Aidan Woods
13932bca9a Simplify match logic 2020-01-19 15:09:44 +00:00
Aidan Woods
0a6408043f Only run units on 7.4snapshot 2019-09-09 23:46:04 +01:00
Aidan Woods
01319b7572 Add 7.4 snapshot 2019-09-09 23:37:31 +01:00
Aidan Woods
0a1e4bd802 Formatting fix 2019-09-09 23:33:06 +01:00
Aidan Woods
bfdd0f29bc More specific annotation 2019-09-09 23:27:36 +01:00
Aidan Woods
5db3687892 $matches is guarenteed to contain data for the full pattern 2019-09-09 23:26:21 +01:00
Aidan Woods
bde621e4c4 Drop master from psalm requirement 2019-09-09 23:15:11 +01:00
Aidan Woods
f75e7bd970 Prefer master until next release 2019-07-31 23:25:25 +01:00
Aidan Woods
18ee4ffe04 Bump min psalm version 2019-07-25 19:18:26 +02:00
Aidan Woods
54f7719a08 Force return type to T
It's currently not a planned feature to allow Psalm to understand
the type relationship of class-name => class-instance as the array
here is constructed.
Ref: https://github.com/vimeo/psalm/issues/1969
2019-07-25 19:16:28 +02:00
Aidan Woods
f51dd8878a Drop use of undefined reference 2019-07-25 19:07:08 +02:00
Aidan Woods
211a7eb5aa Tables always acquire previous 2019-07-25 16:18:00 +02:00
Aidan Woods
37f306c3a8 Utilise constant arrays over static vars 2019-07-25 00:45:53 +02:00
Aidan Woods
ea55a9ffb0 Integer keys aren't necessary 2019-07-25 00:33:15 +02:00
Aidan Woods
b9bc0b7d37 Update expect-to-pass cache 2019-07-25 00:27:05 +02:00
Aidan Woods
34902bc80c Account for type 7 HTML blocks
These differ from type 6 blocks in a few ways (other than the HTML
element names given in the spec).

1. Type 7 blocks cannot interrupt paragraphs
2. Type 7 block must contain ONLY whitespace on the rest of the
   line, whereas type 6 blocks need only be followed by whitespace
   after the tag name, or have the opening tag be complete.
2019-07-25 00:22:09 +02:00
Aidan Woods
f4fb5bd943 Add type 7 HTML block tests 2019-07-25 00:20:59 +02:00
Aidan Woods
614c76be6f Drop pre 7.1
Drop pre 5.6 for constant arrays
Drop pre 7.1 for private constants
2019-07-25 00:18:29 +02:00
Aidan Woods
91b8bda46e Update test cache 2019-06-16 21:36:11 +01:00
Aidan Woods
5a12d4245f Allow unused class in tests 2019-06-16 21:35:13 +01:00
Aidan Woods
298b319d96 Fix malformed return type 2019-06-16 21:33:55 +01:00
Aidan Woods
7b1389b48b More specific return type 2019-06-16 21:32:37 +01:00
92 changed files with 1493 additions and 353 deletions

98
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,98 @@
name: Parsedown
on: [push, pull_request]
jobs:
units:
name: Unit Tests
strategy:
matrix:
os: [ubuntu-latest]
php: [8.1, 8.0, 7.4, 7.3, 7.2, 7.1]
runs-on: ${{ matrix.os }}
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:v2
- uses: actions/checkout@v2
- name: Run Tests
run: |
composer remove infection/infection --no-update --dev
composer remove roave/infection-static-analysis-plugin --no-update --dev
composer update --prefer-dist --no-interaction --no-progress
composer test-units
mutations:
name: Mutation Tests
strategy:
matrix:
os: [ubuntu-latest]
php: [8.1]
runs-on: ${{ matrix.os }}
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:v2
- uses: actions/checkout@v2
- name: Run Tests
run: |
composer update --prefer-dist --no-interaction --no-progress
vendor/bin/roave-infection-static-analysis-plugin --show-mutations --threads=4 --min-msi=80 --min-covered-msi=80
static-analysis:
name: Code Format and Static Analysis
strategy:
matrix:
os: [ubuntu-latest]
php: [8.1]
runs-on: ${{ matrix.os }}
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:v2
- uses: actions/checkout@v2
- name: Run Tests
run: |
composer install --prefer-dist --no-interaction --no-progress
composer test-static -- --shepherd
composer test-formatting
composer test-dead-code
commonmark:
name: CommonMark
continue-on-error: true
strategy:
matrix:
os: [ubuntu-latest]
php: [8.1]
runs-on: ${{ matrix.os }}
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:v2
- uses: actions/checkout@v2
- name: Install
run: composer install --prefer-dist --no-interaction --no-progress
- name: CommonMark Strict
continue-on-error: true
run: composer test-commonmark
- name: CommonMark Weak
continue-on-error: true
run: composer test-commonmark-weak

2
.gitignore vendored
View File

@@ -2,3 +2,5 @@ composer.lock
vendor/
infection.log
tests/spec_cache.txt
.phpunit.result.cache
composer.lock

View File

@@ -29,9 +29,9 @@ $rules = [
'strict_param' => true,
'whitespace_after_comma_in_array' => true,
];
return Config::create()
return (new Config)
->setRules($rules)
->setFinder($finder)
->setUsingCache(false)
->setRiskyAllowed(true)
;
;

View File

@@ -1,73 +0,0 @@
language: php
dist: trusty
sudo: false
stages:
- Code Format and Static Analysis
- Units
- Test CommonMark (weak)
matrix:
fast_finish: true
allow_failures:
- env: ALLOW_FAILURE
cache:
directories:
- $HOME/.composer/cache
jobs:
include:
- stage: Code Format and Static Analysis
php: 7.3
install: composer install --prefer-dist --no-interaction --no-progress
script:
- '[ -z "$TRAVIS_TAG" ] || [ "$TRAVIS_TAG" == "$(php -r "require(\"vendor/autoload.php\"); echo Erusev\Parsedown\Parsedown::version;")" ]'
- composer test-static
- composer test-formatting
- composer test-dead-code
- &UNIT_TEST
stage: Units
php: 5.5
install:
# remove packages with PHP requirements higher than 7.0 to prevent composer trying to resolve these, see: https://github.com/composer/composer/issues/6011
- composer remove vimeo/psalm friendsofphp/php-cs-fixer infection/infection --dev --no-update --no-interaction
- composer install --prefer-dist --no-interaction --no-progress
script: composer test-units
- <<: *UNIT_TEST
php: 5.6
- <<: *UNIT_TEST
php: 7.0
- &MUTATION_AND_UNIT_TEST
<<: *UNIT_TEST
php: 7.1
install:
- composer install --prefer-dist --no-interaction --no-progress
script:
- composer test-units
- vendor/bin/infection --show-mutations --threads=4 --min-msi=90 --min-covered-msi=90
- <<: *MUTATION_AND_UNIT_TEST
php: 7.2
- <<: *MUTATION_AND_UNIT_TEST
php: 7.3
- <<: *UNIT_TEST
php: nightly
env: ALLOW_FAILURE
- &COMMONMARK_TEST
stage: CommonMark
name: Weak
php: 7.3
env: ALLOW_FAILURE
install: composer install --prefer-dist --no-interaction --no-progress
script:
- composer test-commonmark-weak
- <<: *COMMONMARK_TEST
name: Strict
script:
- composer test-commonmark

View File

@@ -13,14 +13,15 @@
}
],
"require": {
"php": "^7||^5.5",
"php": "^7.1||^8.0",
"ext-mbstring": "*"
},
"require-dev": {
"phpunit/phpunit": "^7.4||^6.5.13||^5.7.27||^4.8.36",
"vimeo/psalm": "^3.0.11",
"friendsofphp/php-cs-fixer": "^2.13",
"infection/infection": "^0.12.0"
"phpunit/phpunit": "^9.3.11||^8.5.21||^7.5.20",
"vimeo/psalm": "^4.10.0",
"friendsofphp/php-cs-fixer": "^3.0.0",
"infection/infection": "^0.25.0",
"roave/infection-static-analysis-plugin": "^1.10.0"
},
"autoload": {
"psr-4": {"Erusev\\Parsedown\\": "src/"}

View File

@@ -0,0 +1,222 @@
# Implementing "Extensions" in v2.0
Parsedown v1.x allowed extensability through class extensions, where an developer
could extend the core Parsedown class, and access or override any of the `protected`
level methods and variables.
Whilst this approach allows huge breadth to the type of functionality that can
be added by an extension, it has some downsides too:
* ### Composability: extensions cannot be combined easily
An extension must extend another extension for two extensions to work together.
This limits the usefulness of small extensions, because they cannot be combined with another small or popular extension.
If an extension author wishes the extension to be compatible with another extension, they can only pick one.
* ### API stability
Because extensions have access to functions and variables at the `protected` API layer, it is hard to determine impacts of
internal changes. Yet, without being able to make a certain amount of internal change it is impractical to fix bugs or develop
new features. In the `1.x` branch, `1.8` was never released outside of a "beta" version for this reason: changes in the
`protected` API layer would break extensions.
In order to address these concerns, "extensions" in Parsedown v2.0 will become more like "plugins", and with that comes a lot of
flexability.
ParsedownExtra is a popular extension for Parsedown, and this has been completely re-implemented for 2.0. In order to use
ParsedownExtra with Parsedown, a user simply needs to write the following:
```php
$Parsedown = new Parsedown(new ParsedownExtra);
$actualMarkup = $Parsedown->toHtml($markdown);
```
Here, ParsedownExtra is *composed* with Parsedown, but does not extend it.
A key feature of *composability* is the ability to compose *multiple* extensions together, for example another
extension, say, `ParsedownMath` could be composed with `ParsedownExtra` in a user-defined order.
This time using the `::from` method, rather than the convinence constructor provided by `ParsedownExtra`.
```php
$Parsedown = new Parsedown(ParsedownExtra::from(ParsedownMath::from(new State)));
```
```php
$Parsedown = new Parsedown(ParsedownMath::from(ParsedownExtra::from(new State)));
```
In the above, the first object that we initialise the chain of composed extensions is the `State` object. This `State`
object is passed from `ParsedownExtra` to `ParsedownMath`, and then finally, to `Parsedown`. At each stage new
information is added to the `State`: adding or removing parsing instructions, and to enabling or disabling features.
The `State` object both contains instructions for how to parse a document (e.g. new blocks and inlines), as well as
information used throughout parsing (such as link reference definitions, or recursion depth). By writing `new State`,
we create a `State` object that is setup with Parsedown's default behaviours, and by passing that object through
different extensions (using the `::from` method), these extensions are free to alter, add to, or remove from that
default behaviour.
## Introduction to the `State` Object
Key to Parsedown's new composability for extensions is the `State` object.
This name is a little obtuse, but is importantly accurate.
A `State` object incorporates `Block`s, `Inline`s, some additional render steps, and any custom configuration options that
the user might want to set. This can **fully** control how a document is parsed and rendered.
In the above code, `ParsedownExtra` and `ParsedownMath` would both be implementing the `StateBearer` interface, which
essentially means "this class holds onto a particular Parsedown State". A `StateBearer` should be constructable from
an existing `State` via `::from(StateBearer $StateBearer)`, and reveals the `State` it is holding onto via `->state(): State`.
Implementing the `StateBearer` interface is **strongly encouraged** if implementing an extension, but not necessarily required.
In the end, you can modify Parsedown's behaviour by producing an appropriate `State` object (which itself is trivially a
`StateBearer`).
In general, extensions are encouraged to go further still, and split each self-contained piece of functionality out into its own
`StateBearer`. This will allow your users to cherry-pick specific pieces of functionality and combine it with other
functionality from different authors as they like. For example, a feature of ParsedownExtra is the ability to define and expand
"abbreviations". This feature is self-contained, and does not depend on other features (e.g. "footnotes").
A user could import *only* the abbreviations feature from ParsedownExtra by using the following:
```php
use Erusev\Parsedown\State;
use Erusev\Parsedown\Parsedown;
use Erusev\ParsedownExtra\Features\Abbreviations;
$State = Abbreviations::from(new State);
$Parsedown = new Parsedown($State);
$actualMarkup = $Parsedown->toHtml($markdown);
```
This allows a user to have fine-grained control over which features they import, and will allow them much more control over
combining features from multiple sources. E.g. a user may not like the way ParsedownExtra has implemented the "footnotes" feature,
and so may wish to utilise an implementation from another source. By implementing each feature as its own `StateBearer`, we give
users the freedom to compose features in a way that works for them.
## Anatomy of the `State` Object
The `State` object, generically, consists of a set of `Configurable`s. The word "set" is important here: only one instance of each
`Configurable` may exist in a `State`. If you need to store related data in a `Configurable`, your `Configurable` needs to handle
this containerisation itself.
`State` has a special property: all `Configurable`s "exist" in any `State` object when retrieving that `Configurable` with `->get`.
This means that retrieval cannot fail when using this method, though does mean that all `Configurable`s need to be "default constructable" (i.e. can be constructed into a "default" state). All `Configurable`s must therefore implement the static method
`initial`, which must return an instance of the given `Configurable`. No initial data will be provided, but the `Configurable` **must** arrive at some sane default instance.
`Configurable`s must also be immutable, unless they declare themeslves otherwise by implementing the `MutableConfigurable` interface.
### Blocks
One of the "core" `Configurable`s in Parsedown is `BlockTypes`. This contains a mapping of "markers" (a character that Parsedown
looks for, before handing off to the block-specific parser), and a list of `Block`s that can begin parsing from a specific marker.
Also contained, is a list of "unmarked" blocks, which Parsedown will hand off to prior to trying any marked blocks. Within marked
blocks there is also a precedence order, where the first block type to successfully parse in this list will be the one chosen.
The default value given by `BlockTypes::initial()` consists of Parsedown's default blocks. The following is a snapshot of this list:
```php
const DEFAULT_BLOCK_TYPES = [
'#' => [Header::class],
'*' => [Rule::class, TList::class],
'+' => [TList::class],
'-' => [SetextHeader::class, Table::class, Rule::class, TList::class],
...
```
This means that if a `-` marker is found, Parsedown will first try to parse a `SetextHeader`, then try to parse a `Table`, and
so on...
A new block can be added to this list in several ways. ParsedownExtra, for example, adds a new `Abbreviation` block as follows:
```php
$BlockTypes = $State->get(BlockTypes::class)
->addingMarkedLowPrecedence('*', [Abbreviation::class])
;
$State = $State->setting($BlockTypes);
```
This first retrieves the current value of the `BlockTypes` configurable, adds `Abbreviation` with low precedence (i.e. the
back of the list) to the `*` marker, and then updates the `$State` object by using the `->setting` method.
### Immutability
Note that the `->setting` method must be used to create a new instance of the `State` object because `BlockTypes` is immutable,
the same will be true of most configurables. This approach is preferred because mutations to `State` are localised by default: i.e.
only affect copies of `$State` which we provide to other methods, but does not affect copies of `$State` which were provided to our
code by a parent caller.
Localised mutability allows for more sensible reasoning by default, for example (this time talking about `Inline`s), the `Link` inline
can enforce that no inline `Url`s are parsed (which would cause double links in output when parsing something like:
`[https://example.com](https://example.com)`). This can be done by updating the copy of `$State` which is passed down to lower level
parsers to simply no longer include parsing of `Url`s:
```php
$State = $State->setting(
$State->get(InlineTypes::class)->removing([Url::class])
);
```
If `InlineTypes` were mutable, this change would not only affect decendent parsing, but would also affect all parsing which occured after our link was parsed (i.e. would stop URL parsing from that point on in the document).
Another use case for this is implementing a recursion limiter (which *is* implemented as a configurable). After a user-specifiable
max-depth is exceeded: further parsing will halt. The implementaion for this is extremely simple, only because of immutability.
### Mutability
The preference toward immutability by default is not an assertion that "mutability is bad", rather that "unexpected mutability
is bad". By opting-in to mutability, we can treat mutability with the care it deserves.
While immutabiltiy can do a lot to simplify reasoning in the majority of cases, there are some cirumstances where mutability is
required to implement a specific feature. An exmaple of this is found in ParsedownExtra's "abbreviations" feature, which implements
the following:
```php
final class AbbreviationBook implements MutableConfigurable
{
/** @var array<string, string> */
private $book;
/**
* @param array<string, string> $book
*/
public function __construct(array $book = [])
{
$this->book = $book;
}
/** @return self */
public static function initial()
{
return new self;
}
public function mutatingSet(string $abbreviation, string $definition): void
{
$this->book[$abbreviation] = $definition;
}
public function lookup(string $abbreviation): ?string
{
return $this->book[$abbreviation] ?? null;
}
/** @return array<string, string> */
public function all()
{
return $this->book;
}
/** @return self */
public function isolatedCopy(): self
{
return new self($this->book);
}
}
```
Under the hood, `AbbreviationBook` is nothing more than a string-to-string mapping between an abbreviation, and its definition.
The powerful feature here is that when an abbreviation is identified during parsing, that definition can be updated immediately
everywhere, without needing to worry about the current parsing depth, or organise an alternate method to sharing this data. Footnotes
also make use of this with a `FootnoteBook`, with slightly more complexity in what is stored (so that inline references can be
individually numbered).

View File

@@ -1,6 +1,6 @@
<?xml version="1.0"?>
<psalm
totallyTyped="true"
errorLevel="1"
strictBinaryOperands="true"
checkForThrowsDocblock="true"
>
@@ -19,7 +19,7 @@
<errorLevel type="suppress"><directory name="tests" /></errorLevel>
</PropertyNotSetInConstructor>
<UnusedClass>
<errorLevel type="suppress"><directory name="tests/src" /></errorLevel>
<errorLevel type="suppress"><directory name="tests" /></errorLevel>
</UnusedClass>
<UndefinedInterfaceMethod>
<errorLevel type="suppress"><directory name="tests/src" /></errorLevel>
@@ -30,5 +30,10 @@
<PossiblyNullReference>
<errorLevel type="suppress"><directory name="tests/src" /></errorLevel>
</PossiblyNullReference>
<InternalMethod>
<errorLevel type="suppress">
<directory name="tests" />
</errorLevel>
</InternalMethod>
</issueHandlers>
</psalm>

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\ContinuableBlock;
use Erusev\Parsedown\Html\Renderables\Element;
@@ -62,7 +61,7 @@ final class BlockQuote implements ContinuableBlock
*/
public function advance(Context $Context, State $State)
{
if ($Context->previousEmptyLines() > 0) {
if ($Context->precedingEmptyLines() > 0) {
return null;
}
@@ -82,7 +81,7 @@ final class BlockQuote implements ContinuableBlock
return new self($Lines);
}
if (! $Context->previousEmptyLines() > 0) {
if (!($Context->precedingEmptyLines() > 0)) {
$indentOffset = $Context->line()->indentOffset() + $Context->line()->indent();
$Lines = $this->Lines->appendingTextLines($Context->line()->text(), $indentOffset);
@@ -93,7 +92,7 @@ final class BlockQuote implements ContinuableBlock
}
/**
* @return array{0: Block[], 1: State}
* @return array{Block[], State}
*/
public function contents(State $State)
{

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\ContinuableBlock;
use Erusev\Parsedown\Html\Renderables\Element;
@@ -88,7 +87,7 @@ final class FencedCode implements ContinuableBlock
$newCode = $this->code;
$newCode .= $Context->previousEmptyLinesText();
$newCode .= $Context->precedingEmptyLinesText();
if (($len = \strspn($Context->line()->text(), $this->marker)) >= $this->openerLength
&& \chop(\substr($Context->line()->text(), $len), ' ') === ''

View File

@@ -3,8 +3,9 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Configurables\HeaderSlug;
use Erusev\Parsedown\Configurables\SlugRegister;
use Erusev\Parsedown\Configurables\StrictMode;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Parsedown;
@@ -96,9 +97,17 @@ final class Header implements Block
return new Handler(
/** @return Element */
function (State $State) {
$HeaderSlug = $State->get(HeaderSlug::class);
$Register = $State->get(SlugRegister::class);
$attributes = (
$HeaderSlug->isEnabled()
? ['id' => $HeaderSlug->transform($Register, $this->text())]
: []
);
return new Element(
'h' . \strval($this->level()),
[],
$attributes,
$State->applyTo(Parsedown::line($this->text(), $State))
);
}

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\ContinuableBlock;
use Erusev\Parsedown\Html\Renderables\Element;
@@ -35,7 +34,7 @@ final class IndentedCode implements ContinuableBlock
State $State,
Block $Block = null
) {
if (isset($Block) && $Block instanceof Paragraph && ! $Context->previousEmptyLines() > 0) {
if (isset($Block) && $Block instanceof Paragraph && ! ($Context->precedingEmptyLines() > 0)) {
return null;
}
@@ -61,8 +60,8 @@ final class IndentedCode implements ContinuableBlock
$offset = $Context->line()->indentOffset();
if ($Context->previousEmptyLines() > 0) {
foreach (\explode("\n", $Context->previousEmptyLinesText()) as $line) {
if ($Context->precedingEmptyLines() > 0) {
foreach (\explode("\n", $Context->precedingEmptyLinesText()) as $line) {
$newCode .= (new Line($line, $offset))->ltrimBodyUpto(4) . "\n";
}

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\ContinuableBlock;
use Erusev\Parsedown\Configurables\SafeMode;
@@ -15,18 +14,81 @@ use Erusev\Parsedown\State;
final class Markup implements ContinuableBlock
{
const REGEX_HTML_ATTRIBUTE = '[a-zA-Z_:][\w:.-]*+(?:\s*+=\s*+(?:[^"\'=<>`\s]+|"[^"]*+"|\'[^\']*+\'))?+';
private const REGEX_HTML_ATTRIBUTE = '[a-zA-Z_:][\w:.-]*+(?:\s*+=\s*+(?:[^"\'=<>`\s]+|"[^"]*+"|\'[^\']*+\'))?+';
/** @var array{2: string, 3: string, 4: string, 5: string} */
private static $simpleContainsEndConditions = [
private const BLOCK_ELEMENTS = [
'address' => true,
'article' => true,
'aside' => true,
'base' => true,
'basefont' => true,
'blockquote' => true,
'body' => true,
'caption' => true,
'center' => true,
'col' => true,
'colgroup' => true,
'dd' => true,
'details' => true,
'dialog' => true,
'dir' => true,
'div' => true,
'dl' => true,
'dt' => true,
'fieldset' => true,
'figcaption' => true,
'figure' => true,
'footer' => true,
'form' => true,
'frame' => true,
'frameset' => true,
'h1' => true,
'h2' => true,
'h3' => true,
'h4' => true,
'h5' => true,
'h6' => true,
'head' => true,
'header' => true,
'hr' => true,
'html' => true,
'iframe' => true,
'legend' => true,
'li' => true,
'link' => true,
'main' => true,
'menu' => true,
'menuitem' => true,
'nav' => true,
'noframes' => true,
'ol' => true,
'optgroup' => true,
'option' => true,
'p' => true,
'param' => true,
'section' => true,
'source' => true,
'summary' => true,
'table' => true,
'tbody' => true,
'td' => true,
'tfoot' => true,
'th' => true,
'thead' => true,
'title' => true,
'tr' => true,
'track' => true,
'ul' => true,
];
private const SIMPLE_CONTAINS_END_CONDITIONS = [
2 => '-->',
3 => '?>',
4 => '>',
5 => ']]>'
5 => ']]>',
];
/** @var array<string, string> */
private static $specialHtmlBlockTags = [
private const SPECIAL_HTML_BLOCK_TAGS = [
'script' => true,
'style' => true,
'pre' => true,
@@ -87,17 +149,37 @@ final class Markup implements ContinuableBlock
return new self($rawLine, 5, self::closes12345TypeMarkup(5, $text));
}
if (\preg_match('/^<[\/]?+(\w++)(?:[ ]*+'.self::REGEX_HTML_ATTRIBUTE.')*+[ ]*+(\/)?>/', $text, $matches)) {
$element = \strtolower($matches[1]);
if (\preg_match('/^<([\/]?+)(\w++)(.*+)$/', $text, $matches)) {
$isClosing = ($matches[1] === '/');
$element = \strtolower($matches[2]);
$tail = $matches[3];
if (
\array_key_exists($element, Element::$TEXT_LEVEL_ELEMENTS)
|| \array_key_exists($element, self::$specialHtmlBlockTags)
if (\array_key_exists($element, self::BLOCK_ELEMENTS)
&& \preg_match('/^(?:\s|$|>|\/)/', $tail)
) {
return null;
return new self($rawLine, 6);
}
return new self($rawLine, 6);
if (
! $isClosing && \preg_match(
'/^(?:[ ]*+'.self::REGEX_HTML_ATTRIBUTE.')*(?:[ ]*+)[\/]?+[>](.*+)$/',
$tail,
$matches
) || $isClosing && \preg_match(
'/^(?:[ ]*+)[\/]?+[>](.*+)$/',
$tail,
$matches
)
) {
$tail = $matches[1];
if (! \array_key_exists($element, self::SPECIAL_HTML_BLOCK_TAGS)
&& ! (isset($Block) && $Block instanceof Paragraph && $Context->precedingEmptyLines() < 1)
&& \preg_match('/^\s*+$/', $tail)
) {
return new self($rawLine, 7);
}
}
}
return null;
@@ -117,7 +199,7 @@ final class Markup implements ContinuableBlock
return null;
}
if (($type === 6 || $type === 7) && $Context->previousEmptyLines() > 0) {
if (($type === 6 || $type === 7) && $Context->precedingEmptyLines() > 0) {
return null;
}
@@ -125,7 +207,7 @@ final class Markup implements ContinuableBlock
$closed = self::closes12345TypeMarkup($type, $Context->line()->text());
}
$html = $this->html . \str_repeat("\n", $Context->previousEmptyLines() + 1);
$html = $this->html . \str_repeat("\n", $Context->precedingEmptyLines() + 1);
$html .= $Context->line()->rawLine();
return new self($html, $type, $closed);
@@ -142,7 +224,7 @@ final class Markup implements ContinuableBlock
if (\preg_match('/<\/(?:script|pre|style)>/i', $text)) {
return true;
}
} elseif (\stripos($text, self::$simpleContainsEndConditions[$type]) !== false) {
} elseif (\stripos($text, self::SIMPLE_CONTAINS_END_CONDITIONS[$type]) !== false) {
return true;
}

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\ContinuableBlock;
use Erusev\Parsedown\Html\Renderables\Element;
@@ -45,7 +44,7 @@ final class Paragraph implements ContinuableBlock
*/
public function advance(Context $Context, State $State)
{
if ($Context->previousEmptyLines() > 0) {
if ($Context->precedingEmptyLines() > 0) {
return null;
}

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\StateUpdatingBlock;
use Erusev\Parsedown\Configurables\DefinitionBook;
@@ -43,9 +42,7 @@ final class Reference implements StateUpdatingBlock
'title' => isset($matches[3]) ? $matches[3] : null,
];
$State = $State->setting(
$State->get(DefinitionBook::class)->setting($id, $Data)
);
$State->get(DefinitionBook::class)->mutatingSet($id, $Data);
return new self($State);
}

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Parsing\Context;

View File

@@ -3,9 +3,10 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\AcquisitioningBlock;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Configurables\HeaderSlug;
use Erusev\Parsedown\Configurables\SlugRegister;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Parsedown;
use Erusev\Parsedown\Parsing\Context;
@@ -40,7 +41,7 @@ final class SetextHeader implements AcquisitioningBlock
State $State,
Block $Block = null
) {
if (! isset($Block) || ! $Block instanceof Paragraph || $Context->previousEmptyLines() > 0) {
if (! isset($Block) || ! $Block instanceof Paragraph || $Context->precedingEmptyLines() > 0) {
return null;
}
@@ -88,9 +89,17 @@ final class SetextHeader implements AcquisitioningBlock
return new Handler(
/** @return Element */
function (State $State) {
$HeaderSlug = $State->get(HeaderSlug::class);
$Register = $State->get(SlugRegister::class);
$attributes = (
$HeaderSlug->isEnabled()
? ['id' => $HeaderSlug->transform($Register, $this->text())]
: []
);
return new Element(
'h' . \strval($this->level()),
[],
$attributes,
$State->applyTo(Parsedown::line($this->text(), $State))
);
}

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\ContinuableBlock;
use Erusev\Parsedown\Html\Renderables\Element;
@@ -134,7 +133,7 @@ final class TList implements ContinuableBlock
$listStart !== 1
&& isset($Block)
&& $Block instanceof Paragraph
&& ! $Context->previousEmptyLines() > 0
&& ! ($Context->precedingEmptyLines() > 0)
) {
return null;
}
@@ -161,11 +160,11 @@ final class TList implements ContinuableBlock
*/
public function advance(Context $Context, State $State)
{
if ($Context->previousEmptyLines() > 0 && \end($this->Lis)->isEmpty()) {
if ($Context->precedingEmptyLines() > 0 && \end($this->Lis)->isEmpty()) {
return null;
}
$newlines = \str_repeat("\n", $Context->previousEmptyLines());
$newlines = \str_repeat("\n", $Context->precedingEmptyLines());
$requiredIndent = $this->indent + \strlen($this->marker) + $this->afterMarkerSpaces;
$isLoose = $this->isLoose;
@@ -173,16 +172,16 @@ final class TList implements ContinuableBlock
$Lis = $this->Lis;
if ($this->type === 'ol') {
$regex = '/^([0-9]++'.$this->markerTypeRegex.')([\t ]++.*|$)/';
} else {
$regex = '/^('.$this->markerTypeRegex.')([\t ]++.*|$)/';
}
if ($Context->line()->indent() < $requiredIndent
&& ((
$this->type === 'ol'
&& \preg_match('/^([0-9]++'.$this->markerTypeRegex.')([\t ]++.*|$)/', $Context->line()->text(), $matches)
) || (
$this->type === 'ul'
&& \preg_match('/^('.$this->markerTypeRegex.')([\t ]++.*|$)/', $Context->line()->text(), $matches)
))
&& \preg_match($regex, $Context->line()->text(), $matches)
) {
if ($Context->previousEmptyLines() > 0) {
if ($Context->precedingEmptyLines() > 0) {
$Lis[\count($Lis) -1] = $Lis[\count($Lis) -1]->appendingBlankLines(1);
$isLoose = true;
@@ -224,8 +223,8 @@ final class TList implements ContinuableBlock
}
if ($Context->line()->indent() >= $requiredIndent) {
if ($Context->previousEmptyLines() > 0) {
$Lis[\count($Lis) -1] = $Lis[\count($Lis) -1]->appendingBlankLines($Context->previousEmptyLines());
if ($Context->precedingEmptyLines() > 0) {
$Lis[\count($Lis) -1] = $Lis[\count($Lis) -1]->appendingBlankLines($Context->precedingEmptyLines());
$isLoose = true;
}
@@ -248,7 +247,7 @@ final class TList implements ContinuableBlock
);
}
if (! $Context->previousEmptyLines() > 0) {
if (! ($Context->precedingEmptyLines() > 0)) {
$text = $Context->line()->ltrimBodyUpto($requiredIndent);
$Lis[\count($Lis) -1] = $Lis[\count($Lis) -1]->appendingTextLines(
@@ -273,12 +272,12 @@ final class TList implements ContinuableBlock
}
/**
* @return array{0: Block[], 1: State}[]
* @return array{Block[], State}[]
*/
public function items(State $State)
{
return \array_map(
/** @return array{0: Block[], 1: State} */
/** @return array{Block[], State} */
function (Lines $Lines) use ($State) {
return Parsedown::blocks($Lines, $State);
},
@@ -317,7 +316,7 @@ final class TList implements ContinuableBlock
),
\array_map(
/**
* @param array{0: Block[], 1: State} $Item
* @param array{Block[], State} $Item
* @return Element
* */
function ($Item) {

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Blocks;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\AcquisitioningBlock;
use Erusev\Parsedown\Components\Block;
use Erusev\Parsedown\Components\ContinuableBlock;
@@ -18,30 +17,25 @@ use Erusev\Parsedown\State;
*/
final class Table implements AcquisitioningBlock, ContinuableBlock
{
/** @var bool */
private $acquired;
/** @var array<int, _Alignment|null> */
/** @var list<_Alignment|null> */
private $alignments;
/** @var array<int, string> */
/** @var list<string> */
private $headerCells;
/** @var array<int, array<int, string>> */
/** @var list<list<string>> */
private $rows;
/**
* @param array<int, _Alignment|null> $alignments
* @param array<int, string> $headerCells
* @param array<int, array<int, string>> $rows
* @param bool $acquired
* @param list<_Alignment|null> $alignments
* @param list<string> $headerCells
* @param list<list<string>> $rows
*/
private function __construct($alignments, $headerCells, $rows, $acquired = false)
private function __construct($alignments, $headerCells, $rows)
{
$this->alignments = $alignments;
$this->headerCells = $headerCells;
$this->rows = $rows;
$this->acquired = $acquired;
}
/**
@@ -91,7 +85,7 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
# ~
return new self($alignments, $headerCells, [], true);
return new self($alignments, $headerCells, []);
}
/**
@@ -101,7 +95,7 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
*/
public function advance(Context $Context, State $State)
{
if ($Context->previousEmptyLines() > 0) {
if ($Context->precedingEmptyLines() > 0) {
return null;
}
@@ -117,12 +111,14 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
if (
! \preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]++`|`)++/', $row, $matches)
|| ! isset($matches[0])
|| ! \is_array($matches[0])
) {
return null;
}
$cells = \array_map('trim', \array_slice($matches[0], 0, \count($this->alignments)));
$cells = \array_map(
'trim',
\array_slice($matches[0], 0, \count($this->alignments))
);
return new self(
$this->alignments,
@@ -133,7 +129,7 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
/**
* @param string $dividerRow
* @return array<int, _Alignment|null>|null
* @return list<_Alignment|null>|null
*/
private static function parseAlignments($dividerRow)
{
@@ -142,7 +138,7 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
$dividerCells = \explode('|', $dividerRow);
/** @var array<int, _Alignment|null> */
/** @var list<_Alignment|null> */
$alignments = [];
foreach ($dividerCells as $dividerCell) {
@@ -175,7 +171,7 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
return true;
}
/** @return array<int, Inline[]> */
/** @return list<Inline[]> */
public function headerRow(State $State)
{
return \array_map(
@@ -190,13 +186,13 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
);
}
/** @return array<int, Inline[]>[] */
/** @return list<Inline[]>[] */
public function rows(State $State)
{
return \array_map(
/**
* @param array<int, string> $cells
* @return array<int, Inline[]>
* @param list<string> $cells
* @return list<Inline[]>
*/
function ($cells) use ($State) {
return \array_map(
@@ -214,7 +210,7 @@ final class Table implements AcquisitioningBlock, ContinuableBlock
);
}
/** @return array<int, _Alignment|null> */
/** @return list<_Alignment|null> */
public function alignments()
{
return $this->alignments;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Html\Renderables\Text;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Html\Renderables\Text;

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Html\Renderables\Text;
@@ -21,14 +20,12 @@ final class Emphasis implements Inline
/** @var 'em'|'strong' */
private $type;
/** @var array{*: string, _: string} */
private static $STRONG_REGEX = [
private const STRONG_REGEX = [
'*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*+[*])+?)[*]{2}(?![*])/s',
'_' => '/^__((?:\\\\_|[^_]|_[^_]*+_)+?)__(?!_)/us',
];
/** @var array{*: string, _: string} */
private static $EM_REGEX = [
private const EM_REGEX = [
'*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
'_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
];
@@ -58,9 +55,9 @@ final class Emphasis implements Inline
return null;
}
if (\preg_match(self::$STRONG_REGEX[$marker], $Excerpt->text(), $matches)) {
if (\preg_match(self::STRONG_REGEX[$marker], $Excerpt->text(), $matches)) {
$emphasis = 'strong';
} elseif (\preg_match(self::$EM_REGEX[$marker], $Excerpt->text(), $matches)) {
} elseif (\preg_match(self::EM_REGEX[$marker], $Excerpt->text(), $matches)) {
$emphasis = 'em';
} else {
return null;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Text;
use Erusev\Parsedown\Parsing\Excerpt;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\BacktrackingInline;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Configurables\SafeMode;
use Erusev\Parsedown\Html\Renderables\Element;
@@ -71,12 +70,12 @@ final class Image implements Inline
}
/**
* @return Handler<Element|Text>
* @return Handler<Element>
*/
public function stateRenderable()
{
return new Handler(
/** @return Element|Text */
/** @return Element */
function (State $State) {
$attributes = [
'src' => $this->url(),

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Configurables\DefinitionBook;
use Erusev\Parsedown\Configurables\InlineTypes;
@@ -113,12 +112,12 @@ final class Link implements Inline
}
/**
* @return Handler<Element|Text>
* @return Handler<Element>
*/
public function stateRenderable()
{
return new Handler(
/** @return Element|Text */
/** @return Element */
function (State $State) {
$attributes = ['href' => $this->url()];

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Configurables\SafeMode;
use Erusev\Parsedown\Html\Renderables\RawHtml;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Text;
use Erusev\Parsedown\Parsing\Excerpt;

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\BacktrackingInline;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Configurables\Breaks;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\RawHtml;
use Erusev\Parsedown\Html\Renderables\Text;

View File

@@ -3,7 +3,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\Handler;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Html\Renderables\Text;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\BacktrackingInline;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;
@@ -14,6 +13,9 @@ final class Url implements BacktrackingInline
{
use WidthTrait;
private const URI = 'https?+:[^\s[:cntrl:]<>]*';
private const NO_TRAILING_PUNCT = '(?<![?!.,:*_~])';
/** @var string */
private $url;
@@ -38,13 +40,31 @@ final class Url implements BacktrackingInline
*/
public static function build(Excerpt $Excerpt, State $State)
{
if (\preg_match(
'/(?<=^|\s|[*_~(])https?+:[\/]{2}[^\s<]+\b\/*+/ui',
$Excerpt->context(),
$matches,
\PREG_OFFSET_CAPTURE
)) {
return new self($matches[0][0], \intval($matches[0][1]));
// this needs some work to follow spec
if (
\preg_match(
'/'.self::URI.self::NO_TRAILING_PUNCT.'/iu',
$Excerpt->context(),
$matches,
\PREG_OFFSET_CAPTURE
)
) {
/** @var array{0: array{string, int}} $matches */
$url = $matches[0][0];
$position = \intval($matches[0][1]);
if (\preg_match('/[)]++$/', $url, $matches)) {
$trailingParens = \strlen($matches[0]);
$openingParens = \substr_count($url, '(');
$closingParens = \substr_count($url, ')');
if ($closingParens > $openingParens) {
$url = \substr($url, 0, -\min($trailingParens, $closingParens - $openingParens));
}
}
return new self($url, $position);
}
return null;

View File

@@ -2,7 +2,6 @@
namespace Erusev\Parsedown\Components\Inlines;
use Erusev\Parsedown\AST\StateRenderable;
use Erusev\Parsedown\Components\Inline;
use Erusev\Parsedown\Html\Renderables\Element;
use Erusev\Parsedown\Html\Renderables\Text;

View File

@@ -17,8 +17,7 @@ use Erusev\Parsedown\Configurable;
final class BlockTypes implements Configurable
{
/** @var array<array-key, array<int, class-string<Block>>> */
private static $defaultBlockTypes = [
private const DEFAULT_BLOCK_TYPES = [
'#' => [Header::class],
'*' => [Rule::class, TList::class],
'+' => [TList::class],
@@ -44,20 +43,19 @@ final class BlockTypes implements Configurable
'~' => [FencedCode::class],
];
/** @var array<int, class-string<Block>> */
private static $defaultUnmarkedBlockTypes = [
private const DEFAULT_UNMARKED_BLOCK_TYPES = [
IndentedCode::class,
];
/** @var array<array-key, array<int, class-string<Block>>> */
/** @var array<array-key, list<class-string<Block>>> */
private $blockTypes;
/** @var array<int, class-string<Block>> */
/** @var list<class-string<Block>> */
private $unmarkedBlockTypes;
/**
* @param array<array-key, array<int, class-string<Block>>> $blockTypes
* @param array<int, class-string<Block>> $unmarkedBlockTypes
* @param array<array-key, list<class-string<Block>>> $blockTypes
* @param list<class-string<Block>> $unmarkedBlockTypes
*/
public function __construct(array $blockTypes, array $unmarkedBlockTypes)
{
@@ -69,14 +67,14 @@ final class BlockTypes implements Configurable
public static function initial()
{
return new self(
self::$defaultBlockTypes,
self::$defaultUnmarkedBlockTypes
self::DEFAULT_BLOCK_TYPES,
self::DEFAULT_UNMARKED_BLOCK_TYPES
);
}
/**
* @param string $marker
* @param array<int, class-string<Block>> $newBlockTypes
* @param list<class-string<Block>> $newBlockTypes
* @return self
*/
public function settingMarked($marker, array $newBlockTypes)
@@ -89,7 +87,7 @@ final class BlockTypes implements Configurable
/**
* @param string $marker
* @param array<int, class-string<Block>> $newBlockTypes
* @param list<class-string<Block>> $newBlockTypes
* @return self
*/
public function addingMarkedHighPrecedence($marker, array $newBlockTypes)
@@ -103,9 +101,48 @@ final class BlockTypes implements Configurable
);
}
/**
* @param class-string<Block> $searchBlockType
* @param class-string<Block> $replacementBlockType
*/
public function replacing($searchBlockType, $replacementBlockType): self
{
$replacer = self::makeReplacer($searchBlockType, $replacementBlockType);
return new self(
\array_map($replacer, $this->blockTypes),
$replacer($this->unmarkedBlockTypes)
);
}
/**
* @param class-string<Block> $searchBlockType
* @param class-string<Block> $replacementBlockType
* @return \Closure(list<class-string<Block>>):list<class-string<Block>>
*/
private static function makeReplacer($searchBlockType, $replacementBlockType)
{
/**
* @param list<class-string<Block>> $blockTypes
* @return list<class-string<Block>>
*/
return function ($blockTypes) use ($searchBlockType, $replacementBlockType) {
return \array_map(
/**
* @param class-string<Block> $blockType
* @return class-string<Block>
*/
function ($blockType) use ($searchBlockType, $replacementBlockType) {
return $blockType === $searchBlockType ? $replacementBlockType : $blockType;
},
$blockTypes
);
};
}
/**
* @param string $marker
* @param array<int, class-string<Block>> $newBlockTypes
* @param list<class-string<Block>> $newBlockTypes
* @return self
*/
public function addingMarkedLowPrecedence($marker, array $newBlockTypes)
@@ -120,7 +157,7 @@ final class BlockTypes implements Configurable
}
/**
* @param array<int, class-string<Block>> $newUnmarkedBlockTypes
* @param list<class-string<Block>> $newUnmarkedBlockTypes
* @return self
*/
public function settingUnmarked(array $newUnmarkedBlockTypes)
@@ -129,7 +166,7 @@ final class BlockTypes implements Configurable
}
/**
* @param array<int, class-string<Block>> $newBlockTypes
* @param list<class-string<Block>> $newBlockTypes
* @return self
*/
public function addingUnmarkedHighPrecedence(array $newBlockTypes)
@@ -140,7 +177,7 @@ final class BlockTypes implements Configurable
}
/**
* @param array<int, class-string<Block>> $newBlockTypes
* @param list<class-string<Block>> $newBlockTypes
* @return self
*/
public function addingUnmarkedLowPrecedence(array $newBlockTypes)
@@ -151,7 +188,7 @@ final class BlockTypes implements Configurable
}
/**
* @param array<int, class-string<Block>> $removeBlockTypes
* @param list<class-string<Block>> $removeBlockTypes
* @return self
*/
public function removing(array $removeBlockTypes)
@@ -159,21 +196,21 @@ final class BlockTypes implements Configurable
return new self(
\array_map(
/**
* @param array<int, class-string<Block>> $blockTypes
* @return array<int, class-string<Block>>
* @param list<class-string<Block>> $blockTypes
* @return list<class-string<Block>>
*/
function ($blockTypes) use ($removeBlockTypes) {
return \array_diff($blockTypes, $removeBlockTypes);
return \array_values(\array_diff($blockTypes, $removeBlockTypes));
},
$this->blockTypes
),
\array_diff($this->unmarkedBlockTypes, $removeBlockTypes)
\array_values(\array_diff($this->unmarkedBlockTypes, $removeBlockTypes))
);
}
/**
* @param string $marker
* @return array<int, class-string<Block>>
* @return list<class-string<Block>>
*/
public function markedBy($marker)
{
@@ -185,7 +222,7 @@ final class BlockTypes implements Configurable
}
/**
* @return array<int, class-string<Block>>
* @return list<class-string<Block>>
*/
public function unmarked()
{

View File

@@ -2,12 +2,12 @@
namespace Erusev\Parsedown\Configurables;
use Erusev\Parsedown\Configurable;
use Erusev\Parsedown\MutableConfigurable;
/**
* @psalm-type _Data=array{url: string, title: string|null}
*/
final class DefinitionBook implements Configurable
final class DefinitionBook implements MutableConfigurable
{
/** @var array<string, _Data> */
private $book;
@@ -29,14 +29,10 @@ final class DefinitionBook implements Configurable
/**
* @param string $id
* @param _Data $data
* @return self
*/
public function setting($id, array $data)
public function mutatingSet($id, array $data): void
{
$book = $this->book;
$book[$id] = $data;
return new self($book);
$this->book[$id] = $data;
}
/**
@@ -51,4 +47,10 @@ final class DefinitionBook implements Configurable
return null;
}
/** @return static */
public function isolatedCopy(): self
{
return new self($this->book);
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace Erusev\Parsedown\Configurables;
use Erusev\Parsedown\Configurable;
final class HeaderSlug implements Configurable
{
/** @var bool */
private $enabled = false;
/** @var \Closure(string):string */
private $slugCallback;
/** @var \Closure(string,int):string */
private $duplicationCallback;
/**
* @param bool $enabled
* @param (\Closure(string):string)|null $slugCallback
* @param (\Closure(string, int):string)|null $duplicationCallback
*/
public function __construct(
$enabled,
$slugCallback = null,
$duplicationCallback = null
) {
$this->enabled = $enabled;
if (! isset($slugCallback)) {
$this->slugCallback = function (string $text): string {
$slug = \mb_strtolower($text);
$slug = \str_replace(' ', '-', $slug);
$slug = \preg_replace('/[^\p{L}\p{Nd}\p{Nl}\p{M}-]+/u', '', $slug);
$slug = \trim($slug, '-');
return $slug;
};
} else {
$this->slugCallback = $slugCallback;
}
if (! isset($duplicationCallback)) {
$this->duplicationCallback = function (string $slug, int $duplicateNumber): string {
return $slug . '-' . \strval($duplicateNumber-1);
};
} else {
$this->duplicationCallback = $duplicationCallback;
}
}
/** @return bool */
public function isEnabled()
{
return $this->enabled;
}
public function transform(SlugRegister $SlugRegister, string $text): string
{
$slug = ($this->slugCallback)($text);
if ($SlugRegister->slugCount($slug) > 0) {
$newSlug = ($this->duplicationCallback)($slug, $SlugRegister->mutatingIncrement($slug));
while ($SlugRegister->slugCount($newSlug) > 0) {
$newSlug = ($this->duplicationCallback)($slug, $SlugRegister->mutatingIncrement($slug));
}
return $newSlug;
}
$SlugRegister->mutatingIncrement($slug);
return $slug;
}
/** @param \Closure(string):string $slugCallback */
public static function withCallback($slugCallback): self
{
return new self(true, $slugCallback);
}
/** @param \Closure(string,int):string $duplicationCallback */
public static function withDuplicationCallback($duplicationCallback): self
{
return new self(true, null, $duplicationCallback);
}
/** @return self */
public static function enabled()
{
return new self(true);
}
/** @return self */
public static function initial()
{
return new self(false);
}
}

View File

@@ -20,8 +20,7 @@ use Erusev\Parsedown\Configurable;
final class InlineTypes implements Configurable
{
/** @var array<array-key, array<int, class-string<Inline>>> */
private static $defaultInlineTypes = [
private const DEFAULT_INLINE_TYPES = [
'!' => [Image::class],
'*' => [Emphasis::class],
'_' => [Emphasis::class],
@@ -35,14 +34,14 @@ final class InlineTypes implements Configurable
"\n" => [HardBreak::class, SoftBreak::class],
];
/** @var array<array-key, array<int, class-string<Inline>>> */
/** @var array<array-key, list<class-string<Inline>>> */
private $inlineTypes;
/** @var string */
private $inlineMarkers;
/**
* @param array<array-key, array<int, class-string<Inline>>> $inlineTypes
* @param array<array-key, list<class-string<Inline>>> $inlineTypes
*/
public function __construct(array $inlineTypes)
{
@@ -53,12 +52,12 @@ final class InlineTypes implements Configurable
/** @return self */
public static function initial()
{
return new self(self::$defaultInlineTypes);
return new self(self::DEFAULT_INLINE_TYPES);
}
/**
* @param string $marker
* @param array<int, class-string<Inline>> $newInlineTypes
* @param list<class-string<Inline>> $newInlineTypes
* @return self
*/
public function setting($marker, array $newInlineTypes)
@@ -69,9 +68,38 @@ final class InlineTypes implements Configurable
return new self($inlineTypes);
}
/**
* @param class-string<Inline> $searchInlineType
* @param class-string<Inline> $replacementInlineType
*/
public function replacing($searchInlineType, $replacementInlineType): self
{
return new self(
\array_map(
/**
* @param list<class-string<Inline>> $inlineTypes
* @return list<class-string<Inline>>
*/
function ($inlineTypes) use ($searchInlineType, $replacementInlineType) {
return \array_map(
/**
* @param class-string<Inline> $inlineType
* @return class-string<Inline>
*/
function ($inlineType) use ($searchInlineType, $replacementInlineType) {
return $inlineType === $searchInlineType ? $replacementInlineType : $inlineType;
},
$inlineTypes
);
},
$this->inlineTypes
)
);
}
/**
* @param string $marker
* @param array<int, class-string<Inline>> $newInlineTypes
* @param list<class-string<Inline>> $newInlineTypes
* @return self
*/
public function addingHighPrecedence($marker, array $newInlineTypes)
@@ -87,7 +115,7 @@ final class InlineTypes implements Configurable
/**
* @param string $marker
* @param array<int, class-string<Inline>> $newInlineTypes
* @param list<class-string<Inline>> $newInlineTypes
* @return self
*/
public function addingLowPrecedence($marker, array $newInlineTypes)
@@ -102,18 +130,18 @@ final class InlineTypes implements Configurable
}
/**
* @param array<int, class-string<Inline>> $removeInlineTypes
* @param list<class-string<Inline>> $removeInlineTypes
* @return self
*/
public function removing(array $removeInlineTypes)
{
return new self(\array_map(
/**
* @param array<int, class-string<Inline>> $inlineTypes
* @return array<int, class-string<Inline>>
* @param list<class-string<Inline>> $inlineTypes
* @return list<class-string<Inline>>
*/
function ($inlineTypes) use ($removeInlineTypes) {
return \array_diff($inlineTypes, $removeInlineTypes);
return \array_values(\array_diff($inlineTypes, $removeInlineTypes));
},
$this->inlineTypes
));
@@ -121,7 +149,7 @@ final class InlineTypes implements Configurable
/**
* @param string $marker
* @return array<int, class-string<Inline>>
* @return list<class-string<Inline>>
*/
public function markedBy($marker)
{

View File

@@ -38,7 +38,7 @@ final class RecursionLimiter implements Configurable
}
/** @return self */
public function increment()
public function incremented()
{
return new self($this->maxDepth, $this->currentDepth + 1);
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Erusev\Parsedown\Configurables;
use Erusev\Parsedown\Configurable;
use Erusev\Parsedown\Html\Renderable;
use Erusev\Parsedown\State;
final class RenderStack implements Configurable
{
/** @var list<\Closure(Renderable[],State):Renderable[]> */
private $stack;
/**
* @param list<\Closure(Renderable[],State):Renderable[]> $stack
*/
private function __construct($stack = [])
{
$this->stack = $stack;
}
/** @return self */
public static function initial()
{
return new self;
}
/**
* @param \Closure(Renderable[],State):Renderable[] $RenderMap
* @return self
*/
public function push(\Closure $RenderMap): self
{
return new self(\array_merge($this->stack, [$RenderMap]));
}
/** @return list<\Closure(Renderable[],State):Renderable[]> */
public function getStack(): array
{
return $this->stack;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Erusev\Parsedown\Configurables;
use Erusev\Parsedown\MutableConfigurable;
final class SlugRegister implements MutableConfigurable
{
/** @var array<string, int> */
private $register;
/**
* @param array<string, int> $register
*/
public function __construct(array $register = [])
{
$this->register = $register;
}
/** @return self */
public static function initial()
{
return new self;
}
public function mutatingIncrement(string $slug): int
{
if (! isset($this->register[$slug])) {
$this->register[$slug] = 0;
}
return ++$this->register[$slug];
}
public function slugCount(string $slug): int
{
return $this->register[$slug] ?? 0;
}
/** @return static */
public function isolatedCopy(): self
{
return new self($this->register);
}
}

View File

@@ -3,8 +3,9 @@
namespace Erusev\Parsedown\Html\Renderables;
use Erusev\Parsedown\Html\Renderable;
use Erusev\Parsedown\Html\TransformableRenderable;
final class Container implements Renderable
final class Container implements TransformableRenderable
{
use CanonicalStateRenderable;
@@ -14,7 +15,7 @@ final class Container implements Renderable
/**
* @param Renderable[] $Contents
*/
public function __construct($Contents)
public function __construct($Contents = [])
{
$this->Contents = $Contents;
}
@@ -27,6 +28,10 @@ final class Container implements Renderable
return $this->Contents;
}
public function adding(Renderable $Renderable): Container
{
return new Container(\array_merge($this->Contents, [$Renderable]));
}
/** @return string */
public function getHtml()
@@ -44,4 +49,36 @@ final class Container implements Renderable
''
);
}
/**
* @param \Closure(string):TransformableRenderable $Transform
* @return TransformableRenderable
*/
public function transformingContent(\Closure $Transform): TransformableRenderable
{
return new Container(\array_map(
function (Renderable $R) use ($Transform): Renderable {
if (! $R instanceof TransformableRenderable) {
return $R;
}
return $R->transformingContent($Transform);
},
$this->Contents
));
}
public function replacingAll(string $search, TransformableRenderable $Replacement): TransformableRenderable
{
return new Container(\array_map(
function (Renderable $R) use ($search, $Replacement): Renderable {
if (! $R instanceof TransformableRenderable) {
return $R;
}
return $R->replacingAll($search, $Replacement);
},
$this->Contents
));
}
}

View File

@@ -5,13 +5,13 @@ namespace Erusev\Parsedown\Html\Renderables;
use Erusev\Parsedown\Html\Renderable;
use Erusev\Parsedown\Html\Sanitisation\CharacterFilter;
use Erusev\Parsedown\Html\Sanitisation\Escaper;
use Erusev\Parsedown\Html\TransformableRenderable;
final class Element implements Renderable
final class Element implements TransformableRenderable
{
use CanonicalStateRenderable;
/** @var array<string, true> */
public static $TEXT_LEVEL_ELEMENTS = [
const TEXT_LEVEL_ELEMENTS = [
'a' => true,
'b' => true,
'i' => true,
@@ -167,7 +167,7 @@ final class Element implements Renderable
foreach ($this->Contents as $C) {
if (
$C instanceof Element
&& ! \array_key_exists(\strtolower($C->name()), self::$TEXT_LEVEL_ELEMENTS)
&& ! \array_key_exists(\strtolower($C->name()), self::TEXT_LEVEL_ELEMENTS)
) {
$html .= "\n";
}
@@ -179,7 +179,7 @@ final class Element implements Renderable
if (
$Last instanceof Element
&& ! \array_key_exists(\strtolower($Last->name()), self::$TEXT_LEVEL_ELEMENTS)
&& ! \array_key_exists(\strtolower($Last->name()), self::TEXT_LEVEL_ELEMENTS)
) {
$html .= "\n";
}
@@ -192,4 +192,44 @@ final class Element implements Renderable
return $html;
}
/**
* @param \Closure(string):TransformableRenderable $Transform
* @return TransformableRenderable
*/
public function transformingContent(\Closure $Transform): TransformableRenderable
{
if (! isset($this->Contents)) {
return $this;
}
return new self($this->name, $this->attributes, \array_map(
function (Renderable $R) use ($Transform): Renderable {
if (! $R instanceof TransformableRenderable) {
return $R;
}
return $R->transformingContent($Transform);
},
$this->Contents
));
}
public function replacingAll(string $search, TransformableRenderable $Replacement): TransformableRenderable
{
if (! isset($this->Contents)) {
return $this;
}
return new self($this->name, $this->attributes, \array_map(
function (Renderable $R) use ($search, $Replacement): Renderable {
if (! $R instanceof TransformableRenderable) {
return $R;
}
return $R->replacingAll($search, $Replacement);
},
$this->Contents
));
}
}

View File

@@ -2,10 +2,10 @@
namespace Erusev\Parsedown\Html\Renderables;
use Erusev\Parsedown\Html\Renderable;
use Erusev\Parsedown\Html\Sanitisation\Escaper;
use Erusev\Parsedown\Html\TransformableRenderable;
final class Text implements Renderable
final class Text implements TransformableRenderable
{
use CanonicalStateRenderable;
@@ -31,4 +31,59 @@ final class Text implements Renderable
{
return Escaper::htmlElementValueEscapingDoubleQuotes($this->text);
}
/**
* @param \Closure(string):TransformableRenderable $Transform
* @return TransformableRenderable
*/
public function transformingContent(\Closure $Transform): TransformableRenderable
{
return $Transform($this->text);
}
public function replacingAll(string $search, TransformableRenderable $Replacement): TransformableRenderable
{
$searchLen = \strlen($search);
if ($searchLen < 1) {
return $this;
}
$result = \preg_match_all(
'/\b'.\preg_quote($search, '/').'\b/',
$this->text,
$matches,
\PREG_OFFSET_CAPTURE
);
if (empty($result)) {
return $this;
}
$lastEndPos = 0;
$Container = new Container;
foreach ($matches[0] as $match) {
$pos = $match[1];
$endPos = $pos + $searchLen;
if ($pos !== $lastEndPos) {
$Container = $Container->adding(
new Text(\substr($this->text, $lastEndPos, $pos - $lastEndPos))
);
}
$Container = $Container->adding($Replacement);
$lastEndPos = $endPos;
}
if (\strlen($this->text) !== $lastEndPos) {
$Container = $Container->adding(
new Text(\substr($this->text, $lastEndPos))
);
}
return $Container;
}
}

View File

@@ -4,8 +4,7 @@ namespace Erusev\Parsedown\Html\Sanitisation;
final class UrlSanitiser
{
/** @var string[] */
private static $COMMON_SCHEMES = [
private const COMMON_SCHEMES = [
'http://',
'https://',
'ftp://',
@@ -33,7 +32,7 @@ final class UrlSanitiser
public static function filter($url, $permittedSchemes = null)
{
if (! isset($permittedSchemes)) {
$permittedSchemes = self::$COMMON_SCHEMES;
$permittedSchemes = self::COMMON_SCHEMES;
}
foreach ($permittedSchemes as $scheme) {

View File

@@ -0,0 +1,34 @@
<?php
namespace Erusev\Parsedown\Html;
interface TransformableRenderable extends Renderable
{
/**
* Takes a closure $Transform which will provide a transformation of
* a "contained text" into Renderables.
*
* In order for TransformableRenderable to make sense, a Renderable must
* have:
* 1. Some concept of "contained text". $Transform can be applied
* piece-wise if your container contains logically disjoint sections
* of text.
* 2. A generic mechanism for containing other Renderables, or replacing
* the current renderable with a container.
*
* It is acceptable to only partially transform "contained text".
*
* @param \Closure(string):TransformableRenderable $Transform
* @return TransformableRenderable
*/
public function transformingContent(\Closure $Transform): TransformableRenderable;
/**
* Similar to transformingContent, but replace the string $search in text content
* with the renderable $Replacement and return the result.
*
* @param string $search
* @return TransformableRenderable
*/
public function replacingAll(string $search, TransformableRenderable $Replacement): TransformableRenderable;
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Erusev\Parsedown;
/**
* Beware that the values of MutableConfigurables are NOT stable. Values SHOULD
* be accessed as close to use as possible. Parsing operations sharing the same
* State SHOULD NOT be triggered between where values are read and where they
* need to be relied upon.
*/
interface MutableConfigurable extends Configurable
{
/**
* Objects contained in State can generally be regarded as immutable,
* however, when mutability is *required* then isolatedCopy (this method)
* MUST be implemented to take a reliable copy of the contained state,
* which MUST be fully seperable from the current instance. This is
* sometimes referred to as a "deep copy".
*
* The following assumption is made when you implement
* MutableConfigurable:
*
* A shared, (more or less) globally writable, instantaniously updating
* (at all parsing levels), single copy of a Configurable is intentional
* and desired.
*
* As such, Parsedown will use the isolatedCopy method to ensure state
* isolation between successive parsing calls (which are considered to be
* isolated documents).
*
* You MUST NOT depend on the method `initial` being called when a clean
* parsing state is desired, this will not reliably occur; implement
* isolatedCopy properly to allow Parsedown to manage this.
*
* Failing to implement this method properly can result in unintended
* side-effects. If possible, you should design your Configurable to be
* immutable, which allows a single copy to be shared safely, and mutations
* localised to a heirarchy for which the order of operations is easy to
* reason about.
*
* @return static
*/
public function isolatedCopy();
}

View File

@@ -14,8 +14,8 @@ use Erusev\Parsedown\Components\StateUpdatingBlock;
use Erusev\Parsedown\Configurables\BlockTypes;
use Erusev\Parsedown\Configurables\InlineTypes;
use Erusev\Parsedown\Configurables\RecursionLimiter;
use Erusev\Parsedown\Configurables\RenderStack;
use Erusev\Parsedown\Html\Renderable;
use Erusev\Parsedown\Html\Renderables\Text;
use Erusev\Parsedown\Parsing\Excerpt;
use Erusev\Parsedown\Parsing\Line;
use Erusev\Parsedown\Parsing\Lines;
@@ -29,23 +29,34 @@ final class Parsedown
public function __construct(StateBearer $StateBearer = null)
{
$StateBearer = $StateBearer ?: new State;
$State = ($StateBearer ?? new State)->state();
$this->State = $StateBearer->state();
$this->State = $State->isolatedCopy();
}
/**
* @param string $text
* @param string $markdown
* @return string
*/
public function text($text)
public function toHtml($markdown)
{
list($StateRenderables, $State) = self::lines(
Lines::fromTextLines($text, 0),
$this->State
Lines::fromTextLines($markdown, 0),
$this->State->isolatedCopy()
);
$Renderables = $State->applyTo($StateRenderables);
$Renderables = \array_reduce(
\array_reverse($State->get(RenderStack::class)->getStack()),
/**
* @param Renderable[] $Renderables
* @param \Closure(Renderable[],State):Renderable[] $RenderMap
* @return Renderable[]
*/
function (array $Renderables, \Closure $RenderMap) use ($State): array {
return $RenderMap($Renderables, $State);
},
$State->applyTo($StateRenderables)
);
$html = self::render($Renderables);
@@ -53,7 +64,7 @@ final class Parsedown
}
/**
* @return array{0: StateRenderable[], 1: State}
* @return array{StateRenderable[], State}
*/
public static function lines(Lines $Lines, State $State)
{
@@ -79,11 +90,11 @@ final class Parsedown
}
/**
* @return array{0: Block[], 1: State}
* @return array{Block[], State}
*/
public static function blocks(Lines $Lines, State $State)
{
$RecursionLimiter = $State->get(RecursionLimiter::class)->increment();
$RecursionLimiter = $State->get(RecursionLimiter::class)->incremented();
if ($RecursionLimiter->isDepthExceeded()) {
$State = $State->setting(new BlockTypes([], []));
@@ -189,7 +200,7 @@ final class Parsedown
# standardize line breaks
$text = \str_replace(["\r\n", "\r"], "\n", $text);
$RecursionLimiter = $State->get(RecursionLimiter::class)->increment();
$RecursionLimiter = $State->get(RecursionLimiter::class)->incremented();
if ($RecursionLimiter->isDepthExceeded()) {
return [Plaintext::build(new Excerpt($text, 0), $State)];

View File

@@ -7,21 +7,21 @@ final class Context
/** @var Line */
private $Line;
/** @var int */
private $previousEmptyLines;
/** @var int|null */
private $precedingEmptyLines;
/** @var string */
private $previousEmptyLinesText;
private $precedingEmptyLinesText;
/**
* @param Line $Line
* @param string $previousEmptyLinesText
* @param string $precedingEmptyLinesText
*/
public function __construct($Line, $previousEmptyLinesText)
public function __construct($Line, $precedingEmptyLinesText)
{
$this->Line = $Line;
$this->previousEmptyLinesText = $previousEmptyLinesText;
$this->previousEmptyLines = \substr_count($previousEmptyLinesText, "\n");
$this->precedingEmptyLinesText = $precedingEmptyLinesText;
$this->precedingEmptyLines = null;
}
/** @return Line */
@@ -31,14 +31,18 @@ final class Context
}
/** @return int */
public function previousEmptyLines()
public function precedingEmptyLines()
{
return $this->previousEmptyLines;
if (! isset($this->precedingEmptyLines)) {
$this->precedingEmptyLines = \substr_count($this->precedingEmptyLinesText, "\n");
}
return $this->precedingEmptyLines;
}
/** @return string */
public function previousEmptyLinesText()
public function precedingEmptyLinesText()
{
return $this->previousEmptyLinesText;
return $this->precedingEmptyLinesText;
}
}

View File

@@ -30,7 +30,7 @@ final class Lines
if (! $containsBlankLines) {
foreach ($Contexts as $Context) {
if ($Context->previousEmptyLines() > 0) {
if ($Context->precedingEmptyLines() > 0) {
$containsBlankLines = true;
break;
}
@@ -57,33 +57,33 @@ final class Lines
$text = \str_replace(["\r\n", "\r"], "\n", $text);
$Contexts = [];
$sequentialLines = '';
$sequentialEmptyLines = '';
foreach (\explode("\n", $text) as $line) {
if (\chop($line) === '') {
$sequentialLines .= $line . "\n";
$sequentialEmptyLines .= $line . "\n";
continue;
}
$Contexts[] = new Context(
new Line($line, $indentOffset),
$sequentialLines
$sequentialEmptyLines
);
$sequentialLines = '';
$sequentialEmptyLines = '';
}
return new self($Contexts, $sequentialLines);
return new self($Contexts, $sequentialEmptyLines);
}
/** @return bool */
public function isEmpty()
{
return \count($this->Contexts) === 0 && $this->trailingBlankLines === 0;
return ! $this->containsBlankLines && \count($this->Contexts) === 0;
}
/** @return Context[] */
public function Contexts()
public function contexts()
{
return $this->Contexts;
}
@@ -140,7 +140,7 @@ final class Lines
$NextLines->Contexts[0] = new Context(
$NextLines->Contexts[0]->line(),
$NextLines->Contexts[0]->previousEmptyLinesText() . $Lines->trailingBlankLinesText
$NextLines->Contexts[0]->precedingEmptyLinesText() . $Lines->trailingBlankLinesText
);
$Lines->Contexts = \array_merge($Lines->Contexts, $NextLines->Contexts);
@@ -162,10 +162,10 @@ final class Lines
$Context = new Context(
$Context->line(),
$Context->previousEmptyLinesText() . $Lines->trailingBlankLinesText
$Context->precedingEmptyLinesText() . $Lines->trailingBlankLinesText
);
if ($Context->previousEmptyLines() > 0) {
if ($Context->precedingEmptyLines() > 0) {
$Lines->containsBlankLines = true;
}

View File

@@ -15,7 +15,7 @@ final class State implements StateBearer
/**
* @var array<class-string<Configurable>, Configurable>
*/
private static $initialCache;
private static $initialCache = [];
/**
* @param Configurable[] $Configurables
@@ -24,7 +24,7 @@ final class State implements StateBearer
{
$this->state = \array_combine(
\array_map(
/** @return class-string */
/** @return class-string<Configurable> */
function (Configurable $C) { return \get_class($C); },
$Configurables
),
@@ -50,21 +50,34 @@ final class State implements StateBearer
/**
* @template T as Configurable
* @template-typeof T $configurableClass
* @param class-string<Configurable> $configurableClass
* @template-typeof T $className
* @param class-string<T> $className
* @return T
*/
public function get($configurableClass)
public function get($className)
{
if (isset($this->state[$configurableClass])) {
return $this->state[$configurableClass];
if (
! isset($this->state[$className])
&& \is_subclass_of($className, MutableConfigurable::class, true)
) {
if (! isset(self::$initialCache[$className])) {
/** @var T */
self::$initialCache[$className] = $className::initial();
}
/**
* @var T
* @psalm-suppress PossiblyUndefinedMethod
*/
$this->state[$className] = self::$initialCache[$className]->isolatedCopy();
}
if (! isset(self::$initialCache[$configurableClass])) {
self::$initialCache[$configurableClass] = $configurableClass::initial();
}
return self::$initialCache[$configurableClass];
/** @var T */
return (
$this->state[$className]
?? self::$initialCache[$className]
?? self::$initialCache[$className] = $className::initial()
);
}
public function __clone()
@@ -89,11 +102,24 @@ final class State implements StateBearer
);
}
/**
* @return State
*/
public function state()
public function state(): State
{
return $this;
}
/** @return self */
public static function from(StateBearer $StateBearer)
{
return $StateBearer->state();
}
public function isolatedCopy(): self
{
return new self(\array_map(
function ($C) {
return $C instanceof MutableConfigurable ? $C->isolatedCopy() : $C;
},
$this->state
));
}
}

View File

@@ -4,8 +4,7 @@ namespace Erusev\Parsedown;
interface StateBearer
{
/**
* @return State
*/
public function state();
public function state(): State;
/** @return static */
public static function from(StateBearer $StateBearer);
}

View File

@@ -50,7 +50,7 @@ class CommonMarkTestStrict extends TestCase
*/
public function testExample($_, $__, $markdown, $expectedHtml)
{
$actualHtml = $this->Parsedown->text($markdown);
$actualHtml = $this->Parsedown->toHtml($markdown);
$this->assertEquals($expectedHtml, $actualHtml);
}

View File

@@ -28,18 +28,13 @@ class CommonMarkTestWeak extends CommonMarkTestStrict
*/
public function __construct($name = null, array $data = [], $dataName = '')
{
$textLevelElements = \array_keys(Element::$TEXT_LEVEL_ELEMENTS);
$textLevelElements = \array_keys(Element::TEXT_LEVEL_ELEMENTS);
\array_walk(
$textLevelElements,
/**
* @param string &$element
* @return void
*/
function (&$element) {
$element = \preg_quote($element, '/');
}
$textLevelElements = \array_map(
function ($e) { return \preg_quote($e, '/'); },
$textLevelElements
);
$this->textLevelElementRegex = '\b(?:' . \implode('|', $textLevelElements) . ')\b';
parent::__construct($name, $data, $dataName);
@@ -59,7 +54,7 @@ class CommonMarkTestWeak extends CommonMarkTestStrict
{
$expectedHtml = $this->cleanupHtml($expectedHtml);
$actualHtml = $this->Parsedown->text($markdown);
$actualHtml = $this->Parsedown->toHtml($markdown);
$actualHtml = $this->cleanupHtml($actualHtml);
$this->assertEquals($expectedHtml, $actualHtml);

View File

@@ -6,11 +6,13 @@ use Erusev\Parsedown\Components\Blocks\Markup as BlockMarkup;
use Erusev\Parsedown\Components\Inlines\Markup as InlineMarkup;
use Erusev\Parsedown\Configurables\BlockTypes;
use Erusev\Parsedown\Configurables\Breaks;
use Erusev\Parsedown\Configurables\HeaderSlug;
use Erusev\Parsedown\Configurables\InlineTypes;
use Erusev\Parsedown\Configurables\SafeMode;
use Erusev\Parsedown\Configurables\StrictMode;
use Erusev\Parsedown\Parsedown;
use Erusev\Parsedown\State;
use Erusev\Parsedown\StateBearer;
use PHPUnit\Framework\TestCase;
class ParsedownTest extends TestCase
@@ -38,6 +40,16 @@ class ParsedownTest extends TestCase
return [\dirname(__FILE__).'/data/'];
}
protected function initState(string $testName): StateBearer
{
return new State([
new SafeMode(\substr($testName, 0, 3) === 'xss'),
new StrictMode(\substr($testName, 0, 6) === 'strict'),
new Breaks(\substr($testName, 0, 14) === 'breaks_enabled'),
new HeaderSlug(\substr($testName, 0, 4) === 'slug'),
]);
}
/**
* @dataProvider data
* @param string $test
@@ -55,28 +67,21 @@ class ParsedownTest extends TestCase
$expectedMarkup = \str_replace("\r\n", "\n", $expectedMarkup);
$expectedMarkup = \str_replace("\r", "\n", $expectedMarkup);
$Parsedown = new Parsedown(new State([
new SafeMode(\substr($test, 0, 3) === 'xss'),
new StrictMode(\substr($test, 0, 6) === 'strict'),
new Breaks(\substr($test, 0, 14) === 'breaks_enabled'),
]));
$Parsedown = new Parsedown($this->initState($test));
$actualMarkup = $Parsedown->text($markdown);
$actualMarkup = $Parsedown->toHtml($markdown);
$this->assertEquals($expectedMarkup, $actualMarkup);
}
/** @return array<int, array{0:string, 1:string} */
/** @return array<int, array{0:string, 1:string}> */
public function data()
{
$data = [];
foreach ($this->dirs as $dir) {
$Folder = new \DirectoryIterator($dir);
foreach ($Folder as $File) {
/** @var $File DirectoryIterator */
if (! $File->isFile()) {
continue;
}
@@ -154,6 +159,6 @@ EXPECTED_HTML;
InlineTypes::initial()->removing([InlineMarkup::class]),
]));
$this->assertEquals($expectedHtml, $parsedownWithNoMarkup->text($markdownWithHtml));
$this->assertEquals($expectedHtml, $parsedownWithNoMarkup->toHtml($markdownWithHtml));
}
}

View File

@@ -0,0 +1,3 @@
<div id="foo"
class="bar">
</div>

View File

@@ -0,0 +1,3 @@
<div id="foo"
class="bar">
</div>

View File

@@ -1,3 +1,3 @@
<div>
*foo*
<p><em>bar</em></p>
<div id="foo" class="bar
baz">
</div>

View File

@@ -1,4 +1,3 @@
<div>
*foo*
*bar*
<div id="foo" class="bar
baz">
</div>

View File

@@ -0,0 +1,2 @@
<div id="foo"
*hi*

View File

@@ -0,0 +1,2 @@
<div id="foo"
*hi*

View File

@@ -0,0 +1,2 @@
<div class
foo

View File

@@ -0,0 +1,2 @@
<div class
foo

View File

@@ -1 +1,2 @@
<div><a href="bar">*foo*</a></div>
<div *???-&&&-<---
*foo*

View File

@@ -1 +1,2 @@
<div><a href="bar">*foo*</a></div>
<div *???-&&&-<---
*foo*

View File

@@ -1,3 +1,3 @@
<Warning>
<a href="foo">
*bar*
</Warning>
</a>

View File

@@ -1,3 +1,3 @@
<Warning>
<a href="foo">
*bar*
</Warning>
</a>

View File

@@ -0,0 +1,3 @@
<i class="foo">
*bar*
</i>

View File

@@ -0,0 +1,3 @@
<i class="foo">
*bar*
</i>

View File

@@ -0,0 +1,2 @@
</ins>
*bar*

View File

@@ -0,0 +1,2 @@
</ins>
*bar*

View File

@@ -0,0 +1,3 @@
<del>
*foo*
</del>

View File

@@ -0,0 +1,3 @@
<del>
*foo*
</del>

View File

@@ -1 +1,3 @@
<p><del><em>foo</em></del></p>
<del>
<p><em>foo</em></p>
</del>

View File

@@ -1 +1,5 @@
<del>*foo*</del>
<del>
*foo*
</del>

View File

@@ -0,0 +1 @@
<a href="/bar\/)">

View File

@@ -0,0 +1 @@
<a href="/bar\/)">

View File

@@ -1 +1 @@
<p><code>f&amp;ouml;&amp;ouml;</code></p>
<a href="&ouml;&ouml;.html">

View File

@@ -1 +1 @@
`f&ouml;&ouml;`
<a href="&ouml;&ouml;.html">

View File

@@ -1 +1 @@
<p><a href="/uri">foo *bar</a></p>
<p><a href="/uri">foo *bar</a>*</p>

View File

@@ -1,3 +1,3 @@
[foo *bar][ref]
[foo *bar][ref]*
[ref]: /uri

View File

@@ -334,4 +334,28 @@ bar
<p>foo</p>
<body> foo
<p>bar</p>
<p>foo</p>
<hr />
<img>
</script>
bar
<p>foo</p>
<img>
-->
bar
<p>foo</p>
<img>
?>
bar
<p>foo</p>
<img>
>
bar
<p>foo</p>
<img>
]]>
bar
<p>foo</p>
<img>
<p>bar</p>
<p>foo</p>

View File

@@ -480,4 +480,42 @@ foo
bar
foo
---
<img>
</script>
bar
foo
<img>
-->
bar
foo
<img>
?>
bar
foo
<img>
>
bar
foo
<img>
]]>
bar
foo
<img>
bar
foo

View File

@@ -0,0 +1,11 @@
<h1 id="foo">foo</h1>
<h1 id="foo-bar">foo bar</h1>
<h1 id="foobar">foo_bar</h1>
<h1 id="foobar-1">foo+bar-1</h1>
<h1 id="foobar-2">foo+bar</h1>
<h1 id="2rer0ගම්මැද්ද-v-force-ඉනොවේශන්-නේෂන්-සඳහා-එවූ-නි">2rer*(0👍ගම්මැද්ද V FORCE ඉනොවේශන් නේෂන් සඳහා එවූ නි</h1>
<h2 id="foo-1">foo</h2>
<h2 id="foo-bar-1">foo bar</h2>
<h2 id="foobar-3">foo_bar</h2>
<h2 id="foobar-4">foo+bar</h2>
<h2 id="2rer0ගම්මැද්ද-v-force-ඉනොවේශන්-නේෂන්-සඳහා-එවූ-නි-1">2rer*(0👍ගම්මැද්ද V FORCE ඉනොවේශන් නේෂන් සඳහා එවූ නි</h2>

View File

@@ -0,0 +1,26 @@
# foo
# foo bar
# foo_bar
# foo+bar-1
# foo+bar
# 2rer*(0👍ගම්මැද්ද V FORCE ඉනොවේශන් නේෂන් සඳහා එවූ නි
foo
---
foo bar
---
foo_bar
---
foo+bar
---
2rer*(0👍ගම්මැද්ද V FORCE ඉනොවේශන් නේෂන් සඳහා එවූ නි
---

View File

@@ -1,3 +1,9 @@
<p>an autolink <a href="http://example.com">http://example.com</a></p>
<p>inside of parentheses (<a href="http://example.com">http://example.com</a>)</p>
<p>trailing slash <a href="http://example.com/">http://example.com/</a> and <a href="http://example.com/path/">http://example.com/path/</a></p>
<p><a href="http://www.google.com/search?q=Markup+(business)">http://www.google.com/search?q=Markup+(business)</a></p>
<p><a href="http://www.google.com/search?q=Markup+(business)">http://www.google.com/search?q=Markup+(business)</a>))</p>
<p>(<a href="http://www.google.com/search?q=Markup+(business)">http://www.google.com/search?q=Markup+(business)</a>)</p>
<p>(<a href="http://www.google.com/search?q=Markup+(business)">http://www.google.com/search?q=Markup+(business)</a></p>
<p>trailing slash <a href="http://example.com/">http://example.com/</a> and <a href="http://example.com/path/">http://example.com/path/</a></p>
<p>trailing paren <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)">https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)</a></p>
<p>complex link <a href="http://elk.canda.biz/app/kibana#/discover?_g=()&amp;_a=(columns:!(_source),index:&#039;deve-*&#039;,interval:auto,query:(query_string:(analyze_wildcard:!t,query:&#039;*&#039;)),sort:!(&#039;@timestamp&#039;,desc))">http://elk.canda.biz/app/kibana#/discover?_g=()&amp;_a=(columns:!(_source),index:'deve-*',interval:auto,query:(query_string:(analyze_wildcard:!t,query:'*')),sort:!('@timestamp',desc))</a></p>

View File

@@ -2,4 +2,16 @@ an autolink http://example.com
inside of parentheses (http://example.com)
trailing slash http://example.com/ and http://example.com/path/
http://www.google.com/search?q=Markup+(business)
http://www.google.com/search?q=Markup+(business)))
(http://www.google.com/search?q=Markup+(business))
(http://www.google.com/search?q=Markup+(business)
trailing slash http://example.com/ and http://example.com/path/
trailing paren https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
complex link http://elk.canda.biz/app/kibana#/discover?_g=()&_a=(columns:!(_source),index:'deve-*',interval:auto,query:(query_string:(analyze_wildcard:!t,query:'*')),sort:!('@timestamp',desc))

View File

@@ -2,6 +2,7 @@
namespace Erusev\Parsedown\Tests\Configurables;
use Erusev\Parsedown\Components\Blocks\FencedCode;
use Erusev\Parsedown\Components\Blocks\IndentedCode;
use Erusev\Parsedown\Components\Blocks\Markup;
use Erusev\Parsedown\Components\Blocks\Rule;
@@ -14,6 +15,7 @@ final class BlockTypesTest extends TestCase
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @psalm-suppress InvalidDocblock
*/
public function testAddingTypes()
{
@@ -41,5 +43,9 @@ final class BlockTypesTest extends TestCase
$BlockTypes = $BlockTypes->addingUnmarkedLowPrecedence([IndentedCode::class]);
$this->assertSame([Markup::class, IndentedCode::class, Rule::class], $BlockTypes->markedBy('@'));
$this->assertSame([Rule::class, Markup::class, IndentedCode::class], $BlockTypes->unmarked());
$BlockTypes = $BlockTypes->replacing(IndentedCode::class, FencedCode::class);
$this->assertSame([Markup::class, FencedCode::class, Rule::class], $BlockTypes->markedBy('@'));
$this->assertSame([Rule::class, Markup::class, FencedCode::class], $BlockTypes->unmarked());
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Erusev\Parsedown\Tests\Configurables;
use Erusev\Parsedown\Configurables\HeaderSlug;
use Erusev\Parsedown\Configurables\SlugRegister;
use Erusev\Parsedown\State;
use PHPUnit\Framework\TestCase;
final class HeaderSlugTest extends TestCase
{
/**
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testNamedConstructor()
{
$State = new State([HeaderSlug::enabled()]);
$this->assertSame(true, $State->get(HeaderSlug::class)->isEnabled());
}
/**
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testCustomCallback()
{
$HeaderSlug = HeaderSlug::withCallback(function (string $t): string {
return \preg_replace('/[^A-Za-z0-9]++/', '_', $t);
});
$this->assertSame(
'foo_bar',
$HeaderSlug->transform(SlugRegister::initial(), 'foo bar')
);
}
/**
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testCustomDuplicationCallback()
{
$HeaderSlug = HeaderSlug::withDuplicationCallback(function (string $t, int $n): string {
return $t . '_' . \strval($n-1);
});
$SlugRegister = new SlugRegister;
$HeaderSlug->transform($SlugRegister, 'foo bar');
$this->assertSame(
'foo-bar_1',
$HeaderSlug->transform($SlugRegister, 'foo bar')
);
}
}

View File

@@ -5,6 +5,7 @@ namespace Erusev\Parsedown\Tests\Configurables;
use Erusev\Parsedown\Components\Inlines\Code;
use Erusev\Parsedown\Components\Inlines\Emphasis;
use Erusev\Parsedown\Components\Inlines\Link;
use Erusev\Parsedown\Components\Inlines\Url;
use Erusev\Parsedown\Configurables\InlineTypes;
use PHPUnit\Framework\TestCase;
@@ -28,5 +29,8 @@ final class InlineTypesTest extends TestCase
$InlineTypes = $InlineTypes->addingLowPrecedence('@', [Link::class]);
$this->assertSame([Code::class, Emphasis::class, Link::class], $InlineTypes->markedBy('@'));
$InlineTypes = $InlineTypes->replacing(Link::class, Url::class);
$this->assertSame([Code::class, Emphasis::class, Url::class], $InlineTypes->markedBy('@'));
}
}

View File

@@ -30,7 +30,7 @@ final class RecursionLimiterTest extends TestCase
. '<p>foo</p>'
. \str_repeat("\n</blockquote>", 3)
),
$Parsedown->text($borderline)
$Parsedown->toHtml($borderline)
);
$this->assertSame(
@@ -39,7 +39,7 @@ final class RecursionLimiterTest extends TestCase
. '<p>&gt; foo</p>'
. \str_repeat("\n</blockquote>", 3)
),
$Parsedown->text($exceeded)
$Parsedown->toHtml($exceeded)
);
$this->assertSame(
@@ -48,7 +48,7 @@ final class RecursionLimiterTest extends TestCase
. '<p>fo*o*</p>'
. \str_repeat("\n</blockquote>", 3)
),
$Parsedown->text($exceededByInline)
$Parsedown->toHtml($exceededByInline)
);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Erusev\Parsedown\Tests\Configurables;
use Erusev\Parsedown\Configurables\RenderStack;
use Erusev\Parsedown\Html\Renderable;
use Erusev\Parsedown\Html\Renderables\Text;
use Erusev\Parsedown\Parsedown;
use Erusev\Parsedown\State;
use PHPUnit\Framework\TestCase;
final class RenderStackTest extends TestCase
{
/**
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testRenderStack()
{
$State = new State;
$RenderStack = $State->get(RenderStack::class)
->push(
/**
* @param Renderable[] $Rs
* @param State $_
* @return Renderable[]
*/
function ($Rs, $_) { return \array_merge($Rs, [new Text('baz')]); }
)
->push(
/**
* @param Renderable[] $Rs
* @param State $_
* @return Renderable[]
*/
function ($Rs, $_) { return \array_merge($Rs, [new Text('bar')]); }
)
;
$State = $State->setting($RenderStack);
$this->assertSame(
"<p>foo</p>\nbar\nbaz",
(new Parsedown($State))->toHtml('foo')
);
}
}

View File

@@ -21,11 +21,15 @@ final class ContainerTest extends TestCase
new Text('bar'),
]);
$Container = $Container->adding(new Text('boo'));
$Contents = $Container->contents();
$this->assertTrue($Contents[0] instanceof Element);
$this->assertSame($Contents[0]->name(), 'foo');
$this->assertTrue($Contents[1] instanceof Text);
$this->assertSame($Contents[1]->getHtml(), 'bar');
$this->assertTrue($Contents[2] instanceof Text);
$this->assertSame($Contents[2]->getHtml(), 'boo');
}
}

View File

@@ -32,11 +32,23 @@ final class StateTest extends TestCase
/**
* @return void
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \PHPUnit\Framework\Exception
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testStateCloneVisibility()
{
$this->assertInstanceOf(State::class, clone(new State));
}
/**
* @return void
* @throws \PHPUnit\Framework\Exception
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testStateFromStateIdentical()
{
$State = new State;
$this->assertSame($State, State::from($State));
}
}