sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
private function serializeBodyObject($object): string
{
try {
return $this->serializer->serialize($object, 'atol_client', $this->getSerializeBodyObjectContext());
} catch (\RuntimeException $exception) {
throw ParseException::becauseOfRuntimeException($exception, ParseException::REQUEST);
}
} | @param mixed $object
@throws ParseException
@return string | entailment |
public function get($key, $default = null)
{
$value = $this->settings;
$value = set_nested_array_value($value, $key);
if ( ! is_null($value))
{
return $value;
}
return $default;
} | Gets a value
@param $key
@param null $default
@return mixed | entailment |
public function getAll()
{
$values = json_decode(file_get_contents($this->cacheFile), true);
if ( ! is_null($values))
{
return $values;
}
return [];
} | Gets all cached settings
@return array | entailment |
public function addSubquery(Zend_Search_Lucene_Search_Query $subquery, $sign=null)
{
if ($sign !== true || $this->_signs !== null) { // Skip, if all subqueries are required
if ($this->_signs === null) { // Check, If all previous subqueries are required
$this->_signs = array();
foreach ($this->_subqueries as $prevSubquery) {
$this->_signs[] = true;
}
}
$this->_signs[] = $sign;
}
$this->_subqueries[] = $subquery;
} | Add a $subquery (Zend_Search_Lucene_Search_Query) to this query.
The sign is specified as:
TRUE - subquery is required
FALSE - subquery is prohibited
NULL - subquery is neither prohibited, nor required
@param Zend_Search_Lucene_Search_Query $subquery
@param boolean|null $sign
@return void | entailment |
public function rewrite(Zend_Search_Lucene_Interface $index)
{
$query = new Zend_Search_Lucene_Search_Query_Boolean();
$query->setBoost($this->getBoost());
foreach ($this->_subqueries as $subqueryId => $subquery) {
$query->addSubquery(
$subquery->rewrite($index),
($this->_signs === null)? true : $this->_signs[$subqueryId]
);
}
return $query;
} | Re-write queries into primitive queries
@param Zend_Search_Lucene_Interface $index
@return Zend_Search_Lucene_Search_Query | entailment |
public function optimize(Zend_Search_Lucene_Interface $index)
{
$subqueries = array();
$signs = array();
// Optimize all subqueries
foreach ($this->_subqueries as $id => $subquery) {
$subqueries[] = $subquery->optimize($index);
$signs[] = ($this->_signs === null)? true : $this->_signs[$id];
}
// Remove insignificant subqueries
foreach ($subqueries as $id => $subquery) {
if ($subquery instanceof Zend_Search_Lucene_Search_Query_Insignificant) {
// Insignificant subquery has to be removed anyway
unset($subqueries[$id]);
unset($signs[$id]);
}
}
if (count($subqueries) == 0) {
// Boolean query doesn't has non-insignificant subqueries
include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php';
return new Zend_Search_Lucene_Search_Query_Insignificant();
}
// Check if all non-insignificant subqueries are prohibited
$allProhibited = true;
foreach ($signs as $sign) {
if ($sign !== false) {
$allProhibited = false;
break;
}
}
if ($allProhibited) {
include_once 'Zend/Search/Lucene/Search/Query/Insignificant.php';
return new Zend_Search_Lucene_Search_Query_Insignificant();
}
// Check for empty subqueries
foreach ($subqueries as $id => $subquery) {
if ($subquery instanceof Zend_Search_Lucene_Search_Query_Empty) {
if ($signs[$id] === true) {
// Matching is required, but is actually empty
include_once 'Zend/Search/Lucene/Search/Query/Empty.php';
return new Zend_Search_Lucene_Search_Query_Empty();
} else {
// Matching is optional or prohibited, but is empty
// Remove it from subqueries and signs list
unset($subqueries[$id]);
unset($signs[$id]);
}
}
}
// Check, if reduced subqueries list is empty
if (count($subqueries) == 0) {
include_once 'Zend/Search/Lucene/Search/Query/Empty.php';
return new Zend_Search_Lucene_Search_Query_Empty();
}
// Check if all non-empty subqueries are prohibited
$allProhibited = true;
foreach ($signs as $sign) {
if ($sign !== false) {
$allProhibited = false;
break;
}
}
if ($allProhibited) {
include_once 'Zend/Search/Lucene/Search/Query/Empty.php';
return new Zend_Search_Lucene_Search_Query_Empty();
}
// Check, if reduced subqueries list has only one entry
if (count($subqueries) == 1) {
// It's a query with only one required or optional clause
// (it's already checked, that it's not a prohibited clause)
if ($this->getBoost() == 1) {
return reset($subqueries);
}
$optimizedQuery = clone reset($subqueries);
$optimizedQuery->setBoost($optimizedQuery->getBoost()*$this->getBoost());
return $optimizedQuery;
}
// Prepare first candidate for optimized query
$optimizedQuery = new Zend_Search_Lucene_Search_Query_Boolean($subqueries, $signs);
$optimizedQuery->setBoost($this->getBoost());
$terms = array();
$tsigns = array();
$boostFactors = array();
// Try to decompose term and multi-term subqueries
foreach ($subqueries as $id => $subquery) {
if ($subquery instanceof Zend_Search_Lucene_Search_Query_Term) {
$terms[] = $subquery->getTerm();
$tsigns[] = $signs[$id];
$boostFactors[] = $subquery->getBoost();
// remove subquery from a subqueries list
unset($subqueries[$id]);
unset($signs[$id]);
} else if ($subquery instanceof Zend_Search_Lucene_Search_Query_MultiTerm) {
$subTerms = $subquery->getTerms();
$subSigns = $subquery->getSigns();
if ($signs[$id] === true) {
// It's a required multi-term subquery.
// Something like '... +(+term1 -term2 term3 ...) ...'
// Multi-term required subquery can be decomposed only if it contains
// required terms and doesn't contain prohibited terms:
// ... +(+term1 term2 ...) ... => ... +term1 term2 ...
//
// Check this
$hasRequired = false;
$hasProhibited = false;
if ($subSigns === null) {
// All subterms are required
$hasRequired = true;
} else {
foreach ($subSigns as $sign) {
if ($sign === true) {
$hasRequired = true;
} else if ($sign === false) {
$hasProhibited = true;
break;
}
}
}
// Continue if subquery has prohibited terms or doesn't have required terms
if ($hasProhibited || !$hasRequired) {
continue;
}
foreach ($subTerms as $termId => $term) {
$terms[] = $term;
$tsigns[] = ($subSigns === null)? true : $subSigns[$termId];
$boostFactors[] = $subquery->getBoost();
}
// remove subquery from a subqueries list
unset($subqueries[$id]);
unset($signs[$id]);
} else { // $signs[$id] === null || $signs[$id] === false
// It's an optional or prohibited multi-term subquery.
// Something like '... (+term1 -term2 term3 ...) ...'
// or
// something like '... -(+term1 -term2 term3 ...) ...'
// Multi-term optional and required subqueries can be decomposed
// only if all terms are optional.
//
// Check if all terms are optional.
$onlyOptional = true;
if ($subSigns === null) {
// All subterms are required
$onlyOptional = false;
} else {
foreach ($subSigns as $sign) {
if ($sign !== null) {
$onlyOptional = false;
break;
}
}
}
// Continue if non-optional terms are presented in this multi-term subquery
if (!$onlyOptional) {
continue;
}
foreach ($subTerms as $termId => $term) {
$terms[] = $term;
$tsigns[] = ($signs[$id] === null)? null /* optional */ :
false /* prohibited */;
$boostFactors[] = $subquery->getBoost();
}
// remove subquery from a subqueries list
unset($subqueries[$id]);
unset($signs[$id]);
}
}
}
// Check, if there are no decomposed subqueries
if (count($terms) == 0 ) {
// return prepared candidate
return $optimizedQuery;
}
// Check, if all subqueries have been decomposed and all terms has the same boost factor
if (count($subqueries) == 0 && count(array_unique($boostFactors)) == 1) {
include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
$optimizedQuery = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $tsigns);
$optimizedQuery->setBoost(reset($boostFactors)*$this->getBoost());
return $optimizedQuery;
}
// This boolean query can't be transformed to Term/MultiTerm query and still contains
// several subqueries
// Separate prohibited terms
$prohibitedTerms = array();
foreach ($terms as $id => $term) {
if ($tsigns[$id] === false) {
$prohibitedTerms[] = $term;
unset($terms[$id]);
unset($tsigns[$id]);
unset($boostFactors[$id]);
}
}
if (count($terms) == 1) {
include_once 'Zend/Search/Lucene/Search/Query/Term.php';
$clause = new Zend_Search_Lucene_Search_Query_Term(reset($terms));
$clause->setBoost(reset($boostFactors));
$subqueries[] = $clause;
$signs[] = reset($tsigns);
// Clear terms list
$terms = array();
} else if (count($terms) > 1 && count(array_unique($boostFactors)) == 1) {
include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
$clause = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $tsigns);
$clause->setBoost(reset($boostFactors));
$subqueries[] = $clause;
// Clause sign is 'required' if clause contains required terms. 'Optional' otherwise.
$signs[] = (in_array(true, $tsigns))? true : null;
// Clear terms list
$terms = array();
}
if (count($prohibitedTerms) == 1) {
// (boost factors are not significant for prohibited clauses)
include_once 'Zend/Search/Lucene/Search/Query/Term.php';
$subqueries[] = new Zend_Search_Lucene_Search_Query_Term(reset($prohibitedTerms));
$signs[] = false;
// Clear prohibited terms list
$prohibitedTerms = array();
} else if (count($prohibitedTerms) > 1) {
// prepare signs array
$prohibitedSigns = array();
foreach ($prohibitedTerms as $id => $term) {
// all prohibited term are grouped as optional into multi-term query
$prohibitedSigns[$id] = null;
}
// (boost factors are not significant for prohibited clauses)
include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
$subqueries[] = new Zend_Search_Lucene_Search_Query_MultiTerm($prohibitedTerms, $prohibitedSigns);
// Clause sign is 'prohibited'
$signs[] = false;
// Clear terms list
$prohibitedTerms = array();
}
/**
* @todo Group terms with the same boost factors together
*/
// Check, that all terms are processed
// Replace candidate for optimized query
if (count($terms) == 0 && count($prohibitedTerms) == 0) {
$optimizedQuery = new Zend_Search_Lucene_Search_Query_Boolean($subqueries, $signs);
$optimizedQuery->setBoost($this->getBoost());
}
return $optimizedQuery;
} | 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/Boolean.php';
$this->_weight = new Zend_Search_Lucene_Search_Weight_Boolean($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 |
private function _calculateConjunctionResult()
{
$this->_resVector = null;
if (count($this->_subqueries) == 0) {
$this->_resVector = array();
}
$resVectors = array();
$resVectorsSizes = array();
$resVectorsIds = array(); // is used to prevent arrays comparison
foreach ($this->_subqueries as $subqueryId => $subquery) {
$resVectors[] = $subquery->matchedDocs();
$resVectorsSizes[] = count(end($resVectors));
$resVectorsIds[] = $subqueryId;
}
// 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);
// Used algorithm doesn't change elements order
} | Calculate result vector for Conjunction query
(like '<subquery1> AND <subquery2> AND <subquery3>') | entailment |
private function _calculateNonConjunctionResult()
{
$requiredVectors = array();
$requiredVectorsSizes = array();
$requiredVectorsIds = array(); // is used to prevent arrays comparison
$optional = array();
foreach ($this->_subqueries as $subqueryId => $subquery) {
if ($this->_signs[$subqueryId] === true) {
// required
$requiredVectors[] = $subquery->matchedDocs();
$requiredVectorsSizes[] = count(end($requiredVectors));
$requiredVectorsIds[] = $subqueryId;
} elseif ($this->_signs[$subqueryId] === false) {
// prohibited
// Do nothing. matchedDocs() may include non-matching id's
// Calculating prohibited vector may take significant time, but do not affect the result
// Skipped.
} else {
// neither required, nor prohibited
// array union
$optional += $subquery->matchedDocs();
}
}
// sort resvectors in order of subquery cardinality increasing
array_multisort(
$requiredVectorsSizes, SORT_ASC, SORT_NUMERIC,
$requiredVectorsIds, SORT_ASC, SORT_NUMERIC,
$requiredVectors
);
$required = null;
foreach ($requiredVectors as $nextResVector) {
if($required === null) {
$required = $nextResVector;
} else {
//$required = array_intersect_key($required, $nextResVector);
/**
* This code is used as workaround for array_intersect_key() slowness problem.
*/
$updatedVector = array();
foreach ($required as $id => $value) {
if (isset($nextResVector[$id])) {
$updatedVector[$id] = $value;
}
}
$required = $updatedVector;
}
if (count($required) == 0) {
// Empty result set, we don't need to check other terms
break;
}
}
if ($required !== null) {
$this->_resVector = &$required;
} else {
$this->_resVector = &$optional;
}
ksort($this->_resVector, SORT_NUMERIC);
} | Calculate result vector for non Conjunction query
(like '<subquery1> AND <subquery2> AND NOT <subquery3> OR <subquery4>') | entailment |
public function _conjunctionScore($docId, Zend_Search_Lucene_Interface $reader)
{
if ($this->_coord === null) {
$this->_coord = $reader->getSimilarity()->coord(
count($this->_subqueries),
count($this->_subqueries)
);
}
$score = 0;
foreach ($this->_subqueries as $subquery) {
$subscore = $subquery->score($docId, $reader);
if ($subscore == 0) {
return 0;
}
$score += $subquery->score($docId, $reader) * $this->_coord;
}
return $score * $this->_coord * $this->getBoost();
} | Score calculator for conjunction queries (all subqueries are required)
@param integer $docId
@param Zend_Search_Lucene_Interface $reader
@return float | entailment |
public function _nonConjunctionScore($docId, Zend_Search_Lucene_Interface $reader)
{
if ($this->_coord === null) {
$this->_coord = array();
$maxCoord = 0;
foreach ($this->_signs as $sign) {
if ($sign !== false /* not prohibited */) {
$maxCoord++;
}
}
for ($count = 0; $count <= $maxCoord; $count++) {
$this->_coord[$count] = $reader->getSimilarity()->coord($count, $maxCoord);
}
}
$score = 0;
$matchedSubqueries = 0;
foreach ($this->_subqueries as $subqueryId => $subquery) {
$subscore = $subquery->score($docId, $reader);
// Prohibited
if ($this->_signs[$subqueryId] === false && $subscore != 0) {
return 0;
}
// is required, but doen't match
if ($this->_signs[$subqueryId] === true && $subscore == 0) {
return 0;
}
if ($subscore != 0) {
$matchedSubqueries++;
$score += $subscore;
}
}
return $score * $this->_coord[$matchedSubqueries] * $this->getBoost();
} | Score calculator for non conjunction queries (not all subqueries are required)
@param integer $docId
@param Zend_Search_Lucene_Interface $reader
@return float | entailment |
public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
{
// Initialize weight if it's not done yet
$this->_initWeight($reader);
if ($docsFilter === null) {
// Create local documents filter if it's not provided by upper query
include_once 'Zend/Search/Lucene/Index/DocsFilter.php';
$docsFilter = new Zend_Search_Lucene_Index_DocsFilter();
}
foreach ($this->_subqueries as $subqueryId => $subquery) {
if ($this->_signs == null || $this->_signs[$subqueryId] === true) {
// Subquery is required
$subquery->execute($reader, $docsFilter);
} else {
$subquery->execute($reader);
}
}
if ($this->_signs === null) {
$this->_calculateConjunctionResult();
} else {
$this->_calculateNonConjunctionResult();
}
} | 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->_signs === null) {
return $this->_conjunctionScore($docId, $reader);
} else {
return $this->_nonConjunctionScore($docId, $reader);
}
} else {
return 0;
}
} | Score specified document
@param integer $docId
@param Zend_Search_Lucene_Interface $reader
@return float | entailment |
public function getQueryTerms()
{
$terms = array();
foreach ($this->_subqueries as $id => $subquery) {
if ($this->_signs === null || $this->_signs[$id] !== false) {
$terms = array_merge($terms, $subquery->getQueryTerms());
}
}
return $terms;
} | Return query terms
@return array | entailment |
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter)
{
foreach ($this->_subqueries as $id => $subquery) {
if ($this->_signs === null || $this->_signs[$id] !== false) {
$subquery->_highlightMatches($highlighter);
}
}
} | Query specific matches highlighting
@param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting) | entailment |
public static function parse(DocumentationPage $page, $baselink = null)
{
if (!$page || (!$page instanceof DocumentationPage)) {
return false;
}
$md = $page->getMarkdown(true);
// Pre-processing
$md = self::rewrite_image_links($md, $page);
$md = self::rewrite_relative_links($md, $page, $baselink);
$md = self::rewrite_api_links($md, $page);
$md = self::rewrite_heading_anchors($md, $page);
$md = self::rewrite_code_blocks($md);
$parser = new ParsedownExtra();
$parser->setBreaksEnabled(false);
$text = $parser->text($md);
return $text;
} | Parse a given path to the documentation for a file. Performs a case
insensitive lookup on the file system. Automatically appends the file
extension to one of the markdown extensions as well so /install/ in a
web browser will match /install.md or /INSTALL.md.
Filepath: /var/www/myproject/src/cms/en/folder/subfolder/page.md
URL: http://myhost/mywebroot/dev/docs/2.4/cms/en/folder/subfolder/page
Webroot: http://myhost/mywebroot/
Baselink: dev/docs/2.4/cms/en/
Pathparts: folder/subfolder/page
@param DocumentationPage $page
@param string $baselink Link relative to webroot, up until the "root" of the module.
Necessary to rewrite relative links of the module. Necessary
to rewrite relative links
@return string | entailment |
private static function finalize_code_output($i, $output)
{
if (isset($output[$i]) && trim($output[$i])) {
$output[$i] .= "\n```\n";
} else {
$output[$i] = "```";
}
return $output;
} | Adds the closing code backticks. Removes trailing whitespace.
@param int
@param array
@return array | entailment |
public static function rewrite_api_links($markdown, $doc_page)
{
$version = $doc_page->getVersion();
$module = $doc_page->getEntity()->getKey();
// define regexs of the api links to be parsed (note: do not include backticks)
$regexs = array(
'title_and_method' => '# \[ ([^\]]*) \] \( api: ([^\)]*\(\)) \) #x', // title_and_method = (6) (must be first)
'title_remaining' => '# \[ ([^\]]*) \] \( api: ([^\)]*) \) #x', // title_and_remaining = (4) and (5)
'no_title' => '# \[ api: ([^\]]*) \] #x' // no_title = (1),(2) and (3)
);
// define output format for parsing api links without backticks into html
$html_format = '<a href="http://api.silverstripe.org/search/lookup/?q=%s&version=%s&module=%s">%s</a>';
// parse api links without backticks into html
foreach ($regexs as $type => $regex) {
preg_match_all($regex, $markdown, $links);
if ($links) {
foreach ($links[0] as $i => $match) {
if ($type === 'no_title') {
$title = $links[1][$i];
$link = $links[1][$i];
// change backticked links to avoid being parsed in the same way as non-backticked links
$markdown = str_replace('`'.$match.'`', 'XYZ'.$link.'XYZ', $markdown);
} else {
$title = $links[1][$i];
$link = $links[2][$i];
// change backticked links to avoid being parsed in the same way as non-backticked links
$markdown = str_replace('`'.$match.'`', 'XX'.$title.'YY'.$link.'ZZ', $markdown);
}
$html = sprintf($html_format, $link, $version, $module, $title);
$markdown = str_replace($match, $html, $markdown);
}
}
}
// recover backticked links with no titles
preg_match_all('#XYZ(.*)?XYZ#', $markdown, $links);
if ($links) {
foreach ($links[0] as $i => $match) {
$link = $links[1][$i];
$markdown = str_replace($match, '`[api:'.$link.']`', $markdown);
}
}
// recover backticked links with titles
preg_match_all('#XX(.*)?YY(.*)?ZZ#', $markdown, $links);
if ($links) {
foreach ($links[0] as $i => $match) {
$title = $links[1][$i];
$link = $links[2][$i];
$markdown = str_replace($match, '`['.$title.'](api:'.$link.')`', $markdown);
}
}
return $markdown;
} | Rewrite links with special "api:" prefix to html as in the following example:
(1) [api:DataObject] gets re-written to
<a href="https://api.silverstripe.org/search/lookup/?q=DataObject&version=2.4&module=framework">DataObject</a>
(2) [api:DataObject::$defaults] gets re-written to
<a href="https://api.silverstripe.org/search/lookup/?q=DataObject::$defaults&version=2.4&module=framework">DataObject::$defaults</a>
(3) [api:DataObject::populateDefaults()] gets re-written to
<a href="https://api.silverstripe.org/search/lookup/?q=DataObject::populateDefaults()&version=2.4&module=framework">DataObject::$defaults</a>
(4) [Title](api:DataObject) gets re-written to
<a href="https://api.silverstripe.org/search/lookup/?q=DataObject&version=2.4&module=framework">Title</a>
(5) [Title](api:DataObject::$defaults) gets re-written to
<a href="https://api.silverstripe.org/search/lookup/?q=DataObject::$defaults&version=2.4&module=framework">Title</a>
(6) [Title](api:DataObject->populateDefaults()) gets re-written to
<a href="https://api.silverstripe.org/search/lookup/?q=DataObject::populateDefaults()&version=2.4&module=framework">Title</a>
The above api links can be enclosed in backticks.
The markdown parser gets confused by the extra pair of parentheses in links of the form [DataObject](api:DataObject::populateDefaults()) so
all links are re-written as html markup instead of markdown [Title](url). This also prevents other markdown parsing problems.
@param String $markdown
@param DocumentationPage $doc_page
@return String | entailment |
public static function generate_html_id($title)
{
$t = $title;
$t = str_replace('&', '-and-', $t);
$t = str_replace('&', '-and-', $t);
$t = preg_replace('/[^A-Za-z0-9]+/', '-', $t);
$t = preg_replace('/-+/', '-', $t);
$t = trim($t, '-');
$t = strtolower($t);
return $t;
} | Generate an html element id from a string
@return String | entailment |
public static function rewrite_relative_links($md, $page)
{
$baselink = $page->getEntity()->Link();
$re = '/
([^\!]?) # exclude image format
\[
(.*?) # link title (non greedy)
\]
\(
(.*?) # link url (non greedy)
\)
/x';
preg_match_all($re, $md, $matches);
// relative path (relative to module base folder), without the filename.
// For "sapphire/en/current/topics/templates", this would be "templates"
$relativePath = DocumentationHelper::normalizePath(dirname($page->getRelativePath()));
if (strpos($page->getRelativePath(), 'index.md')) {
$relativeLink = $page->getRelativeLink();
} else {
$relativeLink = DocumentationHelper::normalizePath(dirname($page->getRelativeLink()));
}
if ($relativePath == '.') {
$relativePath = '';
}
if ($relativeLink == ".") {
$relativeLink = '';
}
// file base link
$fileBaseLink = DocumentationHelper::relativePath(DocumentationHelper::normalizePath(dirname($page->getPath())));
if ($matches) {
foreach ($matches[0] as $i => $match) {
$title = $matches[2][$i];
$url = $matches[3][$i];
// Don't process API links
if (preg_match('/^api:/', $url)) {
continue;
}
// Don't process absolute links (based on protocol detection)
$urlParts = parse_url($url);
if ($urlParts && isset($urlParts['scheme'])) {
continue;
}
// for images we need to use the file base path
if (preg_match('/_images/', $url)) {
$relativeUrl = Controller::join_links(
Director::absoluteBaseURL(),
$fileBaseLink,
$url
);
} elseif (preg_match('/^#/', $url)) {
// for relative links begining with a hash use the current page link
$relativeUrl = Controller::join_links($baselink, $page->getRelativeLink(), $url);
} else {
// Rewrite public URL
if (preg_match('/^\//', $url)) {
// Absolute: Only path to module base
$relativeUrl = Controller::join_links($baselink, $url, '/');
} else {
// Relative: Include path to module base and any folders
$relativeUrl = Controller::join_links($baselink, $relativeLink, $url, '/');
}
}
// Resolve relative paths
while (strpos($relativeUrl, '..') !== false) {
$relativeUrl = preg_replace('/[-\w]+\/\.\.\//', '', $relativeUrl);
}
// Replace any double slashes (apart from protocol)
$relativeUrl = preg_replace('/([^:])\/{2,}/', '$1/', $relativeUrl);
// Replace in original content
$md = str_replace(
$match,
sprintf('%s[%s](%s)', $matches[1][$i], $title, $relativeUrl),
$md
);
}
}
return $md;
} | Resolves all relative links within markdown.
@param String $md Markdown content
@param DocumentationPage $page
@return String Markdown | entailment |
public static function load($data)
{
$termDictionary = array();
$termInfos = array();
$pos = 0;
// $tiVersion = $tiiFile->readInt();
$tiVersion = ord($data[0]) << 24 | ord($data[1]) << 16 | ord($data[2]) << 8 | ord($data[3]);
$pos += 4;
if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */
&& $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */
) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Wrong TermInfoIndexFile file format');
}
// $indexTermCount = $tiiFile->readLong();
if (PHP_INT_SIZE > 4) {
$indexTermCount = ord($data[$pos]) << 56 |
ord($data[$pos+1]) << 48 |
ord($data[$pos+2]) << 40 |
ord($data[$pos+3]) << 32 |
ord($data[$pos+4]) << 24 |
ord($data[$pos+5]) << 16 |
ord($data[$pos+6]) << 8 |
ord($data[$pos+7]);
} else {
if ((ord($data[$pos]) != 0)
|| (ord($data[$pos+1]) != 0)
|| (ord($data[$pos+2]) != 0)
|| (ord($data[$pos+3]) != 0)
|| ((ord($data[$pos+4]) & 0x80) != 0)
) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Largest supported segment size (for 32-bit mode) is 2Gb');
}
$indexTermCount = ord($data[$pos+4]) << 24 |
ord($data[$pos+5]) << 16 |
ord($data[$pos+6]) << 8 |
ord($data[$pos+7]);
}
$pos += 8;
// $tiiFile->readInt(); // IndexInterval
$pos += 4;
// $skipInterval = $tiiFile->readInt();
$skipInterval = ord($data[$pos]) << 24 | ord($data[$pos+1]) << 16 | ord($data[$pos+2]) << 8 | ord($data[$pos+3]);
$pos += 4;
if ($indexTermCount < 1) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Wrong number of terms in a term dictionary index');
}
if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) {
/* Skip MaxSkipLevels value */
$pos += 4;
}
$prevTerm = '';
$freqPointer = 0;
$proxPointer = 0;
$indexPointer = 0;
for ($count = 0; $count < $indexTermCount; $count++) {
//$termPrefixLength = $tiiFile->readVInt();
$nbyte = ord($data[$pos++]);
$termPrefixLength = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$termPrefixLength |= ($nbyte & 0x7F) << $shift;
}
// $termSuffix = $tiiFile->readString();
$nbyte = ord($data[$pos++]);
$len = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$len |= ($nbyte & 0x7F) << $shift;
}
if ($len == 0) {
$termSuffix = '';
} else {
$termSuffix = substr($data, $pos, $len);
$pos += $len;
for ($count1 = 0; $count1 < $len; $count1++ ) {
if (( ord($termSuffix[$count1]) & 0xC0 ) == 0xC0) {
$addBytes = 1;
if (ord($termSuffix[$count1]) & 0x20 ) {
$addBytes++;
// Never used for Java Lucene created index.
// Java2 doesn't encode strings in four bytes
if (ord($termSuffix[$count1]) & 0x10 ) {
$addBytes++;
}
}
$termSuffix .= substr($data, $pos, $addBytes);
$pos += $addBytes;
$len += $addBytes;
// Check for null character. Java2 encodes null character
// in two bytes.
if (ord($termSuffix[$count1]) == 0xC0
&& ord($termSuffix[$count1+1]) == 0x80
) {
$termSuffix[$count1] = 0;
$termSuffix = substr($termSuffix, 0, $count1+1)
. substr($termSuffix, $count1+2);
}
$count1 += $addBytes;
}
}
}
// $termValue = Zend_Search_Lucene_Index_Term::getPrefix($prevTerm, $termPrefixLength) . $termSuffix;
$pb = 0; $pc = 0;
while ($pb < strlen($prevTerm) && $pc < $termPrefixLength) {
$charBytes = 1;
if ((ord($prevTerm[$pb]) & 0xC0) == 0xC0) {
$charBytes++;
if (ord($prevTerm[$pb]) & 0x20 ) {
$charBytes++;
if (ord($prevTerm[$pb]) & 0x10 ) {
$charBytes++;
}
}
}
if ($pb + $charBytes > strlen($data)) {
// wrong character
break;
}
$pc++;
$pb += $charBytes;
}
$termValue = substr($prevTerm, 0, $pb) . $termSuffix;
// $termFieldNum = $tiiFile->readVInt();
$nbyte = ord($data[$pos++]);
$termFieldNum = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$termFieldNum |= ($nbyte & 0x7F) << $shift;
}
// $docFreq = $tiiFile->readVInt();
$nbyte = ord($data[$pos++]);
$docFreq = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$docFreq |= ($nbyte & 0x7F) << $shift;
}
// $freqPointer += $tiiFile->readVInt();
$nbyte = ord($data[$pos++]);
$vint = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$vint |= ($nbyte & 0x7F) << $shift;
}
$freqPointer += $vint;
// $proxPointer += $tiiFile->readVInt();
$nbyte = ord($data[$pos++]);
$vint = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$vint |= ($nbyte & 0x7F) << $shift;
}
$proxPointer += $vint;
if($docFreq >= $skipInterval ) {
// $skipDelta = $tiiFile->readVInt();
$nbyte = ord($data[$pos++]);
$vint = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$vint |= ($nbyte & 0x7F) << $shift;
}
$skipDelta = $vint;
} else {
$skipDelta = 0;
}
// $indexPointer += $tiiFile->readVInt();
$nbyte = ord($data[$pos++]);
$vint = $nbyte & 0x7F;
for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
$nbyte = ord($data[$pos++]);
$vint |= ($nbyte & 0x7F) << $shift;
}
$indexPointer += $vint;
// $this->_termDictionary[] = new Zend_Search_Lucene_Index_Term($termValue, $termFieldNum);
$termDictionary[] = array($termFieldNum, $termValue);
$termInfos[] =
// new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipDelta, $indexPointer);
array($docFreq, $freqPointer, $proxPointer, $skipDelta, $indexPointer);
$prevTerm = $termValue;
}
// Check special index entry mark
if ($termDictionary[0][0] != (int)0xFFFFFFFF) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Wrong TermInfoIndexFile file format');
}
if (PHP_INT_SIZE > 4) {
// Treat 64-bit 0xFFFFFFFF as -1
$termDictionary[0][0] = -1;
}
return array($termDictionary, $termInfos);
} | Dictionary index loader.
It takes a string which is actually <segment_name>.tii index file data and
returns two arrays - term and tremInfo lists.
See Zend_Search_Lucene_Index_SegmintInfo class for details
@param string $data
@return array
@throws Zend_Search_Lucene_Exception | entailment |
public function writeAMFData($data,$forcetype=null) {
//If theres no type forced we'll try detecting it
if (is_null($forcetype)) {
$type=false;
// NULL type
if (!$type && is_null($data)) $type = SabreAMF_AMF0_Const::DT_NULL;
// Boolean
if (!$type && is_bool($data)) $type = SabreAMF_AMF0_Const::DT_BOOL;
// Number
if (!$type && (is_int($data) || is_float($data))) $type = SabreAMF_AMF0_Const::DT_NUMBER;
// String (a long one)
if (!$type && is_string($data) && strlen($data)>65536) $type = SabreAMF_AMF0_Const::DT_LONGSTRING;
// Normal string
if (!$type && is_string($data)) $type = SabreAMF_AMF0_Const::DT_STRING;
// Checking if its an array
if (!$type && is_array($data)) {
if ( $this->isPureArray( $data ) ) {
$type = SabreAMF_AMF0_Const::DT_ARRAY;
} else {
$type = SabreAMF_AMF0_Const::DT_MIXEDARRAY;
}
}
// Its an object
if (!$type && is_object($data)) {
// If its an AMF3 wrapper.. we treat it as such
if ($data instanceof SabreAMF_AMF3_Wrapper) $type = SabreAMF_AMF0_Const::DT_AMF3;
else if ($data instanceof DateTime) $type = SabreAMF_AMF0_Const::DT_DATE;
// We'll see if its registered in the classmapper
else if ($this->getRemoteClassName(get_class($data))) $type = SabreAMF_AMF0_Const::DT_TYPEDOBJECT;
// Otherwise.. check if it its an TypedObject
else if ($data instanceof SabreAMF_ITypedObject) $type = SabreAMF_AMF0_Const::DT_TYPEDOBJECT;
// If everything else fails, its a general object
else $type = SabreAMF_AMF0_Const::DT_OBJECT;
}
// If everything failed, throw an exception
if ($type===false) {
throw new Exception('Unhandled data-type: ' . gettype($data));
return null;
}
} else $type = $forcetype;
$this->stream->writeByte($type);
switch ($type) {
case SabreAMF_AMF0_Const::DT_NUMBER : return $this->stream->writeDouble($data);
case SabreAMF_AMF0_Const::DT_BOOL : return $this->stream->writeByte($data==true);
case SabreAMF_AMF0_Const::DT_STRING : return $this->writeString($data);
case SabreAMF_AMF0_Const::DT_OBJECT : return $this->writeObject($data);
case SabreAMF_AMF0_Const::DT_NULL : return true;
case SabreAMF_AMF0_Const::DT_MIXEDARRAY : return $this->writeMixedArray($data);
case SabreAMF_AMF0_Const::DT_ARRAY : return $this->writeArray($data);
case SabreAMF_AMF0_Const::DT_DATE : return $this->writeDate($data);
case SabreAMF_AMF0_Const::DT_LONGSTRING : return $this->writeLongString($data);
case SabreAMF_AMF0_Const::DT_TYPEDOBJECT : return $this->writeTypedObject($data);
case SabreAMF_AMF0_Const::DT_AMF3 : return $this->writeAMF3Data($data);
default : throw new Exception('Unsupported type: ' . gettype($data)); return false;
}
} | writeAMFData
@param mixed $data
@param int $forcetype
@return mixed | entailment |
public function writeMixedArray($data) {
$this->stream->writeLong(0);
foreach($data as $key=>$value) {
$this->writeString($key);
$this->writeAMFData($value);
}
$this->writeString('');
$this->stream->writeByte(SabreAMF_AMF0_Const::DT_OBJECTTERM);
} | writeMixedArray
@param array $data
@return void | entailment |
public function writeArray($data) {
if (!count($data)) {
$this->stream->writeLong(0);
} else {
end($data);
$last = key($data);
$this->stream->writeLong($last+1);
for($i=0;$i<=$last;$i++) {
if (isset($data[$i])) {
$this->writeAMFData($data[$i]);
} else {
$this->stream->writeByte(SabreAMF_AMF0_Const::DT_UNDEFINED);
}
}
}
} | writeArray
@param array $data
@return void | entailment |
public function writeObject($data) {
foreach($data as $key=>$value) {
$this->writeString($key);
$this->writeAmfData($value);
}
$this->writeString('');
$this->stream->writeByte(SabreAMF_AMF0_Const::DT_OBJECTTERM);
return true;
} | writeObject
@param object $data
@return void | entailment |
public function writeString($string) {
$this->stream->writeInt(strlen($string));
$this->stream->writeBuffer($string);
} | writeString
@param string $string
@return void | entailment |
public function writeLongString($string) {
$this->stream->writeLong(strlen($string));
$this->stream->writeBuffer($string);
} | writeLongString
@param string $string
@return void | entailment |
public function writeTypedObject($data) {
if ($data instanceof SabreAMF_ITypedObject) {
$classname = $data->getAMFClassName();
$data = $data->getAMFData();
} else $classname = $this->getRemoteClassName(get_class($data));
$this->writeString($classname);
return $this->writeObject($data);
} | writeTypedObject
@param object $data
@return void | entailment |
public function writeAMF3Data(SabreAMF_AMF3_Wrapper $data) {
$serializer = new SabreAMF_AMF3_Serializer($this->stream);
return $serializer->writeAMFData($data->getData());
} | writeAMF3Data
@param mixed $data
@return void | entailment |
public function writeDate(DateTime $data) {
$this->stream->writeDouble($data->format('U')*1000);
// empty timezone
$this->stream->writeInt(0);
} | Writes a date object
@param DateTime $data
@return void | entailment |
public function set($key, $value)
{
$keyExp = explode('.', $key);
$row = $this->database
->table($this->config['db_table'])
->where('setting_key', $keyExp[0])
->first(['setting_value']);
if (is_null($row))
{
$newKeyExp = array_slice($keyExp, 1);
$newValue = $value;
// if want to set a value directly from a dot keys
if (count($newKeyExp) > 0)
{
// we should compose a new array with keys from setter key
$newValue = build_array($newKeyExp, $value);
}
$this->database->table($this->config['db_table'])
->insert([
'setting_key' => $keyExp[0],
'setting_value' => ( ! empty($newValue) ? json_encode($newValue) : null),
]);
}
else
{
$setting_value = json_decode($row->setting_value, true);
set_nested_array_value($setting_value, $keyExp, $value);
$this->database->table($this->config['db_table'])
->where('setting_key', $keyExp[0])
->update([
'setting_value' => json_encode($setting_value)
]);
}
$this->cache->set($key, $value);
return $value;
} | Store value into registry
@param string $key
@param mixed $value
@return mixed | entailment |
public function get($key, $default = null)
{
$value = $this->fetch($key);
if ( ! is_null($value))
{
return $value;
}
if ($default != null)
{
return $default;
}
if ($this->config['fallback'])
{
if ( ! is_null($this->config['primary_config_file']))
{
$key2 = $this->config['primary_config_file'] . '.' . $key;
if (Config::has($key2))
{
return Config::get($key2);
}
}
return Config::get($key, null);
}
return $default;
} | Gets a value
@param string $key
@param string $default
@return mixed | entailment |
public function getAll($cache = true)
{
if ($cache)
{
return $this->cache->getAll();
}
$all = [];
$rows = $this->database->table($this->config['db_table'])->get();
foreach ($rows as $row)
{
$value = json_decode($row->setting_value, true);
$all[$row->setting_key] = $value;
}
return $all;
} | Fetch all values
@param $cache
@return mixed | entailment |
public function has($key)
{
$keyExp = explode('.', $key);
if ($this->cache->has($key))
{
return true;
}
$row = $this->database
->table($this->config['db_table'])
->where('setting_key', $keyExp[0])
->first(['setting_value']);
if ( ! is_null($row))
{
$setting_value = json_decode($row->setting_value, true);
array_shift($keyExp);
return multi_key_exists($keyExp, $setting_value);
}
return false;
} | Checks if setting exists
@param $key
@return bool | entailment |
public function forget($key)
{
$keyExp = explode('.', $key);
// get settings value by first key name
$query = $this->database
->table($this->config['db_table'])
->where('setting_key', $keyExp[0]);
$row = $query->first(['setting_value']);
if ( ! is_null($row))
{
if (count($keyExp) > 1)
{
// if found more keys, then forget last key from array
$setting_value = json_decode($row->setting_value, true);
unset($keyExp[0]);
$newKey = implode('.', $keyExp);
Arr::forget($setting_value, $newKey);
if (count($setting_value) > 0)
{
// if we still have settings, update settings row
$query->update(['setting_value' => json_encode($setting_value)]);
}
else
{
// if settings value remain blank, delete settings row
$query->delete();
}
}
else
{
// if found only one key, delete settings row
$query->delete();
}
}
$this->cache->forget($key);
} | Remove a settings from database and cache file
@param string $key
@return void | entailment |
public function clean($params = [])
{
if ( ! empty($this->config['primary_config_file']))
{
$default_settings = Arr::dot(Config::get($this->config['primary_config_file']));
$saved_settings = Arr::dot($this->getAll($cache = false));
if (array_key_exists('flush', $params) && $params['flush'] == true)
{
$this->flush();
$saved_settings = [];
}
else
{
foreach ($saved_settings as $key => $value)
{
if ( ! array_key_exists($key, $default_settings))
{
if ( ! key_represents_an_array($key, $default_settings))
{
$this->forget($key);
}
}
}
}
// update with new settings
foreach ($default_settings as $key => $value)
{
if ( ! preg_key_exists($key, $saved_settings))
{
// check if key does not represents an array and exists in saved settings
if ( ! key_represents_an_array($key, $saved_settings))
{
$this->set($key, $value);
}
}
}
}
} | Cleans settings that are no longer used in primary config file
@param $params | entailment |
public function flush()
{
$this->cache->flush();
return $this->database->table($this->config['db_table'])->delete();
} | Remove all settings
@return bool | entailment |
private function fetch($key)
{
$keyExp = explode('.', $key);
if ($this->cache->has($key))
{
return $this->cache->get($key);
}
$row = $this->database
->table($this->config['db_table'])
->where('setting_key', $keyExp[0])
->first(['setting_value']);
if ( ! is_null($row))
{
$setting_value = json_decode($row->setting_value, true);
$value = set_nested_array_value($setting_value, $keyExp);
return $this->cache->set($key, $value);
}
return null;
} | @param $key
@return mixed|null | entailment |
public static function obtainWriteLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->createFile(self::WRITE_LOCK_FILE);
if (!$lock->lock(LOCK_EX)) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Can\'t obtain exclusive index lock');
}
return $lock;
} | Obtain exclusive write lock on the index
@param Zend_Search_Lucene_Storage_Directory $lockDirectory
@return Zend_Search_Lucene_Storage_File
@throws Zend_Search_Lucene_Exception | entailment |
public static function releaseWriteLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->getFileObject(self::WRITE_LOCK_FILE);
$lock->unlock();
} | Release exclusive write lock
@param Zend_Search_Lucene_Storage_Directory $lockDirectory | entailment |
private static function _startReadLockProcessing(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->createFile(self::READ_LOCK_PROCESSING_LOCK_FILE);
if (!$lock->lock(LOCK_EX)) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Can\'t obtain exclusive lock for the read lock processing file');
}
return $lock;
} | Obtain the exclusive "read escalation/de-escalation" lock
Required to protect the escalate/de-escalate read lock process
on GFS (and potentially other) mounted filesystems.
Why we need this:
While GFS supports cluster-wide locking via flock(), it's
implementation isn't quite what it should be. The locking
semantics that work consistently on a local filesystem tend to
fail on GFS mounted filesystems. This appears to be a design defect
in the implementation of GFS. How this manifests itself is that
conditional promotion of a shared lock to exclusive will always
fail, lock release requests are honored but not immediately
processed (causing erratic failures of subsequent conditional
requests) and the releasing of the exclusive lock before the
shared lock is set when a lock is demoted (which can open a window
of opportunity for another process to gain an exclusive lock when
it shoudln't be allowed to).
@param Zend_Search_Lucene_Storage_Directory $lockDirectory
@return Zend_Search_Lucene_Storage_File
@throws Zend_Search_Lucene_Exception | entailment |
private static function _stopReadLockProcessing(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->getFileObject(self::READ_LOCK_PROCESSING_LOCK_FILE);
$lock->unlock();
} | Release the exclusive "read escalation/de-escalation" lock
Required to protect the escalate/de-escalate read lock process
on GFS (and potentially other) mounted filesystems.
@param Zend_Search_Lucene_Storage_Directory $lockDirectory | entailment |
public static function obtainReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->createFile(self::READ_LOCK_FILE);
if (!$lock->lock(LOCK_SH)) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Can\'t obtain shared reading index lock');
}
return $lock;
} | Obtain shared read lock on the index
It doesn't block other read or update processes, but prevent index from the premature cleaning-up
@param Zend_Search_Lucene_Storage_Directory $defaultLockDirectory
@return Zend_Search_Lucene_Storage_File
@throws Zend_Search_Lucene_Exception | entailment |
public static function releaseReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->getFileObject(self::READ_LOCK_FILE);
$lock->unlock();
} | Release shared read lock
@param Zend_Search_Lucene_Storage_Directory $lockDirectory | entailment |
public static function escalateReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
self::_startReadLockProcessing($lockDirectory);
$lock = $lockDirectory->getFileObject(self::READ_LOCK_FILE);
// First, release the shared lock for the benefit of GFS since
// it will fail the conditional request to promote the lock to
// "exclusive" while the shared lock is held (even when we are
// the only holder).
$lock->unlock();
// GFS is really poor. While the above "unlock" returns, GFS
// doesn't clean up it's tables right away (which will potentially
// cause the conditional locking for the "exclusive" lock to fail.
// We will retry the conditional lock request several times on a
// failure to get past this. The performance hit is negligible
// in the grand scheme of things and only will occur with GFS
// filesystems or if another local process has the shared lock
// on local filesystems.
for ($retries = 0; $retries < 10; $retries++) {
if ($lock->lock(LOCK_EX, true)) {
// Exclusive lock is obtained!
self::_stopReadLockProcessing($lockDirectory);
return true;
}
// wait 1 microsecond
usleep(1);
}
// Restore lock state
$lock->lock(LOCK_SH);
self::_stopReadLockProcessing($lockDirectory);
return false;
} | Escalate Read lock to exclusive level
@param Zend_Search_Lucene_Storage_Directory $lockDirectory
@return boolean | entailment |
public static function deEscalateReadLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->getFileObject(self::READ_LOCK_FILE);
$lock->lock(LOCK_SH);
} | De-escalate Read lock to shared level
@param Zend_Search_Lucene_Storage_Directory $lockDirectory | entailment |
public static function obtainOptimizationLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->createFile(self::OPTIMIZATION_LOCK_FILE);
if (!$lock->lock(LOCK_EX, true)) {
return false;
}
return $lock;
} | Obtain exclusive optimization lock on the index
Returns lock object on success and false otherwise (doesn't block execution)
@param Zend_Search_Lucene_Storage_Directory $lockDirectory
@return mixed | entailment |
public static function releaseOptimizationLock(Zend_Search_Lucene_Storage_Directory $lockDirectory)
{
$lock = $lockDirectory->getFileObject(self::OPTIMIZATION_LOCK_FILE);
$lock->unlock();
} | Release exclusive optimization lock
@param Zend_Search_Lucene_Storage_Directory $lockDirectory | entailment |
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'legal_type', [
'type' => 'int',
'label' => 'Customer Legal Type',
'input' => 'select',
'source' => 'Techspot\Brcustomer\Model\Config\Source\Legaltype',
'required' => true,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'legal_type')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]
]);
$attribute->save();
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'state_inscription', [
'type' => 'varchar',
'label' => 'State Inscription',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 334,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'state_inscription')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]
]);
$attribute->save();
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'county_inscription', [
'type' => 'varchar',
'label' => 'County Inscription',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 335,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'county_inscription')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]
]);
$attribute->save();
} | {@inheritdoc} | entailment |
public static function getActualGeneration(Zend_Search_Lucene_Storage_Directory $directory)
{
/**
* Zend_Search_Lucene uses segments.gen file to retrieve current generation number
*
* Apache Lucene index format documentation mentions this method only as a fallback method
*
* Nevertheless we use it according to the performance considerations
*
* @todo check if we can use some modification of Apache Lucene generation determination algorithm
* without performance problems
*/
include_once 'Zend/Search/Lucene/Exception.php';
try {
for ($count = 0; $count < self::GENERATION_RETRIEVE_COUNT; $count++) {
// Try to get generation file
$genFile = $directory->getFileObject('segments.gen', false);
$format = $genFile->readInt();
if ($format != (int)0xFFFFFFFE) {
throw new Zend_Search_Lucene_Exception('Wrong segments.gen file format');
}
$gen1 = $genFile->readLong();
$gen2 = $genFile->readLong();
if ($gen1 == $gen2) {
return $gen1;
}
usleep(self::GENERATION_RETRIEVE_PAUSE * 1000);
}
// All passes are failed
throw new Zend_Search_Lucene_Exception('Index is under processing now');
} catch (Zend_Search_Lucene_Exception $e) {
if (strpos($e->getMessage(), 'is not readable') !== false) {
try {
// Try to open old style segments file
$segmentsFile = $directory->getFileObject('segments', false);
// It's pre-2.1 index
return 0;
} catch (Zend_Search_Lucene_Exception $e) {
if (strpos($e->getMessage(), 'is not readable') !== false) {
return -1;
} else {
throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
}
}
} else {
throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
}
}
return -1;
} | Get current generation number
Returns generation number
0 means pre-2.1 index format
-1 means there are no segments files.
@param Zend_Search_Lucene_Storage_Directory $directory
@return integer
@throws Zend_Search_Lucene_Exception | entailment |
public function setFormatVersion($formatVersion)
{
if ($formatVersion != self::FORMAT_PRE_2_1
&& $formatVersion != self::FORMAT_2_1
&& $formatVersion != self::FORMAT_2_3
) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Unsupported index format');
}
$this->_formatVersion = $formatVersion;
} | Set index format version.
Index is converted to this format at the nearest upfdate time
@param int $formatVersion
@throws Zend_Search_Lucene_Exception | entailment |
private function _readPre21SegmentsFile()
{
$segmentsFile = $this->_directory->getFileObject('segments');
$format = $segmentsFile->readInt();
if ($format != (int)0xFFFFFFFF) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Wrong segments file format');
}
// read version
$segmentsFile->readLong();
// read segment name counter
$segmentsFile->readInt();
$segments = $segmentsFile->readInt();
$this->_docCount = 0;
// read segmentInfos
for ($count = 0; $count < $segments; $count++) {
$segName = $segmentsFile->readString();
$segSize = $segmentsFile->readInt();
$this->_docCount += $segSize;
$this->_segmentInfos[$segName] =
new Zend_Search_Lucene_Index_SegmentInfo(
$this->_directory,
$segName,
$segSize
);
}
// Use 2.1 as a target version. Index will be reorganized at update time.
$this->_formatVersion = self::FORMAT_2_1;
} | Read segments file for pre-2.1 Lucene index format
@throws Zend_Search_Lucene_Exception | entailment |
private function _readSegmentsFile()
{
$segmentsFile = $this->_directory->getFileObject(self::getSegmentFileName($this->_generation));
$format = $segmentsFile->readInt();
if ($format == (int)0xFFFFFFFC) {
$this->_formatVersion = self::FORMAT_2_3;
} else if ($format == (int)0xFFFFFFFD) {
$this->_formatVersion = self::FORMAT_2_1;
} else {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Unsupported segments file format');
}
// read version
$segmentsFile->readLong();
// read segment name counter
$segmentsFile->readInt();
$segments = $segmentsFile->readInt();
$this->_docCount = 0;
// read segmentInfos
for ($count = 0; $count < $segments; $count++) {
$segName = $segmentsFile->readString();
$segSize = $segmentsFile->readInt();
// 2.1+ specific properties
$delGen = $segmentsFile->readLong();
if ($this->_formatVersion == self::FORMAT_2_3) {
$docStoreOffset = $segmentsFile->readInt();
if ($docStoreOffset != (int)0xFFFFFFFF) {
$docStoreSegment = $segmentsFile->readString();
$docStoreIsCompoundFile = $segmentsFile->readByte();
$docStoreOptions = array('offset' => $docStoreOffset,
'segment' => $docStoreSegment,
'isCompound' => ($docStoreIsCompoundFile == 1));
} else {
$docStoreOptions = null;
}
} else {
$docStoreOptions = null;
}
$hasSingleNormFile = $segmentsFile->readByte();
$numField = $segmentsFile->readInt();
$normGens = array();
if ($numField != (int)0xFFFFFFFF) {
for ($count1 = 0; $count1 < $numField; $count1++) {
$normGens[] = $segmentsFile->readLong();
}
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Separate norm files are not supported. Optimize index to use it with Zend_Search_Lucene.');
}
$isCompoundByte = $segmentsFile->readByte();
if ($isCompoundByte == 0xFF) {
// The segment is not a compound file
$isCompound = false;
} else if ($isCompoundByte == 0x00) {
// The status is unknown
$isCompound = null;
} else if ($isCompoundByte == 0x01) {
// The segment is a compound file
$isCompound = true;
}
$this->_docCount += $segSize;
$this->_segmentInfos[$segName] =
new Zend_Search_Lucene_Index_SegmentInfo(
$this->_directory,
$segName,
$segSize,
$delGen,
$docStoreOptions,
$hasSingleNormFile,
$isCompound
);
}
} | Read segments file
@throws Zend_Search_Lucene_Exception | entailment |
private function _close()
{
if ($this->_closed) {
// index is already closed and resources are cleaned up
return;
}
$this->commit();
// Release "under processing" flag
Zend_Search_Lucene_LockManager::releaseReadLock($this->_directory);
if ($this->_closeDirOnExit) {
$this->_directory->close();
}
$this->_directory = null;
$this->_writer = null;
$this->_segmentInfos = null;
$this->_closed = true;
} | Close current index and free resources | entailment |
private function _getIndexWriter()
{
if ($this->_writer === null) {
include_once 'Zend/Search/Lucene/Index/Writer.php';
$this->_writer = new Zend_Search_Lucene_Index_Writer(
$this->_directory,
$this->_segmentInfos,
$this->_formatVersion
);
}
return $this->_writer;
} | Returns an instance of Zend_Search_Lucene_Index_Writer for the index
@return Zend_Search_Lucene_Index_Writer | entailment |
public function numDocs()
{
$numDocs = 0;
foreach ($this->_segmentInfos as $segmentInfo) {
$numDocs += $segmentInfo->numDocs();
}
return $numDocs;
} | Returns the total number of non-deleted documents in this index.
@return integer | entailment |
public function isDeleted($id)
{
if ($id >= $this->_docCount) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
}
$segmentStartId = 0;
foreach ($this->_segmentInfos as $segmentInfo) {
if ($segmentStartId + $segmentInfo->count() > $id) {
break;
}
$segmentStartId += $segmentInfo->count();
}
return $segmentInfo->isDeleted($id - $segmentStartId);
} | Checks, that document is deleted
@param integer $id
@return boolean
@throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range | entailment |
public function find($query)
{
if (is_string($query)) {
include_once 'Zend/Search/Lucene/Search/QueryParser.php';
$query = Zend_Search_Lucene_Search_QueryParser::parse($query);
}
if (!$query instanceof Zend_Search_Lucene_Search_Query) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Query must be a string or Zend_Search_Lucene_Search_Query object');
}
$this->commit();
$hits = array();
$scores = array();
$ids = array();
$query = $query->rewrite($this)->optimize($this);
$query->execute($this);
$topScore = 0;
/**
* Zend_Search_Lucene_Search_QueryHit
*/
include_once 'Zend/Search/Lucene/Search/QueryHit.php';
foreach ($query->matchedDocs() as $id => $num) {
$docScore = $query->score($id, $this);
if($docScore != 0 ) {
$hit = new Zend_Search_Lucene_Search_QueryHit($this);
$hit->id = $id;
$hit->score = $docScore;
$hits[] = $hit;
$ids[] = $id;
$scores[] = $docScore;
if ($docScore > $topScore) {
$topScore = $docScore;
}
}
if (self::$_resultSetLimit != 0 && count($hits) >= self::$_resultSetLimit) {
break;
}
}
if (count($hits) == 0) {
// skip sorting, which may cause a error on empty index
return array();
}
if ($topScore > 1) {
foreach ($hits as $hit) {
$hit->score /= $topScore;
}
}
if (func_num_args() == 1) {
// sort by scores
array_multisort(
$scores, SORT_DESC, SORT_NUMERIC,
$ids, SORT_ASC, SORT_NUMERIC,
$hits
);
} else {
// sort by given field names
$argList = func_get_args();
$fieldNames = $this->getFieldNames();
$sortArgs = array();
// PHP 5.3 now expects all arguments to array_multisort be passed by
// reference (if it's invoked through call_user_func_array());
// since constants can't be passed by reference, create some placeholder variables.
$sortReg = SORT_REGULAR;
$sortAsc = SORT_ASC;
$sortNum = SORT_NUMERIC;
$sortFieldValues = array();
include_once 'Zend/Search/Lucene/Exception.php';
for ($count = 1; $count < count($argList); $count++) {
$fieldName = $argList[$count];
if (!is_string($fieldName)) {
throw new Zend_Search_Lucene_Exception('Field name must be a string.');
}
if (strtolower($fieldName) == 'score') {
$sortArgs[] = &$scores;
} else {
if (!in_array($fieldName, $fieldNames)) {
throw new Zend_Search_Lucene_Exception('Wrong field name.');
}
if (!isset($sortFieldValues[$fieldName])) {
$valuesArray = array();
foreach ($hits as $hit) {
try {
$value = $hit->getDocument()->getFieldValue($fieldName);
} catch (Zend_Search_Lucene_Exception $e) {
if (strpos($e->getMessage(), 'not found') === false) {
throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
} else {
$value = null;
}
}
$valuesArray[] = $value;
}
// Collect loaded values in $sortFieldValues
// Required for PHP 5.3 which translates references into values when source
// variable is destroyed
$sortFieldValues[$fieldName] = $valuesArray;
}
$sortArgs[] = &$sortFieldValues[$fieldName];
}
if ($count + 1 < count($argList) && is_integer($argList[$count+1])) {
$count++;
$sortArgs[] = &$argList[$count];
if ($count + 1 < count($argList) && is_integer($argList[$count+1])) {
$count++;
$sortArgs[] = &$argList[$count];
} else {
if ($argList[$count] == SORT_ASC || $argList[$count] == SORT_DESC) {
$sortArgs[] = &$sortReg;
} else {
$sortArgs[] = &$sortAsc;
}
}
} else {
$sortArgs[] = &$sortAsc;
$sortArgs[] = &$sortReg;
}
}
// Sort by id's if values are equal
$sortArgs[] = &$ids;
$sortArgs[] = &$sortAsc;
$sortArgs[] = &$sortNum;
// Array to be sorted
$sortArgs[] = &$hits;
// Do sort
call_user_func_array('array_multisort', $sortArgs);
}
return $hits;
} | Performs a query against the index and returns an array
of Zend_Search_Lucene_Search_QueryHit objects.
Input is a string or Zend_Search_Lucene_Search_Query.
@param Zend_Search_Lucene_Search_QueryParser|string $query
@return array Zend_Search_Lucene_Search_QueryHit
@throws Zend_Search_Lucene_Exception | entailment |
public function getFieldNames($indexed = false)
{
$result = array();
foreach( $this->_segmentInfos as $segmentInfo ) {
$result = array_merge($result, $segmentInfo->getFields($indexed));
}
return $result;
} | Returns a list of all unique field names that exist in this index.
@param boolean $indexed
@return array | entailment |
public function getDocument($id)
{
if ($id instanceof Zend_Search_Lucene_Search_QueryHit) {
/* @var $id Zend_Search_Lucene_Search_QueryHit */
$id = $id->id;
}
if ($id >= $this->_docCount) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
}
$segmentStartId = 0;
foreach ($this->_segmentInfos as $segmentInfo) {
if ($segmentStartId + $segmentInfo->count() > $id) {
break;
}
$segmentStartId += $segmentInfo->count();
}
$fdxFile = $segmentInfo->openCompoundFile('.fdx');
$fdxFile->seek(($id-$segmentStartId)*8, SEEK_CUR);
$fieldValuesPosition = $fdxFile->readLong();
$fdtFile = $segmentInfo->openCompoundFile('.fdt');
$fdtFile->seek($fieldValuesPosition, SEEK_CUR);
$fieldCount = $fdtFile->readVInt();
$doc = new Zend_Search_Lucene_Document();
for ($count = 0; $count < $fieldCount; $count++) {
$fieldNum = $fdtFile->readVInt();
$bits = $fdtFile->readByte();
$fieldInfo = $segmentInfo->getField($fieldNum);
if (!($bits & 2)) { // Text data
$field = new Zend_Search_Lucene_Field(
$fieldInfo->name,
$fdtFile->readString(),
'UTF-8',
true,
$fieldInfo->isIndexed,
$bits & 1
);
} else { // Binary data
$field = new Zend_Search_Lucene_Field(
$fieldInfo->name,
$fdtFile->readBinary(),
'',
true,
$fieldInfo->isIndexed,
$bits & 1,
true
);
}
$doc->addField($field);
}
return $doc;
} | Returns a Zend_Search_Lucene_Document object for the document
number $id in this index.
@param integer|Zend_Search_Lucene_Search_QueryHit $id
@return Zend_Search_Lucene_Document
@throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range | entailment |
public function hasTerm(Zend_Search_Lucene_Index_Term $term)
{
foreach ($this->_segmentInfos as $segInfo) {
if ($segInfo->getTermInfo($term) !== null) {
return true;
}
}
return false;
} | Returns true if index contain documents with specified term.
Is used for query optimization.
@param Zend_Search_Lucene_Index_Term $term
@return boolean | entailment |
public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
{
$subResults = array();
$segmentStartDocId = 0;
foreach ($this->_segmentInfos as $segmentInfo) {
$subResults[] = $segmentInfo->termDocs($term, $segmentStartDocId, $docsFilter);
$segmentStartDocId += $segmentInfo->count();
}
if (count($subResults) == 0) {
return array();
} else if (count($subResults) == 1) {
// Index is optimized (only one segment)
// Do not perform array reindexing
return reset($subResults);
} else {
$result = call_user_func_array('array_merge', $subResults);
}
return $result;
} | Returns IDs of all documents containing term.
@param Zend_Search_Lucene_Index_Term $term
@param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
@return array | entailment |
public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
{
$result = array();
$segmentStartDocId = 0;
foreach ($this->_segmentInfos as $segmentInfo) {
$result += $segmentInfo->termFreqs($term, $segmentStartDocId, $docsFilter);
$segmentStartDocId += $segmentInfo->count();
}
return $result;
} | Returns an array of all term freqs.
Result 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 docFreq(Zend_Search_Lucene_Index_Term $term)
{
$result = 0;
foreach ($this->_segmentInfos as $segInfo) {
$termInfo = $segInfo->getTermInfo($term);
if ($termInfo !== null) {
$result += $termInfo->docFreq;
}
}
return $result;
} | Returns the number of documents in this index containing the $term.
@param Zend_Search_Lucene_Index_Term $term
@return integer | entailment |
public function norm($id, $fieldName)
{
if ($id >= $this->_docCount) {
return null;
}
$segmentStartId = 0;
foreach ($this->_segmentInfos as $segInfo) {
if ($segmentStartId + $segInfo->count() > $id) {
break;
}
$segmentStartId += $segInfo->count();
}
if ($segInfo->isDeleted($id - $segmentStartId)) {
return 0;
}
return $segInfo->norm($id - $segmentStartId, $fieldName);
} | Returns a normalization factor for "field, document" pair.
@param integer $id
@param string $fieldName
@return float | entailment |
public function delete($id)
{
if ($id instanceof Zend_Search_Lucene_Search_QueryHit) {
/* @var $id Zend_Search_Lucene_Search_QueryHit */
$id = $id->id;
}
if ($id >= $this->_docCount) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
}
$segmentStartId = 0;
foreach ($this->_segmentInfos as $segmentInfo) {
if ($segmentStartId + $segmentInfo->count() > $id) {
break;
}
$segmentStartId += $segmentInfo->count();
}
$segmentInfo->delete($id - $segmentStartId);
$this->_hasChanges = true;
} | Deletes a document from the index.
$id is an internal document id
@param integer|Zend_Search_Lucene_Search_QueryHit $id
@throws Zend_Search_Lucene_Exception | entailment |
public function addDocument(Zend_Search_Lucene_Document $document)
{
$this->_getIndexWriter()->addDocument($document);
$this->_docCount++;
$this->_hasChanges = true;
} | Adds a document to this index.
@param Zend_Search_Lucene_Document $document | entailment |
private function _updateDocCount()
{
$this->_docCount = 0;
foreach ($this->_segmentInfos as $segInfo) {
$this->_docCount += $segInfo->count();
}
} | Update document counter | entailment |
public function commit()
{
if ($this->_hasChanges) {
$this->_getIndexWriter()->commit();
$this->_updateDocCount();
$this->_hasChanges = false;
}
} | Commit changes resulting from delete() or undeleteAll() operations.
@todo undeleteAll processing. | entailment |
public function optimize()
{
// Commit changes if any changes have been made
$this->commit();
if (count($this->_segmentInfos) > 1 || $this->hasDeletions()) {
$this->_getIndexWriter()->optimize();
$this->_updateDocCount();
}
} | Optimize index.
Merges all segments into one | entailment |
public function terms()
{
$result = array();
/**
* Zend_Search_Lucene_Index_TermsPriorityQueue
*/
include_once 'Zend/Search/Lucene/Index/TermsPriorityQueue.php';
$segmentInfoQueue = new Zend_Search_Lucene_Index_TermsPriorityQueue();
foreach ($this->_segmentInfos as $segmentInfo) {
$segmentInfo->resetTermsStream();
// Skip "empty" segments
if ($segmentInfo->currentTerm() !== null) {
$segmentInfoQueue->put($segmentInfo);
}
}
while (($segmentInfo = $segmentInfoQueue->pop()) !== null) {
if ($segmentInfoQueue->top() === null
|| $segmentInfoQueue->top()->currentTerm()->key() != $segmentInfo->currentTerm()->key()
) {
// We got new term
$result[] = $segmentInfo->currentTerm();
}
if ($segmentInfo->nextTerm() !== null) {
// Put segment back into the priority queue
$segmentInfoQueue->put($segmentInfo);
}
}
return $result;
} | Returns an array of all terms in this index.
@return array | entailment |
public function resetTermsStream()
{
if ($this->_termsStream === null) {
/**
* Zend_Search_Lucene_TermStreamsPriorityQueue
*/
include_once 'Zend/Search/Lucene/TermStreamsPriorityQueue.php';
$this->_termsStream = new Zend_Search_Lucene_TermStreamsPriorityQueue($this->_segmentInfos);
} else {
$this->_termsStream->resetTermsStream();
}
} | Reset terms stream. | entailment |
public function findOrFail($id): Model
{
if (!is_numeric($id) && empty($id)) {
throw new RepositoryException($this, 'Provided id can not be empty.');
}
if (($this->model->getKeyType() === 'int' && !is_int($id)) ||
($this->model->getKeyType() === 'string' && is_int($id))
) {
throw new RepositoryException($this, 'Provided id type does not match model primary key type.');
}
try {
return $this->query()->findOrFail($id);
} catch (EloquentModelNotFountException $exception) {
throw new ModelNotFoundException($this, $id, $exception);
}
} | {@inheritdoc} | entailment |
public function create(Model $model): Model
{
$this->validateServedEntity($model);
if (!$model->save()) {
throw new RepositoryException($this, "Cannot create $this->modelClass record");
}
return $model;
} | {@inheritdoc} | entailment |
public function delete(Model $model): void
{
$this->validateServedEntity($model);
try {
$result = $model->delete();
} catch (Throwable $exception) {
throw new RepositoryException($this, "Cannot delete $this->modelClass record", 500, $exception);
}
if (!$result) {
throw new RepositoryException($this, "Cannot delete $this->modelClass record");
}
} | {@inheritdoc} | entailment |
public function getPage(PagingInfo $paging, array $fieldValues = []): LengthAwarePaginator
{
$builder = $this->query();
$builder->addNestedWhereQuery($this->getNestedWhereConditions($builder->getQuery(), $fieldValues));
return $builder->paginate($paging->pageSize, ['*'], 'page', $paging->page);
} | {@inheritdoc} | entailment |
public function getCursorPage(CursorRequest $cursor, array $fieldValues = []): CursorResult
{
$builder = $this->query();
$builder->addNestedWhereQuery($this->getNestedWhereConditions($builder->getQuery(), $fieldValues));
return $this->toCursorResult($cursor, $builder);
} | {@inheritdoc} | entailment |
private function performJoin($query, string $table, string $foreign, string $other)
{
// Check that table not joined yet
$joins = [];
foreach ((array)$query->getQuery()->joins as $key => $join) {
$joins[] = $join->table;
}
if (!in_array($table, $joins)) {
$query->leftJoin($table, $foreign, '=', $other);
}
return $query;
} | Perform join query.
@param Builder|QueryBuilder $query Query builder to apply joins
@param string $table Joined table
@param string $foreign Foreign key
@param string $other Other table key
@return Builder|QueryBuilder | entailment |
protected function getWithBuilder(
array $with,
?array $withCounts = null,
?array $where = null,
?SortOptions $sortOptions = null
): Builder {
return $this->query()
->when($with, function (Builder $query) use ($with) {
return $query->with($with);
})
->when($withCounts, function (Builder $query) use ($withCounts) {
return $query->withCount($withCounts);
})
->when($where, function (Builder $query) use ($where) {
return $query->where($where);
})
->when($sortOptions, function (Builder $query) use ($sortOptions) {
return $query->orderBy($sortOptions->orderBy, $sortOptions->sortOrder);
});
} | Returns builder that satisfied requested conditions, with eager loaded requested relations and relations counts,
ordered by requested rules.
@param array $with Which relations should be preloaded
@param array|null $withCounts Which related entities should be counted
@param array|null $where Conditions that retrieved entities should satisfy
@param SortOptions|null $sortOptions How list of item should be sorted
@return Builder
@deprecated This method unnecessary anymore and will be removed in next version | entailment |
public function count(array $where = []): int
{
$builder = $this->query();
if (count($where)) {
$builder->addNestedWhereQuery($this->getNestedWhereConditions($builder->getQuery(), $where));
}
return $builder->count();
} | {@inheritdoc} | entailment |
public function getWith(
array $with,
?array $withCounts = null,
?array $where = null,
?SortOptions $sortOptions = null
): Collection {
$builder = $this->query()
->with($with)
->when($withCounts, function (Builder $query) use ($withCounts) {
return $query->withCount($withCounts);
})
->when($sortOptions, function (Builder $query) use ($sortOptions) {
return $query->orderBy($sortOptions->orderBy, $sortOptions->sortOrder);
});
if ($where) {
$builder->addNestedWhereQuery($this->getNestedWhereConditions($builder->getQuery(), $where));
}
return $builder->get();
} | {@inheritdoc} | entailment |
public function getWhere(array $fieldValues): Collection
{
$builder = $this->query();
return $builder
->addNestedWhereQuery($this->getNestedWhereConditions($builder->getQuery(), $fieldValues))
->get();
} | {@inheritdoc} | entailment |
public function findWhere(array $fieldValues): ?Model
{
$builder = $this->query();
return $builder
->addNestedWhereQuery($this->getNestedWhereConditions($builder->getQuery(), $fieldValues))
->first();
} | {@inheritdoc} | entailment |
protected function getNestedWhereConditions($builder, array $criteria)
{
$subQuery = $builder->forNestedWhere();
foreach ($criteria as $key => $criterionData) {
switch (true) {
case $criterionData instanceof Criterion:
$criterion = $criterionData;
break;
case is_string($key)
&& ((!is_array($criterionData) && !is_object($criterionData))
|| $criterionData instanceof Carbon):
$criterion = new Criterion([Criterion::ATTRIBUTE => $key, Criterion::VALUE => $criterionData]);
break;
case is_int($key) && is_array($criterionData) && $this->isNestedCriteria($criterionData):
$boolean = 'and';
if (isset($criterionData[Criterion::BOOLEAN])) {
$boolean = $criterionData[Criterion::BOOLEAN];
unset($criterionData[Criterion::BOOLEAN]);
}
$subQuery->addNestedWhereQuery(
$this->getNestedWhereConditions($subQuery, $criterionData),
$boolean
);
continue 2;
default:
$criterion = $this->parseCriterion($criterionData);
}
if (!$this->isCriterionValid($criterion)) {
throw new BadCriteriaException($this);
}
switch ($criterion->operator) {
case 'in':
$subQuery->whereIn($criterion->attribute, $criterion->value, $criterion->boolean);
break;
case 'not in':
$subQuery->whereNotIn($criterion->attribute, $criterion->value, $criterion->boolean);
break;
default:
$subQuery->where(
$criterion->attribute,
$criterion->operator,
$criterion->value,
$criterion->boolean
);
break;
}
}
return $subQuery;
} | Returns query builder with applied criteria. This method work recursively and group nested criteria in one level.
@param QueryBuilder $builder Top level query builder
@param array $criteria Nested list of criteria
@return QueryBuilder
@throws BadCriteriaException when any criterion is not valid | entailment |
protected function isNestedCriteria(array $criterionData): bool
{
$isValid = true;
foreach ($criterionData as $key => $possibleCriterion) {
$isValid = $isValid &&
(
(is_int($key) && is_array($possibleCriterion)) ||
($key === Criterion::BOOLEAN && in_array($possibleCriterion, ['and', 'or']))
);
}
return $isValid;
} | Shows whether given criterion data is nested.
@param array $criterionData Criterion data to check
@return boolean | entailment |
protected function parseCriterion(array $criterionData): Criterion
{
return new Criterion([
Criterion::ATTRIBUTE => $criterionData[0] ?? null,
Criterion::OPERATOR => $criterionData[1] ?? null,
Criterion::VALUE => $criterionData[2] ?? null,
Criterion::BOOLEAN => $criterionData[3] ?? 'and',
]);
} | Transforms criterion data into DTO.
@param array $criterionData Criterion data to transform
@return Criterion | entailment |
protected function isCriterionValid(Criterion $criterion): bool
{
$isMultipleOperator = (is_array($criterion->value) || $criterion->value instanceof Collection) &&
in_array($criterion->operator, $this->multipleOperators);
$isSingleOperator = is_string($criterion->value) && in_array(strtolower($criterion->operator), $this->singleOperators);
return is_string($criterion->attribute) &&
is_string($criterion->boolean) &&
($isMultipleOperator || $isSingleOperator);
} | Checks whether the criterion is valid.
@param Criterion $criterion Criterion to check validity
@return boolean | entailment |
public function validate($attributes, Constraint $constraint)
{
if ($attributes->getEmail() || $attributes->getPhone()) {
return;
}
$this->context
->buildViolation($constraint->message)
->atPath('phone / email')
->addViolation();
} | {@inheritdoc}
@param Attributes $attributes
@param EmailOrPhone $constraint | entailment |
public function getBreadcrumbTitle($divider = ' - ')
{
$pathParts = explode('/', trim($this->getRelativePath(), '/'));
// from the page from this
array_pop($pathParts);
// add the module to the breadcrumb trail.
$pathParts[] = $this->entity->getTitle();
$titleParts = array_map(
array(
'DocumentationHelper',
'clean_page_name'
),
$pathParts
);
$titleParts = array_filter(
$titleParts,
function ($val) {
if ($val) {
return $val;
}
}
);
if ($this->getTitle()) {
array_unshift($titleParts, $this->getTitle());
}
return implode($divider, $titleParts);
} | @param string - has to be plain text for open search compatibility.
@return string | entailment |
public function getMarkdown($removeMetaData = false)
{
try {
if (is_file($this->getPath()) && $md = file_get_contents($this->getPath())) {
$this->populateMetaDataFromText($md, $removeMetaData);
return $md;
}
$this->read = true;
} catch (InvalidArgumentException $e) {
}
return false;
} | Return the raw markdown for a given documentation page.
@param boolean $removeMetaData
@return string|false | entailment |
public function getRelativeLink()
{
$path = $this->getRelativePath();
$url = explode('/', $path);
$url = implode(
'/',
array_map(
function ($a) {
return DocumentationHelper::clean_page_url($a);
},
$url
)
);
$url = trim($url, '/') . '/';
return $url;
} | This should return the link from the entity root to the page. The link
value has the cleaned version of the folder names. See
{@link getRelativePath()} for the actual file path.
@return string | entailment |
public function Link($short = false)
{
return Controller::join_links(
$this->entity->Link($short),
$this->getRelativeLink()
);
} | Returns the URL that will be required for the user to hit to view the
given document base name.
@param boolean $short If true, will attempt to return a short version of the url
This might omit the version number if this is the default version.
@return string | entailment |
public function populateCanonicalUrl()
{
$url = Director::absoluteURL(Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getEntity()->getLanguage(),
$this->getRelativeLink()
));
$this->setCanonicalUrl($url);
} | Determine and set the canonical URL for the given record, for example: dev/docs/en/Path/To/Document | entailment |
public function populateMetaDataFromText(&$md, $removeMetaData = false)
{
if (!$md) {
return;
}
// See if there is YAML metadata block at the top of the document. e.g.
// ---
// property: value
// another: value
// ---
//
// If we found one, then we'll use a YAML parser to extract the
// data out and then remove the whole block from the markdown string.
$parser = new \Mni\FrontYAML\Parser();
$document = $parser->parse($md, false);
$yaml = $document->getYAML();
if ($yaml) {
foreach ($yaml as $key => $value) {
if (!property_exists(get_class($this), $key)) {
continue;
}
$this->$key = $value;
}
if ($removeMetaData) {
$md = $document->getContent();
}
return;
}
// this is the alternative way of parsing the properties out that don't contain
// a YAML block declared with ---
//
// get the text up to the first empty line
$extPattern = "/^(.+)\n\r*\n/Uis";
$matches = preg_match($extPattern, $md, $block);
if ($matches && $block[1]) {
$metaDataFound = false;
// find the key/value pairs
$lines = preg_split('/\v+/', $block[1]);
$key = '';
$value = '';
foreach ($lines as $line) {
if (strpos($line, ':') !== false) {
list($key, $value) = explode(':', $line, 2);
$key = trim($key);
$value = trim($value);
} else {
$value .= ' ' . trim($line);
}
if (property_exists(get_class(), $key)) {
$this->$key = $value;
$metaDataFound = true;
}
}
// optionally remove the metadata block (only on the page that
// is displayed)
if ($metaDataFound && $removeMetaData) {
$md = preg_replace($extPattern, '', $md);
}
}
} | Return metadata from the first html block in the page, then remove the
block on request
@param DocumentationPage $md
@param bool $remove | entailment |
public function finishExpression()
{
if ($this->getState() != self::ST_LITERAL) {
include_once 'Zend/Search/Lucene/Exception.php';
throw new Zend_Search_Lucene_Exception('Literal expected.');
}
$this->_conjunctions[] = $this->_currentConjunction;
return $this->_conjunctions;
} | Finish an expression and return result
Result is a set of boolean query conjunctions
Each conjunction is an array of conjunction elements
Each conjunction element is presented with two-elements array:
array(<literal>, <is_negative>)
So, it has a structure:
array( array( array(<literal>, <is_negative>), // first literal of first conjuction
array(<literal>, <is_negative>), // second literal of first conjuction
...
array(<literal>, <is_negative>)
), // end of first conjuction
array( array(<literal>, <is_negative>), // first literal of second conjuction
array(<literal>, <is_negative>), // second literal of second conjuction
...
array(<literal>, <is_negative>)
), // end of second conjuction
...
) // end of structure
@return array
@throws Zend_Search_Lucene_Exception | entailment |
public function literalAction()
{
// Add literal to the current conjunction
$this->_currentConjunction[] = array($this->_literal, !$this->_negativeLiteral);
// Switch off negative signal
$this->_negativeLiteral = false;
} | Literal processing | entailment |
final public function map(callable $callback): self
{
$literal = [];
for ($i = 0, $rows = $this->getRowCount(); $i < $rows; $i++) {
$row = [];
for ($j = 0, $columns = $this->getColumnCount(); $j < $columns; $j++) {
$row[] = $callback($this->get($i, $j), $i, $j, $this);
}
$literal[] = $row;
}
return new self($literal);
} | Iterates over the current matrix with a callback function to return a new
matrix with the mapped values. $callback takes four arguments:
- The current matrix element
- The current row
- The current column
- The matrix being iterated over
@param callable $callback
@return self | entailment |
protected function _fread($length = 1)
{
$returnValue = substr($this->_data, $this->_position, $length);
$this->_position += $length;
return $returnValue;
} | Reads $length number of bytes at the current position in the
file and advances the file pointer.
@param integer $length
@return string | entailment |
public function seek($offset, $whence=SEEK_SET)
{
switch ($whence) {
case SEEK_SET:
$this->_position = $offset;
break;
case SEEK_CUR:
$this->_position += $offset;
break;
case SEEK_END:
$this->_position = strlen($this->_data);
$this->_position += $offset;
break;
default:
break;
}
} | Sets the file position indicator and advances the file pointer.
The new position, measured in bytes from the beginning of the file,
is obtained by adding offset to the position specified by whence,
whose values are defined as follows:
SEEK_SET - Set position equal to offset bytes.
SEEK_CUR - Set position to current location plus offset.
SEEK_END - Set position to end-of-file plus offset. (To move to
a position before the end-of-file, you need to pass a negative value
in offset.)
Upon success, returns 0; otherwise, returns -1
@param integer $offset
@param integer $whence
@return integer | entailment |
protected function _fwrite($data, $length=null)
{
// We do not need to check if file position points to the end of "file".
// Only append operation is supported now
if ($length !== null) {
$this->_data .= substr($data, 0, $length);
} else {
$this->_data .= $data;
}
$this->_position = strlen($this->_data);
} | Writes $length number of bytes (all, if $length===null) to the end
of the file.
@param string $data
@param integer $length | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.