-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathTemplate.php
More file actions
100 lines (85 loc) · 2.16 KB
/
Template.php
File metadata and controls
100 lines (85 loc) · 2.16 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
declare(strict_types=1);
namespace BitWasp\Buffertools;
use BitWasp\Buffertools\Types\TypeInterface;
class Template implements \Countable
{
/**
* @var TypeInterface[]
*/
private $template = [];
/**
* @param array $items
*/
public function __construct(array $items = [])
{
foreach ($items as $item) {
$this->addItem($item);
}
}
/**
* {@inheritdoc}
* @see \Countable::count()
* @return int
*/
public function count(): int
{
return count($this->template);
}
/**
* Return an array of type serializers in the template
*
* @return Types\TypeInterface[]
*/
public function getItems(): array
{
return $this->template;
}
/**
* Add a new TypeInterface to the Template
*
* @param TypeInterface $item
* @return Template
*/
public function addItem(TypeInterface $item): Template
{
$this->template[] = $item;
return $this;
}
/**
* Parse a sequence of objects from binary, using the current template.
*
* @param Parser $parser
* @return mixed[]|Buffer[]|int[]|string[]
*/
public function parse(Parser $parser): array
{
if (empty($this->template)) {
throw new \RuntimeException('No items in template');
}
$values = [];
foreach ($this->template as $reader) {
$values[] = $reader->read($parser);
}
return $values;
}
/**
* Write the array of $items to binary according to the template. They must
* each be an instance of Buffer or implement SerializableInterface.
*
* @param array $items
* @return BufferInterface
*/
public function write(array $items): BufferInterface
{
if (count($items) != count($this->template)) {
throw new \RuntimeException('Number of items must match template');
}
$binary = '';
foreach ($this->template as $serializer) {
$item = array_shift($items);
$binary .= $serializer->write($item);
}
return new Buffer($binary);
}
}