@param HasResourceContext $object
@param string $context_relation_name
@param string $context_name

@return HasResourceContext
13021
public function addContextRelationToObject($object, $context_name = 'default')
    {
        $context = $this->findContext($context_name);

        $object->setContext($context);

        return $object;
    }
157438
public function hasOne($entity, string $related, string $foreignKey = null, string $localKey = null): HasOne
    {
        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $relatedMapper = Manager::getInstance()->mapper($related);

        $relatedMap = $relatedMapper->getEntityMap();

        $localKey = $localKey ?: $this->getKeyName();

        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addSingleRelation($relation);
        $this->addForeignRelation($relation);
        $this->addNonProxyRelation($relation);

        // This relationship will always be eager loaded, as proxying it would
        // mean having an object that doesn't actually exists.
        if (!in_array($relation, $this->with)) {
            $this->with[] = $relation;
        }

        return new HasOne($relatedMapper, $entity, /*$relatedMap->getTable().'.'*/$foreignKey, $localKey);
    }
44187
public static function useConnection($connection_name='', $db = null) {
        if(!$connection_name){
            $connection_name=Connection::class;
        }
        CoContext::getContext()->set(CoContext::CONNECTION_NAME, $connection_name);
        if ($db) {
            CoContext::getContext()->set(CoContext::CONNECTION_scheme, $db);
        }
    }
1120507
public function fromResource($object, ResourceObject $resource)
    {
        $context = $this->createContext(get_class($object));

        $this->identifierHandler->setIdentifier($object, $resource->getId(), $context);

        foreach ($this->handlers as $handler)
        {
            $handler->fromResource($object, $resource, $context);
        }
    }
157214
public function withContext(RelationContext $source, RelationContext $target = null): self
    {
        $definition = clone $this;
        $definition->sourceContext = $source;
        $definition->targetContext = $target;

        return $definition;
    }
120930
public function normalize($object, $format = null, array $context = [])
    {
        $this->maxDepthHandler->handleMaxDepth($context);

        if ($this->byReferenceHandler->isByShortReference($context)) {
            return $this->getShortReference($object, $format, $context);
        }

        if ($this->byReferenceHandler->isByReference($context)) {
            return $this->getReference($object, $format, $context);
        }

        try {
            return parent::normalize($object, $format, $context);
        } catch (CircularReferenceException $e) {
            return $this->getShortReference($object, $format, $context);
        }
    }
1279242
public function deleteContext($context) {
        global $DB;

        $contextid = $context->getRecordId();

        $params = ['id' => $contextid];

        // Delete any outstanding share keys for resource links for this context.
        $where = "resourcelinkid IN (
                    SELECT rl.id
                      FROM {{$this->resourcelinktable}} rl
                     WHERE rl.contextid = :id
               )";
        $DB->delete_records_select($this->sharekeytable, $where, $params);

        // Delete any users in resource links for this context.
        $DB->delete_records_select($this->userresulttable, $where, $params);

        // Update any resource links for which this consumer is acting as a primary resource link.
        $where = "primaryresourcelinkid IN (
                    SELECT rl.id
                      FROM {{$this->resourcelinktable}} rl
                     WHERE rl.contextid = :id
               )";
        $updaterecords = $DB->get_records_select($this->resourcelinktable, $where, $params);
        foreach ($updaterecords as $record) {
            $record->primaryresourcelinkid = null;
            $record->shareapproved = null;
            $DB->update_record($this->resourcelinktable, $record);
        }

        // Delete any resource links for this context.
        $DB->delete_records($this->resourcelinktable, ['contextid' => $contextid]);

        // Delete context.
        $DB->delete_records($this->contexttable, $params);

        $context->initialize();

        return true;
    }
380918
public function setRelationValue($object, $relationName, $value)
    {
        $this->assertObjectInstance($object);

        $relation = $this->getRelation($relationName);

        $relationData = $relation->getForeignKeyValue($value);
        $state        = $this->getState($object);
        $state->setRelationForeignKeys($relationName, $relationData);
        $state->setRelationLoaded($relationName);

        return $relation->set($object, $value);
    }
1144871
public function addContextFilterToQueryBuilder($queryBuilder, $context_relation_name = 'context', $context_name = 'default')
    {
        $context = $this->findContext($context_name);

        $queryBuilder->andWhere(
            $queryBuilder->getRootAliases()[0] . '.' . $context_relation_name
            . '=' .
            $this->addNamedParameter($context_relation_name, $context->getId(), $queryBuilder, null)
        );

        return $queryBuilder;
    }
677180
public function normalize($object, $format = null, array $context = []): array
    {
        if (!$object instanceof RelationCollection && !$object instanceof ActionCollection) {
            throw new \InvalidArgumentException(sprintf(
                'The normalizer support only "%s" or "%s" but "%s" given.',
                RelationCollection::class,
                ActionCollection::class,
                is_object($object) ? get_class($object) : gettype($object)
            ));
        }

        $data = [];

        foreach ($object as $relation) {
            $data[$relation->getName()] = $this->normalizer->normalize($relation, $format);
        }

        return $data;
    }
1338783
public function withContext(
        RecordInterface $parent,
        bool $loaded = false,
        array $data = null
    ): RelationInterface {
        $relation = parent::withContext($parent, $loaded, $data);

        /** @var self $relation */
        return $relation->initInstances();
    }
32986
public function validate($object, ValidatorContextInterface $context = null, string $path = '')
    {
        $context = $context ?? ValidatorContextBuilder::create()->getContext();

        $class = is_object($object) ? get_class($object) : $object;

        $objectMapping = $this->getObjectMapping($class);

        $errors = [];
        foreach ($this->validateClass(
            $context,
            $objectMapping->getValidationClassMapping($path),
            $path,
            $object
        ) as $classError) {
            $errors[] = $classError;
        }

        foreach ($objectMapping->getValidationPropertyMappings($path) as $propertyMapping) {
            foreach ($this->validateProperty($context, $propertyMapping, $path, $object) as $propertyError) {
                $errors[] = $propertyError;
            }
        }

        return $errors;
    }
1184816
public function resolve($object, array $args, $context, ResolveInfo $info)
    {
        // Get the args
        $id = $args['ID'];
        $rollbackVersion = $args['ToVersion'];

        // Pull the latest version of the record
        /** @var Versioned|DataObject $record */
        $record = Versioned::get_latest_version($this->getDataObjectClass(), $id);

        // Assert permission
        $user = $context['currentUser'];
        if (!$record->canEdit($user)) {
            throw new InvalidArgumentException('Current user does not have permission to roll back this resource');
        }

        // Perform the rollback
        $record = $record->rollbackRecursive($rollbackVersion);

        return $record;
    }
41638
protected static function reqGetResourceRelationships(ContextInterface $context): array
    {
        assert(static::reqHasResourceRelationships($context));

        $value = $context->getRequest()->get(RequestProperties::REQ_RESOURCE_RELATIONSHIPS);

        assert(is_array($value));

        return $value;
    }
689131
protected function isCircularReference($object, &$context)
    {
        $objectHash = spl_object_hash($object);

        $circularReferenceLimit = $context[self::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[self::CIRCULAR_REFERENCE_LIMIT] ?? $this->circularReferenceLimit;
        if (isset($context[self::CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash])) {
            if ($context[self::CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] >= $circularReferenceLimit) {
                unset($context[self::CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash]);

                return true;
            }

            ++$context[self::CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash];
        } else {
            $context[self::CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] = 1;
        }

        return false;
    }
423310
public static function getRelationFieldNames($object)
    {
        $class = BeanFactory::getObjectClass($object);
        if(!isset(static::$relationFieldsNames[$class]))
        {
            $relations = AnnotationManager::getPropertiesAnnotations($class, RelationBase::class);
            $result = array_keys($relations);
            foreach($relations as $annotations)
            {
                $annotation = $annotations[0];
                if(($annotation instanceof ManyToMany || $annotation instanceof PolymorphicManyToMany) && $annotation->rightMany)
                {
                    $result[] = $annotation->rightMany;
                }
            }
            static::$relationFieldsNames[$class] = $result;
        }
        return static::$relationFieldsNames[$class];
    }
208735
public function normalize($object, $format = null, array $context = [])
    {
        if (!$object instanceof ResourceCollection) {
            throw new \InvalidArgumentException(sprintf(
                'The normalizer support only "%s" but "%s" given.',
                ResourceCollection::class,
                is_object($object) ? get_class($object) : gettype($object)
            ));
        }

        $data = [];
        $links = [];

        if (count($object->getRelations())) {
            $links = array_merge($links, $this->normalizer->normalize($object->getRelations(), $format, $context));
        }

        if (count($object->getActions())) {
            $links = array_merge($links, $this->normalizer->normalize($object->getActions(), $format, $context));
        }

        foreach ($object as $resource) {
            $data[] = $this->normalizer->normalize($resource, $format, $context);
        }

        if (count($links)) {
            return [
                '_links' => $links,
                '_embedded' => [
                    'items' => $data,
                ],
            ];
        }

        return $data;
    }