11<?php namespace web \rest \unittest ;
22
3+ use ArrayIterator , Iterator , IteratorAggregate ;
34use test \{Assert , Expect , Ignore , Test , Values };
45use web \Error ;
5- use web \rest \format \Json ;
6+ use web \rest \format \{ Json , EntityFormat } ;
67use web \rest \unittest \api \{Monitoring , Users };
78use web \rest \{MethodsIn , ResourcesIn , RestApi };
89
@@ -233,4 +234,36 @@ public function accept_json_returns_json() {
233234 public function does_not_accept ($ mime ) {
234235 $ this ->run (new RestApi (new Users ()), 'GET ' , '/users/1549 ' , ['Accept ' => $ mime ]);
235236 }
237+
238+ #[Test]
239+ public function register_csv_as_output_format () {
240+ $ api = (new RestApi (new Users ()))->register ('text/csv ' , new class () extends EntityFormat {
241+ public function mimeType () { return 'text/csv; charset=utf-8 ' ; }
242+ public function read ($ request , $ name ) { return null ; }
243+ public function write ($ response , $ value ) {
244+ if ($ value instanceof Iterator) {
245+ $ it = $ value ;
246+ } else if ($ value instanceof IteratorAggregate) {
247+ $ it = $ value ->getIterator ();
248+ } else {
249+ $ it = new ArrayIterator ((array )$ value );
250+ }
251+
252+ // Incomplete CSV implementation - for test purposes only!
253+ $ out = $ response ->stream ();
254+ $ record = $ it ->current ();
255+ $ out ->write (implode ('; ' , array_keys ($ record ))."\n" );
256+ do {
257+ $ out ->write (implode ('; ' , $ record )."\n" );
258+ $ it ->next ();
259+ $ record = $ it ->current ();
260+ } while ($ it ->valid ());
261+
262+ $ out ->close ();
263+ }
264+ });
265+
266+ $ res = $ this ->run ($ api , 'GET ' , '/users?select=thekid ' , ['Accept ' => 'text/csv ' ]);
267+ $ this ->assertPayload (200 , 'text/csv; charset=utf-8 ' , "id;handle;name \n1549;thekid;Timm \n" , $ res );
268+ }
236269}
0 commit comments