Skip to content

Commit

Permalink
feat: add withLinkTargets option
Browse files Browse the repository at this point in the history
  • Loading branch information
simonerd committed Jan 18, 2024
1 parent 9f764ca commit 3b50c25
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
5 changes: 2 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
node_modules
vendor
mix-manifest.json
/.idea
/vendor
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,27 @@ class MyReplicatorFieldTransformer
}
```

### Preserving links targets

When using the Content Renderer within a search transformer, it might be useful to be able to preserve link targets in the rendered output, to be able to find entries based on urls linked in the content. You can instruct the renderer to add link targets in parenthesis behind the link text:

```php
$renderer = (new Renderer())->$withLinkTargets();

// read more <a href="https://visuellverstehen.de">about the author</a> of this package
// becomes: read more about the author (https://visuellverstehen.de) of this package
```

### Preserving HTML tags

If you want to keep the HTML tags and/or modify the content in your own way, you can instruct the renderer to keep them:

```php
$renderer = (new Renderer())->withHtmlTags();
```

When you choose to preserve HTML tags, the `withLinkTargets` option (see above) will be ignored.

## More about us

- [www.visuellverstehen.de](https://visuellverstehen.de)
Expand Down
21 changes: 21 additions & 0 deletions src/Renderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Renderer
protected $fieldValue;
protected $viewPath;
protected $withHtmlTags = false;
protected $withLinkTargets = false;

public function render(): string
{
Expand Down Expand Up @@ -70,13 +71,27 @@ public function withHtmlTags(): self

return $this;
}

public function withLinkTargets(): self
{
$this->withLinkTargets = true;

return $this;
}

public function withoutHtmlTags(): self
{
$this->withHtmlTags = false;

return $this;
}

public function withoutLinkTargets(): self
{
$this->withLinkTargets = false;

return $this;
}

protected function renderContent(): string
{
Expand Down Expand Up @@ -153,6 +168,12 @@ protected function sanitizeContent(string $content): string
$content = preg_replace('/\>[\s+]?\</', '> <', $content);

if (! $this->withHtmlTags) {
// optionally extract link targets and add them in () behind the link name
if ($this->withLinkTargets) {
$content = preg_replace("/<a (?:.+ )?href=\"([-_.~!*'();:@&=+$,\/?%#[A-z0-9]+)\"(?: .+)?>(.+)<\/a>/", '$2 ($1)', $content);
}

// add whitespace between strings within html tags
$content = preg_replace('/\>(\w+)\<\//', '/> $1 <', $content);
$content = strip_tags($content);
}
Expand Down

0 comments on commit 3b50c25

Please sign in to comment.