sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function processFuzzyProximityModifier($parameter = null) { $this->_proximityQuery = true; if ($parameter !== null) { $this->_wordsDistance = $parameter; } }
Process modifier ('~') @param mixed $parameter
entailment
public function getQuery($encoding) { /** * Zend_Search_Lucene_Search_Query_Preprocessing_Phrase */ include_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Phrase.php'; $query = new Zend_Search_Lucene_Search_Query_Preprocessing_Phrase( $this->_phrase, $encoding, ($this->_field !== null)? iconv($encoding, 'UTF-8', $this->_field) : null ); if ($this->_proximityQuery) { $query->setSlop($this->_wordsDistance); } $query->setBoost($this->_boost); return $query; }
Transform entry to a subquery @param string $encoding @return Zend_Search_Lucene_Search_Query @throws Zend_Search_Lucene_Search_QueryParserException
entailment
protected function createGuzzleRequest($method, $uri, array $extraParameters) { $extraParameters = $this->mergeGuzzleRequestExtraParams($extraParameters); return new Request( strtoupper($method), $uri, $extraParameters['headers'], $extraParameters['body'], $extraParameters['protocolVersion'] ); }
@param string $method @param string $uri @param array $extraParameters @return Request
entailment
protected function sendRequest($method, $uri, array $extraParameters = array(), array $clientOptions = array()) { $request = $this->createGuzzleRequest($method, $uri, $extraParameters); $client = $this->getGuzzleClientIntance(); return $client->send($request, $clientOptions); }
@param string $method @param string $uri @param array $extraParameters @param array $clientOptions @return Response @throws \LogicException
entailment
protected function setOptionsCurlUpload($curlResource, array $options) { foreach ($options as $key => $value) { curl_setopt($curlResource, $key, $value); } return $curlResource; }
@param resource $curlResource @param array $options @return bool
entailment
protected function getOptionsCurlUpload($uri, array $postFields) { return array( CURLOPT_HEADER => 0, CURLOPT_VERBOSE => 0, CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $uri, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postFields, ); }
@param string $uri @param array $postFields @return array
entailment
protected function sendFile($uri, array $postFields) { $curlResource = $this->initCurlUpload(); $curlOptions = $this->getOptionsCurlUpload($uri, $postFields); $curlResource = $this->setOptionsCurlUpload($curlResource, $curlOptions); return $this->execCurlUpload($curlResource); }
@param string $uri @param array $postFields @return string|bool
entailment
private function _translateInput($char) { if (strpos(self::QUERY_WHITE_SPACE_CHARS, $char) !== false) { return self::IN_WHITE_SPACE; } else if (strpos(self::QUERY_SYNT_CHARS, $char) !== false) { return self::IN_SYNT_CHAR; } else if (strpos(self::QUERY_MUTABLE_CHARS, $char) !== false) { return self::IN_MUTABLE_CHAR; } else if (strpos(self::QUERY_LEXEMEMODIFIER_CHARS, $char) !== false) { return self::IN_LEXEME_MODIFIER; } else if (strpos(self::QUERY_ASCIIDIGITS_CHARS, $char) !== false) { return self::IN_ASCII_DIGIT; } else if ($char === '"' ) { return self::IN_QUOTE; } else if ($char === '.' ) { return self::IN_DECIMAL_POINT; } else if ($char === '\\') { return self::IN_ESCAPE_CHAR; } else { return self::IN_CHAR; } }
Translate input char to an input symbol of state machine @param string $char @return integer
entailment
public function tokenize($inputString, $encoding) { $this->reset(); $this->_lexemes = array(); $this->_queryString = array(); if (PHP_OS == 'AIX' && $encoding == '') { $encoding = 'ISO8859-1'; } $strLength = iconv_strlen($inputString, $encoding); // Workaround for iconv_substr bug $inputString .= ' '; for ($count = 0; $count < $strLength; $count++) { $this->_queryString[$count] = iconv_substr($inputString, $count, 1, $encoding); } for ($this->_queryStringPosition = 0; $this->_queryStringPosition < count($this->_queryString); $this->_queryStringPosition++) { $this->process($this->_translateInput($this->_queryString[$this->_queryStringPosition])); } $this->process(self::IN_WHITE_SPACE); if ($this->getState() != self::ST_WHITE_SPACE) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Unexpected end of query'); } $this->_queryString = null; return $this->_lexemes; }
This method is used to tokenize query string into lexemes @param string $inputString @param string $encoding @return array @throws Zend_Search_Lucene_Search_QueryParserException
entailment
public function addQuerySyntaxLexeme() { $lexeme = $this->_queryString[$this->_queryStringPosition]; // Process two char lexemes if (strpos(self::QUERY_DOUBLECHARLEXEME_CHARS, $lexeme) !== false) { // increase current position in a query string $this->_queryStringPosition++; // check, if ($this->_queryStringPosition == count($this->_queryString) || $this->_queryString[$this->_queryStringPosition] != $lexeme ) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Two chars lexeme expected. ' . $this->_positionMsg()); } // duplicate character $lexeme .= $lexeme; } $token = new Zend_Search_Lucene_Search_QueryToken( Zend_Search_Lucene_Search_QueryToken::TC_SYNTAX_ELEMENT, $lexeme, $this->_queryStringPosition ); // Skip this lexeme if it's a field indicator ':' and treat previous as 'field' instead of 'word' if ($token->type == Zend_Search_Lucene_Search_QueryToken::TT_FIELD_INDICATOR) { $token = array_pop($this->_lexemes); if ($token === null || $token->type != Zend_Search_Lucene_Search_QueryToken::TT_WORD) { include_once 'Zend/Search/Lucene/Search/QueryParserException.php'; throw new Zend_Search_Lucene_Search_QueryParserException('Field mark \':\' must follow field name. ' . $this->_positionMsg()); } $token->type = Zend_Search_Lucene_Search_QueryToken::TT_FIELD; } $this->_lexemes[] = $token; }
Add query syntax lexeme @throws Zend_Search_Lucene_Search_QueryParserException
entailment
public function addLexemeModifier() { $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( Zend_Search_Lucene_Search_QueryToken::TC_SYNTAX_ELEMENT, $this->_queryString[$this->_queryStringPosition], $this->_queryStringPosition ); }
Add lexeme modifier
entailment
public function addLexeme() { $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( Zend_Search_Lucene_Search_QueryToken::TC_WORD, $this->_currentLexeme, $this->_queryStringPosition - 1 ); $this->_currentLexeme = ''; }
Add lexeme
entailment
public function addQuotedLexeme() { $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( Zend_Search_Lucene_Search_QueryToken::TC_PHRASE, $this->_currentLexeme, $this->_queryStringPosition ); $this->_currentLexeme = ''; }
Add quoted lexeme
entailment
public function addNumberLexeme() { $this->_lexemes[] = new Zend_Search_Lucene_Search_QueryToken( Zend_Search_Lucene_Search_QueryToken::TC_NUMBER, $this->_currentLexeme, $this->_queryStringPosition - 1 ); $this->_currentLexeme = ''; }
Add number lexeme
entailment
public function send($recipient, $body, $originator = '') { if (null === $this->accessToken) { throw new Exception\InvalidCredentialsException('No API credentials provided'); } $params = array( 'messageContent' => $body, 'recipientAddressList' => array( $this->removeLeadingPlusIfPresent( $this->localNumberToInternational($recipient, $this->internationalPrefix) ) ) ); return $this->executeQuery(self::ENDPOINT_URL, $params, array( 'recipient' => $recipient, 'body' => $body, 'originator' => $originator, )); }
{@inheritDoc}
entailment
protected function executeQuery($url, array $data = array(), array $extra_result_data = array()) { $headers = array( sprintf('Authorization: Bearer %s', $this->accessToken), 'Content-Type: application/json', 'Accept: application/json' ); // Issue the request $content = $this->getAdapter()->getContent($url, 'POST', $headers, json_encode($data)); if (null === $content) { return array_merge($this->getDefaults(), $extra_result_data); } return $this->parseResults($content, $extra_result_data); }
Issues the actual HTTP query. @param $url @param array $data @param array $extra_result_data @return array
entailment
protected function parseResults($result, array $extra_result_data = array()) { $data = json_decode($result, true); $smsData = array(); // There was an error if (empty($data['transferId']) || empty($data['statusCode'])) { return array_merge($this->getDefaults(), $extra_result_data, array( 'status' => ResultInterface::STATUS_FAILED, ) ); } // Get the transfer id $smsData['id'] = $data['transferId']; // Get the status switch ($data['statusCode']) { case 2000: $smsData['status'] = ResultInterface::STATUS_SENT; break; case 2001: $smsData['status'] = ResultInterface::STATUS_QUEUED; break; default: $smsData['status'] = ResultInterface::STATUS_FAILED; break; } return array_merge($this->getDefaults(), $extra_result_data, $smsData); }
Parses the data returned by the API. @param string $result The raw result string. @return array
entailment
public static function getPrefix($str, $length) { $prefixBytes = 0; $prefixChars = 0; while ($prefixBytes < strlen($str) && $prefixChars < $length) { $charBytes = 1; if ((ord($str[$prefixBytes]) & 0xC0) == 0xC0) { $charBytes++; if (ord($str[$prefixBytes]) & 0x20 ) { $charBytes++; if (ord($str[$prefixBytes]) & 0x10 ) { $charBytes++; } } } if ($prefixBytes + $charBytes > strlen($str)) { // wrong character break; } $prefixChars++; $prefixBytes += $charBytes; } return substr($str, 0, $prefixBytes); }
Get term prefix @param string $str @param integer $length @return string
entailment
public static function getLength($str) { $bytes = 0; $chars = 0; while ($bytes < strlen($str)) { $charBytes = 1; if ((ord($str[$bytes]) & 0xC0) == 0xC0) { $charBytes++; if (ord($str[$bytes]) & 0x20 ) { $charBytes++; if (ord($str[$bytes]) & 0x10 ) { $charBytes++; } } } if ($bytes + $charBytes > strlen($str)) { // wrong character break; } $chars++; $bytes += $charBytes; } return $chars; }
Get UTF-8 string length @param string $str @return string
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { // Allow to use wildcards within phrases // They are either removed by text analyzer or used as a part of keyword for keyword fields // // if (strpos($this->_phrase, '?') !== false || strpos($this->_phrase, '*') !== false) { // require_once 'Zend/Search/Lucene/Search/QueryParserException.php'; // throw new Zend_Search_Lucene_Search_QueryParserException('Wildcards are only allowed in a single terms.'); // } // Split query into subqueries if field name is not specified if ($this->_field === null) { include_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; $query = new Zend_Search_Lucene_Search_Query_Boolean(); $query->setBoost($this->getBoost()); include_once 'Zend/Search/Lucene.php'; if (Zend_Search_Lucene::getDefaultSearchField() === null) { $searchFields = $index->getFieldNames(true); } else { $searchFields = array(Zend_Search_Lucene::getDefaultSearchField()); } foreach ($searchFields as $fieldName) { $subquery = new Zend_Search_Lucene_Search_Query_Preprocessing_Phrase( $this->_phrase, $this->_phraseEncoding, $fieldName ); $subquery->setSlop($this->getSlop()); $query->addSubquery($subquery->rewrite($index)); } $this->_matches = $query->getQueryTerms(); return $query; } // Recognize exact term matching (it corresponds to Keyword fields stored in the index) // encoding is not used since we expect binary matching include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($this->_phrase, $this->_field); if ($index->hasTerm($term)) { include_once 'Zend/Search/Lucene/Search/Query/Term.php'; $query = new Zend_Search_Lucene_Search_Query_Term($term); $query->setBoost($this->getBoost()); $this->_matches = $query->getQueryTerms(); return $query; } // tokenize phrase using current analyzer and process it as a phrase query include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_phrase, $this->_phraseEncoding); if (count($tokens) == 0) { $this->_matches = array(); include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php'; return new Zend_Search_Lucene_Search_Query_Insignificant(); } if (count($tokens) == 1) { include_once 'Zend/Search/Lucene/Index/Term.php'; $term = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field); include_once 'Zend/Search/Lucene/Search/Query/Term.php'; $query = new Zend_Search_Lucene_Search_Query_Term($term); $query->setBoost($this->getBoost()); $this->_matches = $query->getQueryTerms(); return $query; } //It's non-trivial phrase query $position = -1; include_once 'Zend/Search/Lucene/Search/Query/Phrase.php'; $query = new Zend_Search_Lucene_Search_Query_Phrase(); include_once 'Zend/Search/Lucene/Index/Term.php'; foreach ($tokens as $token) { $position += $token->getPositionIncrement(); $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $this->_field); $query->addTerm($term, $position); $query->setSlop($this->getSlop()); } $this->_matches = $query->getQueryTerms(); return $query; }
Re-write query into primitive queries in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query
entailment
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { /** * Skip fields detection. We don't need it, since we expect all fields presented in the HTML body and don't differentiate them */ /** * Skip exact term matching recognition, keyword fields highlighting is not supported */ /** * Skip wildcard queries recognition. Supported wildcards are removed by text analyzer */ // tokenize phrase using current analyzer and process it as a phrase query include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_phrase, $this->_phraseEncoding); if (count($tokens) == 0) { // Do nothing return; } if (count($tokens) == 1) { $highlighter->highlight($tokens[0]->getTermText()); return; } //It's non-trivial phrase query $words = array(); foreach ($tokens as $token) { $words[] = $token->getTermText(); } $highlighter->highlight($words); }
Query specific matches highlighting @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
entailment
protected function isPureArray(array $array ) { $i=0; foreach($array as $k=>$v) { if ( $k !== $i ) { return false; } $i++; } return true; }
Checks wether the provided array has string keys and if it's not sparse. @param array $arr @return bool
entailment
public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) { return $this->_index->termDocs($term, $docsFilter); }
Returns IDs of all the documents containing term. @param Zend_Search_Lucene_Index_Term $term @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter @return array
entailment
public function termDocsFilter(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) { return $this->_index->termDocsFilter($term, $docsFilter); }
Returns documents filter for all documents containing term. It performs the same operation as termDocs, but return result as Zend_Search_Lucene_Index_DocsFilter object @param Zend_Search_Lucene_Index_Term $term @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter @return Zend_Search_Lucene_Index_DocsFilter
entailment
public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) { return $this->_index->termFreqs($term, $docsFilter); }
Returns an array of all term freqs. Return array structure: array( docId => freq, ...) @param Zend_Search_Lucene_Index_Term $term @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter @return integer
entailment
public function termPositions(Zend_Search_Lucene_Index_Term $term, $docsFilter = null) { return $this->_index->termPositions($term, $docsFilter); }
Returns an array of all term positions in the documents. Return array structure: array( docId => array( pos1, pos2, ...), ...) @param Zend_Search_Lucene_Index_Term $term @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter @return array
entailment
public function flush(SmsSenderInterface $sender) { $results = array(); $errors = array(); foreach ($this->messages as $message) { try { $results[] = $sender->send($message['recipient'], $message['body'], $message['originator']); } catch (Exception $e) { $errors[] = $e; } } return array($results, $errors); }
{@inheritdoc}
entailment
public function getContent($url, $method = 'GET', array $headers = array(), $data = array()) { if (!function_exists('curl_init')) { throw new \RuntimeException('cURL has to be enabled.'); } $c = curl_init(); // build the request... curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1); // allow redirects. curl_setopt($c, CURLOPT_CUSTOMREQUEST, strtoupper($method)); // define the HTTP method // join the data if (!empty($data) && 'POST' === strtoupper($method)) { if (is_array($data)) { $data = $this->encodePostData($data); } curl_setopt($c, CURLOPT_POSTFIELDS, $data); } // and add the headers if (!empty($headers)) { curl_setopt($c, CURLOPT_HTTPHEADER, $headers); } // execute the request $content = curl_exec($c); curl_close($c); if (false === $content) { $content = null; } return $content; }
{@inheritDoc}
entailment
protected function getUri($module, $method, $responseFormat, array $requestParameters = array()) { if (!$this->hasMethod($method)) { throw new \InvalidArgumentException(sprintf('The method %s is not registered', $method)); } if (!$this->hasResponseFormat($responseFormat)) { throw new \InvalidArgumentException(sprintf('The response format %s is not registered', $responseFormat)); } if (!isset($requestParameters['scope'])) { $requestParameters['scope'] = self::API_DEFAULT_SCOPE; } if (!isset($requestParameters['version'])) { $requestParameters['version'] = self::API_DEFAULT_VERSION; } $uri = sprintf( self::API_BASE_URL, $responseFormat, $module, $method, $this->getAuthToken() ); return $uri . $this->generateQueryStringByRequestParams($requestParameters); }
@param string $module @param string $method @param string $responseFormat @param array $requestParameters @return string @throws \InvalidArgumentException
entailment
protected function getUnserializedData(Response $response, $responseFormat) { return UnserializerBuilder::create($responseFormat)->unserialize( $response->getBody()->getContents() ); }
@param Response $response @param string $responseFormat @return array
entailment
public function run($request) { $this->start(); $registered = Config::inst()->get('DocumentationManifest', 'register_entities'); foreach ($registered as $details) { // validate the details provided through the YAML configuration $required = array('Path', 'Title'); // Check required configs foreach ($required as $require) { if (!isset($details[$require])) { $this->showError("$require is a required key in DocumentationManifest.register_entities"); } } // Check path is loaded $path = $this->getRealPath($details['Path']); if (!$path || !is_dir($path)) { $this->showError($details['Path'] . ' is not a valid documentation directory'); } } $this->end(); }
Validate all source files @param SS_HTTPRequest $request @throws Exception
entailment
public function addTerm(Zend_Search_Lucene_Index_Term $term, $position = null) { if ((count($this->_terms) != 0)&&(end($this->_terms)->field != $term->field)) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception( 'All phrase terms must be in the same field: ' . $term->field . ':' . $term->text ); } $this->_terms[] = $term; if ($position !== null) { $this->_offsets[] = $position; } else if (count($this->_offsets) != 0) { $this->_offsets[] = end($this->_offsets) + 1; } else { $this->_offsets[] = 0; } }
Adds a term to the end of the query phrase. The relative position of the term is specified explicitly or the one immediately after the last term added. @param Zend_Search_Lucene_Index_Term $term @param integer $position
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { if (count($this->_terms) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } else if ($this->_terms[0]->field !== null) { return $this; } else { include_once 'Zend/Search/Lucene/Search/Query/Boolean.php'; $query = new Zend_Search_Lucene_Search_Query_Boolean(); $query->setBoost($this->getBoost()); foreach ($index->getFieldNames(true) as $fieldName) { $subquery = new Zend_Search_Lucene_Search_Query_Phrase(); $subquery->setSlop($this->getSlop()); include_once 'Zend/Search/Lucene/Index/Term.php'; foreach ($this->_terms as $termId => $term) { $qualifiedTerm = new Zend_Search_Lucene_Index_Term($term->text, $fieldName); $subquery->addTerm($qualifiedTerm, $this->_offsets[$termId]); } $query->addSubquery($subquery); } return $query; } }
Re-write query into primitive queries in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query
entailment
public function optimize(Zend_Search_Lucene_Interface $index) { // Check, that index contains all phrase terms foreach ($this->_terms as $term) { if (!$index->hasTerm($term)) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } } if (count($this->_terms) == 1) { // It's one term query include_once 'Zend/Search/Lucene/Search/Query/Term.php'; $optimizedQuery = new Zend_Search_Lucene_Search_Query_Term(reset($this->_terms)); $optimizedQuery->setBoost($this->getBoost()); return $optimizedQuery; } if (count($this->_terms) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } return $this; }
Optimize query in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query
entailment
public function createWeight(Zend_Search_Lucene_Interface $reader) { include_once 'Zend/Search/Lucene/Search/Weight/Phrase.php'; $this->_weight = new Zend_Search_Lucene_Search_Weight_Phrase($this, $reader); return $this->_weight; }
Constructs an appropriate Weight implementation for this query. @param Zend_Search_Lucene_Interface $reader @return Zend_Search_Lucene_Search_Weight
entailment
public function _exactPhraseFreq($docId) { $freq = 0; // Term Id with lowest cardinality $lowCardTermId = null; // Calculate $lowCardTermId foreach ($this->_terms as $termId => $term) { if ($lowCardTermId === null || count($this->_termsPositions[$termId][$docId]) <count($this->_termsPositions[$lowCardTermId][$docId]) ) { $lowCardTermId = $termId; } } // Walk through positions of the term with lowest cardinality foreach ($this->_termsPositions[$lowCardTermId][$docId] as $lowCardPos) { // We expect phrase to be found $freq++; // Walk through other terms foreach ($this->_terms as $termId => $term) { if ($termId != $lowCardTermId) { $expectedPosition = $lowCardPos + ($this->_offsets[$termId] - $this->_offsets[$lowCardTermId]); if (!in_array($expectedPosition, $this->_termsPositions[$termId][$docId])) { $freq--; // Phrase wasn't found. break; } } } } return $freq; }
Score calculator for exact phrase queries (terms sequence is fixed) @param integer $docId @return float
entailment
public function _sloppyPhraseFreq($docId, Zend_Search_Lucene_Interface $reader) { $freq = 0; $phraseQueue = array(); $phraseQueue[0] = array(); // empty phrase $lastTerm = null; // Walk through the terms to create phrases. foreach ($this->_terms as $termId => $term) { $queueSize = count($phraseQueue); $firstPass = true; // Walk through the term positions. // Each term position produces a set of phrases. foreach ($this->_termsPositions[$termId][$docId] as $termPosition ) { if ($firstPass) { for ($count = 0; $count < $queueSize; $count++) { $phraseQueue[$count][$termId] = $termPosition; } } else { for ($count = 0; $count < $queueSize; $count++) { if ($lastTerm !== null && abs( $termPosition - $phraseQueue[$count][$lastTerm] - ($this->_offsets[$termId] - $this->_offsets[$lastTerm]) ) > $this->_slop) { continue; } $newPhraseId = count($phraseQueue); $phraseQueue[$newPhraseId] = $phraseQueue[$count]; $phraseQueue[$newPhraseId][$termId] = $termPosition; } } $firstPass = false; } $lastTerm = $termId; } foreach ($phraseQueue as $phrasePos) { $minDistance = null; for ($shift = -$this->_slop; $shift <= $this->_slop; $shift++) { $distance = 0; $start = reset($phrasePos) - reset($this->_offsets) + $shift; foreach ($this->_terms as $termId => $term) { $distance += abs($phrasePos[$termId] - $this->_offsets[$termId] - $start); if($distance > $this->_slop) { break; } } if ($minDistance === null || $distance < $minDistance) { $minDistance = $distance; } } if ($minDistance <= $this->_slop) { $freq += $reader->getSimilarity()->sloppyFreq($minDistance); } } return $freq; }
Score calculator for sloppy phrase queries (terms sequence is fixed) @param integer $docId @param Zend_Search_Lucene_Interface $reader @return float
entailment
public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) { $this->_resVector = null; if (count($this->_terms) == 0) { $this->_resVector = array(); } $resVectors = array(); $resVectorsSizes = array(); $resVectorsIds = array(); // is used to prevent arrays comparison foreach ($this->_terms as $termId => $term) { $resVectors[] = array_flip($reader->termDocs($term)); $resVectorsSizes[] = count(end($resVectors)); $resVectorsIds[] = $termId; $this->_termsPositions[$termId] = $reader->termPositions($term); } // sort resvectors in order of subquery cardinality increasing array_multisort( $resVectorsSizes, SORT_ASC, SORT_NUMERIC, $resVectorsIds, SORT_ASC, SORT_NUMERIC, $resVectors ); foreach ($resVectors as $nextResVector) { if($this->_resVector === null) { $this->_resVector = $nextResVector; } else { //$this->_resVector = array_intersect_key($this->_resVector, $nextResVector); /** * This code is used as workaround for array_intersect_key() slowness problem. */ $updatedVector = array(); foreach ($this->_resVector as $id => $value) { if (isset($nextResVector[$id])) { $updatedVector[$id] = $value; } } $this->_resVector = $updatedVector; } if (count($this->_resVector) == 0) { // Empty result set, we don't need to check other terms break; } } // ksort($this->_resVector, SORT_NUMERIC); // Docs are returned ordered. Used algorithm doesn't change elements order. // Initialize weight if it's not done yet $this->_initWeight($reader); }
Execute query in context of index reader It also initializes necessary internal structures @param Zend_Search_Lucene_Interface $reader @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
entailment
public function score($docId, Zend_Search_Lucene_Interface $reader) { if (isset($this->_resVector[$docId])) { if ($this->_slop == 0) { $freq = $this->_exactPhraseFreq($docId); } else { $freq = $this->_sloppyPhraseFreq($docId, $reader); } if ($freq != 0) { $tf = $reader->getSimilarity()->tf($freq); $weight = $this->_weight->getValue(); $norm = $reader->norm($docId, reset($this->_terms)->field); return $tf * $weight * $norm * $this->getBoost(); } // Included in result, but culculated freq is zero return 0; } else { return 0; } }
Score specified document @param integer $docId @param Zend_Search_Lucene_Interface $reader @return float
entailment
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { $words = array(); foreach ($this->_terms as $term) { $words[] = $term->text; } $highlighter->highlight($words); }
Query specific matches highlighting @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
entailment
public function sumOfSquaredWeights() { $sum = 0; foreach ($this->_weights as $weight) { // sum sub weights $sum += $weight->sumOfSquaredWeights(); } // boost each sub-weight $sum *= $this->_query->getBoost() * $this->_query->getBoost(); // check for empty query (like '-something -another') if ($sum == 0) { $sum = 1.0; } return $sum; }
The sum of squared weights of contained query clauses. @return float
entailment
public function normalize($queryNorm) { // incorporate boost $queryNorm *= $this->_query->getBoost(); foreach ($this->_weights as $weight) { $weight->normalize($queryNorm); } }
Assigns the query normalization factor to this. @param float $queryNorm
entailment
public static function add($map = array()) { if (ArrayLib::is_associative($map)) { self::$mapping = array_merge(self::$mapping, $map); } else { user_error("DocumentationPermalinks::add() requires an associative array", E_USER_ERROR); } }
Add a mapping of nice short permalinks to a full long path <code> DocumentationPermalinks::add(array( 'debugging' => 'current/en/sapphire/topics/debugging' )); </code> Do not need to include the language or the version current as it will add it based off the language or version in the session @param array
entailment
public static function map($url) { return (isset(self::$mapping[$url])) ? self::$mapping[$url] : false; }
Return the location for a given short value. @return string|false
entailment
public function sendRequest($servicePath,$data) { // We're using the FLEX Messaging framework if($this->encoding & SabreAMF_Const::FLEXMSG) { // Setting up the message $message = new SabreAMF_AMF3_RemotingMessage(); $message->body = $data; // We need to split serviceName.methodName into separate variables $service = explode('.',$servicePath); $method = array_pop($service); $service = implode('.',$service); $message->operation = $method; $message->source = $service; $data = $message; } $this->amfRequest->addBody(array( // If we're using the flex messaging framework, target is specified as the string 'null' 'target' => $this->encoding & SabreAMF_Const::FLEXMSG?'null':$servicePath, 'response' => '/1', 'data' => $data )); $this->amfRequest->serialize($this->amfOutputStream); $headers = array_merge(array( 'Content-type: ' . SabreAMF_Const::MIMETYPE ), $this->httpHeaders); // The curl request $ch = curl_init($this->endPoint); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_TIMEOUT,20); curl_setopt($ch,CURLOPT_HTTPHEADER,$headers); curl_setopt($ch,CURLOPT_POSTFIELDS,$this->amfOutputStream->getRawData()); if ($this->httpProxy) { curl_setopt($ch,CURLOPT_PROXY,$this->httpProxy); } $result = curl_exec($ch); if (curl_errno($ch)) { throw new Exception('CURL error: ' . curl_error($ch)); false; } else { curl_close($ch); } $this->amfInputStream = new SabreAMF_InputStream($result); $this->amfResponse = new SabreAMF_Message(); $this->amfResponse->deserialize($this->amfInputStream); $this->parseHeaders(); foreach($this->amfResponse->getBodies() as $body) { if (strpos($body['target'],'/1')===0) return $body['data'] ; } }
sendRequest sendRequest sends the request to the server. It expects the servicepath and methodname, and the parameters of the methodcall @param string $servicePath The servicepath (e.g.: myservice.mymethod) @param array $data The parameters you want to send @return mixed
entailment
public function addHeader($name,$required,$data) { $this->amfRequest->addHeader(array('name'=>$name,'required'=>$required==true,'data'=>$data)); }
addHeader Add a header to the client request @param string $name @param bool $required @param mixed $data @return void
entailment
private function parseHeaders() { foreach($this->amfResponse->getHeaders() as $header) { switch($header['name']) { case 'ReplaceGatewayUrl' : if (is_string($header['data'])) { $this->endPoint = $header['data']; } break; } } }
parseHeaders @return void
entailment
public function setEncoding($encoding) { $this->encoding = $encoding; $this->amfRequest->setEncoding($encoding & SabreAMF_Const::AMF3); }
Change the AMF encoding (0 or 3) @param int $encoding @return void
entailment
public function process(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container'); $configuration = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles')); foreach ($configuration as $bundleName => $data) { if (!isset($bundles[$bundleName])) { throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName)); } $rc = new \ReflectionClass($bundles[$bundleName]); $directory = dirname($rc->getFileName()); $directories = array_map( function ($v) use ($directory) { return $directory.'/'.$v; }, $data['directories'] ); $definition = new Definition( $container->getParameter('atoum.configuration.bundle.class'), array($bundleName, $directories) ); $bundleContainer->addMethodCall('add', array($definition)); } }
@param ContainerBuilder $container @throws \LogicException
entailment
public function processFuzzyProximityModifier($parameter = null) { $this->_fuzzyQuery = true; if ($parameter !== null) { $this->_similarity = $parameter; } else { /** * Zend_Search_Lucene_Search_Query_Fuzzy */ include_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php'; $this->_similarity = Zend_Search_Lucene_Search_Query_Fuzzy::DEFAULT_MIN_SIMILARITY; } }
Process modifier ('~') @param mixed $parameter
entailment
public function getQuery($encoding) { if ($this->_fuzzyQuery) { /** * Zend_Search_Lucene_Search_Query_Preprocessing_Fuzzy */ include_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Fuzzy.php'; $query = new Zend_Search_Lucene_Search_Query_Preprocessing_Fuzzy( $this->_term, $encoding, ($this->_field !== null)? iconv($encoding, 'UTF-8', $this->_field) : null, $this->_similarity ); $query->setBoost($this->_boost); return $query; } /** * Zend_Search_Lucene_Search_Query_Preprocessing_Term */ include_once 'Zend/Search/Lucene/Search/Query/Preprocessing/Term.php'; $query = new Zend_Search_Lucene_Search_Query_Preprocessing_Term( $this->_term, $encoding, ($this->_field !== null)? iconv($encoding, 'UTF-8', $this->_field) : null ); $query->setBoost($this->_boost); return $query; }
Transform entry to a subquery @param string $encoding @return Zend_Search_Lucene_Search_Query @throws Zend_Search_Lucene_Search_QueryParserException
entailment
function get($key, $default = null) { if (!is_string($key)) { throw new InvalidArgumentException('$key must be a string'); } $value = apcu_fetch($key, $success); if (!$success) { return $default; } return $value; }
Fetches a value from the cache. @param string $key The unique key of this item in the cache. @param mixed $default Default value to return if the key does not exist. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if the $key string is not a legal value. @return mixed The value of the item from the cache, or $default in case of cache miss.
entailment
function set($key, $value, $ttl = null) { if (!is_string($key)) { throw new InvalidArgumentException('$key must be a string'); } if ($ttl instanceof DateInterval) { // Converting to a TTL in seconds $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time(); } return apcu_store($key, $value, (int)$ttl); }
Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time. @param string $key The key of the item to store. @param mixed $value The value of the item to store, must be serializable. @param null|int|DateInterval $ttl Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if the $key string is not a legal value. @return bool True on success and false on failure.
entailment
function setMultiple($values, $ttl = null) { if (!is_array($values) && !$values instanceof Traversable) { throw new InvalidArgumentException('$values must be traversable'); } if ($ttl instanceof DateInterval) { // Converting to a TTL in seconds $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time(); } if ($values instanceof Traversable) { $values = iterator_to_array($values); } return apcu_store($values, null, (int)$ttl); }
Persists a set of key => value pairs in the cache, with an optional TTL. @param iterable $values A list of key => value pairs for a multiple-set operation. @param null|int|DateInterval $ttl Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if $values is neither an array nor a Traversable, or if any of the $values are not a legal value. @return bool True on success and false on failure.
entailment
function deleteMultiple($keys) { if ($keys instanceof Traversable) { $keys = iterator_to_array($keys); } elseif (!is_array($keys)) { throw new InvalidArgumentException('$keys must be iterable'); } return apcu_delete($keys); }
Deletes multiple cache items in a single operation. @param iterable $keys A list of string-based keys to be deleted. @throws \Psr\SimpleCache\InvalidArgumentException MUST be thrown if $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. @return bool True if the items were successfully removed. False if there was an error.
entailment
public function getSearchedEntities() { $entities = array(); if (!empty($_REQUEST['Entities'])) { if (is_array($_REQUEST['Entities'])) { $entities = Convert::raw2att($_REQUEST['Entities']); } else { $entities = explode(',', Convert::raw2att($_REQUEST['Entities'])); $entities = array_combine($entities, $entities); } } return $entities; }
Return an array of folders and titles @return array
entailment
public function getSearchedVersions() { $versions = array(); if (!empty($_REQUEST['Versions'])) { if (is_array($_REQUEST['Versions'])) { $versions = Convert::raw2att($_REQUEST['Versions']); $versions = array_combine($versions, $versions); } else { $version = Convert::raw2att($_REQUEST['Versions']); $versions[$version] = $version; } } return $versions; }
Return an array of versions that we're allowed to return @return array
entailment
public function getSearchQuery() { if (isset($_REQUEST['Search'])) { return DBField::create_field('HTMLText', $_REQUEST['Search']); } elseif (isset($_REQUEST['q'])) { return DBField::create_field('HTMLText', $_REQUEST['q']); } }
Return the current search query. @return HTMLText|null
entailment
public function getSearchResults() { $query = $this->getSearchQuery(); $search = new DocumentationSearch(); $search->setQuery($query); $search->setVersions($this->getSearchedVersions()); $search->setModules($this->getSearchedEntities()); $search->setOutputController($this->owner); return $search->renderResults(); }
Past straight to results, display and encode the query.
entailment
public function attr($attribute) { $node = $this->getNode(); $value = null; if ($node instanceof \DOMNode) { $value = $node->getAttribute($attribute); } else { foreach ($node as $item) { if ($item->hasAttribute($attribute)) { $value = $node->attr($attribute); } break; } } return $value; }
@param string $attribute @return null|string
entailment
protected function registerCustomBindings(): void { $repositoryFactory = $this->app->make(IRepositoryFactory::class); foreach (config('laravel_repositories.bindings') as $className => $repository) { $repositoryFactory->register($className, $repository); } }
Register custom repositories implementations. @return void @throws BindingResolutionException
entailment
static public function getLocalClass($remoteClass) { $localClass = false; $cb = false; $localClass=(isset(self::$maps[$remoteClass]))?self::$maps[$remoteClass]:false; if (!$localClass && is_callable(self::$onGetLocalClass)) { $cb = true; $localClass = call_user_func(self::$onGetLocalClass,$remoteClass); } if (!$localClass) return false; if (!is_string($localClass) && $cb) { throw new Exception('Classname received from onGetLocalClass should be a string or return false. ' . gettype($localClass) . ' was returned'); } if (!class_exists($localClass)) { throw new Exception('Class ' . $localClass . ' is not defined'); } return $localClass; }
Get the local classname for a remote class This method will return FALSE when the class is not found @param string $remoteClass @return mixed
entailment
static public function getRemoteClass($localClass) { $remoteClass = false; $cb = false; $remoteClass = array_search($localClass,self::$maps); if (!$remoteClass && is_callable(self::$onGetRemoteClass)) { $cb = true; $remoteClass = call_user_func(self::$onGetRemoteClass,$localClass); } if (!$remoteClass) return false; if (!is_string($remoteClass) && $cb) { throw new Exception('Classname received from onGetRemoteClass should be a string or return false. ' . gettype($remoteClass) . ' was returned'); } return $remoteClass; }
Get the remote classname for a local class This method will return FALSE when the class is not found @param string $localClass @return mixed
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { if ($this->_term->field != null) { return $this; } else { include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); $query->setBoost($this->getBoost()); include_once 'Zend/Search/Lucene/Index/Term.php'; foreach ($index->getFieldNames(true) as $fieldName) { $term = new Zend_Search_Lucene_Index_Term($this->_term->text, $fieldName); $query->addTerm($term); } return $query->rewrite($index); } }
Re-write query into primitive queries in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query
entailment
public function createWeight(Zend_Search_Lucene_Interface $reader) { include_once 'Zend/Search/Lucene/Search/Weight/Term.php'; $this->_weight = new Zend_Search_Lucene_Search_Weight_Term($this->_term, $this, $reader); return $this->_weight; }
Constructs an appropriate Weight implementation for this query. @param Zend_Search_Lucene_Interface $reader @return Zend_Search_Lucene_Search_Weight
entailment
public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null) { $this->_docVector = array_flip($reader->termDocs($this->_term, $docsFilter)); $this->_termFreqs = $reader->termFreqs($this->_term, $docsFilter); // Initialize weight if it's not done yet $this->_initWeight($reader); }
Execute query in context of index reader It also initializes necessary internal structures @param Zend_Search_Lucene_Interface $reader @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
entailment
public function score($docId, Zend_Search_Lucene_Interface $reader) { if (isset($this->_docVector[$docId])) { return $reader->getSimilarity()->tf($this->_termFreqs[$docId]) * $this->_weight->getValue() * $reader->norm($docId, $this->_term->field) * $this->getBoost(); } else { return 0; } }
Score specified document @param integer $docId @param Zend_Search_Lucene_Interface $reader @return float
entailment
public function highlight($words) { $color = $this->_highlightColors[$this->_currentColorIndex]; $this->_currentColorIndex = ($this->_currentColorIndex + 1) % count($this->_highlightColors); $this->_doc->highlight($words, $color); }
Highlight specified words @param string|array $words Words to highlight. They could be organized using the array or string.
entailment
public function tokenize($data, $encoding = '') { $this->setInput($data, $encoding); $tokenList = array(); while (($nextToken = $this->nextToken()) !== null) { $tokenList[] = $nextToken; } return $tokenList; }
Tokenize text to a terms Returns array of Zend_Search_Lucene_Analysis_Token objects Tokens are returned in UTF-8 (internal Zend_Search_Lucene encoding) @param string $data @return array
entailment
public function setInput($data, $encoding = '') { $this->_input = $data; $this->_encoding = $encoding; $this->reset(); }
Tokenization stream API Set input @param string $data
entailment
public function addState($state) { $this->_states[$state] = $state; if ($this->_currentState === null) { $this->_currentState = $state; } }
Add state to the state machine @param integer|string $state
entailment
public function setState($state) { if (!isset($this->_states[$state])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('State \'' . $state . '\' is not on of the possible FSM states.'); } $this->_currentState = $state; }
Set FSM state. No any action is invoked @param integer|string $state @throws Zend_Search_Exception
entailment
public function addRules($rules) { foreach ($rules as $rule) { $this->addrule($rule[0], $rule[1], $rule[2], isset($rule[3])?$rule[3]:null); } }
Add transition rules array structure: array( array(sourseState, input, targetState[, inputAction]), array(sourseState, input, targetState[, inputAction]), array(sourseState, input, targetState[, inputAction]), ... ) @param array $rules
entailment
public function addRule($sourceState, $input, $targetState, $inputAction = null) { if (!isset($this->_states[$sourceState])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined source state (' . $sourceState . ').'); } if (!isset($this->_states[$targetState])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined target state (' . $targetState . ').'); } if (!isset($this->_inputAphabet[$input])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined input symbol (' . $input . ').'); } if (!isset($this->_rules[$sourceState])) { $this->_rules[$sourceState] = array(); } if (isset($this->_rules[$sourceState][$input])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Rule for {state,input} pair (' . $sourceState . ', '. $input . ') is already defined.'); } $this->_rules[$sourceState][$input] = $targetState; if ($inputAction !== null) { $this->addInputAction($sourceState, $input, $inputAction); } }
Add symbol to the input alphabet @param integer|string $sourceState @param integer|string $input @param integer|string $targetState @param Zend_Search_Lucene_FSMAction|null $inputAction @throws Zend_Search_Exception
entailment
public function addEntryAction($state, Zend_Search_Lucene_FSMAction $action) { if (!isset($this->_states[$state])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined state (' . $state. ').'); } if (!isset($this->_entryActions[$state])) { $this->_entryActions[$state] = array(); } $this->_entryActions[$state][] = $action; }
Add state entry action. Several entry actions are allowed. Action execution order is defined by addEntryAction() calls @param integer|string $state @param Zend_Search_Lucene_FSMAction $action
entailment
public function addExitAction($state, Zend_Search_Lucene_FSMAction $action) { if (!isset($this->_states[$state])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined state (' . $state. ').'); } if (!isset($this->_exitActions[$state])) { $this->_exitActions[$state] = array(); } $this->_exitActions[$state][] = $action; }
Add state exit action. Several exit actions are allowed. Action execution order is defined by addEntryAction() calls @param integer|string $state @param Zend_Search_Lucene_FSMAction $action
entailment
public function addInputAction($state, $inputSymbol, Zend_Search_Lucene_FSMAction $action) { if (!isset($this->_states[$state])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined state (' . $state. ').'); } if (!isset($this->_inputAphabet[$inputSymbol])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined input symbol (' . $inputSymbol. ').'); } if (!isset($this->_inputActions[$state])) { $this->_inputActions[$state] = array(); } if (!isset($this->_inputActions[$state][$inputSymbol])) { $this->_inputActions[$state][$inputSymbol] = array(); } $this->_inputActions[$state][$inputSymbol][] = $action; }
Add input action (defined by {state, input} pair). Several input actions are allowed. Action execution order is defined by addInputAction() calls @param integer|string $state @param integer|string $input @param Zend_Search_Lucene_FSMAction $action
entailment
public function addTransitionAction($sourceState, $targetState, Zend_Search_Lucene_FSMAction $action) { if (!isset($this->_states[$sourceState])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined source state (' . $sourceState. ').'); } if (!isset($this->_states[$targetState])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('Undefined source state (' . $targetState. ').'); } if (!isset($this->_transitionActions[$sourceState])) { $this->_transitionActions[$sourceState] = array(); } if (!isset($this->_transitionActions[$sourceState][$targetState])) { $this->_transitionActions[$sourceState][$targetState] = array(); } $this->_transitionActions[$sourceState][$targetState][] = $action; }
Add transition action (defined by {state, input} pair). Several transition actions are allowed. Action execution order is defined by addTransitionAction() calls @param integer|string $sourceState @param integer|string $targetState @param Zend_Search_Lucene_FSMAction $action
entailment
public function process($input) { if (!isset($this->_rules[$this->_currentState])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('There is no any rule for current state (' . $this->_currentState . ').'); } if (!isset($this->_rules[$this->_currentState][$input])) { include_once 'Zend/Search/Exception.php'; throw new Zend_Search_Exception('There is no any rule for {current state, input} pair (' . $this->_currentState . ', ' . $input . ').'); } $sourceState = $this->_currentState; $targetState = $this->_rules[$this->_currentState][$input]; if ($sourceState != $targetState && isset($this->_exitActions[$sourceState])) { foreach ($this->_exitActions[$sourceState] as $action) { $action->doAction(); } } if (isset($this->_inputActions[$sourceState]) && isset($this->_inputActions[$sourceState][$input]) ) { foreach ($this->_inputActions[$sourceState][$input] as $action) { $action->doAction(); } } $this->_currentState = $targetState; if (isset($this->_transitionActions[$sourceState]) && isset($this->_transitionActions[$sourceState][$targetState]) ) { foreach ($this->_transitionActions[$sourceState][$targetState] as $action) { $action->doAction(); } } if ($sourceState != $targetState && isset($this->_entryActions[$targetState])) { foreach ($this->_entryActions[$targetState] as $action) { $action->doAction(); } } }
Process an input @param mixed $input @throws Zend_Search_Exception
entailment
public function getToken(string $login, string $pass): GetTokenResponse { $response = $this->request('GET', 'getToken', [ 'login' => $login, 'pass' => $pass, ]); return $this->converter->getResponseObject(GetTokenResponse::class, $response); }
Get auth token. @param string $login @param string $pass @throws ParseException @throws ValidationException @return GetTokenResponse
entailment
public function report(string $uuid, string $token): ReportResponse { $response = $this->request( 'GET', "{$this->groupCode}/report/$uuid", ['tokenid' => $token] ); return $this->converter->getResponseObject(ReportResponse::class, $response); }
Report. @param string $uuid @param string $token @return ReportResponse
entailment
private function register(SellRequest $request, string $operation): SellResponse { $response = $this->request( 'POST', "{$this->groupCode}/{$operation}", ['tokenid' => $request->getToken()], $request ); return $this->converter->getResponseObject(SellResponse::class, $response); }
Register (sell / buy with / without refund). @param SellRequest $request @param string $operation @return SellResponse
entailment
private function request(string $method, string $path, array $query = [], $body = null): string { // Prepare request: $query = build_query($query); $body = $this->parseBody($body); $path = trim($path, '/'); $request = new Request( $method, "{$this->baseUri}/v3/$path/?$query", ['Content-Type' => 'application/json'], $body ); return (string) $this->query($request)->getBody(); }
Send request. @param string $method @param string $path @param array $query @param string|object|null $body @throws ParseException @return string
entailment
private function query(RequestInterface $request) { return $this->client->send($request, array_merge( [RequestOptions::HTTP_ERRORS => false], $this->clientOptions )); }
@param RequestInterface $request @throws GuzzleException @return ResponseInterface
entailment
public function createStoredFieldsFiles() { $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx'); $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt'); $this->_files[] = $this->_name . '.fdx'; $this->_files[] = $this->_name . '.fdt'; }
Create stored fields files and open them for write
entailment
public function close() { if ($this->_docCount == 0) { return null; } $this->_dumpFNM(); $this->_generateCFS(); /** * Zend_Search_Lucene_Index_SegmentInfo */ include_once 'Zend/Search/Lucene/Index/SegmentInfo.php'; return new Zend_Search_Lucene_Index_SegmentInfo( $this->_directory, $this->_name, $this->_docCount, -1, null, true, true ); }
Close segment, write it to disk and return segment info @return Zend_Search_Lucene_Index_SegmentInfo
entailment
public function close() { if ($this->_fileHandle !== null ) { @fclose($this->_fileHandle); $this->_fileHandle = null; } }
Close File object
entailment
public function size() { $position = ftell($this->_fileHandle); fseek($this->_fileHandle, 0, SEEK_END); $size = ftell($this->_fileHandle); fseek($this->_fileHandle, $position); return $size; }
Get the size of the already opened file @return integer
entailment
protected function _fread($length=1) { if ($length == 0) { return ''; } if ($length < 1024) { return fread($this->_fileHandle, $length); } $data = ''; while ( $length > 0 && ($nextBlock = fread($this->_fileHandle, $length)) != false ) { $data .= $nextBlock; $length -= strlen($nextBlock); } return $data; }
Read a $length bytes from the file and advance the file pointer. @param integer $length @return string
entailment
protected function _fwrite($data, $length=null) { if ($length === null ) { fwrite($this->_fileHandle, $data); } else { fwrite($this->_fileHandle, $data, $length); } }
Writes $length number of bytes (all, if $length===null) to the end of the file. @param string $data @param integer $length
entailment
public function lock($lockType, $nonBlockingLock = false) { if ($nonBlockingLock) { return flock($this->_fileHandle, $lockType | LOCK_NB); } else { return flock($this->_fileHandle, $lockType); } }
Lock file Lock type may be a LOCK_SH (shared lock) or a LOCK_EX (exclusive lock) @param integer $lockType @param boolean $nonBlockingLock @return boolean
entailment
public function handle(Request $request, Closure $next, $resource = null, $permission = null) { if ($this->auth->guest()) { if (!$this->acl->isAllowed('guest', $resource, $permission)) { return $this->notAllowed($request); } } elseif (!$this->acl->isAllowed($this->auth->user(), $resource, $permission)) { return $this->notAllowed($request); } return $next($request); }
Run the request filter. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
protected function notAllowed(Request $request) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { $action = $this->config->get('zendacl.action', 'redirect'); if ($action == 'redirect') { $url = $this->config->get('zendacl.redirect', 'auth/login'); return redirect($url); } elseif ($action == 'route') { $route = $this->config->get('zendacl.redirect'); return redirect()->route($route); } elseif ($action == 'view') { $view = $this->config->get('zendacl.view', 'zendacl::unauthorized'); return view($view); } } }
Processes not allowed response @param Request $request @return \Illuminate\Http\Response
entailment
public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) { if (array_key_exists($srcToken->getTermText(), $this->_stopSet)) { return null; } else { return $srcToken; } }
Normalize Token or remove it (if null is returned) @param Zend_Search_Lucene_Analysis_Token $srcToken @return Zend_Search_Lucene_Analysis_Token
entailment
public function loadFromFile($filepath = null) { if (! $filepath || ! file_exists($filepath)) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('You have to provide valid file path'); } $fd = fopen($filepath, "r"); if (! $fd) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Cannot open file ' . $filepath); } while (!feof($fd)) { $buffer = trim(fgets($fd)); if (strlen($buffer) > 0 && $buffer[0] != '#') { $this->_stopSet[$buffer] = 1; } } if (!fclose($fd)) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Cannot close file ' . $filepath); } }
Fills stopwords set from a text file. Each line contains one stopword, lines with '#' in the first column are ignored (as comments). You can call this method one or more times. New stopwords are always added to current set. @param string $filepath full path for text file with stopwords @throws Zend_Search_Exception When the file doesn`t exists or is not readable.
entailment
public static function setDefaults($options = []) { $options = empty($options) ? '{}' : Json::encode($options); $view = Yii::$app->getView(); $js = <<<EOD fotoramaDefaults = {$options}; EOD; $view->registerJs($js, View::POS_HEAD, 'fotorama-defaults'); }
Setup default Fotorama widget options {@link http://fotorama.io/customize/options/#defaults} @param array $options
entailment
public function init() { parent::init(); if (empty($this->htmlOptions['id'])) { $this->htmlOptions['id'] = $this->id; } if ($this->useHtmlData) { if (isset($this->options['data'])) { $this->items = (array)$this->options['data']; unset($this->options['data']); } if (isset($this->options['spinner'])) { $this->spinner = (array)$this->options['spinner']; unset($this->options['spinner']); } foreach ($this->options as $option => $value) { $this->htmlOptions['data-' . $option] = $value; } $this->options = []; } $this->htmlOptions['data-auto'] = 'false'; // disable auto init if (!empty($this->items)) { $this->options['data'] = $this->items; } if (!empty($this->spinner)) { $this->options['spinner'] = $this->spinner; } echo Html::beginTag($this->tagName, $this->htmlOptions) . "\n"; }
Initializes the widget. This renders the open tag.
entailment
public function getRepository(string $modelClass): IRepository { if (empty($this->sharedInstances[$modelClass])) { $this->sharedInstances[$modelClass] = $this->build($modelClass); } return $this->sharedInstances[$modelClass]; }
{@inheritdoc}
entailment
protected function build(string $modelClass): IRepository { $repositoryClass = $this->registeredRepositories[$modelClass] ?? Repository::class; $parameters = []; if ($repositoryClass === Repository::class || is_subclass_of($repositoryClass, Repository::class) ) { $parameters = ['modelClass' => $modelClass]; } return $this->container->make($repositoryClass, $parameters); }
Build repository by model class from registered instances or creates default. @param string $modelClass Model class @return IRepository @throws BindingResolutionException
entailment
public function register(string $modelClass, string $repositoryClass): void { if (!is_subclass_of($modelClass, Model::class)) { throw new RepositoryRegisterException("$modelClass must extend " . Model::class); } if (!is_subclass_of($repositoryClass, IRepository::class)) { throw new RepositoryRegisterException("$repositoryClass must implement " . IRepository::class); } $this->registeredRepositories[$modelClass] = $repositoryClass; }
{@inheritdoc}
entailment