-
Notifications
You must be signed in to change notification settings - Fork 0
/
Transform.php
64 lines (58 loc) · 1.75 KB
/
Transform.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
59
60
61
62
63
64
<?php
/**
* Provides mappings of XML elements to Markdown fields.
*
* @version 0.1.0 2020-01-21
* @license WTFPL 2.0
* @author Rene Serradeil <serradeil@webmechanic.biz>
*/
namespace WebMechanic\Converter;
use DOMNode;
use WebMechanic\Converter\Wordpress\Item;
class Transform
{
/** @var null replacement or callable */
private $handler;
/**
* Transform constructor takes a $handler function that does the job.
* The Closure itself must accept a `DOMNode` or `DOMElement` as its
* 1st argument and an optional `Item` (or derivative) to `apply()`
* the transformation.
*
* There's no requirement to use the `Closure` class. using a vanilla
* `new Transform( function(DOMNode $node, Item $item) {...} )`
* will do.
*
* @param \Closure|null $handler
* @see apply(), Meta::addHandler()
*/
function __construct(\Closure $handler = null)
{
$this->handler = $handler;
}
/**
* Apply the transformation handler.
*
* Since a transformation is virtually applicable to any public property
* of the two objects incl. der DOMNode's child nodes, a callback's
* return value (if any) is unpredictable and thus ignored.
* Something like this inside an Item-ish class' custom setWhatever()
* method is usually fine:
* <listing>
* $this->transform($node->nodeName)->apply($node);
* $this->url = $node->textContent;
* </listing>
*
* See Item::set() and Meta::apply() for a more complex examples.
*
* @param DOMNode $node the XML node
* @param Item $post usually a Wordpress\Page|Attachment object (so far)
* @see Item::set(), Meta::apply(), Meta::addHandler()
*/
function apply(DOMNode $node, Item $post = null): void
{
if (is_callable($this->handler)) {
call_user_func($this->handler, $node, $post);
}
}
}