/
CountingCommentBlock.php
58 lines (52 loc) · 1.28 KB
/
CountingCommentBlock.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace ppFinal\ApplyingFinalKeyword\PreferInterfaceImplementation;
use ppCache\CounterInterface;
use ppFinal\Comment;
/**
* Block of comments counting views
*/
final class CountingCommentBlock implements CommentBlock
{
/**
* @var Comment[] Array of comments
*/
protected $comments = [];
/**
* @var CounterInterface PSR-16 compatible cache
*/
private $cache;
/**
* CountingCommentBlock constructor
*
* @param CounterInterface $cache
*/
public function __construct(CounterInterface $cache)
{
$this->cache = $cache;
}
/**
* Returns a string view of the comment and increments the counter value in the cache
*
* @param string $key
* @return string
*/
public function viewComment(string $key): string
{
$this->cache->increment($key);
return $this->comments[$key]->view();
}
/**
* Returns a string view of all comments in the block as a single string
* and increments the counter values in the cache
*
* @return string
*/
public function viewComments(): string
{
$view = '';
foreach ($this->comments as $key => $comment) {
$view .= $this->viewComment($key);
}
return $view;
}
}