1 | <?php |
---|
2 | |
---|
3 | /** |
---|
4 | * Collection resource |
---|
5 | * @namespace Tonic\Examples\Filesystem |
---|
6 | * @uri /filesystem/collection |
---|
7 | */ |
---|
8 | class FilesystemCollection extends FilesystemResource { |
---|
9 | |
---|
10 | /** |
---|
11 | * Path to the collections files |
---|
12 | * @var str |
---|
13 | */ |
---|
14 | var $collection; |
---|
15 | |
---|
16 | function __construct($parameters) { |
---|
17 | parent::__construct($parameters); |
---|
18 | $this->collection = dirname(__FILE__).'/representations/collection'; |
---|
19 | } |
---|
20 | |
---|
21 | /** |
---|
22 | * Handle a GET request |
---|
23 | * @param Request request |
---|
24 | * @return Response |
---|
25 | */ |
---|
26 | function get($request) { |
---|
27 | |
---|
28 | $response = new Response($request); |
---|
29 | $collection = str_replace('/', DIRECTORY_SEPARATOR, $this->collection); |
---|
30 | |
---|
31 | $resourceUris = ''; |
---|
32 | $files = glob($collection.DIRECTORY_SEPARATOR.'*'); |
---|
33 | if ($files) { |
---|
34 | foreach ($files as $filepath) { |
---|
35 | $filepath = str_replace(DIRECTORY_SEPARATOR, '/', $filepath); |
---|
36 | $resourceUris .= '<li><a href="'.$this->turnFilePathIntoUri($filepath, $request).'">'.basename($filepath).'</a></li>'; |
---|
37 | } |
---|
38 | } else { |
---|
39 | $resourceUris .= '<li>Empty collection</li>'; |
---|
40 | } |
---|
41 | |
---|
42 | $response->body = '<ul>'.$resourceUris.'</ul>'; |
---|
43 | |
---|
44 | return $response; |
---|
45 | |
---|
46 | } |
---|
47 | |
---|
48 | protected function getNextAvailableItemUri() { |
---|
49 | $collection = str_replace('/', DIRECTORY_SEPARATOR, $this->collection); |
---|
50 | $filename = 1; |
---|
51 | while (file_exists($collection.DIRECTORY_SEPARATOR.$filename)) { |
---|
52 | $filename++; |
---|
53 | } |
---|
54 | return $this->uriStub.substr($this->collection, strlen($this->path)).'/'.$filename; |
---|
55 | } |
---|
56 | |
---|
57 | function post($request) { |
---|
58 | |
---|
59 | $response = new Response($request); |
---|
60 | |
---|
61 | if ($request->data) { |
---|
62 | $uri = $this->getNextAvailableItemUri(); |
---|
63 | $filePath = $this->turnUriIntoFilePath($uri, $request); |
---|
64 | if (file_put_contents($filePath, $request->data)) { |
---|
65 | $response->code = Response::CREATED; |
---|
66 | $response->addHeader('Location', $uri); |
---|
67 | } else { |
---|
68 | $response->code = Response::INTERNALSERVERERROR; |
---|
69 | } |
---|
70 | } else { |
---|
71 | $response->code = Response::LENGTHREQUIRED; |
---|
72 | } |
---|
73 | |
---|
74 | return $response; |
---|
75 | |
---|
76 | } |
---|
77 | |
---|
78 | } |
---|
79 | |
---|