Completed
Push — master ( 12bc5d...f69768 )
by Oscar
58:41
created

CacheMessageTrait::cache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Psr\Http\Message\MessageInterface;
6
7
/**
8
 * Trait used by all middlewares that needs to a psr-7 message into a psr-6 cache.
9
 */
10
trait CacheMessageTrait
11
{
12
    /**
13
     * @var CacheItemPoolInterface The cache implementation used
14
     */
15
    private $cache;
16
17
    /**
18
     * Provide the cache implementation.
19
     * 
20
     * @param CacheItemPoolInterface $cache
21
     * 
22
     * @return self
23
     */
24
    public function cache(CacheItemPoolInterface $cache)
25
    {
26
        $this->cache = $cache;
27
28
        return $this;
29
    }
30
31
    /**
32
     * Restore a message from the cache.
33
     * 
34
     * @param string           $key     The message key
35
     * @param MessageInterface $message
36
     *
37
     * @return MessageInterface|false
38
     */
39
    private function getFromCache($key, MessageInterface $message)
40
    {
41
        if ($this->cache) {
42
            $item = $this->cache->getItem($key);
43
44
            if ($item->isHit()) {
45
                list($headers, $body) = $item->get();
46
47
                foreach ($headers as $name => $header) {
48
                    $message = $message->withHeader($name, $header);
49
                }
50
51
                $message->getBody()->write($body);
52
53
                return $message;
54
            }
55
        }
56
57
        return false;
58
    }
59
60
    /**
61
     * Store a message in the cache.
62
     * 
63
     * @param string           $key     The message key
64
     * @param MessageInterface $message
65
     */
66
    private function saveIntoCache($key, MessageInterface $message)
67
    {
68
        if ($this->cache) {
69
            $item = $this->cache->getItem($key);
70
71
            $item->set([
72
                $message->getHeaders(),
73
                (string) $message->getBody(),
74
            ]);
75
76
            $this->cache->save($item);
77
        }
78
    }
79
}
80