-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathresource_spec_api.php
More file actions
70 lines (56 loc) · 2.1 KB
/
resource_spec_api.php
File metadata and controls
70 lines (56 loc) · 2.1 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
<?php
declare(strict_types=1);
use alsvanzelf\jsonapi\ResourceDocument;
use alsvanzelf\jsonapi\enums\RelationshipTypeEnum;
use alsvanzelf\jsonapi\objects\AttributesObject;
use alsvanzelf\jsonapi\objects\LinksObject;
use alsvanzelf\jsonapi\objects\MetaObject;
use alsvanzelf\jsonapi\objects\RelationshipObject;
use alsvanzelf\jsonapi\objects\RelationshipsObject;
use alsvanzelf\jsonapi\objects\ResourceObject;
require __DIR__.'/bootstrap_examples.php';
$user1 = ExampleDataset::getEntity('user', 1);
$user42 = ExampleDataset::getEntity('user', 42);
/**
* send a single entity, called a resource, via the specification-based api
*
* @note this is the other extreme, it can be done in any way in between as well
*/
$attributes1 = new AttributesObject();
$attributes1->add('name', $user1->name);
$attributes1->add('heads', $user1->heads);
$attributes1->add('unknown', $user1->unknown);
$attributes1->add('location', $user1->getCurrentLocation());
$attributes42 = new AttributesObject();
$attributes42->add('name', $user42->name);
$attributes42->add('heads', $user42->heads);
$attributes42->add('unknown', $user42->unknown);
$links = new LinksObject();
$links->addLinkString('homepage', 'https://jsonapi.org');
$meta = new MetaObject();
$meta->add('difference', 'is in the code to generate this');
$resource = new ResourceObject();
$resource->setId($user42->id);
$resource->setType('user');
$resource->setAttributesObject($attributes42);
$relationship = new RelationshipObject(RelationshipTypeEnum::ToOne);
$relationship->setResource($resource);
$relationships = new RelationshipsObject();
$relationships->addRelationshipObject('friend', $relationship);
$document = new ResourceDocument();
$document->setId($user1->id);
$document->setType('user');
$document->setAttributesObject($attributes1);
$document->setLinksObject($links);
$document->setMetaObject($meta);
$document->setRelationshipsObject($relationships);
/**
* get the json
*
* using $document->toJson() here for example purposes
* use $document->sendResponse() to send directly
*/
$options = [
'prettyPrint' => true,
];
echo '<pre>'.$document->toJson($options).'</pre>';