media.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2010, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. /**
  9. * The `Collection` class, which serves as the base class for some of Lithium's data objects
  10. * (`RecordSet` and `Document`) provides a way to manage data collections in a very flexible and
  11. * intuitive way, using closures and SPL interfaces. The `to()` method allows a `Collection` (or
  12. * subclass) to be converted to another format, such as an array. The `Collection` class also allows
  13. * other classes to be connected as handlers to convert `Collection` objects to other formats.
  14. *
  15. * The following connects the `Media` class as a format handler, which allows `Collection`s to be
  16. * exported to any format with a handler provided by `Media`, i.e. JSON. This enables things like
  17. * the following:
  18. * {{{
  19. * $posts = Post::find('all');
  20. * return $posts->to('json');
  21. * }}}
  22. */
  23. use lithium\util\Collection;
  24. Collection::formats('lithium\net\http\Media');
  25. /**
  26. * This filter is a convenience method which allows you to automatically route requests for static
  27. * assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the
  28. * `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js`
  29. * will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem.
  30. * In production, it is recommended that you disable this filter in favor of symlinking each
  31. * plugin's `webroot` directory into your main application's `webroot` directory, or adding routing
  32. * rules in your web server's configuration.
  33. */
  34. use lithium\action\Dispatcher;
  35. use lithium\action\Response;
  36. use lithium\net\http\Media;
  37. Dispatcher::applyFilter('_callable', function($self, $params, $chain) {
  38. list($library, $asset) = explode('/', $params['request']->url, 2) + array("", "");
  39. if ($asset && ($path = Media::webroot($library)) && file_exists($file = "{$path}/{$asset}")) {
  40. return function() use ($file) {
  41. $info = pathinfo($file);
  42. $media = Media::type($info['extension']);
  43. $content = (array) $media['content'];
  44. return new Response(array(
  45. 'headers' => array('Content-type' => reset($content)),
  46. 'body' => file_get_contents($file)
  47. ));
  48. };
  49. }
  50. return $chain->next($self, $params, $chain);
  51. });
  52. Media::type('jpg', 'image/jpeg', array('cast' => false, 'encode' => function($data) {
  53. return $data['photo']->file->getBytes();
  54. }));
  55. ?>