/** * @param $data * @param null|ShopCategory $parent */ public function importCategories($data, $parent = null) { foreach ($data->{"Группа"} as $category) { // Find category by external id $model = C1ExternalFinder::getObject(C1ExternalFinder::OBJECT_TYPE_CATEGORY, $category->{"Ид"}); if (!$model) { $model = new ShopCategory(); $model->name = $category->{"Наименование"}; $model->seo_alias = CMS::translit($category->{"Наименование"}); $model->appendTo($this->getRootCategory()); $this->createExternalId(C1ExternalFinder::OBJECT_TYPE_CATEGORY, $model->id, $category->{"Ид"}); } if ($parent === null) { $model->moveAsLast($this->getRootCategory()); } else { $model->moveAsLast($parent); } $model->saveNode(); // Process subcategories if (isset($category->{"Группы"})) { $this->importCategories($category->{"Группы"}, $model); } } }
/** * Get category id by path. If category not exits it will new one. * @param $path string Main/Music/Rock * @return integer category id */ protected function getCategoryByPath($path) { if (isset($this->categoriesPathCache[$path])) { return $this->categoriesPathCache[$path]; } if ($this->rootCategory === null) { $this->rootCategory = ShopCategory::model()->findByPk(1); } $result = preg_split($this->subCategoryPattern, $path, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $result = array_map('stripcslashes', $result); $parent = $this->rootCategory; $level = 2; // Level 1 is only root foreach ($result as $name) { $cr = new CDbCriteria(); $cr->with = array('cat_translate'); $cr->compare('cat_translate.name', $name); $model = ShopCategory::model()->find($cr); if (!$model) { $model = new ShopCategory(); $model->name = $name; $model->appendTo($parent); } $parent = $model; $level++; } // Cache category id $this->categoriesPathCache[$path] = $model->id; if (isset($model)) { return $model->id; } return 1; // root category }