Returns references by meta reference data.

@param ModelMetaReference $data
@param string|null        $search
@return string[]
350459
protected function getReferencesByMetaData(ModelMetaReference $data, $search = null)
    {
        $references = $this->referenceRepository->getReferencesForModelMetaReference($data, $search)->all();

        return $this->formatReferenceOutput($references);
    }
499035
public function findByNameForAjax($search)
    {
        $resultArray = [];

        $users = $this->findByName($search);

        foreach ($users as $user) {
            $resultArray[] = [
                'id' => $user->getId(),
                'text' => $user->getFirstName().' '.$user->getLastName(),
            ];
        }

        return $resultArray;
    }
831111
protected function searchWithPagination(ModelCriteria $search, &$pagination)
    {
        $page  = (int) $this->getArgValue('page');
        $limit = (int) $this->getArgValue('limit');

        $pagination = $search->paginate($page, $limit);

        if ($page > $pagination->getLastPage()) {
            return [];
        } else {
            return $pagination;
        }
    }
1180477
def runSearchReferences(self, request):
        
        return self.runSearchRequest(
            request, protocol.SearchReferencesRequest,
            protocol.SearchReferencesResponse,
            self.referencesGenerator)
309326
private function getPropertyFilters($search = '')
    {
        $propertyFilters = [];

        if(is_string($search) && strlen(trim($search)) > 0){
            $propertyFilters[self::LABEL_URI] = $search;
        }
        if(is_array($search)){
            foreach($search as $uri => $value){
                if( is_string($uri) &&
                    (is_string($value) && strlen(trim($value)) > 0) ||
                    (is_array($value) && count($value) > 0) ) {
                    $propertyFilters[$uri] = $value;
                }
            }
        }
        return $propertyFilters;
    }
644404
public function resolveEmbeddedReferences($string)
    {
        $regexp = $this->getEmbeddedRegexp();
        $count = preg_match_all($regexp, $string, $matches);
        // $matches[0][] will have the matched full string eg.: [reference:example_reference]
        if ($count) {
            foreach ($matches[0] as $referenceIdentifier) {
                $reference = $this->getReferenceValue(substr($referenceIdentifier, 1, -1));
                if (!is_array($reference)) {
                    $string = str_replace($referenceIdentifier, $reference, $string);
                }
            }
        }

        return $string;
    }
1283800
public function mapCollectionReferences(array $data): array
    {
        $collectionReferences = [];

        foreach ($data as $dataItem) {
            $collectionReferences[] = CollectionReference::fromArray(
                [
                    'blockId' => (int) $dataItem['block_id'],
                    'blockStatus' => (int) $dataItem['block_status'],
                    'collectionId' => (int) $dataItem['collection_id'],
                    'collectionStatus' => (int) $dataItem['collection_status'],
                    'identifier' => $dataItem['identifier'],
                ]
            );
        }

        return $collectionReferences;
    }
1355870
public function getMetadataQuery($data, $metadata)
    {
        foreach ($metadata as $searchMetadata) {
            $data[] = $this->setData(['metadata' => $searchMetadata], 'input');
        }

        return $data;
    }
716510
public static String[] replaceDataReferencesInArray(final String[] args, final Map<String, Map<String, String>> data) {
        return replaceDataReferencesInArray(args, data, null, false);
    }
1144923
protected function _getRefItems( array $refIdMap )
	{
		$items = array();
		$context = $this->_getContext();

		foreach( $refIdMap as $domain => $list )
		{
			try
			{
				$manager = MShop_Factory::createManager( $context, $domain );

				$search = $manager->createSearch( true );
				$expr = array(
					$search->compare( '==', str_replace( '/', '.', $domain ) . '.id', array_keys( $list ) ),
					$search->getConditions(),
				);
				$search->setConditions( $search->combine( '&&', $expr ) );
				$search->setSlice( 0, 0x7fffffff );

				foreach( $manager->searchItems( $search ) as $id => $item )
				{
					foreach( $list[ $id ] as $parentId ) {
						$items[ $parentId ][ $domain ][ $id ] = $item;
					}
				}
			}
			catch( MShop_Exception $e )
			{
				$logger = $context->getLogger();
				$logger->log( sprintf( 'Item referenced in domain "%1$s" not found: %2$s', $domain, $e->getMessage() ) );
				$logger->log( $e->getTraceAsString() );
			}
		}

		return $items;
	}
515688
protected function transformByMeta(string $meta, array $data, ...$parameters): array
    {
        $name = Str::singular($meta);
        $types = $this->options[$meta];

        if (empty($types)) {
            return $data;
        }

        foreach ($types as $type => $index) {
            if (is_array($type)) {
                continue;
            }

            $method = $name.Str::studly($type);

            if (method_exists($this, $method)) {
                $data = $this->{$method}($data, ...$parameters);
            }
        }

        return $data;
    }
1062444
public function getReferencesByParameters(array $parameters, $transform = true, $keepChildren = false, $type = null)
    {
        $viewsReferences = [];
        $refsId = $this->repository->getAllBy($parameters, $type);

        $references = $this->repository->getResults($refsId);
        foreach ($references as $reference) {
            if ($transform === true) {
                $transformViewReferenceFn = function ($parentViewReference) use (&$transformViewReferenceFn, $keepChildren) {
                    $transformer = ViewReferenceManager::findTransformerFromElement($parentViewReference);
                    $reference = $transformer->transform($parentViewReference);
                    if ($keepChildren) {
                        foreach ($this->repository->getChildren($parentViewReference['id']) as $child) {
                            $reference->addChild($transformViewReferenceFn($this->repository->findById($child)));
                        }
                    }

                    return $reference;
                };

                $reference = $transformViewReferenceFn($reference);
            }
            $viewsReferences[] = $reference;
        }

        return $viewsReferences;
    }
282841
protected function getReferencesForModelKeys(array $keys, $targetModel = null)
    {
        $keys = array_filter($keys);

        if ( ! count($keys)) {
            return [];
        }

        $referenceData = $this->getReferenceDataProvider()->getForModelClassByType(
            $this->model,
            'form.field',
            $this->field->key(),
            $targetModel
        );

        if ( ! $referenceData) {
            return [];
        }

        $references = [];

        foreach ($keys as $key) {
            $references[ $key ] = $this->getReferenceRepository()
                ->getReferenceForModelMetaReferenceByKey($referenceData, $key);
        }

        return $references;
    }
25181
def search(self, query, search_term, search_field, catalog):
        
        logger.info("Reference Widget Catalog: {}".format(catalog.id))
        if not search_term:
            return catalog(query)

        index = self.get_index(search_field, catalog)
        if not index:
            logger.warn("*** Index not found: '{}'".format(search_field))
            return []

        meta = index.meta_type
        if meta == "TextIndexNG3":
            query[index.id] = "{}*".format(search_term)

        elif meta == "ZCTextIndex":
            logger.warn("*** Field '{}' ({}). Better use TextIndexNG3"
                        .format(meta, search_field))
            query[index.id] = "{}*".format(search_term)

        elif meta in ["FieldIndex", "KeywordIndex"]:
            logger.warn("*** Field '{}' ({}). Better use TextIndexNG3"
                        .format(meta, search_field))
            query[index.id] = search_term

        else:
            logger.warn("*** Index '{}' ({}) not supported"
                        .format(search_field, meta))
            return []

        logger.info("Reference Widget Query: {}".format(repr(query)))
        return catalog(query)
467852
public function getSearchResults($data = null, $form = null) {

		// Determine whether a search engine has been selected.

		$page = $this->data();
		$engine = $page->SearchEngine;
		$classes = Config::inst()->get(FulltextSearchable::class, 'searchable_classes');
		if(!$engine || (($engine !== 'Full-Text') && !ClassInfo::exists($engine)) || (($engine === 'Full-Text') && (!is_array($classes) || (count($classes) === 0)))) {

			// The search engine has not been selected.

			return $this->httpError(404);
		}

		// The analytics require the time taken.

		$time = microtime(true);

		// This is because the search form pulls from the request directly.

		if(!isset($data['Search'])) {
			$data['Search'] = '';
		}
		$search = $data['Search'];
		$request = $this->getRequest();
		$request->offsetSet('Search', $search);

		// Determine whether the remaining search parameters have been passed through.

		if(!isset($data['SortBy']) || !$data['SortBy']) {
			$data['SortBy'] = $page->SortBy;
		}
		if(!isset($data['SortDirection']) || !$data['SortDirection']) {
			$data['SortDirection'] = $page->SortDirection;
		}
		if(!isset($form)) {
			$form = $this->getForm($request);
		}

		// Instantiate some default templates.

		$templates = array(
			'ExtensibleSearch',
			'ExtensibleSearchPage',
			'Page'
		);

		// Determine the search engine that has been selected.

		if($engine !== 'Full-Text') {

			// The analytics require the time taken.

			$time = microtime(true);

			// Determine the search engine specific search results.

			$results = singleton($engine)->getSearchResults($data, $form, $page);

			// The search results format needs to be correct.

			if(!isset($results['Results'])) {
				$results = array(
					'Results' => $results
				);
			}

			// Determine the number of search results.

			$count = isset($results['Count']) ? (int)$results['Count'] : count($results['Results']);

			// Instantiate the search engine specific templates.

			$explode = explode('\\', $engine);
			$explode = end($explode);
			$templates = array_merge(array(
				"{$explode}_results",
				"{$explode}Page_results",
				'ExtensibleSearch_results',
				'ExtensibleSearchPage_results',
				'Page_results',
				$explode,
				"{$explode}Page"
			), $templates);
		}

		// Determine the full-text specific search results.

		else {

			// The paginated list needs to be manipulated, as filtering and sorting is not possible otherwise.

			$start = $request->getVar('start') ? (int)$request->getVar('start') : 0;
			$form->setPageLength(PHP_INT_MAX);

			// This is because the search form pulls from the request directly.

			$request->offsetSet('start', 0);
			$list = $form->getResults()->getList();

			// The search engine may only support limited hierarchy filtering for multiple sites.

			$filter = $page->SearchTrees()->column();
			if(count($filter) && (($hierarchy = $page->supports_hierarchy) || ClassInfo::exists(Multisites::class))) {

				// Apply the search trees filtering.

				$list = $list->filter($hierarchy ? 'ParentID' : 'SiteID', $filter);
			}

			// Apply custom filtering.

			$this->extend('updateFiltering', $list);

			// Apply the sorting.

			$list = $list->sort("{$data['SortBy']} {$data['SortDirection']}");

			// The paginated list needs to be instantiated again.

			$results = array(
				'Title' => _t('EXTENSIBLE_SEARCH.SEARCH_RESULTS', 'Search Results'),
				'Query' => $form->getSearchQuery(),
				'Results' => PaginatedList::create(
					$list
				)->setPageLength($page->ResultsPerPage)->setPageStart($start)->setTotalItems($count = $list->count())
			);

			// Instantiate the full-text specific templates.

			$templates = array_merge(array(
				'ExtensibleSearch_results',
				'ExtensibleSearchPage_results',
				'Page_results'
			), $templates);
		}

		// Determine the template to use.

		$this->extend('updateTemplates', $templates);
		$output = $this->customise($results)->renderWith($templates);
		$output->Count = $count;

		// Determine whether analytics are to be suppressed.

		if($search && ($request->getVar('analytics') !== 'false')) {

			// Update the search page specific analytics.

			$this->service->logSearch($search, $count, microtime(true) - $time, $engine, $page->ID);
		}

		// Display the search form results.

		return $output;
	}
308723
protected function getAjaxViewVars(array $searchData, RepositoryInterface $table, Search $search): array
    {
        /** @var \Cake\ORM\Table */
        $table = $table;

        $searchData['sort_by_field'] = Hash::get($this->request->getQueryParams(), 'sort', '');
        $searchData['sort_by_order'] = Hash::get(
            $this->request->getQueryParams(),
            'direction',
            SearchOptions::DEFAULT_SORT_BY_ORDER
        );

        /** @var \Cake\ORM\Query */
        $query = $search->execute($searchData);
        $resultSet = $this->paginate($query);

        $event = new Event(
            (string)SearchEventName::MODEL_SEARCH_AFTER_FIND(),
            $this,
            ['entities' => $resultSet, 'table' => $table]
        );
        $this->getEventManager()->dispatch($event);
        $resultSet = $event->getResult() instanceof ResultSetInterface ? $event->getResult() : $resultSet;

        $primaryKeys = [];
        foreach ((array)$table->getPrimaryKey() as $primaryKey) {
            $primaryKeys[] = $table->aliasField($primaryKey);
        }

        $displayColumns = empty($searchData['group_by']) ?
            $searchData['display_columns'] :
            [$searchData['group_by'], pluginSplit($searchData['group_by'])[0] . '.' . Search::GROUP_BY_FIELD];
        $displayColumns = array_merge($primaryKeys, $displayColumns);

        return [
            'success' => true,
            'data' => Utility::instance()->formatter($resultSet, $displayColumns, $table, $this->Auth->user()),
            'pagination' => ['count' => $query->count()],
            '_serialize' => ['success', 'data', 'pagination']
        ];
    }
792680
private function fetchReferences() {
        $qry = "SELECT i.CONSTRAINT_NAME as constraintName, i.CONSTRAINT_TYPE as constraintType,
			j.COLUMN_NAME as columnName, j.REFERENCED_TABLE_SCHEMA as refDB, j.REFERENCED_TABLE_NAME as refTable,
			j.REFERENCED_COLUMN_NAME as refColumn, k.UPDATE_RULE as onUpdate, k.DELETE_RULE as onDelete" .
                " FROM information_schema.TABLE_CONSTRAINTS i" .
                " LEFT JOIN information_schema.KEY_COLUMN_USAGE j
                    ON i.CONSTRAINT_NAME = j.CONSTRAINT_NAME AND j.TABLE_SCHEMA = '" . $this->connection->getDBName() . "'
			AND j.TABLE_NAME = '" . $this->name . "'" .
                " LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS k
                    ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND j.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA
			AND k.TABLE_NAME = '" . $this->name . "'" .
                " WHERE i.TABLE_SCHEMA = '" . $this->connection->getDBName() . "'
								AND i.TABLE_NAME = '" . $this->name . "'";

        $define = $this->connection->doPrepare($qry);
        if (is_bool($define)) return;

        foreach ($define as $info) {
            if (isset($info['constraintType']) && $info['constraintType'] === 'PRIMARY KEY') {
                if (isset($info['columnName']))
                        $this->primaryKey = $info['columnName'];
            } else if ($info['refTable']) {
                if (isset($info['constraintType']))
                        unset($info['constraintType']);
                if (isset($info['columnName'])) {
                    $name = $info['columnName'];
                    unset($info['columnName']);
                }
                $this->references[$name] = $info;
            }
        }
    }