Function getSubCategory

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 10/10/18 01:35

@param        $list_category
@param null   $current_parent
@param int    $parent_id
@param string $char
498608
public function getSubCategory($list_category, $current_parent = NULL, $parent_id = 0, $char = '')
    {
        if (count($list_category) > 0) {
            foreach ($list_category as $key => $category) {
                if ($category->parent == $parent_id) {
                    $selected = $current_parent == $category->id ? 'selected' : '';
                    echo '<option ' . $selected . ' value="' . $category->id . '">' . $char . ' ' . $category->name . '</option>';
                    unset($list_category[$key]);
                    self::getSubCategory($list_category, $current_parent, $category->id, $char . '----');
                }
            }
        }
    }
999650
protected function retrieveCategoryFromQueryString()
    {
        $request = $this->getCurrentRequest();
        $categoryId = $request->get('category_id');
        $categorySlug = $request->get('category_slug');

        if (!$categoryId || !$categorySlug) {
            return null;
        }

        return $this->getCategoryManager()->findOneBy([
            'id' => $categoryId,
            'enabled' => true,
        ]);
    }
1165096
protected function getChildrenCategoryList($obCategoryItem, $sPageCode, $sURL)
    {
        if (empty($obCategoryItem) || $obCategoryItem->children->isEmpty()) {
            return [];
        }

        $arResult = [];
        foreach ($obCategoryItem->children as $obChildrenCategory) {
            $arMenuItem = $this->getCategoryMenuData($obChildrenCategory, $sPageCode, $sURL);
            if ($obChildrenCategory->children->isNotEmpty()) {
                $arMenuItem['items'] = $this->getChildrenCategoryList($obChildrenCategory, $sPageCode, $sURL);
            }

            $arResult[] = $arMenuItem;
        }

        return $arResult;
    }
4407
public function update_category($updateid, $newparent, $newname, $newinfo, $newinfoformat = FORMAT_HTML,
            $idnumber = null, $redirect = true) {
        global $CFG, $DB;
        if (empty($newname)) {
            print_error('categorynamecantbeblank', 'question');
        }

        // Get the record we are updating.
        $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
        $lastcategoryinthiscontext = question_is_only_child_of_top_category_in_context($updateid);

        if (!empty($newparent) && !$lastcategoryinthiscontext) {
            list($parentid, $tocontextid) = explode(',', $newparent);
        } else {
            $parentid = $oldcat->parent;
            $tocontextid = $oldcat->contextid;
        }

        // Check permissions.
        $fromcontext = context::instance_by_id($oldcat->contextid);
        require_capability('moodle/question:managecategory', $fromcontext);

        // If moving to another context, check permissions some more, and confirm contextid,stamp uniqueness.
        $newstamprequired = false;
        if ($oldcat->contextid != $tocontextid) {
            $tocontext = context::instance_by_id($tocontextid);
            require_capability('moodle/question:managecategory', $tocontext);

            // Confirm stamp uniqueness in the new context. If the stamp already exists, generate a new one.
            if ($DB->record_exists('question_categories', array('contextid' => $tocontextid, 'stamp' => $oldcat->stamp))) {
                $newstamprequired = true;
            }
        }

        if ((string) $idnumber === '') {
            $idnumber = null;
        } else if (!empty($tocontextid)) {
            // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
            if ($DB->record_exists('question_categories',
                    ['idnumber' => $idnumber, 'contextid' => $tocontextid])) {
                $idnumber = null;
            }
        }

        // Update the category record.
        $cat = new stdClass();
        $cat->id = $updateid;
        $cat->name = $newname;
        $cat->info = $newinfo;
        $cat->infoformat = $newinfoformat;
        $cat->parent = $parentid;
        $cat->contextid = $tocontextid;
        if ($idnumber) {
            $cat->idnumber = $idnumber;
        }
        if ($newstamprequired) {
            $cat->stamp = make_unique_id_code();
        }
        $DB->update_record('question_categories', $cat);

        // Log the update of this category.
        $event = \core\event\question_category_updated::create_from_question_category_instance($cat);
        $event->trigger();

        // If the category name has changed, rename any random questions in that category.
        if ($oldcat->name != $cat->name) {
            $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";

            $randomqtype = question_bank::get_qtype('random');
            $randomqname = $randomqtype->question_name($cat, false);
            $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));

            $randomqname = $randomqtype->question_name($cat, true);
            $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
        }

        if ($oldcat->contextid != $tocontextid) {
            // Moving to a new context. Must move files belonging to questions.
            question_move_category_to_context($cat->id, $oldcat->contextid, $tocontextid);
        }

        // Cat param depends on the context id, so update it.
        $this->pageurl->param('cat', $updateid . ',' . $tocontextid);
        if ($redirect) {
            redirect($this->pageurl); // Always redirect after successful action.
        }
    }
943693
public function category_listing(core_course_category $category = null) {

        if ($category === null) {
            $selectedparents = array();
            $selectedcategory = null;
        } else {
            $selectedparents = $category->get_parents();
            $selectedparents[] = $category->id;
            $selectedcategory = $category->id;
        }
        $catatlevel = \core_course\management\helper::get_expanded_categories('');
        $catatlevel[] = array_shift($selectedparents);
        $catatlevel = array_unique($catatlevel);

        $listing = core_course_category::top()->get_children();

        $attributes = array(
                'class' => 'ml-1 list-unstyled',
                'role' => 'tree',
                'aria-labelledby' => 'category-listing-title'
        );

        $html  = html_writer::start_div('category-listing card w-100');
        $html .= html_writer::tag('h3', get_string('categories'),
                array('class' => 'card-header', 'id' => 'category-listing-title'));
        $html .= html_writer::start_div('card-body');
        $html .= $this->category_listing_actions($category);
        $html .= html_writer::start_tag('ul', $attributes);
        foreach ($listing as $listitem) {
            // Render each category in the listing.
            $subcategories = array();
            if (in_array($listitem->id, $catatlevel)) {
                $subcategories = $listitem->get_children();
            }
            $html .= $this->category_listitem(
                    $listitem,
                    $subcategories,
                    $listitem->get_children_count(),
                    $selectedcategory,
                    $selectedparents
            );
        }
        $html .= html_writer::end_tag('ul');
        $html .= $this->category_bulk_actions($category);
        $html .= html_writer::end_div();
        $html .= html_writer::end_div();
        return $html;
    }
1170904
private function add_to_parent_category_branch($category, $newnode, &$categoriesbranch) {

        foreach ($categoriesbranch as $key => $branch) {
            if (!empty($branch['categoryid']) && $branch['categoryid'] == $category->parent) {
                // It may be empty (if it does not contain courses and this is the first child cat).
                if (!isset($categoriesbranch[$key]['branches'])) {
                    $categoriesbranch[$key]['branches'] = [];
                }
                $categoriesbranch[$key]['branches'][] = $newnode;
                return true;
            }
            if (!empty($branch['branches'])) {
                $parent = $this->add_to_parent_category_branch($category, $newnode, $categoriesbranch[$key]['branches']);
                if ($parent) {
                    return true;
                }
            }
        }

        return false;
    }
1256094
public function &GetParent()
    {
        $oParent = null;
        if (!empty($this->fieldShopCategoryId)) {
            $oParent = TdbShopCategory::GetNewInstance();
            $oParent->SetLanguage($this->iLanguageId);
            if (!$oParent->Load($this->fieldShopCategoryId)) {
                $oParent = null;
            }
        }

        return $oParent;
    }
1337960
public function findChildrenByParentId($parent_id)
    {
        $qb = $this->createQueryBuilder();
        $qb->andWhere($qb->getRootAliases()[0] . '.parent = ' . $this->addNamedParameter('parent', $parent_id, $qb))
            ->orderBy($qb->getRootAliases()[0] . '.position', 'ASC');
        return $qb->getQuery()->getResult();
    }
696899
public function getRoot($parentNodeCategory = null, $recursionLevel = 3)
    {
        if ($parentNodeCategory === null) {
            if ($this->getCurrentCategoryId()) {
                $this->getRootByIds([$this->getCurrentCategoryId()]);
            }
        }

        return parent::getRoot($parentNodeCategory, $recursionLevel);
    }
635215
public function getAvailableParentCategoriesQueryBuilder($categoryId = null)
    {
        $queryBuilder = $this
            ->createQueryBuilder('c')
            ->where('c.root = 1');

        if (null !== $categoryId) {
            $queryBuilder
                ->andWhere('c.id <> :parent_category')
                ->setParameter('parent_category', $categoryId);
        }

        return $queryBuilder;
    }
371401
public static function GetAncestors($CategoryID, $CheckPermissions = TRUE) {
      $Categories = self::Categories();
      $Result = array();
      
      // Grab the category by ID or url code.
      if (is_numeric($CategoryID)) {
         if (isset($Categories[$CategoryID]))
            $Category = $Categories[$CategoryID];
      } else {
         foreach ($Categories as $ID => $Value) {
            if ($Value['UrlCode'] == $CategoryID) {
               $Category = $Categories[$ID];
               break;
            }
         }
      }

      if (!isset($Category))
         return $Result;

      // Build up the ancestor array by tracing back through parents.
      $Result[$Category['CategoryID']] = $Category;
      $Max = 20;
      while (isset($Categories[$Category['ParentCategoryID']])) {
         // Check for an infinite loop.
         if ($Max <= 0)
            break;
         $Max--;
         
         if ($CheckPermissions && !$Category['PermsDiscussionsView']) {
            $Category = $Categories[$Category['ParentCategoryID']];
            continue;
         }
         
         if ($Category['CategoryID'] == -1)
            break;

         // Return by ID or code.
         if (is_numeric($CategoryID))
            $ID = $Category['CategoryID'];
         else
            $ID = $Category['UrlCode'];

         $Result[$ID] = $Category;

         $Category = $Categories[$Category['ParentCategoryID']];
      }
      $Result = array_reverse($Result, TRUE); // order for breadcrumbs
      return $Result;
   }
172892
public function findRelatedEntries($entry_id, $parent_field_id)
    {
        // We have the entry_id of the entry that has the referenced tag values
        // Lets find out what those handles are so we can then referenced the
        // child section looking for them.
        $handles = Symphony::Database()->fetchCol('handle', sprintf("
            SELECT `handle`
            FROM `tbl_entries_data_%d`
            WHERE `entry_id` = %d
        ", $parent_field_id, $entry_id));

        $ids = Symphony::Database()->fetchCol('entry_id', sprintf("
            SELECT `entry_id`
            FROM `tbl_entries_data_%d`
            WHERE `handle` IN ('%s')
        ", $this->get('id'), implode("','", $handles)));

        return $ids;
    }
933408
private function processCategory(array $element, $parent = null)
    {
        if ($this->isMasterCategory($element)) {
            $this->createCategory($element, MasterCategoryElement::class, $this->parseResult);
        }

        if ($this->isResourceGroup($element)) {
            $this->createCategory($element, ResourceGroupElement::class, $parent);
        }

        if ($this->isDataStructureCategory($element)) {
            $this->createCategory($element, DataStructureCategoryElement::class, $parent);
        }
    }
462866
public function load_parent_category() {
        if (empty($this->parent_category->id)) {
            $this->parent_category = $this->get_parent_category();
        }
        return $this->parent_category;
    }
439642
protected function getChildrenCategories()
    {
        if ($this->childrenCategories === null) {
            $currentCategory = $this->dataProvider->getCategory();
            $this->childrenCategories = $currentCategory->getChildrenCategories();
        }

        return $this->childrenCategories;
    }
439352
protected function parentInList($parentId, $list)
    {
        foreach ($list as $node) {
            if ($parentId === $node->getNodeId()) {
                return true;
            }
        }

        return false;
    }
1036321
private function recursiveSync(int $parentCategoryNumber = null, int $level = 1)
    {
        if ($parentCategoryNumber) {
            $categories = \GuzzleHttp\json_decode($this->api->productData->getDataSubCategories($parentCategoryNumber)->getBody()->getContents());
        } else {
            $categories = \GuzzleHttp\json_decode($this->api->productData->getDataCategories()->getBody()->getContents());
        }

        foreach ($categories as $category) {
            $entity = $this->categoryUpdater->updateFromApiResponse(DandomainFoundation\objectToArray($category));
            $this->logger->info(str_repeat('  ', $level - 1).'- '.$entity->getNumber());
            $this->repository->save($entity);
            $this->recursiveSync((int) $category->number, $level + 1);
        }
    }