-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveOn.php
More file actions
405 lines (335 loc) · 12.3 KB
/
MoveOn.php
File metadata and controls
405 lines (335 loc) · 12.3 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<?php
namespace PRayno\MoveOnApi;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Yaml\Yaml;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class MoveOn
{
protected array $entities_read;
protected array $entities_write;
/**
* Request constructor.
* @param HttpClientInterface $client
* @param int $maxRowsPerQuery
*/
public function __construct(private HttpClientInterface $client, protected int $maxRowsPerQuery=250,string $entitiesReadFile="",string $entitiesWriteFile="")
{
$entitiesReadFile = (empty($entitiesReadFile)) ? __DIR__ . "/Resources/entities_read.yml" : $entitiesReadFile;
$entitiesWriteFile = (empty($entitiesWriteFile)) ? __DIR__ . "/Resources/entities_read.yml" : $entitiesWriteFile;
$this->entities_read = Yaml::parse(file_get_contents($entitiesReadFile));
$this->entities_write = Yaml::parse(file_get_contents($entitiesWriteFile));
}
/**
* Send a plain query to MoveOn
* @param $entity
* @param $action
* @param $data
* @param string $method
* @param int $timeout
* @param bool $retrieveData
* @return \SimpleXMLElement
* @throws \Exception
*/
public function sendQuery(string $entity,string $action,string $data,string $method="queue",int $timeout=10,bool $retrieveData=true): \SimpleXMLElement|int
{
$entities = ($action=="save" ? $this->entities_write:$this->entities_read);
if (!isset($entities[$entity]))
throw new \Exception("Entity $entity does not exist");
$curl_post_data = [
'method' => $method,
'entity' => $entity,
'action' => $action,
'data' => $data
];
$response = $this->client->request('POST',"",['body' => $curl_post_data]);
$content = $response->getContent();
$crawler = new Crawler($content);
$moveonResponse = json_decode($crawler->filterXPath("//response")->text());
if (!isset($moveonResponse->queueId))
{
throw new \Exception("The MoveON server did not respond properly");
}
if ($retrieveData==false)
return $moveonResponse->queueId;
// Retrieve data
$start = time();
while (time() < $start+$timeout)
{
$curl_post_data = array(
'method' => 'get',
'id' => (int) $moveonResponse->queueId
);
$response = $this->client->request('POST',"",['body' => $curl_post_data]);
$content = $response->getContent();
$crawler = new Crawler($content);
if ($crawler->filterXPath("//status")->text() == "success")
{
$responseContent = $crawler->filterXPath("//response")->html();
return simplexml_load_string($responseContent);
}
}
}
/**
* Retrieve data from MoveON DB
* @param string $entity
* @param array $criteria
* @param array $sort
* @param int $rows
* @param int $page
* @param array $columns
* @param string $locale
* @param string $search
* @param string $method
* @param int $timeout
* @return \SimpleXMLElement
* @throws \Exception
*/
public function findBy(string $entity,array $criteria, array $sort=["id"=>"asc"], int $rows=250, int $page=1,array $columns=[],string $locale="eng",string $search="true",string $method="queue",int $timeout=10)
{
if (!isset($this->entities_read[$entity]))
throw new \Exception("Entity $entity does not exist");
$rules='';
$i=1;
$params=[];
foreach ($criteria as $field=>$value)
{
//if (false === $this->validateField($field,$entity,"read"))
// throw new \Exception("The field $field does not belong to the entity $entity");
$params[] = [
"field"=>$this->prefix($field,$entity),
"op"=>(is_array($value)?"in":"eq"),
"data"=>(is_array($value)?implode(",",$value):$value)
];
if (count($criteria) > $i)
$rules .= ',';
$i++;
}
if (empty($columns))
$columns = $this->entities_read[$entity];
$visibleColumns=[];
foreach ($columns as $column)
{
$visibleColumns[] = $this->prefix($column,$entity);
}
$visibleColumns = implode(";",$visibleColumns);
$filterElements = [
"filters"=>json_encode(["groupOp"=>"AND","rules"=>$params]),
"visibleColumns"=>$visibleColumns,
"locale"=>$locale,
"sortName"=>$this->prefix(key($sort),$entity),
"sortOrder"=>current($sort),
"_search"=>$search,
"page"=>$page,
"rows"=>$rows
];
// Simple query if the page number is set directly
if ($page>1)
{
if ($rows > $this->maxRowsPerQuery)
throw new \Exception("The number of rows for a given page must not exceed the limit of ".$this->maxRowsPerQuery);
try {
return $this->sendQuery($entity,"list",json_encode($filterElements),$method,$timeout);
}
catch (\Exception $exception)
{
throw $exception;
}
}
// Recreate xml response after pagination
$remainingRows = $rows;
for ($page=1;$page<=ceil($rows/$this->maxRowsPerQuery);$page++)
{
$rowsToRetrieve = ($remainingRows < $this->maxRowsPerQuery ? $remainingRows:$this->maxRowsPerQuery);
$remainingRows = $remainingRows-$rowsToRetrieve;
$filterElements["rows"] = $rowsToRetrieve;
$filter = json_encode($filterElements);
try {
$response = $this->sendQuery($entity,"list",$filter,$method,$timeout);
}
catch (\Exception $exception)
{
throw $exception;
}
if ($page==1)
{
$finalResponse = clone $response;
unset($finalResponse->rows);
}
foreach ($response->rows as $row)
{
$this->simplexml_import_simplexml($finalResponse,$row);
}
if ($finalResponse->records == count($finalResponse->rows))
break;
}
return $finalResponse;
}
/**
* Save data to MoveON DB
* @param string $entity
* @param array $data
* @param string $method
* @param int $timeout
* @param bool $retrieveData
* @return \SimpleXMLElement
* @throws \Exception
*/
public function save(string $entity, array $data, string $method="queue", int $timeout=10,bool $retrieveData=true)
{
if (!isset($this->entities_write[$entity]))
throw new \Exception("Entity $entity does not exist");
$elements = ["entity"=>$entity];
foreach ($data as $field=>$value)
{
if (false === $this->validateField($field,$entity,"write"))
throw new \Exception("The field $field does not belong to the entity $entity");
$elements[$this->prefix($field,$entity)] = $value;
}
try {
return $this->sendQuery($entity,'save',json_encode($elements),$method,$timeout,$retrieveData);
}
catch (\Exception $exception)
{
throw $exception;
}
}
/**
* Find courses list for a student
* @param string $studentnumber
* @param string $courseCodeField
* @return array
* @throws \Exception
*/
public function getUserCourses(string $studentnumber,string $courseCodeField="courseunit.code")
{
try {
$data = $this->findBy("person",["matriculation_id"=>$studentnumber]);
if ($data->records == 0)
throw new \Exception("Could not find student $studentnumber in MoveON database");
if ($data->records > 1)
throw new \Exception("Several students were found in MoveON db with the number $studentnumber.");
$field = "person.id";
$studentId = $data->rows[0]->$field->__toString();
// Find stay
$data = $this->findBy("stay",["person_id"=>$studentId]);
if ($data->records == 0)
throw new \Exception("Could not find stay in MoveON database");
if ($data->records > 1)
throw new \Exception("Several stays were found in MoveON db for the student $studentnumber.");
// Find courses
$stayIdField = "stay.id";
$courses = $this->findBy("course-unit",["stay.id"=>$data->rows[0]->$stayIdField->__toString()]);
if ($courses->records == 0)
throw new \Exception("No course were linked to the student $studentnumber in MoveON database");
$coursesList=[];
foreach ($courses->rows as $course)
{
$coursesList[] = trim($course->$courseCodeField->__toString());
}
return $coursesList;
}
catch (\Exception $exception)
{
throw $exception;
}
}
/**
* @param string $entity
* @param string $readWrite
* @return mixed
* @throws \Exception
*/
public function getEntity(string $entity,string $readWrite="read")
{
$entities = ($readWrite=="read" ? $this->entities_read : $this->entities_write);
if (!isset($entities[$entity]))
throw new \Exception("Entity $entity does not exist in $readWrite mode");
return $entities[$entity];
}
public function downloadFile(int $documentId)
{
$curl_post_data = [
'method' => "download",
'entity' => "file",
'action' => "download",
'data' => json_encode(["document_id"=>$documentId])
];
$response = $this->client->request('POST',"",['body' => $curl_post_data]);
$content = $response->getContent();
return $content;
}
/**
* @param $field
* @param $object
* @return string
*/
private function prefix($field,$object)
{
if (str_starts_with($field, 'custom'))
return $field;
$prefix = str_replace("-","_",$object).".";
return $prefix.$field;
}
/**
* @param $field
* @param $entity
* @param $readWrite
* @return bool
* @throws \Exception
*/
private function validateField($field,$entity,$readWrite)
{
if (str_starts_with($field, 'custom'))
return true;
return in_array($field,$this->getEntity($entity,$readWrite));
}
/**
* @param \SimpleXMLElement $parent
* @param \SimpleXMLElement $child
* @param false $before
* @return bool
*/
private function simplexml_import_simplexml(\SimpleXMLElement $parent, \SimpleXMLElement $child, $before = false)
{
// check if there is something to add
if ($child[0] == NULL) {
return true;
}
// if it is a list of SimpleXMLElements default to the first one
$child = $child[0];
// insert attribute
if ($child->xpath('.') != array($child)) {
$parent[$child->getName()] = (string)$child;
return true;
}
$xml = $child->asXML();
// remove the XML declaration on document elements
if ($child->xpath('/*') == array($child)) {
$pos = strpos($xml, "\n");
$xml = substr($xml, $pos + 1);
}
return $this->simplexml_import_xml($parent, $xml, $before);
}
/**
* @param \SimpleXMLElement $parent
* @param $xml
* @param false $before
* @return bool
*/
private function simplexml_import_xml(\SimpleXMLElement $parent, $xml, $before = false)
{
$xml = (string)$xml;
// check if there is something to add
if ($nodata = !strlen($xml) or $parent[0] == NULL) {
return $nodata;
}
// add the XML
$node = dom_import_simplexml($parent);
$fragment = $node->ownerDocument->createDocumentFragment();
$fragment->appendXML($xml);
if ($before) {
return (bool)$node->parentNode->insertBefore($fragment, $node);
}
return (bool)$node->appendChild($fragment);
}
}