| Code Coverage
| Lines | Functions and Methods | Classes and Traits
Total | 100.00% covered (success) | 100.00% | 18 / 18 | 100.00% covered (success) | 100.00% | 4 / 4 | CRAP | 100.00% covered (success) | 100.00% | 1 / 1
Cookie | 100.00% covered (success) | 100.00% | 18 / 18 | 100.00% covered (success) | 100.00% | 4 / 4 | 6 | 100.00% covered (success) | 100.00% | 1 / 1
__construct | 100.00% covered (success) | 100.00% | 3 / 3 | 100.00% covered (success) | 100.00% | 1 / 1 | 1 |
setCookieValue | 100.00% covered (success) | 100.00% | 9 / 9 | 100.00% covered (success) | 100.00% | 1 / 1 | 3 |
setExpires | 100.00% covered (success) | 100.00% | 5 / 5 | 100.00% covered (success) | 100.00% | 1 / 1 | 1 |
getHeaderString | 100.00% covered (success) | 100.00% | 1 / 1 | 100.00% covered (success) | 100.00% | 1 / 1 | 1 |

1 | <?php
2 | namespace Headers\Response;
3 |
4 | use DateInterval;
5 | use DateTimeImmutable;
6 | use Headers\Interfaces\HeaderStringInterface;
7 | use InvalidArgumentException;
8 |
9 | class Cookie implements HeaderStringInterface
10 | {
11 | protected array $parameters;
12 |
13 | public function __construct(
14 | protected string $cookieName,
15 | protected string $cookieValue,
16 | protected DateTimeImmutable $startDate = new DateTimeImmutable('now'),
17 | ) {
18 | $this->cookieName = trim($this->cookieName);
19 | $this->cookieValue = trim($this->cookieValue);
20 | $this->setCookieValue();
21 | }
22 |
23 | protected function setCookieValue(): void
24 | {
25 | $cookieNameParts = explode(' ', $this->cookieName);
26 | if (count($cookieNameParts) > 1) {
27 | throw new InvalidArgumentException(
28 | "Cookie name cannot have spaces between provided: $this->cookieName"
29 | );
30 | }
31 |
32 | if (mb_detect_encoding($this->cookieName) !== 'ASCII') {
33 | throw new InvalidArgumentException("Cookie name can only be US ASCII, ex: [0-9][a-zA-Z]-");
34 | }
35 |
36 | $cookieValue = urlencode($this->cookieValue);
37 | $this->parameters[] = "Set-Cookie: {$this->cookieName}={$cookieValue}";
38 | }
39 |
40 | public function setExpires(Expires $expiresComponent): void
41 | {
42 | $dateInterval = $this->startDate->add(
43 | DateInterval::createFromDateString($expiresComponent->get())
44 | );
45 | $formattedDate = $dateInterval->format('D, d M Y H:i:s \G\M\T');
46 | $this->parameters[] = "Expires=$formattedDate";
47 | }
48 |
49 | public function getHeaderString(): string
50 | {
51 | return implode('; ', $this->parameters);
52 | }
53 | }