Passed
Pull Request — master (#12)
by Gabriel
11:49
created

LogCalls::map()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\PsrLogTestDoubles;
6
7
use Psr\Log\LogLevel;
8
9
/**
10
 * Immutable and ordered collection of LogCall objects
11
 *
12
 * @since 2.0
13
 *
14
 * @licence GNU GPL v2+
15
 * @author Jeroen De Dauw < [email protected] >
16
 */
17
class LogCalls implements \IteratorAggregate, \Countable {
18
19
	/**
20
	 * @var LogCall[]
21
	 */
22 6
	private array $calls;
23 6
24 6
	public function __construct( LogCall... $calls ) {
25
		$this->calls = $calls;
26 1
	}
27 1
28
	public function getIterator(): \ArrayIterator {
29
		return new \ArrayIterator( $this->calls );
30
	}
31
32
	/**
33 2
	 * @return string[]
34 2
	 */
35 2
	public function getMessages(): array {
36 1
		return array_map(
37 2
			function( LogCall $logCall ) {
38 2
				return $logCall->getMessage();
39
			},
40
			$this->calls
41
		);
42 2
	}
43 2
44
	public function getFirstCall(): ?LogCall {
45
		return $this->calls[0] ?? null;
46
	}
47
48
	/**
49
	 * @since 3.1
50 1
	 */
51 1
	public function getLastCall(): ?LogCall {
52
		return $this->calls[count( $this->calls ) - 1] ?? null;
53
	}
54
55
	/**
56
	 * @since 2.1
57
	 * @return int
58
	 */
59
	public function count(): int {
60
		return count( $this->calls );
61
	}
62
63
	/**
64
	 * @since 3.2
65
	 * @param callable(LogCall):bool $filter
66
	 * @return self
67
	 */
68
	public function filter( callable $filter ): self {
69
		return new self( ...array_filter( $this->calls, $filter ) );
70
	}
71
72
	/**
73
	 * Returns log calls with log level ERROR and above.
74
	 * @since 3.2
75
	 */
76
	public function getErrors(): self {
77
		return $this->filter( fn( LogCall $call ) => $call->isError() );
78
	}
79
80
	/**
81
	 * @since 3.2
82
	 * @param callable(LogCall):LogCall $map
83
	 * @return self
84
	 */
85
	public function map( callable $map ): self {
86
		$calls = [];
87
88
		foreach ( $this->calls as $call ) {
89
			$calls[] = $map( $call );
90
		}
91
92
		return new self( ...$calls );
93
	}
94
95
	/**
96
	 * Returns a copy of the log calls with their contexts removed.
97
	 * @since 3.2
98
	 */
99
	public function withoutContexts(): self {
100
		return $this->map( fn( LogCall $call ) => $call->withoutContext() );
101
	}
102
103
}
104