Return the index. Note that we override the default ZendSeach index
to allow us to catch the exception thrown during __destruct when running
functional tests.

@param string $indexPath
@param bool $create Create an index or open it

@return Index
516843
private function getIndex($indexPath, $create = false)
    {
        $index = new Index($indexPath, $create);
        $index->setHideException($this->hideIndexException);

        return $index;
    }
118541
public static function factory($index, $driver = null)
	{
		if (null === $driver) {
			$driver = Config::get('search.default', 'zend');
		}
		
		switch ($driver) {
			case 'algolia':
				return new Index\Algolia($index, 'algolia');
				
			case 'elasticsearch':
				return new Index\Elasticsearch($index, 'elasticsearch');
				
			case 'zend':
			default:
				return new Index\Zend($index, 'zend');
		}
	}
340001
private function makeQuery($checkIndex = true)
    {
        $this->projectDiscriminator();
        $this->addFilterCriteria();
        $this->addDiscriminatorCondition();

        if ($checkIndex && !$this->checkIndexIsEligible()) {
            throw ODMException::queryIndexRequiresKeyCondition();
        }

        $keyCondition = $this->getKeyCondition();
        $filter       = $this->getFilter($keyCondition);

        return new Query(
            $this->dm,
            $this->class,
            $this->getIndex(),
            $keyCondition->getExpression(),
            $filter->getExpression(),
            $this->expr->getTokenPathMap(),
            $this->expr->getTokenValueMap(),
            $this->expr->projection->getExpression(),
            $this->primers
        );
    }
81017
public function subtree($path, string &$name = null, bool $create = false): ?self
    {
        $parts = $this->split($path);

        $dirOrFile = array_shift($parts);
        if (!count($parts)) {
            $name = $dirOrFile;
            $subtree = $this;
        } else {
            $exists = isset($this->subTrees[$dirOrFile]);
            if (!$exists && !$create) {
                $subtree = null;
                $name = null;
            } else {
                if (!$exists && $create) {
                    $this->subTrees[$dirOrFile] = new self();
                }
                $subtree = $this->subTrees[$dirOrFile]->subtree($parts, $name, $create);
            }
        }

        return $subtree;
    }
604233
public function createIndex(): bool
    {
        $class = $this->class;

        $indexParams = [
            'index' => $this->index,
        ];

        if (count($this->notAnalyzedFields)) {
            $indexParams['body'] = [
                'mappings' => [
                    $class => [
                        '_source'    => [
                            'enabled' => true
                        ],
                        'properties' => $this->createNotAnalyzedFieldsMapping($this->notAnalyzedFields),
                    ]
                ]
            ];
        }

        $this->client->indices()->create($indexParams);
        $response = $this->client->cluster()->health([
            'index'           => $this->index,
            'wait_for_status' => 'yellow',
            'timeout'         => '5s',
        ]);

        return isset($response['status']) && $response['status'] !== 'red';
    }
879918
private function getFileNode($path, $create = false)
    {
        $fileName = PathHelper::getNodeName('/'.$path);
        $folderPath = PathHelper::getParentPath('/'.$path);
        $folder = $this->getFolderNode($folderPath, $create);

        if ($folder->hasNode($fileName) || !$create) {
            return $folder->getNode($fileName);
        }

        $file = $folder->addNode($fileName, 'nt:file');
        $file->addNode('jcr:content', 'nt:resource');

        return $file;
    }
584804
public function searchAction($path)
    {
        try {
            $this->setPath($path);
        } catch (NotFoundException $e) {
            throw $e;
        }

        $search = $this->wdb->getRequest()->getArgument('s');
        if (empty($search)) {
            return $this->indexAction($path);
        }

        $_s = Helper::makeSearch($search, $this->getPath());

        $title          = _T('Search for "%search_str%"', array('search_str'=>$search));
        $breadcrumbs    = TemplateHelper::getBreadcrumbs($this->getPath());
        $breadcrumbs[]  = $title;
        $dbfile         = new WDBFile($this->getpath());
        $page           = $dbfile->getWDBStack();
        $page['type']   = 'search';
        $tpl_params     = array(
            'page'          => $page,
            'breadcrumbs'   => $breadcrumbs,
            'title'         => $title,
        );

        $search_content = $this->wdb->display($_s, 'search', array(
            'search_str'    => $search,
            'path'          => TemplateHelper::buildPageTitle($this->getPath()),
        ));
        return array('default', $search_content, $tpl_params);
    }
78875
public static function find_or_make($folderPath)
    {
        // Safely split all parts
        $parts = array_filter(preg_split("#[/\\\\]+#", $folderPath));

        $parentID = 0;
        $item = null;
        $filter = FileNameFilter::create();
        foreach ($parts as $part) {
            if (!$part) {
                continue; // happens for paths with a trailing slash
            }

            // Ensure search includes folders with illegal characters removed, but
            // err in favour of matching existing folders if $folderPath
            // includes illegal characters itself.
            $partSafe = $filter->filter($part);
            $item = Folder::get()->filter(array(
                'ParentID' => $parentID,
                'Name' => array($partSafe, $part)
            ))->first();

            if (!$item) {
                $item = new Folder();
                $item->ParentID = $parentID;
                $item->Name = $partSafe;
                $item->Title = $part;
                $item->write();
            }
            $parentID = $item->ID;
        }

        return $item;
    }
226547
private function getDirectoryIterator(string $realPath): \SplHeap
    {
        $directoryIterator = new \RecursiveDirectoryIterator(
            $realPath,
            \RecursiveDirectoryIterator::SKIP_DOTS
        );
        $iterator          = new \RecursiveIteratorIterator(
            $directoryIterator,
            \RecursiveIteratorIterator::SELF_FIRST
        );

        return new class($iterator) extends \SplHeap
        {
            public function __construct(\RecursiveIteratorIterator $iterator)
            {
                foreach ($iterator as $item) {
                    $this->insert($item);
                }
            }

            /**
             * @param mixed $item1
             * @param mixed $item2
             *
             * @return int
             */
            protected function compare($item1, $item2): int
            {
                return strcmp((string)$item2->getRealPath(), (string)$item1->getRealPath());
            }
        };
    }
976927
def get_or_create_index(self, paths=None, name=None, refresh=False):
        
        if not paths:
            paths = sys.path
        if not name:
            name = 'default'
        self._name = name

        idx_dir = get_cache_dir()
        idx_file = os.path.join(idx_dir, name + '.json')

        if os.path.exists(idx_file) and not refresh:
            with open(idx_file) as fd:
                self.deserialize(fd)
        else:
            self.build_index(paths)
            with open(idx_file, 'w') as fd:
                self.serialize(fd)

        return self
351594
public function create($path)
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use passive mode.');
			}

			$buffer = fopen('buffer://tmp', 'r');

			if (@ftp_fput($this->conn, $path, $buffer, FTP_ASCII) === false)
			{
				fclose($buffer);

				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			fclose($buffer);

			return true;
		}

		// Start passive mode
		if (!$this->_passive())
		{
			throw new FilesystemException(__METHOD__ . ': Unable to use passive mode.');
		}

		if (!$this->_putCmd('STOR ' . $path, array(150, 125)))
		{
			@ fclose($this->dataconn);

			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150 or 125].  Path sent: %3$s', __METHOD__, $this->response, $path)
			);
		}

		// To create a zero byte upload close the data port connection
		fclose($this->dataconn);

		if (!$this->_verifyResponse(226))
		{
			throw new FilesystemException(
				sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected: 226].  Path sent: %3$s', __METHOD__, $this->response, $path)
			);
		}

		return true;
	}
1351247
public static function indexFile( $withAccessPath = true )
    {
        $sys  = self::instance();
        $text = $sys->IndexFile;

        if ( $withAccessPath && ( isset( $sys->AccessPath['siteaccess']['url'][0] ) || isset( $sys->AccessPath['path']['url'][0] ) ) )
        {
            $ini = eZINI::instance();
            if ( isset( $sys->AccessPath['siteaccess']['url'][0] ) &&
                 $ini->variable( 'SiteAccessSettings', 'RemoveSiteAccessIfDefaultAccess' ) === 'enabled' )
            {
                $defaultAccess = $ini->variable( 'SiteSettings', 'DefaultAccess' );
                // 1st is proper match where code has used updated api as of 4.4, do not use siteaccess
                if ( $sys->AccessPath['siteaccess']['name'] === $defaultAccess )
                    $accessPath = implode( '/', $sys->AccessPath['path']['url'] );
                // 2nd is for compatability with older code that used eZSys api withouth defining scopes, shift default siteaccess path
                elseif ( $sys->AccessPath['siteaccess']['name'] === 'undefined' && $sys->AccessPath['siteaccess']['url'][0] === $defaultAccess )
                {
                    $accessPathArray = $sys->AccessPath;
                    array_shift( $accessPathArray['siteaccess']['url'] ); //remove default siteaccess
                    $accessPath = implode( '/', array_merge( $accessPathArray['siteaccess']['url'], $accessPathArray['path']['url'] ) );
                }
                // In case there is no default siteaccess match use full url
                else
                    $accessPath = implode( '/', array_merge( $sys->AccessPath['siteaccess']['url'], $sys->AccessPath['path']['url'] ) );
            }
            else
            {
                $accessPath = implode( '/', array_merge( $sys->AccessPath['siteaccess']['url'], $sys->AccessPath['path']['url'] ) );
            }

            $text .= '/' . $accessPath;

            // Make sure we never return just a single '/' in case where siteaccess was shifted
            if ( $text === '/' )
                $text = '';
        }
        return $text;
    }
1362012
private static function createIndexFilesToPreventDirectoryListing($path)
    {
        if (!self::isPathWithinTmpFolder($path)) {
            return;
        }
        $filesToCreate = array(
            $path . '/index.htm',
            $path . '/index.php'
        );
        foreach ($filesToCreate as $file) {
            @file_put_contents($file, 'Nothing to see here.');
        }
    }
164824
public function getFileContent($filePath, $createIfNotExists = false)
    {
        if ($createIfNotExists && ! $this->disk->exists($filePath)) {
            if (! $this->disk->exists($directory = dirname($filePath))) {
                mkdir($directory, 0777, true);
            }

            file_put_contents($filePath, "<?php\n\nreturn [];");

            return [];
        }

        try {
            return (array) include $filePath;
        } catch (\ErrorException $e) {
            throw new FileNotFoundException('File not found: '.$filePath);
        }
    }
737729
function create($callback = false)
    {

        $index = new Index($this->index, $callback);

        $index->connection = $this->connection;

        return $index->create();
    }
241750
protected function addIndicesToFields(DOMXPath $rootPath)
    {
        $fetchedNodes = [];
        $fields = $this->getFields();
        $multipleIndices = [];
        $idMap = array_flip(
            array_map(
                function (MigrationField $field) {
                    return $field->getId();
                },
                $fields
            )
        );

        /** @var MigrationField $field */
        foreach ($fields as $name => $field) {
            $usedId = $field->getId();
            $indexNodes = $rootPath->query(
                './value[@content-struct-name="db.mysql.Index" and @key="indices"]/' .
                'value[@type="object" and @struct-name="db.mysql.Index"]//' .
                'value[@type="object" and @struct-name="db.mysql.IndexColumn"]//' .
                'link[@type="object" and @struct-name="db.Column" and @key="referencedColumn" ' .
                'and text() = "' . $usedId . '"]/' .
                '../' .
                '../' .
                '..'
            );

            if ($indexNodes && $indexNodes->length) {
                $fks = $this->getForeignKeysForField($field, $rootPath);

                /** @var \DOMNode $indexNode */
                foreach ($indexNodes as $indexNode) {
                    if (in_array($nodeId = $indexNode->attributes->getNamedItem('id')->nodeValue, $fetchedNodes)) {
                        continue;
                    } // if

                    $fetchedNodes[] = $nodeId;

                    $indexColumns = $rootPath->query(
                        './/link[@type="object" and @struct-name="db.Column" and @key="referencedColumn"]',
                        $indexNode
                    );

                    $isSingleColumn = $indexColumns && $indexColumns->length <= 1;
                    $genericCall = !$isSingleColumn ? new Base() : null;

                    if ($rootPath->evaluate(
                        'boolean(./value[@type="int" and @key="unique" and number() = 1])',
                        $indexNode
                    )
                    ) {
                        if ($isSingleColumn) {
                            $field->addAdditionalOption('unique');
                        } // if
                        else {
                            $genericMethod = 'unique';
                        } // else
                    } // if

                    $hasIndex = $rootPath->evaluate(
                        'boolean(./value[@type="string" and @key="indexType" and text() = "INDEX"])',
                        $indexNode
                    );

                    if ($hasIndex && (!$fks || !$fks->length)) {
                        if ($isSingleColumn) {
                            $field->addAdditionalOption('index');
                        } // if
                        else {
                            $genericMethod = 'index';
                        } // else
                    } // if

                    if ($rootPath->evaluate(
                        'boolean(./value[@type="string" and @key="indexType" and text() = "PRIMARY"])',
                        $indexNode
                    )
                    ) {
                        if ($isSingleColumn) {
                            $field->addAdditionalOption('primary');
                        } // if
                        else {
                            $genericMethod = 'primary';
                        } // else
                    } // if

                    if ($genericCall && $genericMethod) {
                        $genericParams = [];
                        /** @var DOMNode $column */
                        foreach ($indexColumns as $column) {
                            $genericParams[] = $idMap[$column->nodeValue];
                        } // foreach

                        $this->addGenericCall(call_user_func_array(
                            [$genericCall, $genericMethod],
                            $genericParams ? [$genericParams] : []
                        ));
                    }
                }
            }
        }

        return array_unique($multipleIndices);
    }
477334
private function getFolderNode($path, $create = false)
    {
        $location = $this->applyPathPrefix($path);
        if (!$create && !$this->session->nodeExists($location)) {
            // trigger the phpcr exception rather than trying to create parent nodes.
            return $this->session->getNode($location);
        }

        $folders = array();
        while (!$this->session->nodeExists($location)) {
            $folders[] = PathHelper::getNodeName($location);
            $location = PathHelper::getParentPath($location);
        }

        $node = $this->session->getNode($location);
        while (null !== $folder = array_pop($folders)) {
            $node = $node->addNode($folder, 'nt:folder');
        }
        if (!$node->isNodeType('nt:folder')) {
            throw new \LogicException($path.' is not a folder but '.$node->getPrimaryNodeType()->getName());
        }

        if ($create) {
            $this->session->save();
        }

        return $node;
    }