Get entries to populate a relationships field

@param string $fieldHandle
@param array $fieldInfo
@param string $sectionHandle
@param int|null $id
@return array|null
778258
private function getRelationshipsTo(
        string $fieldHandle,
        array $fieldInfo,
        string $sectionHandle,
        int $id = null
    ): ?array {

        if (!empty($fieldInfo[$fieldHandle]['to'])) {
            try {
                $sexyFieldInstructions = $this->getSexyFieldRelationshipInstructions($fieldInfo, $fieldHandle);

                // You can have a different name for elements through config
                $nameExpression = [];
                if (!empty($sexyFieldInstructions) &&
                    !empty($sexyFieldInstructions['name-expression'])
                ) {
                    $nameExpression = explode('|', $sexyFieldInstructions['name-expression']);
                }

                // Maybe you want to add some more fields to the relationship content
                $addFields = [];
                if (!empty($sexyFieldInstructions) &&
                    !empty($sexyFieldInstructions['add-fields'])
                ) {
                    $addFields = $sexyFieldInstructions['add-fields'];
                }

                $to = $this->readSection->read(
                    $this->getRelationshipReadOptions($fieldHandle, $fieldInfo, $sexyFieldInstructions)
                );
                $fieldInfo[$fieldHandle][$fieldInfo[$fieldHandle]['to']] = [];

                /** @var CommonSectionInterface $entry */
                foreach ($to as $entry) {

                    // Map the name-expression to override naming
                    $name = $entry->getDefault();

                    if ($nameExpression) {
                        $find = $entry;
                        foreach ($nameExpression as $method) {
                            if ($find) {
                                $find = $find->$method();
                            }
                        }
                        if ($find) {
                            $name = $find;
                        }
                    }

                    // Default relationship data
                    $data = [
                        'id' => $entry->getId(),
                        'slug' => (string) $entry->getSlug(),
                        'name' => $name,
                        'created' => $entry->getCreated(),
                        'updated' => $entry->getUpdated(),
                        'selected' => false
                    ];

                    // Add data if configured
                    foreach ($addFields as $field) {
                        $method = 'get' . ucfirst($field);
                        $data[$field] = (string) $entry->{$method}();
                    }

                    $fieldInfo[$fieldHandle][$fieldInfo[$fieldHandle]['to']][] = $data;
                }
            } catch (EntryNotFoundException $exception) {
                $fieldInfo[$fieldHandle][$fieldInfo[$fieldHandle]['to']]['error'] = $exception->getMessage();
            }

            if (!empty($id)) {
                $fieldInfo = $this->setSelectedRelationshipsTo(
                    $sectionHandle,
                    $fieldHandle,
                    $fieldInfo,
                    $id
                );
            }
        }

        return $fieldInfo;
    }
170399
public function getEntriesByFieldValue(string $sectionHandle, string $fieldHandle): JsonResponse
    {
        $request = $this->requestStack->getCurrentRequest();

        $optionsResponse = $this->preFlightOptions($request, self::ALLOWED_HTTP_METHODS);
        if ($optionsResponse) {
            return $optionsResponse;
        }

        $this->dispatcher->dispatch(
            ApiFetchEntries::NAME,
            new ApiFetchEntries($request, $sectionHandle)
        );

        if ($abort = $this->shouldAbort($request)) {
            return $abort;
        }

        // We may join and want to select something on what is in the joined table
        // Like this: accountHasRole:role&value=1,2,3
        $fieldHandles = explode(':', $fieldHandle);
        $fieldHandle = array_shift($fieldHandles);

        // You could have many results on a field value,
        // so add some control over the results with limit, offset and also sorting.
        $fieldValue = (string)$request->get('value');
        if (strpos($fieldValue, ',') !== false) {
            $fieldValue = explode(',', $fieldValue);
        }

        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 100);
        $orderBy = $request->get('orderBy', 'created');
        $sort = $request->get('sort', 'DESC');

        try {
            $section = $this->sectionManager->readByHandle(Handle::fromString($sectionHandle));

            try {
                $this->cache->start(
                    $section->getConfig()->getFullyQualifiedClassName(),
                    $this->getFields(),
                    self::CACHE_CONTEXT_GET_ENTRIES_BY_FIELD_VALUE,
                    $fieldHandle
                );
            } catch (\Psr\Cache\InvalidArgumentException $exception) {
                //
            }

            if ($this->cache->isHit()) {
                return new JsonResponse(
                    $this->cache->get(),
                    JsonResponse::HTTP_OK,
                    $this->getDefaultResponseHeaders($request)
                );
            }

            $readOptions = [
                ReadOptions::SECTION => $sectionHandle,
                ReadOptions::FIELD => [ $fieldHandle => $fieldValue ],
                ReadOptions::RELATE => $fieldHandles,
                ReadOptions::OFFSET => (int) $offset,
                ReadOptions::LIMIT => (int) $limit,
                ReadOptions::ORDER_BY => [ $orderBy => strtolower($sort) ],
                ReadOptions::FETCH_FIELDS => $request->get('fields', null)
            ];
            $entries = $this->readSection->read(ReadOptions::fromArray($readOptions));
            $responseData = [];
            foreach ($entries as $entry) {
                if ($entry instanceof CommonSectionInterface) {
                    $responseData[] = $this->serialize->toArray($request, $entry);
                } else {
                    $responseData[] = $entry;
                }
            }
            $jsonResponse = new JsonResponse(
                $responseData,
                JsonResponse::HTTP_OK,
                $this->getDefaultResponseHeaders($request)
            );
            $this->dispatcher->dispatch(
                ApiEntriesFetched::NAME,
                new ApiEntriesFetched(
                    $request,
                    $responseData,
                    $jsonResponse,
                    $entries
                )
            );

            if ($abort = $this->shouldAbort($request)) {
                return $abort;
            }

            $this->cache->set($responseData);

            return $jsonResponse;
        } catch (\Exception $exception) {
            return $this->errorResponse($request, $exception);
        }
    }
318473
protected function processFieldsCollection($fieldCollection, $data, FormHandler $formHandler)
    {
        $fields = array();
        foreach ($fieldCollection as $field) {
            // Unnamed array fields
            if ($field['name'] === null) {
                if (!isset($i)) $i = 0;

                $field['name'] = $i;
                $field = $this->typeHandler->makeView($field, $data, $formHandler);
                $fields[] = $field;

                $i++;
            }
            // Named array fields
            else {
                $fieldName = $field['name'];
                $field = $this->typeHandler->makeView($field, $data, $formHandler);

                $field['has_error'] = false;
                if ($formHandler->fieldHasError($field['name'])) {
                    $field['has_error'] = true;
                }

                $fields[$fieldName] = $field;
            }
        }

        return $fields;
    }
383960
private function callFormBack($fieldId) {
		if ($this->formOne!==null) {
			/** @noinspection PhpUndefinedMethodInspection */
			$this->formOne->callBack($this, $fieldId);
		}
	}
1372133
public static function get_modules_from_sectionid($sectionid) {
        global $DB;

        // Get the course and sequence of the section
        $secrec = $DB->get_record('course_sections', array('id' => $sectionid), 'course, sequence');
        $courseid = $secrec->course;
        $sequence = $secrec->sequence;

        // Get the section->sequence contents (it roots the activities order)
        // Get all course modules belonging to requested section
        $modulesarr = array();
        $modules = $DB->get_records_sql("
            SELECT cm.id, m.name AS modname
              FROM {course_modules} cm
              JOIN {modules} m ON m.id = cm.module
             WHERE cm.course = ?
               AND cm.section = ?
               AND cm.deletioninprogress <> 1", array($courseid, $sectionid));
        foreach (explode(',', $sequence) as $moduleid) {
            if (isset($modules[$moduleid])) {
                $module = array('id' => $modules[$moduleid]->id, 'modname' => $modules[$moduleid]->modname);
                $modulesarr[] = (object)$module;
                unset($modules[$moduleid]);
            }
        }
        if (!empty($modules)) { // This shouldn't happen, but one borked sequence can lead to it. Add the rest
            foreach ($modules as $module) {
                $module = array('id' => $module->id, 'modname' => $module->modname);
                $modulesarr[] = (object)$module;
            }
        }
        return $modulesarr;
    }
292016
public function loadSectionData($id)
    {
        $query = $this->dbHandler->createSelectQuery();
        $query->select(
            $this->dbHandler->quoteColumn('id'),
            $this->dbHandler->quoteColumn('identifier'),
            $this->dbHandler->quoteColumn('name')
        )->from(
            $this->dbHandler->quoteTable('ezsection')
        )->where(
            $query->expr->eq(
                $this->dbHandler->quoteColumn('id'),
                $query->bindValue($id, null, \PDO::PARAM_INT)
            )
        );

        $statement = $query->prepare();
        $statement->execute();

        return $statement->fetchAll(\PDO::FETCH_ASSOC);
    }
184613
protected function loadFieldData($fieldId, $versionNo)
    {
        $selectQuery = $this->connection->createQueryBuilder();
        $selectQuery
            ->select(
                $this->connection->quoteIdentifier('latitude'),
                $this->connection->quoteIdentifier('longitude'),
                $this->connection->quoteIdentifier('address')
            )
            ->from($this->connection->quoteIdentifier('ezgmaplocation'))
            ->where(
                $selectQuery->expr()->andX(
                    $selectQuery->expr()->eq(
                        $this->connection->quoteIdentifier('contentobject_attribute_id'),
                        ':fieldId'
                    ),
                    $selectQuery->expr()->eq(
                        $this->connection->quoteIdentifier('contentobject_version'),
                        ':versionNo'
                    )
                )
            )
            ->setParameter(':fieldId', $fieldId, PDO::PARAM_INT)
            ->setParameter(':versionNo', $versionNo, PDO::PARAM_INT)
        ;

        $statement = $selectQuery->execute();

        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);
        if (!isset($rows[0])) {
            return null;
        }

        // Cast coordinates as the DB can return them as strings
        $rows[0]['latitude'] = (float)$rows[0]['latitude'];
        $rows[0]['longitude'] = (float)$rows[0]['longitude'];

        return $rows[0];
    }
596795
public function linkUrl($urlId, $fieldId, $versionNo)
    {
        $dbHandler = $this->getConnection();

        $q = $dbHandler->createInsertQuery();
        $q->insertInto(
            $dbHandler->quoteTable(self::URL_LINK_TABLE)
        )->set(
            $dbHandler->quoteColumn('contentobject_attribute_id'),
            $q->bindValue($fieldId, null, PDO::PARAM_INT)
        )->set(
            $dbHandler->quoteColumn('contentobject_attribute_version'),
            $q->bindValue($versionNo, null, PDO::PARAM_INT)
        )->set(
            $dbHandler->quoteColumn('url_id'),
            $q->bindValue($urlId, null, PDO::PARAM_INT)
        );

        $q->prepare()->execute();
    }
1344485
private function getSexyFieldRelationshipInstructions(array $fieldInfo, string $fieldHandle): ?array
    {
        return !empty($fieldInfo[$fieldHandle]['form']['sexy-field-instructions']['relationship']) ?
            $fieldInfo[$fieldHandle]['form']['sexy-field-instructions']['relationship'] : null;
    }
1345155
private function getRelationshipReadOptions(
        string $fieldHandle,
        array $fieldInfo,
        array $sexyFieldInstructions = null
    ): ReadOptionsInterface {
        $options = $this->getOptions();

        $readOptions = [
            ReadOptions::SECTION => $fieldInfo[$fieldHandle]['to'],
            ReadOptions::LIMIT => !empty($options[$fieldHandle]['limit']) ?
                (int)$options[$fieldHandle]['limit'] :
                ((!empty($sexyFieldInstructions) && !empty($sexyFieldInstructions['limit'])) ?
                    (int)$sexyFieldInstructions['limit'] :
                    self::DEFAULT_RELATIONSHIPS_LIMIT),
            ReadOptions::OFFSET => !empty($options[$fieldHandle]['offset']) ?
                (int)$options[$fieldHandle]['offset'] :
                ((!empty($sexyFieldInstructions) && !empty($sexyFieldInstructions['offset'])) ?
                    (int)$sexyFieldInstructions['offset'] :
                    self::DEFAULT_RELATIONSHIPS_OFFSET)
        ];

        // You can add limitations for the relationship through config
        if (!empty($sexyFieldInstructions) &&
            !empty($sexyFieldInstructions['field']) &&
            !empty($sexyFieldInstructions['value'])
        ) {
            if (strpos((string) $sexyFieldInstructions['value'], ',') !== false) {
                $sexyFieldInstructions['value'] = explode(',', $sexyFieldInstructions['value']);
            }
            $readOptions[ReadOptions::FIELD] = [
                $sexyFieldInstructions['field'] => $sexyFieldInstructions['value']
            ];
        }

        // You can add limitations for the relationship through get options
        if (!empty($options) &&
            !empty($options[$fieldHandle]) &&
            !empty($options[$fieldHandle]['field']) &&
            !empty($options[$fieldHandle]['value'])
        ) {
            if (strpos((string) $options[$fieldHandle]['value'], ',') !== false) {
                $options[$fieldHandle]['value'] = explode(',', $options[$fieldHandle]['value']);
            }
            $readOptions[ReadOptions::FIELD] = [
                $options[$fieldHandle]['field'] => $options[$fieldHandle]['value']
            ];
        }

        // You can add limitations for the relationship through get options
        if (!empty($options) &&
            !empty($options[$fieldHandle]) &&
            !empty($options[$fieldHandle]['join']) &&
            !empty($options[$fieldHandle]['value'])
        ) {
            if (strpos((string) $options[$fieldHandle]['value'], ',') !== false) {
                $options[$fieldHandle]['value'] = explode(',', $options[$fieldHandle]['value']);
            }

            $readOptions[ReadOptions::JOIN] = [
                $options[$fieldHandle]['join'] => $options[$fieldHandle]['value']
            ];
        }

        return ReadOptions::fromArray($readOptions);
    }
626983
private function getFolderByHandle(string $folderHandle): \stdClass
    {
        $volume = Craft::$app->volumes->getVolumeByHandle($folderHandle);
        if ($volume) {
            $folder = $this->getFolderByVolumeId($volume->id);
            if ($folder) {
                return  (object) [
                    'id' => $folder->id,
                    'handle' => $folderHandle
                ];
            }
        }
        return null;
    }
536631
public static function findField($fieldsList, $fieldId)
    {
        $fields = self::filterFieldList($fieldsList, $fieldId);

        if (1 != count($fields)) {
            return null;
        }

        return array_shift($fields);
    }
50847
public function __async_quantityFieldsRow($structureId, $entityID)
    {
        $structureFields = null;

        // Get all fields of table structure
        if ($this->query->className('field')
            ->join('structurefield')
            ->cond('StructureID', $structureId)
            ->exec($structureFields)
        ) {

            $fields = array();

            /** @var \samson\cms\CMSField $field Field object */
            foreach ($structureFields as $field) {
                // Add field to fields collection
                $fields[$field->id] = $field;
            }

            $countOfFields = $this->query->className('material')
                ->cond('parent_id', $entityID)
                ->cond('type', 3)
                ->cond('materialfield.FieldID', array_keys($fields))
                ->cond('Active', 1)
                ->join('materialfield')
                ->group_by('MaterialID')
                ->count();

            return array('status' => 1, 'countOfFields' => $countOfFields);
        } else {
            return array('status' => 0);
        }
    }
243240
protected function loadFieldData($fieldId, $versionNo)
    {
        $query = $this->dbHandler->createSelectQuery();
        $query
            ->selectDistinct(
                // Tag
                $this->dbHandler->aliasedColumn($query, 'id', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'parent_id', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'main_tag_id', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'keyword', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'depth', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'path_string', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'modified', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'remote_id', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'main_language_id', 'eztags'),
                $this->dbHandler->aliasedColumn($query, 'language_mask', 'eztags'),
                // Tag keywords
                $this->dbHandler->aliasedColumn($query, 'keyword', 'eztags_keyword'),
                $this->dbHandler->aliasedColumn($query, 'locale', 'eztags_keyword'),
                // Tag attribute links
                $this->dbHandler->aliasedColumn($query, 'priority', 'eztags_attribute_link')
            )
            ->from($this->dbHandler->quoteTable('eztags'))
            ->innerJoin(
                $this->dbHandler->quoteTable('eztags_attribute_link'),
                $query->expr->eq(
                    $this->dbHandler->quoteColumn('id', 'eztags'),
                    $this->dbHandler->quoteColumn('keyword_id', 'eztags_attribute_link')
                )
            )
            ->innerJoin(
                $this->dbHandler->quoteTable('eztags_keyword'),
                $query->expr->eq(
                    $this->dbHandler->quoteColumn('id', 'eztags'),
                    $this->dbHandler->quoteColumn('keyword_id', 'eztags_keyword')
                )
            )->where(
                $query->expr->lAnd(
                    $query->expr->eq(
                        $this->dbHandler->quoteColumn('objectattribute_id', 'eztags_attribute_link'),
                        $query->bindValue($fieldId, null, PDO::PARAM_INT)
                    ),
                    $query->expr->eq(
                        $this->dbHandler->quoteColumn('objectattribute_version', 'eztags_attribute_link'),
                        $query->bindValue($versionNo, null, PDO::PARAM_INT)
                    )
                )
            )
            ->orderBy($this->dbHandler->quoteColumn('priority', 'eztags_attribute_link'));

        $statement = $query->prepare();
        $statement->execute();

        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

        $tagList = [];
        foreach ($rows as $row) {
            $tagId = (int) $row['eztags_id'];
            if (!isset($tagList[$tagId])) {
                $tagList[$tagId] = [];
                $tagList[$tagId]['id'] = (int) $row['eztags_id'];
                $tagList[$tagId]['parent_id'] = (int) $row['eztags_parent_id'];
                $tagList[$tagId]['main_tag_id'] = (int) $row['eztags_main_tag_id'];
                $tagList[$tagId]['keywords'] = [];
                $tagList[$tagId]['depth'] = (int) $row['eztags_depth'];
                $tagList[$tagId]['path_string'] = $row['eztags_path_string'];
                $tagList[$tagId]['modified'] = (int) $row['eztags_modified'];
                $tagList[$tagId]['remote_id'] = $row['eztags_remote_id'];
                $tagList[$tagId]['always_available'] = ((int) $row['eztags_language_mask'] & 1) ? true : false;
                $tagList[$tagId]['main_language_code'] = $this->languageHandler->load($row['eztags_main_language_id'])->languageCode;
                $tagList[$tagId]['language_codes'] = [];
            }

            if (!isset($tagList[$tagId]['keywords'][$row['eztags_keyword_locale']])) {
                $tagList[$tagId]['keywords'][$row['eztags_keyword_locale']] = $row['eztags_keyword_keyword'];
            }

            if (!in_array([$row['eztags_keyword_locale']], $tagList[$tagId]['language_codes'], true)) {
                $tagList[$tagId]['language_codes'][] = $row['eztags_keyword_locale'];
            }
        }

        return array_values($tagList);
    }
1266399
public function resolveField( NodeRef $nodeRef, $fieldId )
    {
        $fields = array($nodeRef->getElement()->getSlug());

        $fields[] = $fieldId;

        return join($fields, '.');
    }
510238
public function findByHandleAndVersion($packageHandle, $packageVersion)
    {
        $result = null;
        $packageHandle = (string) $packageHandle;
        if ($packageHandle !== '') {
            $packageVersion = (string) $packageVersion;
            if ($packageVersion !== '') {
                $list = $this->createQueryBuilder('v')
                    ->innerJoin(Package::class, 'p', Expr\Join::WITH, 'v.package = p.id')
                    ->where('p.handle = :handle')->setParameter('handle', $packageHandle)
                    ->andWhere('v.version = :version')->setParameter('version', $packageVersion)
                    ->setMaxResults(1)
                    ->getQuery()->execute();
                if (!empty($list)) {
                    $result = $list[0];
                }
            }
        }

        return $result;
    }
413390
protected function getSection(FieldTypeInterface $field, $section = null): SectionInterface
    {
        if (is_null($section)) {
            if ($this->repository->hasGroup($field->getOption('group'))) {
                $section = $this->repository->getGroup($field->getOption('group'));
            } else {
                $section = new Section($field->getOption('group'));
            }

            $section->addItem($field);
        }

        return $section;
    }