1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\Fractal\Test\Hal; |
4
|
|
|
|
5
|
|
|
use League\Fractal\Hal\HalInterface; |
6
|
|
|
use League\Fractal\TransformerAbstract; |
7
|
|
|
use League\Fractal\Manager; |
8
|
|
|
use League\Fractal\Resource\Item; |
9
|
|
|
use League\Fractal\Serializer\ArraySerializer; |
10
|
|
|
|
11
|
|
|
class HalTest extends \PHPUnit_Framework_TestCase |
12
|
|
|
{ |
13
|
|
|
public function testHalOutputIsAdded() |
14
|
|
|
{ |
15
|
|
|
$manager = new Manager(); |
16
|
|
|
$manager->setSerializer(new ArraySerializer()); |
17
|
|
|
|
18
|
|
|
$book = Book::getBook(); |
19
|
|
|
$resource = new Item($book, new BookTransformer()); |
20
|
|
|
|
21
|
|
|
$data = $manager->createData($resource)->toArray(); |
22
|
|
|
$this->assertArrayHasKey('_links', $data); |
23
|
|
|
|
24
|
|
|
$data = $data['_links']; |
25
|
|
|
$this->assertArrayHasKey('self', $data); |
26
|
|
|
$this->assertArrayHasKey('next', $data); |
27
|
|
|
$this->assertArrayHasKey('previous', $data); |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
class Book implements HalInterface |
|
|
|
|
32
|
|
|
{ |
33
|
|
|
public $id; |
34
|
|
|
public $title; |
35
|
|
|
public $yr; |
36
|
|
|
public $author_name; |
37
|
|
|
public $author_email; |
38
|
|
|
|
39
|
|
|
public static function getBook(){ |
40
|
|
|
$book = new Book(); |
41
|
|
|
$book->id = 1; |
42
|
|
|
$book->title = 'the title'; |
43
|
|
|
$book->yr = 'the yr'; |
44
|
|
|
$book->author_name = 'test'; |
45
|
|
|
$book->author_email = '[email protected]'; |
46
|
|
|
|
47
|
|
|
return $book; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function getSelfLink() |
51
|
|
|
{ |
52
|
|
|
return 'self.html' . $this->id; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function getNextLink() |
56
|
|
|
{ |
57
|
|
|
return 'next.html' . $this->id; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function getPreviousLink() |
61
|
|
|
{ |
62
|
|
|
return 'previous.html' . $this->id; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function getCurries() |
66
|
|
|
{ |
67
|
|
|
return []; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
class BookTransformer extends TransformerAbstract |
|
|
|
|
72
|
|
|
{ |
73
|
|
|
public function transform(Book $book) |
74
|
|
|
{ |
75
|
|
|
return [ |
76
|
|
|
'id' => (int) $book->id, |
77
|
|
|
'title' => $book->title, |
78
|
|
|
'year' => $book->yr, |
79
|
|
|
'author' => [ |
80
|
|
|
'name' => $book->author_name, |
81
|
|
|
'email' => $book->author_email |
82
|
|
|
] |
83
|
|
|
]; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|
Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.