Skip to content

Commit

Permalink
Merge pull request #23 from bnomei/performance
Browse files Browse the repository at this point in the history
performance
  • Loading branch information
bnomei authored Mar 23, 2023
2 parents 27d2244 + 73770b2 commit 8c2a84c
Show file tree
Hide file tree
Showing 11 changed files with 114 additions and 33 deletions.
30 changes: 23 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
[![Twitter](https://flat.badgen.net/badge/twitter/bnomei?color=66d9ef)](https://twitter.com/bnomei)


Setup [HTTP Status Code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection) Redirects from within the Kirby Panel.
Setup performant [HTTP Status Code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection) Redirects from within the Kirby Panel.

Kirby 3 Redirects can handle Request-URIs like `projects?id=123`, `project/cool.html`, `project\/.*\.html` and send Response-URIs like `https://exter.nal`. This makes it the ideal choice when porting a non Kirby project.
Kirby 3 Redirects can redirect any request URI to any response URI. It can also handle querystrings and regex.

## Similar Plugin

Expand Down Expand Up @@ -54,7 +54,27 @@ sections:
> If you need all http codes you can use `extends: plugin-redirects` instead.

> Since v1.1.0 the plugin will register itself with a `route:before`-hook and take care of the redirecting automatically. Many thanks to _Sebastian Aschenbach_ for suggesting this solution.
## Usage

In the structure field or using the provided site methods add Request-URIs `fromuri` like

- `projects/cool`
- `projects?id=123`
- `projects/cool.html`
- `projects\/.*\.html`

and set Response-URIs `touri` like

- `projects/changed-slug`
- `https://exter.nal`

as well as a HTTP Status Code `code` like `301` or `302`.

This makes it the ideal choice when porting a non Kirby project.

## Regex

You can only use regex to match the Request-URIs `fromuri`. The Response-URIs `touri` will not (yet) be forwarded groups etc.

## Site Methods

Expand Down Expand Up @@ -86,10 +106,6 @@ $success = site()->removeRedirects([
]);
```

## Regex

You can only use regex to match the request URI `fromuri`. The response URI `touri` will not be forwarded groups etc.

## Settings

| bnomei.redirects. | Default | Description |
Expand Down
2 changes: 1 addition & 1 deletion classes/Redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function matches(string $url): bool
$from = rtrim($this->from(), '/');

// plain string
if(in_array($url, [
if (in_array($url, [
$from,
$from . '/', // issue #10
])) {
Expand Down
61 changes: 50 additions & 11 deletions classes/Redirects.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use Kirby\Cms\Page;
use Kirby\Cms\Site;
use Kirby\Data\Yaml;
use Kirby\Filesystem\Dir;
use Kirby\Filesystem\F;
use Kirby\Http\Header;
use Kirby\Http\Url;
use Kirby\Toolkit\A;
Expand Down Expand Up @@ -38,9 +40,8 @@ public function __construct(array $options = [])
$this->options[$key] = $call();
}
}
$this->options['parent'] = is_array($this->options['map']) ? null : $this->options['map']->parent();
$this->options['redirects'] = $this->map($this->options['map']);

$this->checkForRedirect();
}

public function option(?string $key = null)
Expand Down Expand Up @@ -121,6 +122,7 @@ public function updateRedirects(array $data): bool
$page->update([
$map->key() => Yaml::encode($data),
]);
$this->flush();
return true;
// @codeCoverageIgnoreStart
} catch (\Exception $ex) {
Expand All @@ -131,6 +133,31 @@ public function updateRedirects(array $data): bool
return false;
}

// getter function for parent value $option
public function getParent(): Page|Site|null
{
return $this->option('parent');
}

public function validRoutesDir(): string
{
$dir = kirby()->cache('bnomei.redirects')->root() . '/validroutes';
if (!Dir::exists($dir)) {
Dir::make($dir);
}
return $dir;
}

public function isKnownValidRoute(string $path): bool
{
return F::exists($this->validRoutesDir() . '/' . md5($path));
}

public function flush(): bool
{
return Dir::remove($this->validRoutesDir());
}

public function checkForRedirect(): ?Redirect
{
$map = $this->option('redirects');
Expand All @@ -140,6 +167,10 @@ public function checkForRedirect(): ?Redirect

$requesturi = (string) $this->option('request.uri');

if ($this->isKnownValidRoute($requesturi)) {
return null;
}

foreach ($map as $redirect) {
if (!array_key_exists('fromuri', $redirect) ||
!array_key_exists('touri', $redirect)
Expand All @@ -155,6 +186,10 @@ public function checkForRedirect(): ?Redirect
return $redirect;
}
}

// no redirect found, flag as valid route
F::write($this->validRoutesDir() . '/' . md5($requesturi), '');

return null;
}

Expand Down Expand Up @@ -207,13 +242,18 @@ public static function singleton($options = []): Redirects

public static function codes(bool $force = false): ?array
{
$codes = null;
if (! $force && ! option('debug')) {
$codes = kirby()->cache('bnomei.redirects')->get('httpcodes');
}
if ($codes) {
return $codes;
}
// NOTE: do not use a cache in this method as it is
// called in the panel php blueprint and the cache
// is not available there yet. => NullCache issue

// $cache = kirby()->cache('bnomei.redirects');
// $codes = null;
// if (! $force && ! option('debug')) {
// $codes = $cache->get('httpcodes');
// }
// if ($codes) {
// return $codes;
// }

$codes = [];
foreach (Header::$codes as $code => $label) {
Expand All @@ -222,12 +262,11 @@ public static function codes(bool $force = false): ?array
'label' => $label,
];
}
kirby()->cache('bnomei.redirects')->set('httpcodes', $codes, 60 * 24 * 7);
// $cache->set('httpcodes', $codes, 60 * 24 * 7);

return $codes;
}


public static array $cache = [];

public static function staticCache(string $key, Closure $closure)
Expand Down
7 changes: 4 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "bnomei/kirby3-redirects",
"type": "kirby-plugin",
"description": "Setup HTTP Status Code Redirects from within the Kirby Panel",
"description": "Setup performant HTTP Status Code Redirects from within the Kirby Panel",
"homepage": "https://github.com/bnomei/kirby3-redirects",
"version": "1.8.0",
"version": "1.9.0",
"license": "MIT",
"authors": [
{
Expand All @@ -22,7 +22,8 @@
"308",
"status-codes",
"header",
"redirects"
"redirects",
"performance"
],
"autoload": {
"psr-4": {
Expand Down
2 changes: 1 addition & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@
\Bnomei\Redirects::singleton()->redirect();
}
},
'page.update:after' => function (Kirby\Cms\Page $newPage, Kirby\Cms\Page $oldPage) {
$redirects = \Bnomei\Redirects::singleton();
if ($redirects->getParent() && $redirects->getParent()->id() === $newPage->id()) {
$redirects->flush();
}
},
'site.update:after' => function (Kirby\Cms\Site $newSite, Kirby\Cms\Site $oldSite) {
$redirects = \Bnomei\Redirects::singleton();
if ($redirects->getParent() && $redirects->getParent()::class === $newSite::class) {
$redirects->flush();
}
},
],
'siteMethods' => [
'appendRedirects' => function ($data) {
Expand Down
1 change: 0 additions & 1 deletion tests/RedirectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,5 @@ public function testRedirects()

$this->assertNotNull($check);
$this->assertEquals(418, $check->code());

}
}
5 changes: 5 additions & 0 deletions tests/site/config/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

return [
'debug' => true,
];
2 changes: 2 additions & 0 deletions tests/site/templates/default.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<?php

echo $page->title()->value();

var_dump(kirby()->cache('bnomei.redirects')::class);
17 changes: 12 additions & 5 deletions vendor/composer/InstalledVersions.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}

Expand All @@ -119,7 +119,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true)
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints($constraint);
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));

return $provided->matches($constraint);
Expand Down Expand Up @@ -328,7 +328,9 @@ private static function getInstalled()
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
$installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
$installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
Expand All @@ -340,12 +342,17 @@ private static function getInstalled()
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = require __DIR__ . '/installed.php';
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
$installed[] = self::$installed;

if (self::$installed !== array()) {
$installed[] = self::$installed;
}

return $installed;
}
Expand Down
8 changes: 4 additions & 4 deletions vendor/composer/installed.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php return array(
'root' => array(
'name' => 'bnomei/kirby3-redirects',
'pretty_version' => '1.8.0',
'version' => '1.8.0.0',
'pretty_version' => '1.9.0',
'version' => '1.9.0.0',
'reference' => NULL,
'type' => 'kirby-plugin',
'install_path' => __DIR__ . '/../../',
Expand All @@ -11,8 +11,8 @@
),
'versions' => array(
'bnomei/kirby3-redirects' => array(
'pretty_version' => '1.8.0',
'version' => '1.8.0.0',
'pretty_version' => '1.9.0',
'version' => '1.9.0.0',
'reference' => NULL,
'type' => 'kirby-plugin',
'install_path' => __DIR__ . '/../../',
Expand Down

0 comments on commit 8c2a84c

Please sign in to comment.