Skip to content

Commit

Permalink
Cleanup (#91)
Browse files Browse the repository at this point in the history
  • Loading branch information
samdark committed Dec 27, 2021
1 parent d098454 commit 588b753
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 108 deletions.
83 changes: 21 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
<br>
</p>

The package provides FastRoute adapter for [Yii Router](https://github.com/yiisoft/router).

[![Latest Stable Version](https://poser.pugx.org/yiisoft/router-fastroute/v/stable.png)](https://packagist.org/packages/yiisoft/router-fastroute)
[![Total Downloads](https://poser.pugx.org/yiisoft/router-fastroute/downloads.png)](https://packagist.org/packages/yiisoft/router-fastroute)
[![Build status](https://github.com/yiisoft/router-fastroute/workflows/build/badge.svg)](https://github.com/yiisoft/router-fastroute/actions?query=workflow%3Abuild)
Expand All @@ -17,65 +15,26 @@ The package provides FastRoute adapter for [Yii Router](https://github.com/yiiso
[![static analysis](https://github.com/yiisoft/router-fastroute/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/router-fastroute/actions?query=workflow%3A%22static+analysis%22)
[![type-coverage](https://shepherd.dev/github/yiisoft/router-fastroute/coverage.svg)](https://shepherd.dev/github/yiisoft/router-fastroute)

## General usage
The package provides FastRoute adapter for [Yii Router](https://github.com/yiisoft/router).

Router instance could be obtained like the following:
## Requirements

```php
use Yiisoft\Router\FastRoute\FastRouteFactory;
- PHP 7.4 or higher.

$factory = new FastRouteFactory();
$router = $factory();
```
## Installation

## Custom route factory

If you need to make custom route factory you can do something like the following:

```php
namespace App\Factory;

use Psr\Container\ContainerInterface;
use Yiisoft\Router\FastRoute\FastRouteFactory;
use Yiisoft\Router\Route;
use Yiisoft\Router\RouterFactory;
use Yiisoft\Router\RouterInterface;
use App\Controller\SiteController;

class RouteFactory
{
public function __invoke(ContainerInterface $container): RouterInterface
{
$routes = [
Route::get('/')
->action([SiteController::class, 'index'])
->name('site/index'),
Route::get('/about')
->action([SiteController::class, 'about'])
->name('site/about'),
];

return (new RouterFactory(new FastRouteFactory(), $routes))($container);
}
}
```
The package could be installed with composer:

setting up your container
```
composer require yiisoft/router-fastroute --prefer-dist
```

```php
use App\Factory\RouteFactory;
use Yiisoft\Router\RouterInterface;
## General usage

return [
/**
* ...
* There other container configuration.
* ...
*/
The package is not meant to be used separately so check [Yii Router](https://github.com/yiisoft/router) readme for
general usage.

RouterInterface::class => new RouteFactory(),
];
```
## Testing

### Unit testing

Expand All @@ -101,21 +60,21 @@ The code is statically analyzed with [Psalm](https://psalm.dev/). To run static
./vendor/bin/psalm
```

### Support the project
## License

The Yii Router FastRoute adapter is free software. It is released under the terms of the BSD License.
Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

## Support the project

[![Open Collective](https://img.shields.io/badge/Open%20Collective-sponsor-7eadf1?logo=open%20collective&logoColor=7eadf1&labelColor=555555)](https://opencollective.com/yiisoft)

### Follow updates
## Follow updates

[![Official website](https://img.shields.io/badge/Powered_by-Yii_Framework-green.svg?style=flat)](https://www.yiiframework.com/)
[![Twitter](https://img.shields.io/badge/twitter-follow-1DA1F2?logo=twitter&logoColor=1DA1F2&labelColor=555555?style=flat)](https://twitter.com/yiiframework)
[![Telegram](https://img.shields.io/badge/telegram-join-1DA1F2?style=flat&logo=telegram)](https://t.me/yii3en)
[![Facebook](https://img.shields.io/badge/facebook-join-1DA1F2?style=flat&logo=facebook&logoColor=ffffff)](https://www.facebook.com/groups/yiitalk)
[![Slack](https://img.shields.io/badge/slack-join-1DA1F2?style=flat&logo=slack)](https://yiiframework.com/go/slack)

## License

The Yii Router FastRoute adapter is free software. It is released under the terms of the BSD License.
Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).
10 changes: 6 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
"router",
"fastroute"
],
"homepage": "http://www.yiiframework.com/",
"homepage": "https://www.yiiframework.com/",
"license": "BSD-3-Clause",
"support": {
"issues": "https://github.com/yiisoft/router-fastroute/issues?state=open",
"forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/",
"forum": "https://www.yiiframework.com/forum/",
"wiki": "https://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/router-fastroute"
},
Expand All @@ -20,7 +20,9 @@
"php": "^7.4|^8.0",
"nikic/fast-route": "^1.3",
"psr/simple-cache": "^1.0.1",
"yiisoft/router": "^3.0@dev"
"yiisoft/router": "^3.0@dev",
"psr/http-message": "^1.0",
"yiisoft/http": "^1.2"
},
"require-dev": {
"nyholm/psr7": "^1.3",
Expand Down
2 changes: 2 additions & 0 deletions config/common.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use Yiisoft\Router\FastRoute\UrlGenerator;
use Yiisoft\Router\UrlGeneratorInterface;

/** @var array $params */

return [
UrlGeneratorInterface::class => [
'class' => UrlGenerator::class,
Expand Down
2 changes: 1 addition & 1 deletion psalm.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0"?>
<psalm
errorLevel="6"
errorLevel="2"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
Expand Down
52 changes: 29 additions & 23 deletions src/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ public function __construct(
*
* Replacements in FastRoute are written as `{name}` or `{name:<pattern>}`;
* this method uses {@see RouteParser\Std} to search for the best route
* match based on the available substitutions and generates an uri.
* match based on the available substitutions and generates a URI.
*
* @throws RuntimeException if parameter value does not match its regex.
* @throws RuntimeException If parameter value does not match its regex.
*/
public function generate(string $name, array $parameters = []): string
{
Expand All @@ -55,6 +55,7 @@ public function generate(string $name, array $parameters = []): string
&& isset($parameters[$this->localeParameterName])
&& $this->locales !== []
) {
/** @var string $locale */
$locale = $parameters[$this->localeParameterName];
if (isset($this->locales[$locale])) {
$this->locale = $locale;
Expand All @@ -69,20 +70,20 @@ public function generate(string $name, array $parameters = []): string

$missingParameters = [];

// One route pattern can correspond to multiple routes if it has optional parts
// One route pattern can correspond to multiple routes if it has optional parts.
foreach ($parsedRoutes as $parsedRouteParts) {
// Check if all parameters can be substituted
$missingParameters = $this->missingParameters($parsedRouteParts, $parameters);

// If not all parameters can be substituted, try the next route
// If not all parameters can be substituted, try the next route.
if (!empty($missingParameters)) {
continue;
}

return $this->generatePath($parameters, $parsedRouteParts);
}

// No valid route was found: list minimal required parameters
// No valid route was found: list minimal required parameters.
throw new RuntimeException(
sprintf(
'Route `%s` expects at least parameter values for [%s], but received [%s]',
Expand All @@ -101,7 +102,6 @@ public function generateAbsolute(
): string {
$url = $this->generate($name, $parameters);
$route = $this->routeCollection->getRoute($name);
/** @var UriInterface $uri */
$uri = $this->currentRoute && $this->currentRoute->getUri() !== null ? $this->currentRoute->getUri() : null;
$lastRequestScheme = $uri !== null ? $uri->getScheme() : null;

Expand All @@ -122,7 +122,12 @@ public function generateAbsolute(

private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
{
$port = $uri->getPort() === 80 || $uri->getPort() === null ? '' : ':' . $uri->getPort();
$port = '';
$uriPort = $uri->getPort();
if ($uriPort !== 80 && $uriPort !== null) {
$port = ':' . $uriPort;
}

return $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $uri->getScheme());
}

Expand All @@ -131,11 +136,11 @@ private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterfac
*
* If URL is relative or scheme is null, normalization is skipped.
*
* @param string $url the URL to process
* @param string|null $scheme the URI scheme used in URL (e.g. `http` or `https`). Use empty string to
* create protocol-relative URL (e.g. `//example.com/path`)
* @param string $url The URL to process.
* @param string|null $scheme The URI scheme used in URL (e.g. `http` or `https`). Use empty string to
* create protocol-relative URL (e.g. `//example.com/path`).
*
* @return string the processed URL
* @return string The processed URL.
*/
private function ensureScheme(string $url, ?string $scheme): string
{
Expand Down Expand Up @@ -163,9 +168,9 @@ private function ensureScheme(string $url, ?string $scheme): string
* Returns a value indicating whether a URL is relative.
* A relative URL does not have host info part.
*
* @param string $url the URL to be checked
* @param string $url The URL to be checked.
*
* @return bool whether the URL is relative
* @return bool Whether the URL is relative.
*/
private function isRelative(string $url): bool
{
Expand Down Expand Up @@ -203,18 +208,19 @@ public function setLocaleParameterName(string $localeParameterName): void
}

/**
* Checks for any missing route parameters
* Checks for any missing route parameters.
*
* @param array $parts
* @param array $substitutions
*
* @return array with minimum required parameters if any are missing or an empty array if none are missing
* @return array Either an array containing missing required parameters or an empty array if none
* are missing.
*/
private function missingParameters(array $parts, array $substitutions): array
{
$missingParameters = [];

// Gather required parameters
// Gather required parameters.
foreach ($parts as $part) {
if (is_string($part)) {
continue;
Expand All @@ -223,16 +229,16 @@ private function missingParameters(array $parts, array $substitutions): array
$missingParameters[] = $part[0];
}

// Check if all parameters exist
// Check if all parameters exist.
foreach ($missingParameters as $parameter) {
if (!array_key_exists($parameter, $substitutions)) {
// Return the parameters so they can be used in an
// exception if needed
// Return the parameters, so they can be used in an
// exception if needed.
return $missingParameters;
}
}

// All required parameters are available
// All required parameters are available.
return [];
}

Expand All @@ -243,12 +249,12 @@ private function generatePath(array $parameters, array $parts): string

foreach ($parts as $part) {
if (is_string($part)) {
// Append the string
// Append the string.
$path .= $part;
continue;
}

// Check substitute value with regex
// Check substitute value with regex.
$pattern = str_replace('~', '\~', $part[1]);
if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
throw new RuntimeException(
Expand All @@ -260,7 +266,7 @@ private function generatePath(array $parameters, array $parts): string
);
}

// Append the substituted value
// Append the substituted value.
$path .= $this->encodeRaw
? rawurlencode((string)$parameters[$part[0]])
: urlencode((string)$parameters[$part[0]]);
Expand Down
Loading

0 comments on commit 588b753

Please sign in to comment.