Skip to content

Commit

Permalink
- Added declare(strict-types=1); to ensure that every type is strictl…
Browse files Browse the repository at this point in the history
…y followed.

- Added missing return types so callables will know what will be returned
- Reformated code so its more readable with && and || signs.
- Re-arranged the simplicity of the || checks.
- Removed intval() and did (int) casting. Which performs up to 6 times faster.
- Returned void for addLinkHeaders since its private and the return is never used.
- For LinkHeaders.php I've removed the null-operator (?). This could cause an error whenever the null was passed. Now it can't throw an error anymore due to the foreach which was a few lines later.
- Renamed variable instead of rewriting the variable (bad coding behavior)
- Tested everything in the test folder to assure everything complies.
  • Loading branch information
Rodeveer committed Jan 6, 2025
1 parent cf17e82 commit 6380117
Show file tree
Hide file tree
Showing 9 changed files with 40 additions and 38 deletions.
30 changes: 15 additions & 15 deletions src/Data/LinkHeaders.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints\Data;

Expand Down Expand Up @@ -30,7 +30,7 @@ public function setLinkProvider(EvolvableLinkProviderInterface $linkProvider): s
return $this;
}

public function addLink(EvolvableLinkInterface|string|array $uri, string|array|null $rel = null, ?array $attributes = []): static
public function addLink(EvolvableLinkInterface|string|array $uri, string|array|null $rel = null, array $attributes = []): static
{
if (is_array($uri)) {
foreach ($uri as $data) {
Expand Down Expand Up @@ -71,23 +71,23 @@ public function addLink(EvolvableLinkInterface|string|array $uri, string|array|n

public function addFromString(string $link): static
{
$links = explode(',', trim($link));
foreach ($links as $link) {
$parts = explode('; ', trim($link));
$explodedLinks = explode(',', trim($link));
foreach ($explodedLinks as $explodedLink) {
$parts = explode('; ', trim($explodedLink));
$uri = trim(array_shift($parts), '<>');
$rel = null;
$attributes = [];
foreach ($parts as $part) {
preg_match('/(?<key>[^=]+)(?:="?(?<value>.*)"?)?/', trim($part), $matches);
$key = $matches['key'];
$value = $matches['value'] ?? null;
$value = $matches['value'] ?? '1';

if ($key === 'rel') {
$rel = $value;

continue;
}
$attributes[$key] = $value ?? true;
$attributes[$key] = $value;
}

$this->addLink($uri, $rel, $attributes);
Expand All @@ -96,14 +96,14 @@ public function addFromString(string $link): static
return $this;
}

public function makeUnique()
public function makeUnique(): static
{
$handledHashes = [];

foreach ($this->getLinkProvider()->getLinks() as $link) {
/** @var Link $link */
$hash = md5($link->getHref(), serialize($link->getRels()));
if (! in_array($hash, $handledHashes)) {
$hash = md5($link->getHref(), true); // Previous the second parameter was: serialize($link->getRels()) which gives a string, where the second parameter excepts a boolean.
if (!in_array($hash, $handledHashes, true)) {
$handledHashes[] = $hash;

continue;
Expand All @@ -115,18 +115,18 @@ public function makeUnique()
return $this;
}

public function __toString()
public function __toString(): string
{
return trim(collect($this->getLinkProvider()->getLinks())
->map([static::class, 'linkToString'])
->map([self::class, 'linkToString'])
->filter()
->implode(','));
}

public static function linkToString(LinkInterface $link)
public static function linkToString(LinkInterface $link): ?string
{
if ($link->isTemplated()) {
return;
return null;
}

$attributes = ['', sprintf('rel="%s"', implode(' ', $link->getRels()))];
Expand All @@ -140,7 +140,7 @@ public static function linkToString(LinkInterface $link)
continue;
}

if (! \is_bool($value)) {
if (!\is_bool($value)) {
$attributes[] = sprintf('%s="%s"', $key, $value);

continue;
Expand Down
2 changes: 1 addition & 1 deletion src/Events/GenerateEarlyHints.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints\Events;

Expand Down
6 changes: 3 additions & 3 deletions src/Listeners/AddDefaultHeaders.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints\Listeners;

Expand All @@ -7,14 +7,14 @@

class AddDefaultHeaders
{
public function handle(GenerateEarlyHints $event)
public function handle(GenerateEarlyHints $event): void
{
foreach (config('http3earlyhints.default_headers', []) as $header) {
$event->linkHeaders->addFromString($header);
}
}

public static function register()
public static function register(): void
{
Event::listen(GenerateEarlyHints::class, static::class);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Listeners/AddFromBody.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints\Listeners;

Expand Down
28 changes: 15 additions & 13 deletions src/Middleware/AddHttp3EarlyHints.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints\Middleware;

Expand Down Expand Up @@ -26,7 +26,10 @@ public function handle(Request $request, Closure $next, ?int $sizeLimit = null):
$lastPath = Str::afterLast($request->path(), '/');
if (
$request->format() !== 'html'
|| (str_contains($lastPath, '.') && ! in_array(Str::afterLast($lastPath, '.'), config('http3earlyhints.extensions', ['', 'php', 'html'])))
|| (
str_contains($lastPath, '.')
&& !in_array(Str::afterLast($lastPath, '.'), config('http3earlyhints.extensions', ['', 'php', 'html']), true)
)
) {
$this->skipCurrentRequest = true;

Expand Down Expand Up @@ -84,15 +87,15 @@ public function terminate(Request $request, SymfonyResponse $response): void
$this->handleGeneratingLinkHeaders($request, $response);
}

public function handleGeneratingLinkHeaders(Request $request, SymfonyResponse $response)
public function handleGeneratingLinkHeaders(Request $request, SymfonyResponse $response): ?LinkHeaders
{
if (
! $response instanceof Response
$this->skipCurrentRequest
|| !$response instanceof Response
|| $response->isRedirection()
|| ! $response->isSuccessful()
|| $this->skipCurrentRequest
|| !$response->isSuccessful()
) {
return;
return null;
}
$linkHeaders = $this->generateLinkHeaders($request, $response, $this->sizeLimit);

Expand All @@ -112,7 +115,7 @@ protected function generateLinkHeaders(Request $request, SymfonyResponse $respon

$this->linkHeaders->makeUnique();

$sizeLimit = $sizeLimit ?? max(1, intval(config('http3earlyhints.size_limit', 32 * 1024)));
$sizeLimit = $sizeLimit ?? max(1, (int)config('http3earlyhints.size_limit', 32 * 1024));
$headersText = $this->linkHeaders->__toString();

while (strlen($headersText) > $sizeLimit) {
Expand All @@ -126,18 +129,17 @@ protected function generateLinkHeaders(Request $request, SymfonyResponse $respon
/**
* Add Link Header
*/
private function addLinkHeaders(SymfonyResponse $response, LinkHeaders $linkHeaders): SymfonyResponse
private function addLinkHeaders(SymfonyResponse $response, LinkHeaders $linkHeaders): void
{
$link = $linkHeaders->__toString();
if (! $link || ! $response instanceof Response) {
return $response;
if (!$link || !$response instanceof Response) {
return;
}

if ($response->headers->get('Link')) {
$link = $response->headers->get('Link').','.$link;
}

$response->header('Link', $link);

return $response;
}
}
4 changes: 2 additions & 2 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints;

Expand All @@ -13,7 +13,7 @@ class ServiceProvider extends LaravelServiceProvider
*
* @return void
*/
public function boot()
public function boot(): void
{
$this->mergeConfigFrom(__DIR__.'/config.php', 'http3earlyhints');

Expand Down
2 changes: 1 addition & 1 deletion src/config.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

return [
/**
Expand Down
2 changes: 1 addition & 1 deletion tests/AddHttp3EarlyHintsTest.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints\Tests;

Expand Down
2 changes: 1 addition & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php declare(strict_types=1);

namespace JustBetter\Http3EarlyHints\Tests;

Expand Down

0 comments on commit 6380117

Please sign in to comment.