/** * Transform the value in a MongoDBRef if needed * @param $attr * @param $value * @return mixed */ protected function _val($attr, $value) { $reference = \Rocketr\Schema\Reference::get($this->get_collection_name(), $attr); $collection = \Rocketr\Schema\HasCollection::get($this->get_collection_name(), $attr); if ($reference xor $collection) { $ref_attr = \Rocketr\Schema\Map::on($this->get_collection_name(), $attr); $_id = is_array($value) && isset($value[$ref_attr]) || is_object($value) && $value->{$ref_attr} ? is_array($value) ? $value[$ref_attr] : $value->{$ref_attr} : $value; $target = $reference ? $reference : $collection; $_id = $ref_attr == '_id' && \MongoId::isValid($_id) ? new \MongoId($_id) : $_id; return \MongoDBRef::create($target, $_id); } else { return $value; } }
/** * Use Reference defined in Schema to resolve... well, belongs to, ascendent, reference, many to one, whatever you * call it kind of relation. * * @param $criterion * @param $sub_queries * @param $val * @return array */ private function _run_ascendant_queries($criterion, $sub_queries, $val) { $has_error = false; $last_key = array_pop($sub_queries); $collections = []; $collections[] = $this->get_collection_name(); $i = 1; foreach ($sub_queries as $attr) { $sub_collection = \Rocketr\Schema\Reference::get($collections[$i - 1], $attr); $collections[] = $sub_collection; $i++; } array_shift($collections); $references_ids = []; $d = count($collections); for ($d; $d > 0; $d--) { if ($d === count($sub_queries)) { $condition = $this->_attribute_criteria($criterion, $last_key, $val); } else { $condition = $this->_attribute_criteria('IN', $sub_queries[$d] . '.$id', $references_ids); } if ($collections[$d - 1]) { $ref_attr = \Rocketr\Schema\Reference::on($collections[$d - 1], $sub_queries[$d]); $result = $this->_run_sub_query($collections[$d - 1], $condition, $ref_attr); $references_ids = $this->_make_references_ids($result, $ref_attr); unset($result); } else { $has_error = true; break; //TODO : Exeption Missing reference declaration for implode('.', $sub_queries) . $criterion . $val; } } return !$has_error ? $references_ids : []; }