-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTakeFirst.php
More file actions
36 lines (29 loc) · 982 Bytes
/
Copy pathTakeFirst.php
File metadata and controls
36 lines (29 loc) · 982 Bytes
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
<?php
namespace ScriptFUSION\Mapper\Strategy;
use ScriptFUSION\Mapper\Mapping;
/**
* Takes the first value from a collection one or more times according to the specified depth. If the depth exceeds the
* number of nesting levels of the collection the last item encountered will be returned.
*/
class TakeFirst extends Delegate
{
private $depth;
/**
* @param Strategy|Mapping|array|mixed $collection Expression that maps to an array.
* @param int $depth Number of times to descending into nested collections.
*/
public function __construct($collection, $depth = 1)
{
parent::__construct($collection);
$this->depth = max(1, $depth|0);
}
public function __invoke($data, $context = null)
{
$depth = $this->depth;
$structure = parent::__invoke($data, $context);
while (is_array($structure) && $depth--) {
$structure = reset($structure);
}
return $structure;
}
}