Add a method that can either result in an entity or an array of entities.
@param $query QueryBuilderResult a parsed query
@param $methodName string the name of the dsl method
@throws DslSyntaxException if an unsupported result mode was requested
187886
private function addSelectionMethod(QueryBuilderResult $query, $methodName)
    {
        $findMethod = function () use ($query, $methodName) {

            $sth = $this->pdo->prepare($query->getSql());
            /** @noinspection PhpMethodParametersCountMismatchInspection */
            $sth->setFetchMode(\PDO::FETCH_CLASS, $this->entityClass->getName());
            try {
                $sth->execute(func_get_args());
            } catch (PDOException $e) {
                throw new DslSyntaxException('Failed to run query [' . $methodName . '] with parameters ' . print_r(func_get_args(), true));
            }

            switch ($query->getResultMode()) {
                case QueryBuilderResult::RESULT_SELECT_SINGLE:
                    return $sth->fetch();
                case QueryBuilderResult::RESULT_SELECT_MULTIPLE:
                    return $sth->fetchAll();
            }

            throw new DslSyntaxException('Result Mode ' . $query->getResultMode() . ' is not implemented', DATADO_ILLEGAL_RESULT_MODE);

        };

        $this->methods[$methodName] = \Closure::bind($findMethod, $this, get_class());
    }
168058
protected function compileColumnQuery($query, $method, $parameters, $column, $keyword)
    {
        if (method_exists($query, $method) && count($parameters) <= with(new \ReflectionMethod($query, $method))->getNumberOfParameters()
        ) {
            if (Str::contains(Str::lower($method), 'raw') || Str::contains(Str::lower($method), 'exists')
            ) {
                call_user_func_array(
                        [$query, $method], $this->parameterize($parameters, $keyword)
                );
            } else {
                call_user_func_array(
                        [$query, $method], $this->parameterize($column, $parameters, $keyword)
                );
            }
        }
    }
840171
protected function runQueryCallback($query, $bindings, Closure $callback)
    {
        // To execute the statement, we'll simply call the callback, which will actually
        // run the SQL against the PDO connection. Then we can calculate the time it
        // took to execute and log the query SQL, bindings and time in our memory.
        try {
            $result = $callback($query, $bindings);
        }

            // If an exception occurs when attempting to run a query, we'll format the error
            // message to include the bindings with SQL, which will make this exception a
            // lot more helpful to the developer instead of just the database's errors.
        catch (Exception $e) {
            throw new QueryException(
                $query, $bindings, $e
            );
        }

        return $result;
    }
987645
private function setQuery(string $method, array $query, array &$globals, array &$server)
    {
        if ($method === 'get') {
            $globals['_GET'] = $query;

            return;
        }
        if ($method === 'post') {
            $globals['_POST'] = $query;

            return;
        }
        $server = $this->getStdIn($method, $query, $server);
    }
1140122
protected function executeQuery($query)
    {
        $content = (string) $this->getAdapter()->get($query)->getBody();

        if (empty($content)) {
            throw new NoResult(sprintf('Could not execute query %s', $query));
        }

        $data = json_decode($content, true);

        if (empty($data) || false === $data) {
            throw new NoResult(sprintf('Could not execute query %s', $query));
        }

        if (isset($data['features'][0]['properties']['DistanceUnit'])
            && $data['features'][0]['properties']['DistanceUnit'] == 'meter'
            && $data['features'][0]['properties']['Distance'] > 1000
        ) {
            throw new NoResult(sprintf('Result distance to far away'));
        }
        
        $bounds = array(
            'south' => isset($data['features'][0]['bbox'][0]) ? $data['features'][0]['bbox'][0] : null,
            'west'  => isset($data['features'][0]['bbox'][1]) ? $data['features'][0]['bbox'][1] : null,
            'north' => isset($data['features'][0]['bbox'][2]) ? $data['features'][0]['bbox'][3] : null,
            'east'  => isset($data['features'][0]['bbox'][3]) ? $data['features'][0]['bbox'][2] : null,
        );

        return array(array_merge($this->getDefaults(), array(
            'longitude'    => isset($data['features'][0]['geometry']['coordinates'][0]) ? $data['features'][0]['geometry']['coordinates'][0] : null,
            'latitude'     => isset($data['features'][0]['geometry']['coordinates'][1]) ? $data['features'][0]['geometry']['coordinates'][1] : null,
            'bounds'       => $bounds,
            'streetNumber' => isset($data['features'][0]['properties']['StreetNumber']) ? $data['features'][0]['properties']['StreetNumber'] : null,
            'streetName'   => isset($data['features'][0]['properties']['StreetName']) ? $data['features'][0]['properties']['StreetName'] : null,
            'cityDistrict' => isset($data['features'][0]['properties']['CountrySubdivision']) ? $data['features'][0]['properties']['CountrySubdivision'] : null,
            'city'         => isset($data['features'][0]['properties']['Municipality']) ? $data['features'][0]['properties']['Municipality'] : null,
            'zipcode'      => isset($data['features'][0]['properties']['PostalCode']) ? $data['features'][0]['properties']['PostalCode'] : null,
            'county'       => isset($data['features'][0]['properties']['MunicipalitySubdivision']) ? $data['features'][0]['properties']['MunicipalitySubdivision'] : null, //info: ??? - not available (yet ?)
            'countyCode'   => null, //isset($data['features'][0]['properties']['Zaehlbezirk']) ? $data['features'][0]['properties']['Zaehlbezirk'] : null,
            'region'       => isset($data['features'][0]['geometry']['coordinates'][0]) ? 'Vienna' : null,
            'regionCode'   => isset($data['features'][0]['geometry']['coordinates'][0]) ? 'Vienna' : null,
            'country'      => isset($data['features'][0]['geometry']['coordinates'][0]) ? 'Austria' : null,
            'countryCode'  => isset($data['features'][0]['properties']['CountryCode']) ? $data['features'][0]['properties']['CountryCode'] : null,
            'timezone'     => isset($data['features'][0]['geometry']['coordinates'][0]) ? 'Europe/Vienna' : null,
        )));
    }
222942
public function resultsAction($entityName, $query)
    {
        $searcher = $this->getSearcher();

        if (!$searcher->isSearchable($entityName)) {
            throw $this->createNotFoundException(sprintf('Entity "%s" is not searchable.', $entityName));
        }

        $entities = $this->getSearcher()->search($entityName, $query);

        $meta = $searcher->getSearchableEntityMeta($entityName);

        $batchDeleteForm = null;

        if (!empty($entities)
            && $this->isGranted(Permission::CREATE_DELETE, $meta->getEntityClass())
            && $this->getAdminRouter()->isRouteExists($meta->getEntityClass(), AdminRouter::TYPE_BATCH_DELETE)
        ) {
            $batchDeleteForm = $this->getAdminFormFactory()->createBatchDeleteForm($meta->getEntityClass(), $entities)->createView();
        }

        $view = $this->getEntitiesToIndexViewTransformer()->transform($meta, $entities);

        return $this->render('DarvinAdminBundle:Search/widget:results.html.twig', [
            'batch_delete_form' => $batchDeleteForm,
            'entities_count'    => count($entities),
            'meta'              => $meta,
            'view'              => $view,
        ]);
    }
409828
protected function createViolation(MethodNode $method, $statementName)
    {
        $message = sprintf(
            'The method %s contains a "%s" statement which violates the rule "%s"',
            $method->getFullQualifiedName(),
            $statementName,
            static::RULE
        );

        $this->addViolation($method, [$message]);
    }
760535
protected function modifyQuery(&$query, callable $callback)
    {
        $regex = "/('[^']*')/";
        if (!preg_match($regex, $query)) {
            $query = $callback($query);
            return;
        }

        $parts = preg_split($regex, $query, null, PREG_SPLIT_DELIM_CAPTURE);

        $query = "";

        foreach ($parts as $part) {

            # If this part of the query isn't a string, then perform the replace on it
            if (substr($part, 0, 1) != "'") {
                $part = $callback($part);
            }

            # Append this part of the query onto the new query we are constructing
            $query .= $part;
        }
    }
1222041
public function defaultQueryMethod($query, $config)
    {
        switch (strtolower($this->config('search_using', 'plain'))) {
            case 'tsquery':
                return new ToTsQuery($query, $config);
            case 'phrasequery':
                return new PhraseToTsQuery($query, $config);
            case 'plainquery':
            default:
                return new PlainToTsQuery($query, $config);
        }
    }
39958
public function query(
        Query $query,
        array $parameters = []
    ): Result {
        $result = $this
            ->repository
            ->query($query, $parameters);

        return $this->applyTransformersToResult($result);
    }
1072617
public function createQueryTranslation(Query $query, string $locale): void
    {
        $dbQuery = $this->connection->createQueryBuilder()
            ->insert('ngbm_collection_query_translation')
            ->values(
                [
                    'query_id' => ':query_id',
                    'status' => ':status',
                    'locale' => ':locale',
                    'parameters' => ':parameters',
                ]
            )
            ->setParameter('query_id', $query->id, Type::INTEGER)
            ->setParameter('status', $query->status, Type::INTEGER)
            ->setParameter('locale', $locale, Type::STRING)
            ->setParameter('parameters', $query->parameters[$locale], Type::JSON_ARRAY);

        $dbQuery->execute();
    }
209564
public static function addMethod($methodName, $methodCallable)
    {
        if (!is_callable($methodCallable)) {
            throw new InvalidArgumentException('Second param must be callable');
        }
        self::$methods[$methodName] = \Closure::bind($methodCallable, Mailer::instance(), get_class());
    }
620323
public function visit($query, NodeContract $node, string $context)
    {
        if ($node instanceof Nodes\AndNode) {
            $callback = function ($q) use ($node) {
                foreach ($node->getChildren() as $child) {
                    if ($child instanceof Nodes\KeyNode || $child instanceof Nodes\ValueNode) {
                        throw new \Railken\SQ\Exceptions\QuerySyntaxException();
                    }

                    $this->getBuilder()->build($q, $child, Nodes\AndNode::class);
                }
            };

            $context === Nodes\OrNode::class && $query->orWhere($callback);
            $context === Nodes\AndNode::class && $query->where($callback);
        }
    }
974813
public function withQuery($query)
    {
        if (!is_string($query) && !method_exists($query, '__toString')) {
            throw new \InvalidArgumentException('Query string must be a string');
        }
        $query = (string) $query;
        if (strpos($query, '?') === 0) {
            $query = substr($query, 1);
        }
        $query = $this->filterQueryAndFragment($query);

        $new = clone $this;
        $new->query = $query;

        return $new;
    }
1265340
public function parseFql($fieldName, $query)
    {
        // 
        if(is_string($query)) {
            // 
            $lexer = $this->createLexer((string)$query);
            
            $field = new Expr\FieldIdentifier($fieldName);
            try {
                $expr = $this->doParseExpression($lexer, $field);
            } catch(\Exception $ex) {
                throw new ParserException(sprintf('Failed to parse qeury "%s"', $query), 0, $ex);
            }

            if(!$lexer->isEol()) {
                throw new ParserException(sprintf('Invalid query "%s"', $lexer->remain()));
            }

            return $expr;
        } else if(is_array($query)) {
            $exprs = array();
            foreach($query as $q) {
                $exprs[] = $this->parseFql($fieldName, $q);
            }

            //return new Expr\AndX($exprs);
            return new Expr\LogicalExpression($exprs, Expr\LogicalExpression::TYPE_AND);
        } else {
            return new Expr\ComparisonExpression($field, $query, Expr\ComparisonExpression::EQ);
        }

        throw new ParserException('Invalid Fql query.');
    }
871678
protected function executeQuery($query)
    {
        $content = $this->getAdapter()->get($query)->getBody();

        if (null === $content) {
            throw new NoResult(sprintf('Could not execute query: %s', $query));
        }

        $json = json_decode($content, true);

        if (!empty($json['error']) && strtolower($json['error']) == 'invalid api key') {
            throw new InvalidCredentials('Invalid API Key');
        } elseif (!empty($json['error'])) {
            throw new NoResult(sprintf('Error returned from api: %s', $json['error']));
        }

        if (empty($json['results'])) {
            throw new NoResult(sprintf('Could not find results for given query: %s', $query));
        }

        $locations = $json['results'];

        $results = array();

        $ctr = 0;

        foreach ($locations as $location) {
            $ctr++;

            if ($ctr <= $this->getLimit()) {

                $coordinates = $location['location'];
                $address = $location['address_components'];

                //Geocodio does not always return a street, number, or suffix
                if (!isset($address['street']) && isset($json['input']['address_components']['street'])) {
                    //Sometimes Geocodio returns parsed information in the input
                    $addressInput = $json['input']['address_components'];
                    $address['street'] = $addressInput['street'];
                    $address['number'] = $addressInput['number'];
                    $address['suffix'] = $addressInput['suffix'];
                } elseif (!isset($address['street'])) {
                    $address['street'] = '';
                    $address['number'] = ''; // No Street = No Number
                    $address['suffix'] = '';
                }

                if (!empty($address['suffix'])) {
                    $address['street'] .= ' ' . $address['suffix'];
                }

                $results[] = array_merge($this->getDefaults(), array(

                        'latitude'      => $coordinates['lat'] ?: null,
                        'longitude'     => $coordinates['lng'] ?: null,
                        'streetNumber'  => $address['number'] ?: null,
                        'streetName'    => $address['street'] ?: null,
                        'city'          => $address['city'] ?: null,
                        'zipcode'       => $address['zip'] ?: null,
                        'county'        => $address['county'] ?: null,
                        'region'        => $address['state'] ?: null,
                        'country'       => 'US'
                    ));
            }
        }

        return $results;
    }
117995
public function scopeWithName(Builder $query, $name, $locale = null)
    {
        return $this->scopeWhereTranslation($query, 'node_name', $name, $locale);
    }