-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRisWriter.php
114 lines (94 loc) · 2.5 KB
/
RisWriter.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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace Funstaff\RefLibRis;
/**
* RisWriter
*
* @author Bertrand Zuchuat <[email protected]>
*/
class RisWriter
{
const RIS_EOL = "\r\n";
/**
* @var RisDefinitionInterface
*/
private $definition;
/**
* @var array
*/
private $records = [];
/**
* RisWriter constructor.
* @param RisDefinitionInterface $definition
*/
public function __construct(RisDefinitionInterface $definition)
{
$this->definition = $definition;
}
/**
* @param array $record
* @return $this
*/
public function addRecord(array $record)
{
array_push($this->records, $record);
return $this;
}
/**
* @param array $records
* @return $this
*/
public function setRecords(array $records)
{
$this->records = $records;
return $this;
}
/**
* @param bool $validation
* @return string
*/
public function process($validation = false): string
{
if (count($this->records) == 0) {
throw new \LengthException('Add Record before call process function.');
}
$buffer = [];
foreach ($this->records as $record) {
$buffer[] = $this->processRecord($record, $validation);
}
return implode(self::RIS_EOL, $buffer);
}
/**
* @param array $record
* @param $validation
* @return string
*/
private function processRecord(array $record, $validation): string
{
$buffer = [];
if (!array_key_exists('TY', $record)) {
throw new \InvalidArgumentException('TY Tag field not found.');
}
if (is_string($record['TY'])) {
$record['TY'] = [$record['TY']];
}
/* First position for TY (Type) */
array_push($buffer, sprintf('TY - %s', $record['TY'][0]));
unset($record['TY']);
/* Order the array */
ksort($record);
foreach ($record as $tag => $values) {
if ($validation && !$this->definition->hasField($tag)) {
throw new \InvalidArgumentException('Field Tag not found.');
}
if (is_string($values)) {
$values = [$values];
}
foreach ($values as $value) {
array_push($buffer, sprintf('%s - %s', $tag, $value));
}
}
/* End record */
array_push($buffer, 'ER - '.self::RIS_EOL);
return implode(self::RIS_EOL, $buffer);
}
}