Passed
Push — main ( b06378...a6366b )
by Dimitri
11:35
created

ResponseCache.php (1 issue)

Labels
Severity
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Cache;
13
14
use Exception;
15
use Psr\Http\Message\RequestInterface;
16
use Psr\Http\Message\ResponseInterface;
17
use Psr\Http\Message\ServerRequestInterface;
18
use Psr\SimpleCache\CacheInterface;
0 ignored issues
show
This use statement conflicts with another class in this namespace, BlitzPHP\Cache\CacheInterface. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
19
20
/**
21
 * Web Page Caching
22
 */
23
final class ResponseCache
24
{
25
    /**
26
     * Duree de vie du cache.
27
     *
28
     * @var int seconds
29
     */
30
    private int $ttl = 0;
31
32
    /**
33
     * @param bool|string[] $cacheQueryString S'il faut prendre en compte la chaîne de requête URL lors de la génération des fichiers de cache de sortie.
34
     *                                        Les options valides sont :
35
     *                                        false      = Désactivé
36
     *                                        true       = Activé, prend en compte tous les paramètres de requête.
37
     *                                        Veuillez noter que cela peut entraîner de nombreux fichiers de cache générés encore et encore pour la même page.
38
     *                                        array('q') = Activé, mais ne prend en compte que la liste spécifiée de paramètres de requête.
39
	 */
40
    public function __construct(private CacheInterface $cache, private array|bool $cacheQueryString = false)
41
    {
42
    }
43
44
    public function setTtl(int $ttl): self
45
    {
46
        $this->ttl = $ttl;
47
48
        return $this;
49
    }
50
51
    /**
52
     * Génère la clé de cache à utiliser à partir de la requête actuelle.
53
     *
54
     * @internal à des fins de test uniquement
55
     */
56
    public function generateCacheKey(RequestInterface $request): string
57
    {
58
        $uri = clone $request->getUri();
59
60
        // @todo implementation de la recuperation des queriestring
61
        /* $query = $this->cacheQueryString
62
            ? $uri->getQuery(is_array($this->cacheQueryString) ? ['only' => $this->cacheQueryString] : [])
63
            : ''; */
64
65
        $query = '';
66
67
        return md5($uri->withFragment('')->withQuery($query));
68
    }
69
70
    /**
71
     * Met en cache la réponse.
72
     */
73
    public function make(ServerRequestInterface $request, ResponseInterface $response): bool
74
    {
75
        if ($this->ttl === 0) {
76
            return true;
77
        }
78
79
        $headers = [];
80
81
        foreach (array_keys($response->getHeaders()) as $header) {
82
            $headers[$header] = $response->getHeaderLine($header);
83
        }
84
85
        return $this->cache->set(
86
            $this->generateCacheKey($request),
87
            serialize(['headers' => $headers, 'output' => $response->getBody()->getContents()]),
88
            $this->ttl
89
        );
90
    }
91
92
    /**
93
     * Obtient la réponse mise en cache pour la demande.
94
     */
95
    public function get(ServerRequestInterface $request, ResponseInterface $response): ?ResponseInterface
96
    {
97
        if ($cachedResponse = $this->cache->get($this->generateCacheKey($request))) {
98
            $cachedResponse = unserialize($cachedResponse);
99
100
            if (! is_array($cachedResponse) || ! isset($cachedResponse['output']) || ! isset($cachedResponse['headers'])) {
101
                throw new Exception('Erreur lors de la désérialisation du cache de page');
102
            }
103
104
            $headers = $cachedResponse['headers'];
105
            $output  = $cachedResponse['output'];
106
107
            // Effacer tous les en-têtes par défaut
108
            foreach (array_keys($response->getHeaders()) as $key) {
109
                $response = $response->withoutHeader($key);
110
            }
111
112
            // Définir les en-têtes mis en cache
113
            foreach ($headers as $name => $value) {
114
                $response = $response->withHeader($name, $value);
115
            }
116
117
            return $response->withBody(to_stream($output));
118
        }
119
120
        return null;
121
    }
122
}
123