-
Notifications
You must be signed in to change notification settings - Fork 1
/
PreviousSibling.php
46 lines (39 loc) · 1007 Bytes
/
PreviousSibling.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
<?php
declare(strict_types = 1);
namespace Innmind\Xml\Visitor;
use Innmind\Xml\Node;
use Innmind\Immutable\Maybe;
/**
* @psalm-immutable
*/
final class PreviousSibling
{
private Node $node;
private function __construct(Node $node)
{
$this->node = $node;
}
/**
* @return Maybe<Node>
*/
public function __invoke(Node $tree): Maybe
{
$children = ParentNode::of($this->node)($tree)->map(
static fn($parent) => $parent->children(),
);
/** @psalm-suppress InvalidArgument */
return $children
->flatMap(fn($children) => $children->indexOf($this->node))
->filter(static fn($position) => $position >= 0)
->flatMap(static fn($position) => $children->flatMap(
static fn($children) => $children->get($position - 1),
));
}
/**
* @psalm-pure
*/
public static function of(Node $node): self
{
return new self($node);
}
}