/** * Returns a JSON feed of gallery items. * * @param string $id The gallery id or URL * @return string The gallery in JSON format */ public function feed($id = null) { $response = array('success' => true); if (empty($id)) { $response['success'] = false; } // Check to ensure that JSON was used to make the POST request if (!$this->request->is('json')) { $response['success'] = false; } if (preg_match('/[0-9a-f]{24}/', $id)) { $field = '_id'; } else { $field = 'url'; } if ($response['success'] === true) { // Find the gallery document itself (by _id or url) $document = Page::find('first', array('conditions' => array($field => $id, 'published' => true))); if (empty($document)) { $response['success'] = false; } if ($response['success'] === true) { // Find all items for the current gallery $gallery_items = Item::find('all', array('conditions' => array('_galleries' => (string) $document->_id))); // Order those gallery items based on the gallery document's gallery_item_order field (if set) if (isset($document->gallery_item_order) && !empty($document->gallery_item_order)) { // This sort() method is the awesome. $ordering = $document->gallery_item_order->data(); // data() must be called so that the iterator loads up all the documents... // Something that has to be fixed I guess. Then data() doesn't need to be called. $gallery_items->data(); $gallery_items->sort(function ($a, $b) use($ordering) { if ($a['_id'] == $b['_id']) { return strcmp($a['_id'], $b['_id']); } $cmpa = array_search($a['_id'], $ordering); $cmpb = array_search($b['_id'], $ordering); return $cmpa > $cmpb ? 1 : -1; }); } $response['gallery'] = $document->data(); $response['items'] = $gallery_items->data(); } } $this->render(array('json' => $response)); }