/** * Save category relationships * * @param AbstractController $controller * @param Application $application * @return void */ public static function save(AbstractController $controller, Application $application) { $type = null; $contentId = null; if ($_POST && $controller->hasView() && null !== $controller->view()->id && null !== $controller->view()->form && $controller->view()->form instanceof \Pop\Form\Form) { $categories = $controller->view()->form->categories; $type = $controller->view()->form->category_type; $contentId = $controller->view()->id; // Clear categories if (null !== $type && null !== $contentId) { if (!is_array($contentId)) { $contentId = [$contentId]; } foreach ($contentId as $id) { $itemId = $type == 'media' ? 'media_id' : 'content_id'; $c2c = new Table\CategoryItems(); $c2c->delete([$itemId => $id]); } if (is_array($categories) && count($categories) > 0) { foreach ($categories as $category) { foreach ($contentId as $id) { if ($type == 'media') { $fields = ['category_id' => $category, 'content_id' => null, 'media_id' => $id, 'order' => (int) $_POST['category_order_' . $category]]; } else { $fields = ['category_id' => $category, 'content_id' => $id, 'media_id' => null, 'order' => (int) $_POST['category_order_' . $category]]; } $catItem = new Table\CategoryItems($fields); $catItem->save(); } } } } } }
/** * Get category children * * @param \ArrayObject|array $category * @param string $order * @param int $depth * @return array */ protected function getChildren($category, $order, $depth = 0) { $children = []; $child = Table\Categories::findBy(['parent_id' => $category->id], ['order' => $order]); if ($child->hasRows()) { foreach ($child->rows() as $c) { $this->flatMap[] = new \ArrayObject(['id' => $c->id, 'title' => $c->title, 'uri' => $c->uri, 'total' => Table\CategoryItems::findBy(['category_id' => $c->id])->count(), 'order' => $c->order, 'depth' => $depth + 1], \ArrayObject::ARRAY_AS_PROPS); $c->depth = $depth + 1; $c->children = $this->getChildren($c, $order, $depth + 1); $children[] = $c; } } return $children; }
/** * JSON action method * * @param int $id * @param string $type * @return void */ public function json($id, $type = null) { $json = []; if (null !== $type) { $findBy = $type == 'media' ? ['content_id' => null, 'media_id' => $id] : ['content_id' => $id, 'media_id' => null]; $catItems = Table\CategoryItems::findBy($findBy); foreach ($catItems->rows() as $c) { if ($c->order > 0) { $json['category_order_' . $c->category_id] = $c->order; } } } else { $json['parent_uri'] = ''; $content = Table\Categories::findById($id); if (isset($content->id)) { $json['parent_uri'] = $content->uri; } } $this->response->setBody(json_encode($json, JSON_PRETTY_PRINT)); $this->send(200, ['Content-Type' => 'application/json']); }