Create a schema array for one-to-one and many-to-one associations

@param $sourceAssociation
@return ForestField
509870
protected function getFieldForToOneAssociation($sourceAssociation)
    {
        $targetClassMetadata = $this->getClassMetadata($sourceAssociation['targetEntity']);
        $joinedColumn = reset($sourceAssociation['joinColumns']);

        if (!$joinedColumn) {
            // One-to-One referenced only in foreign table => do not create field
            return null;
        }

        $type = $this->getTypeForAssociation($sourceAssociation);

        $fieldName = $sourceAssociation['fieldName'];

        $inverseOf = $sourceAssociation['inversedBy'];

        $foreignTableName = $targetClassMetadata->getTableName();
        $foreignIdentifier = $targetClassMetadata->getIdentifier();
        //if(count($foreignIdentifier) > 1) die(__METHOD__.'::'.__LINE__.': '.$foreignTableName.' has more than one identifier : '.json_encode($foreignIdentifier));
        $foreignIdentifier = reset($foreignIdentifier);
        $reference = $foreignTableName . '.' . $foreignIdentifier;

        // $pivot is just the foreign key in current table
        $pivot = new Pivot($joinedColumn['name']);

        return new ForestField($fieldName, $type, $reference, $inverseOf, $pivot);
    }
1171513
protected function generateAssociation()
    {
        $this->assoc = array();
        # We use sha1 by default.
        $this->assoc['hash']   = 'sha1';
        $this->assoc['mac']    = $this->shared_secret('sha1');
        $this->assoc['handle'] = $this->assoc_handle();
    }
762950
protected function _scaffoldFields(array $associations = [])
    {
        $action = $this->_action();
        $scaffoldFields = (array)$action->getConfig('scaffold.fields');
        if (!empty($scaffoldFields)) {
            $scaffoldFields = Hash::normalize($scaffoldFields);
        }

        if (empty($scaffoldFields) || $action->getConfig('scaffold.autoFields')) {
            $cols = $this->_table()->getSchema()->columns();
            $cols = Hash::normalize($cols);

            $scope = $action->getConfig('scope');
            if ($scope === 'entity' && !empty($associations['manyToMany'])) {
                foreach ($associations['manyToMany'] as $alias => $options) {
                    $cols[sprintf('%s._ids', $options['entities'])] = [
                        'multiple' => true
                    ];
                }
            }

            $scaffoldFields = array_merge($cols, $scaffoldFields);
        }

        // Check for blacklisted fields
        $blacklist = $action->getConfig('scaffold.fields_blacklist');
        if (!empty($blacklist)) {
            $scaffoldFields = array_diff_key($scaffoldFields, array_combine($blacklist, $blacklist));
        }

        // Make sure all array values are an array
        foreach ($scaffoldFields as $field => $options) {
            if (!is_array($options)) {
                $scaffoldFields[$field] = (array)$options;
            }

            $scaffoldFields[$field] += ['formatter' => null];
        }

        $fieldSettings = $action->getConfig('scaffold.field_settings');
        if (empty($fieldSettings)) {
            $fieldSettings = [];
        }
        $fieldSettings = array_intersect_key($fieldSettings, $scaffoldFields);
        $scaffoldFields = Hash::merge($scaffoldFields, $fieldSettings);

        return $scaffoldFields;
    }
89387
public AssociationContext getAssociationContext() {
		if ( associationContext == null ) {
			associationContext = new AssociationContextImpl(
					associationTypeContext,
					hostingEntity != null ? OgmEntityEntryState.getStateFor( session, hostingEntity ).getTuplePointer() : new TuplePointer(),
					transactionContext( session )
			);
		}

		return associationContext;
	}
248475
private function searchAssociationField($associationsByTargetClass, $parentTable, $value)
    {
        foreach ($associationsByTargetClass as $table => $association) {
            if ($table == $parentTable && $association['inversedBy'] == $value) {
                return $association['fieldName'];
            }
        }
    }
1176446
public Association getAssociationOrNull() {
		if ( association == null ) {
			if ( hostingEntity != null ) {
				OgmEntityEntryState entryState = OgmEntityEntryState.getStateFor( session, hostingEntity );
				if ( entryState.hasAssociation( associationKeyMetadata.getCollectionRole() ) ) {
					association = entryState.getAssociation( associationKeyMetadata.getCollectionRole() );
					return association;
				}
			}

			if ( association == null ) {
				association = gridDialect.getAssociation( getAssociationKey(), getAssociationContext() );
				if ( hostingEntity != null ) {
					OgmEntityEntryState.getStateFor( session, hostingEntity )
							.setAssociation( associationKeyMetadata.getCollectionRole(), association );
				}
			}
		}
		return association;
	}
1344550
public function getAssociationTable() {
		if($this->type() !== 'HMABT')
			throw new \Exception('Association table can only be used for HMABT relations.');

		if(!$this->isPolymorphic() && $this->reverse()->isPolymorphic())
			$entityShortName = $this->reverse()->get('as');
		else
			$entityShortName = $this->definition->getShortName();

		if($this->isPolymorphic())
			$relationEntityShortName = $this->get('as');
		else
			$relationEntityShortName = $this->getTargetDefinition()->getShortName();

		if($entityShortName < $relationEntityShortName)
			return $this->dataMapper->getPrefix().$entityShortName.'_'.$relationEntityShortName;
		else
			return $this->dataMapper->getPrefix().$relationEntityShortName.'_'.$entityShortName;
	}
387828
protected function normalizeAssociation($association, $name, $format = null, array $context = array())
    {
        if ($association === null) {
            return;
        }

        $hint = $this->getHintFromObject($association);
        $ids = $this->getIdentifierFromObject($association);
        $id = $this->getIdentifiersAsString($ids);
        $data = array_merge($hint, $ids);
        $objectId = current($hint).'#'.$id;

        if (isset($context['@references'][$objectId])) {
            return $data;
        }

        $context['@references'][$objectId] = false;
        if ($association instanceof Proxy and !$association->__isInitialized()) {
            return $data;
        }

        $normalized = $this->serializer->normalize($association, $format, $context);

        $context['@references'][$objectId] = $normalized;

        return $data;
    }
455872
public function getAssociationMapping($fieldName)
    {
        if ( ! isset($this->associationMappings[$fieldName])) {
            throw MappingException::mappingNotFound($this->name, $fieldName);
        }
        return $this->associationMappings[$fieldName];
    }
283266
public function findAssociationsByAssociation($association, $associationsFilter = null)
    {
        $xmlQuery = $this->associationsApiService->getChildAssociationsFromAssociation($association->getID(), $associationsFilter);

        $associations = new Associations();

        $mapper = new \RGU\Dvoconnector\Mapper\Associations($xmlQuery);
        $mapper->mapToAbstractEntity($associations);

        return $this->completeEntity($associations);
    }
275480
@Override
    public Association addAssociation(String hostAddress, int hostPort, String peerAddress, int peerPort, String assocName)
            throws Exception {
        return addAssociation(hostAddress, hostPort, peerAddress, peerPort, assocName, IpChannelType.SCTP, null);
    }
234884
private function buildBiDirecionalToOneAssociationMappings(ClassMetadataInfo $metadata) {
        $tableName = $metadata->table['name'];
        $foreignKeys = $this->getTableForeignKeys($this->tables[$tableName]);

        foreach ($foreignKeys as $foreignKey) {
            $foreignTable = $foreignKey->getForeignTableName();
            $cols = $foreignKey->getColumns();
            $fkCols = $foreignKey->getForeignColumns();

            $localColumn = current($cols);
            $associationMapping = array();
            $associationMapping['fieldName'] = $this->getFieldNameForColumn($tableName, $localColumn, true);
            $associationMapping['targetEntity'] = $this->getClassNameForTable($foreignTable);

            for ($i = 0; $i < count($cols); $i++) {
                $associationMapping['joinColumns'][] = array(
                    'name' => $cols[$i],
                    'referencedColumnName' => $fkCols[$i],
                );
            }
            $metadata->mapManyToOne($associationMapping);
        }

        foreach ($this->tables as $tableCandidate) {
            if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
                $foreignKeysCandidate = $tableCandidate->getForeignKeys();
            } else {
                $foreignKeysCandidate = array();
            }

            foreach ($foreignKeysCandidate as $foreignKey) {
                $foreignTable = $foreignKey->getForeignTableName();

                if ($foreignTable == $tableName && !isset($this->manyToManyTables[$tableCandidate->getName()])) {

                    $fkCols = $foreignKey->getForeignColumns();
                    $cols = $foreignKey->getColumns();


                    $localColumn = current($cols);

                    $associationMapping = array();
                    $associationMapping['fieldName'] = $this->getFieldNameForColumn($tableCandidate->getName(), $tableCandidate->getName(), true);
                    $associationMapping['targetEntity'] = $this->getClassNameForTable($tableCandidate->getName());
                    $associationMapping['mappedBy'] = $this->getFieldNameForColumn($tableCandidate->getName(), $localColumn, true);

                    try {
                        $primaryKeyColumns = $tableCandidate->getPrimaryKey()->getColumns();
                        if (count($primaryKeyColumns) == 1) {
                            $indexColumn = current($primaryKeyColumns);
                            $associationMapping['indexBy'] = $indexColumn;
                        }
                    } catch (SchemaException $e) {
                        
                    }

                    $metadata->mapOneToMany($associationMapping);
                }
            }
        }
    }
154853
static public function detachedEntityFoundThroughRelationship(array $assoc, $entry)
    {
        return new self("A detached entity of type " . $assoc['targetEntity'] . " (" . self::objToStr($entry) . ") "
                        . " was found through the relationship '" . $assoc['sourceEntity'] . "#" . $assoc['fieldName'] . "' "
                        . "during cascading a persist operation.");
    }
925634
public function getParentAssociationMapping()
    {
        // NEXT_MAJOR: remove array check
        if (\is_array($this->parentAssociationMapping) && $this->getParent()) {
            $parent = $this->getParent()->getCode();

            if (\array_key_exists($parent, $this->parentAssociationMapping)) {
                return $this->parentAssociationMapping[$parent];
            }

            throw new \InvalidArgumentException(sprintf(
                "There's no association between %s and %s.",
                $this->getCode(),
                $this->getParent()->getCode()
            ));
        }

        // NEXT_MAJOR: remove this line
        return $this->parentAssociationMapping;
    }
1374885
public function findAssociationCategories()
    {
        $xmlQuery = $this->metaApiService->getAssociationCategories();

        $categories = new Categories();

        $mapper = new \RGU\Dvoconnector\Mapper\AssociationCategories($xmlQuery);
        $mapper->mapToAbstractEntity($categories);

        return $categories;
    }
1242246
public static function create(Assoc $option)
    {
        $definition = $option->getDefinition();

        switch ($option->getType()) {
            case "m:n":
            case "m>n":
            case "m<n":
                return new ManyToMany(
                    $option->getSourceReflection(),
                    $option->getTargetReflection(),
                    $definition,
                    $option->getType() === "m<n" ? false : true
                );
            case "1:1":
                return new OneToOne(
                    $option->getSourceReflection(),
                    $option->getTargetReflection(),
                    isset($definition[0]) ? $definition[0] : null
                );
            case "1:n":
                return new OneToMany(
                    $option->getSourceReflection(),
                    $option->getTargetReflection(),
                    isset($definition[0]) ? $definition[0] : null
                );
            case "n:1":
                return new ManyToOne(
                    $option->getSourceReflection(),
                    $option->getTargetReflection(),
                    isset($definition[0]) ? $definition[0] : null
                );
            default:
                throw new AssociationException("Unsupported association type");
        }
    }
317063
public function bindAssociations()
    {
        $config = $this->getConfig();
        $tagsAlias = $config['tagsAlias'];
        $tagsAssoc = $config['tagsAssoc'];
        $taggedAlias = $config['taggedAlias'];
        $taggedAssoc = $config['taggedAssoc'];

        $table = $this->_table;
        $tableAlias = $this->_table->getAlias();

        $assocConditions = [$taggedAlias . '.' . $this->getConfig('fkTableField') => $table->getTable()];

        if (!$table->hasAssociation($taggedAlias)) {
            $table->hasMany($taggedAlias, $taggedAssoc + [
                'foreignKey' => $tagsAssoc['foreignKey'],
                'conditions' => $assocConditions,
            ]);
        }

        if (!$table->hasAssociation($tagsAlias)) {
            $table->belongsToMany($tagsAlias, $tagsAssoc + [
                'through' => $table->{$taggedAlias}->getTarget(),
                'conditions' => $assocConditions,
            ]);
        }

        if (!$table->{$tagsAlias}->hasAssociation($tableAlias)) {
            $table->{$tagsAlias}
                ->belongsToMany($tableAlias, [
                    'className' => $table->getTable(),
                ] + $tagsAssoc);
        }

        if (!$table->{$taggedAlias}->hasAssociation($tableAlias)) {
            $table->{$taggedAlias}
                ->belongsTo($tableAlias, [
                    'className' => $table->getTable(),
                    'foreignKey' => $tagsAssoc['foreignKey'],
                    'conditions' => $assocConditions,
                    'joinType' => 'INNER',
                ]);
        }

        if (!$table->{$taggedAlias}->hasAssociation($tableAlias . $tagsAlias)) {
            $table->{$taggedAlias}
                ->belongsTo($tableAlias . $tagsAlias, [
                    'className' => $tagsAssoc['className'],
                    'foreignKey' => $tagsAssoc['targetForeignKey'],
                    'conditions' => $assocConditions,
                    'joinType' => 'INNER',
                ]);
        }
    }