sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function addRouteFromArray($name, array $routeArray) { $route = \Parable\Routing\Route::createFromDataArray($routeArray); $route->setName($name); $this->addRoute($name, $route); return $this; }
Add a route to the routes list from array data. @param string $name @param array $routeArray @return $this
entailment
public function addRoutesFromArray(array $routes) { foreach ($routes as $name => $route) { $this->addRouteFromArray($name, $route); } return $this; }
Add an array of routes defined by array data to the router. @param array $routes @return $this
entailment
public function getRouteByName($name) { if (!isset($this->routes[$name])) { return null; } return $this->routes[$name]; }
Return a route by its name. @param string $name @return \Parable\Routing\Route|null
entailment
public function matchUrl($url) { $url = '/' . ltrim($url, '/'); $url = $this->sanitizeUrl($url); if ($url && $route = $this->matchUrlDirectly($url)) { return $route; } if ($url && $route = $this->matchUrlWithParameters($url)) { return $route; } return null; }
Try to find a match in all available routes. @param string $url @return \Parable\Routing\Route|null
entailment
protected function matchUrlDirectly($url) { foreach ($this->routes as $route) { if ($route->matchDirectly($url)) { return $route; } } return null; }
Loop through routes and try to match directly. @param string $url @return \Parable\Routing\Route|null
entailment
protected function matchUrlWithParameters($url) { foreach ($this->routes as $route) { if ($route->matchWithParameters($url)) { return $route; } } return null; }
Loop through routes and try to match with parameters. @param string $url @return \Parable\Routing\Route|null
entailment
public function getRouteUrlByName($name, array $parameters = []) { $route = $this->getRouteByName($name); if (!$route) { return null; } return $route->buildUrlWithParameters($parameters); }
Return a url based on the $name provided, with $parameters passed (as [key => value]). @param string $name @param array $parameters @return string
entailment
public function leaves(\WP_Query $query) { $post = $query->get_queried_object(); $leaves = []; if ($post instanceof \WP_Post) { $post_format = get_post_format($post); $post_format and $leaves[] = "embed-{$post->post_type}-{$post_format}"; $leaves[] = "embed-{$post->post_type}"; } $leaves[] = 'embed'; return $leaves; }
{@inheritdoc}
entailment
public function getData4CodeType($code, $type) { $query = $this->createQueryBuilder('p') ->select('p') ->where('p.code = :code') ->setParameter('code', $code) ->andWhere('p.expire >= :expire') ->setParameter('expire', new \DateTime()) ->andWhere('p.type = :type') ->setParameter('type', $type) ->getQuery(); return $query->getOneOrNullResult(); }
@param $code @param $type @return null|\PServerCore\Entity\UserCodes
entailment
public function deleteCodes4User($userId, $type) { $query = $this->createQueryBuilder('p') ->delete($this->getEntityName(), 'p') ->where('p.user = :user_id') ->setParameter('user_id', $userId) ->andWhere('p.type = :type') ->setParameter('type', $type) ->getQuery(); return $query->execute(); }
@param $userId @param $type @return mixed
entailment
public function getExpiredCodes($limit = 100) { $query = $this->createQueryBuilder('p') ->select('p') ->andWhere('p.expire < :expire') ->setParameter('expire', new \DateTime()) ->orderBy('p.expire', 'asc') ->setMaxResults($limit) ->getQuery(); return $query->getResult(); }
@param int $limit @return \PServerCore\Entity\UserCodes[]
entailment
public function call() { $this->app->get('/api-docs', array($this, 'apiDocs'))->name('apiDocs'); $this->app->get('/api-docs/:resource', array($this, 'apiDocsForResource'))->name('apiDocsForResource'); $this->app->get('/docs/', array($this, 'docsView'))->name('apiView'); $this->next->call(); }
Call
entailment
public function getPage4Type($type) { $cachingKey = Caching::PAGE_INFO . '_' . $type; $pageInfo = $this->cachingHelperService->getItem($cachingKey, function () use ($type) { /** @var \PServerCore\Entity\Repository\PageInfo $repository */ $repository = $this->entityManager->getRepository( $this->collectionOptions->getEntityOptions()->getPageInfo() ); return $repository->getPageData4Type($type); }); return $pageInfo; }
@param $type @return \PServerCore\Entity\PageInfo|null
entailment
public function run() { $homedir = $this->parameter->getOption('homedir'); $homedir = ltrim($homedir, DS); $homedir_actual = $this->path->getDir($homedir); $this->output->writeln([ "Parable initialization script", "-----------------------------------", "This script will initialize Parable's structure.", "", "The full 'home directory' will be '<green>{$homedir_actual}</green>',", "but you can use the --homedir option to change this.", "", "Example: <yellow>parable init-structure --homedir=http_docs</yellow>", "", "<red>WARNING</red>", "This will overwrite existing files without notice!", ]); if (file_exists($this->path->getDir('app')) && file_exists($this->path->getDir('public'))) { $this->output->writeBlock('Note: It looks like you already have a structure initialized!', 'info'); } else { $this->output->newline(); } for (;;) { $this->output->write('Do you want to continue? [y/N] '); if ($this->input->getYesNo(false)) { break; } else { $this->output->writeln(['', '<red>You chose not to continue.</red>', '']); return $this; } } $this->output->newline(); $this->output->write('Creating folder structure: '); $dirs = [ 'app', 'app/Command', 'app/Config', 'app/Controller', 'app/Init', 'app/Model', 'app/Routing', 'app/View', 'app/View/Home', $homedir, ]; foreach ($dirs as $dir) { if (!file_exists($this->path->getDir($dir))) { mkdir($this->path->getDir($dir)); } $this->output->write('.'); } $this->output->writeln(" <green>OK</green>"); $this->output->write('Copying files: '); copy( $this->path->getDir("{$this->vendor_path}/structure/.htaccess"), $this->path->getDir(".htaccess") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/dynamicReturnTypeMeta.json"), $this->path->getDir("dynamicReturnTypeMeta.json") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/public/index.php_struct"), $this->path->getDir("{$homedir}/index.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/public/.htaccess"), $this->path->getDir("{$homedir}/.htaccess") ); $this->output->write('.'); // And we continue copying files copy( $this->path->getDir("{$this->vendor_path}/structure/app/Command/HelloWorld.php_struct"), $this->path->getDir("app/Command/HelloWorld.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/Config/App.php_struct"), $this->path->getDir("app/Config/App.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/Config/Custom.php_struct"), $this->path->getDir("app/Config/Custom.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/Controller/Home.php_struct"), $this->path->getDir("app/Controller/Home.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/Init/Example.php_struct"), $this->path->getDir("app/Init/Example.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/Model/User.php_struct"), $this->path->getDir("app/Model/User.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/Routing/App.php_struct"), $this->path->getDir("app/Routing/App.php") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/View/Home/index.phtml_struct"), $this->path->getDir("app/View/Home/index.phtml") ); $this->output->write('.'); copy( $this->path->getDir("{$this->vendor_path}/structure/app/View/Home/test.phtml_struct"), $this->path->getDir("app/View/Home/test.phtml") ); $this->output->write('.'); // If the homedir isn't 'public', change the values in Config\App.php and .htaccess. if ($homedir !== 'public') { $config = file_get_contents($this->path->getDir('app/Config/App.php')); $config = str_replace('"homedir" => "public"', '"homedir" => "' . $homedir . '"', $config); file_put_contents($this->path->getDir('app/Config/App.php'), $config); $this->output->write('.'); $htaccess = file_get_contents($this->path->getDir('.htaccess')); $htaccess = str_replace("public/$1", "{$homedir}/$1", $htaccess); file_put_contents($this->path->getDir('.htaccess'), $htaccess); } $this->output->write('.'); $this->output->writeln(' <green>OK</green>'); $this->output->writeln(['', '<green>Completed!</green>', '']); return $this; }
Run the init structure command. @return $this
entailment
public function setMailSender(\Parable\Mail\Sender\SenderInterface $mailSender) { $this->mailSender = $mailSender; return $this; }
Set the mail sender implementation to use. @param Sender\SenderInterface $mailSender @return $this
entailment
public function setFrom($email, $name = null) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new \Parable\Mail\Exception("Email provided is invalid: {$email}"); } $this->addresses['from'] = [ [ 'email' => $email, 'name' => $name, ] ]; return $this; }
Set the from address. @param string $email @param null|string $name @return $this @throws \Parable\Mail\Exception
entailment
protected function addAddress($type, $email, $name = null) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new \Parable\Mail\Exception("Email provided is invalid: {$email}"); } $this->addresses[$type][] = [ 'email' => $email, 'name' => $name, ]; return $this; }
Add an address to the $type stack. @param string $type @param string $email @param null|string $name @return $this @throws \Parable\Mail\Exception
entailment
public function getAddressesForType($type) { if (!isset($this->addresses[$type])) { throw new \Parable\Mail\Exception('Only to, cc, bcc addresses are allowed.'); } $addresses = []; foreach ($this->addresses[$type] as $address) { if (!empty($address['name'])) { $addresses[] = $address['name'] . ' <' . $address['email'] . '>'; } else { $addresses[] = $address['email']; } } return implode(', ', $addresses); }
Return all addresses for type. @param string $type @return string @throws \Parable\Mail\Exception
entailment
public function send() { if (!$this->mailSender) { throw new \Parable\Mail\Exception('No mail sender implementation set.'); } // Check the basics if (count($this->addresses['to']) === 0) { throw new \Parable\Mail\Exception('No to addresses provided.'); } if (empty($this->subject)) { throw new \Parable\Mail\Exception('No subject provided.'); } if (empty($this->body)) { throw new \Parable\Mail\Exception('No body provided.'); } // Handle the to, cc and bcc addresses $to = $this->getAddressesForType('to'); $cc = $this->getAddressesForType('cc'); $bcc = $this->getAddressesForType('bcc'); if (!empty($cc)) { $this->addHeader("Cc: {$cc}"); } if (!empty($bcc)) { $this->addHeader("Bcc: {$bcc}"); } // Handle from $from = $this->getAddressesForType('from'); $this->addHeader("From: {$from}"); $headers = array_merge($this->requiredHeaders, $this->headers); $headers = implode("\r\n", $headers); return $this->getMailSender()->send($to, $this->subject, $this->body, $headers); }
Send the email. @return bool @throws \Parable\Mail\Exception
entailment
protected function sendMail($to, $subject, $body, $headers) { return mail( $to, $subject, $body, $headers ); }
Actually send the email, using PHPs built-in mail() command. @param string $to @param string $subject @param string $body @param string $headers @return bool @codeCoverageIgnore
entailment
public function resetMailData() { // Reset the mail values $this->subject = null; $this->body = null; $this->headers = []; return $this; }
Reset just the subject, body, headers @return $this
entailment
private function isFunctionCall(Tokens $tokens, int $index): bool { $previousIndex = $tokens->getPrevMeaningfulToken($index); return $previousIndex !== null && ($tokens[$previousIndex]->isGivenKind(CT::T_FUNCTION_IMPORT) || $tokens[$previousIndex]->isGivenKind(T_FUNCTION)); }
Detect if this is most probably function call (and not function import or function definition).
entailment
public function trigger($event, &$payload = null) { // Disallow calling a trigger on global hooks if ($event === '*') { return $this; } // Get all global hooks $globalHooks = []; if (isset($this->hooks['*']) && count($this->hooks['*']) > 0) { $globalHooks = $this->hooks['*']; } // Check if the event exists and has callables to run if (!isset($this->hooks[$event]) || count($this->hooks[$event]) === 0) { // There are no specific hooks, but maybe there's global hooks? if (count($globalHooks) === 0) { // There is nothing to do here return $this; } $hooks = $globalHooks; } else { $hooks = $this->hooks[$event]; $hooks = array_merge($hooks, $globalHooks); } // All good, let's call those callables foreach ($hooks as $callable) { $callable($event, $payload); } return $this; }
Trigger $event and run through all hooks referenced, passing along $payload to all $callables. @param string $event @param null|mixed $payload @return $this
entailment
public function setAction($action) { if (!in_array($action, $this->acceptedValues)) { $acceptedValuesString = implode(', ', $this->acceptedValues); throw new \Parable\ORM\Exception("Invalid action set, only {$acceptedValuesString} are allowed."); } $this->action = $action; return $this; }
Set the type of query we're going to do. @param string $action @return $this @throws \Parable\ORM\Exception
entailment
public function where(\Parable\ORM\Query\ConditionSet $set) { $this->where[] = $set; return $this; }
Add a where condition set. @param \Parable\ORM\Query\ConditionSet $set @return $this
entailment
public function whereCondition($key, $comparator, $value = null, $tableName = null) { return $this->where($this->buildAndSet([ [$key, $comparator, $value, $tableName] ])); }
Add a condition based on key/comparator/value, with an optional $tableName. @param string $key @param string $comparator @param string|null $value @param string|null $tableName @return $this
entailment
public function having(\Parable\ORM\Query\ConditionSet $set) { $this->having[] = $set; return $this; }
Add a having condition set. @param \Parable\ORM\Query\ConditionSet $set @return $this
entailment
protected function join( $type, $joinTableName, $key, $comparator, $value = null, $shouldCompareFields = true, $tableName = null ) { if (!$tableName) { $tableName = $this->getTableName(); } $condition = new \Parable\ORM\Query\Condition(); $condition ->setQuery($this) ->setTableName($tableName) ->setJoinTableName($joinTableName) ->setKey($key) ->setComparator($comparator) ->setValue($value) ->setShouldCompareFields($shouldCompareFields); $this->joins[$type][] = $condition; return $this; }
Add a join to the query. @param int $type @param string $joinTableName @param string $key @param string $comparator @param mixed $value @param bool $shouldCompareFields @param string|null $tableName @return $this
entailment
public function innerJoin( $joinTableName, $key, $comparator, $value = null, $shouldCompareFields = true, $tableName = null ) { return $this->join( self::JOIN_INNER, $joinTableName, $key, $comparator, $value, $shouldCompareFields, $tableName ); }
Add an inner join to the query. @param string $joinTableName @param string $key @param string $comparator @param mixed $value @param bool $shouldCompareFields @param string|null $tableName @return $this
entailment
public function leftJoin( $joinTableName, $key, $comparator, $value = null, $shouldCompareFields = true, $tableName = null ) { return $this->join( self::JOIN_LEFT, $joinTableName, $key, $comparator, $value, $shouldCompareFields, $tableName ); }
Add a left join to the query. @param string $joinTableName @param string $key @param string $comparator @param mixed $value @param bool $shouldCompareFields @param string|null $tableName @return $this
entailment
public function rightJoin( $joinTableName, $key, $comparator, $value = null, $shouldCompareFields = true, $tableName = null ) { return $this->join( self::JOIN_RIGHT, $joinTableName, $key, $comparator, $value, $shouldCompareFields, $tableName ); }
Add a right join to the query. @param string $joinTableName @param string $key @param string $comparator @param mixed $value @param bool $shouldCompareFields @param string|null $tableName @return $this
entailment
public function fullJoin( $joinTableName, $key, $comparator, $value = null, $shouldCompareFields = true, $tableName = null ) { return $this->join( self::JOIN_FULL, $joinTableName, $key, $comparator, $value, $shouldCompareFields, $tableName ); }
Add a full join to the query. @param string $joinTableName @param string $key @param string $comparator @param mixed $value @param bool $shouldCompareFields @param string|null $tableName @return $this
entailment
public function addValues(array $values) { foreach ($values as $key => $value) { $this->addValue($key, $value); } return $this; }
Adds an array of values to update/insert queries. @param array $values @return $this
entailment
public function orderBy($key, $direction = self::ORDER_ASC, $tableName = null) { if (!$tableName) { $tableName = $this->getTableName(); } $this->orderBy[] = ['key' => $key, 'direction' => $direction, 'tableName' => $tableName]; return $this; }
Sets the order for select queries. @param string $key @param string $direction @param null|string $tableName @return $this
entailment
public function groupBy($key, $tableName = null) { if (!$tableName) { $tableName = $this->getTableName(); } $this->groupBy[] = ['key' => $key, 'tableName' => $tableName]; return $this; }
Sets the group by for select queries. @param string $key @param null|string $tableName @return $this
entailment
protected function buildSelect() { $selects = []; foreach ($this->select as $select) { $shouldBeQuoted = true; // Check our list of nonQuoteStrings to see if we should quote or not. foreach ($this->nonQuoteStrings as $nonQuoteString) { if (strpos(strtolower($select), $nonQuoteString) !== false) { $shouldBeQuoted = false; break; } } if ($shouldBeQuoted) { $selects[] = $this->getQuotedTableName() . '.' . $this->quoteIdentifier($select); } else { $selects[] = $select; } } return 'SELECT ' . implode(', ', $selects); }
Build and return the select string. @return string
entailment
protected function buildJoins() { $builtJoins = []; foreach ($this->joins as $type => $joins) { if (count($joins) > 0) { foreach ($joins as $join) { if ($type === self::JOIN_INNER) { $builtJoins[] = 'INNER JOIN'; } elseif ($type === self::JOIN_LEFT) { $builtJoins[] = 'LEFT JOIN'; } elseif ($type === self::JOIN_RIGHT) { $builtJoins[] = 'RIGHT JOIN'; } elseif ($type === self::JOIN_FULL) { $builtJoins[] = 'FULL JOIN'; } $builtJoins[] = $this->quoteIdentifier($join->getJoinTableName()) . ' ON'; // Use a ConditionSet to build the joins $conditionSet = new Query\Condition\AndSet($this, [$join]); $builtJoins[] = $conditionSet->buildWithoutParentheses(); } } } return implode(' ', $builtJoins); }
Build and return the join strings. @return string
entailment
protected function buildWheres() { if (count($this->where) === 0) { return ''; } // Use a ConditionSet to build the wheres $conditionSet = new Query\Condition\AndSet($this, $this->where); return "WHERE {$conditionSet->buildWithoutParentheses()}"; }
Build and return the where string. @return string
entailment
protected function buildHaving() { if (count($this->having) === 0) { return ''; } // Use a ConditionSet to build the having clause $conditionSet = new Query\Condition\AndSet($this, $this->having); return "HAVING {$conditionSet->buildWithoutParentheses()}"; }
Build and return the having string. @return string
entailment
protected function buildOrderBy() { if (count($this->orderBy) === 0) { return ''; } $orders = []; foreach ($this->orderBy as $orderBy) { $key = $this->quoteIdentifier($orderBy['tableName']) . '.' . $this->quoteIdentifier($orderBy['key']); $orders[] = $key . ' ' . $orderBy['direction']; } return 'ORDER BY ' . implode(', ', $orders); }
Build and return the order by string. @return string
entailment
protected function buildGroupBy() { if (count($this->groupBy) === 0) { return ''; } $groups = []; foreach ($this->groupBy as $groupBy) { $groupBy = $this->quoteIdentifier($groupBy['tableName']) . '.' . $this->quoteIdentifier($groupBy['key']); $groups[] = $groupBy; } return 'GROUP BY ' . implode(', ', $groups); }
Build and return the group by string. @return string
entailment
protected function buildLimitOffset() { if (empty($this->limitOffset)) { return ''; } $limitOffset = ''; if ($this->limitOffset['limit'] && $this->limitOffset['offset']) { $limitOffset = $this->limitOffset['offset'] . ',' . $this->limitOffset['limit']; } elseif ($this->limitOffset['limit']) { $limitOffset = $this->limitOffset['limit']; } elseif ($this->limitOffset['offset']) { $limitOffset = $this->limitOffset['offset']; } return 'LIMIT ' . $limitOffset; }
Build and return the limit/offset string. @return string
entailment
public function createQuery() { $query = \Parable\ORM\Query::createInstance(); $query->setTableName($this->getModel()->getTableName()); if ($this->onlyCount) { $query->select(['count(*)']); } if (!empty($this->orderBy)) { $query->orderBy($this->orderBy['key'], $this->orderBy['direction']); } if (!empty($this->limitOffset)) { $query->limitOffset($this->limitOffset['limit'], $this->limitOffset['offset']); } if ($this->returnOne) { $query->limitOffset(1); } return $query; }
Generate a query set to use the current Model's table name & key. @return \Parable\ORM\Query
entailment
public function getAll() { $query = $this->createQuery(); $result = $this->database->query($query); $entities = []; if ($result) { $result = $result->fetchAll(\PDO::FETCH_ASSOC); $entities = $this->handleResult($result); } if ($this->returnOne && is_array($entities)) { return current($entities); } return $entities; }
Returns all rows for this model type. @return \Parable\ORM\Model[]|\Parable\ORM\Model
entailment
public function getById($id) { $query = $this->createQuery(); $query->where( $query->buildAndSet([$this->getModel()->getTableKey(), '=', $id]) ); $result = $this->database->query($query); $model = null; if ($result) { $result = $result->fetchAll(\PDO::FETCH_ASSOC); $entities = $this->handleResult($result); $model = current($entities); } return $model; }
Returns a single model, based on $id. @param int $id @return null|\Parable\ORM\Model
entailment
public function getByCondition($key, $comparator, $value = null) { $query = $this->createQuery(); $conditionSet = $query->buildAndSet([$key, $comparator, $value]); return $this->getByConditionSet($conditionSet); }
Returns all rows matching specific condition parameters given. @param string $key @param string $comparator @param mixed|null $value @return \Parable\ORM\Model[]|\Parable\ORM\Model
entailment
public function getByConditionSets(array $conditionSets) { $query = $this->createQuery(); $query->whereMany($conditionSets); $result = $this->database->query($query); $entities = []; if ($result) { $result = $result->fetchAll(\PDO::FETCH_ASSOC); $entities = $this->handleResult($result); } if ($this->returnOne && is_array($entities)) { return current($entities); } return $entities; }
Returns all rows matching all conditions passed. @param array $conditionSets @return \Parable\ORM\Model[]|\Parable\ORM\Model
entailment
public function orderBy($key, $direction = \Parable\ORM\Query::ORDER_ASC) { $this->orderBy = ['key' => $key, 'direction' => $direction]; return $this; }
Allow multiple orders by $key in $direction. @param string $key @param string $direction ASC by default @return $this
entailment
public function setModel(\Parable\ORM\Model $model) { $this->model = $model->reset(); return $this; }
Set a model on the repository. Reset it so there's no unwanted values stored on it. @param \Parable\ORM\Model $model @return $this
entailment
protected function handleResult(array $result) { if ($this->onlyCount && isset($result[0]) && is_array($result[0])) { return (int)current($result[0]); } $entities = []; foreach ($result as $row) { $model = clone $this->getModel(); $model->populate($row); $entities[] = $model; } return $entities; }
Handle the result of one of the get functions. This attempts to create a new model with the values returned properly set. @param array $result @return \Parable\ORM\Model[]|int
entailment
public function reset() { $this->orderBy = []; $this->limitOffset = []; $this->setOnlyCount(false); $this->returnAll(); }
Resets everything but the query and model class to their default values.
entailment
public static function createForModelName($modelName) { if (!class_exists($modelName)) { throw new \Parable\ORM\Exception("Model '{$modelName}' does not exist."); } return self::createForModel($modelName::create()); }
Create an instance of the repository class for given $modelName. @param string $modelName @return \Parable\ORM\Repository @throws \Parable\ORM\Exception
entailment
public static function createForModel(\Parable\ORM\Model $model) { $repository = \Parable\DI\Container::create(static::class); $repository->setModel($model); return $repository; }
Create an instance of the repository class for given $model. @param \Parable\ORM\Model $model @return \Parable\ORM\Repository
entailment
public function initialize() { if ($this->checkAuthentication()) { $data = $this->getAuthenticationData(); if (!isset($data['user_id'])) { return false; } $user = $this->toolkit->getRepository($this->userClassName)->getById($data['user_id']); if (!$user) { $this->setAuthenticated(false); $this->setAuthenticationData([]); return false; } $this->setUser($user); return true; } return false; }
Initialize the authentication, picking up on session data if possible. @return bool
entailment
protected function checkAuthentication() { $authSession = $this->readFromSession(); if ($authSession) { if (isset($authSession['authenticated'])) { $this->setAuthenticated($authSession['authenticated']); } else { $this->setAuthenticated(false); } if (isset($authSession['data'])) { $this->setAuthenticationData($authSession['data']); } else { $this->setAuthenticationData([]); } return true; } return false; }
Checks whether there's an auth session active at this point. @return bool
entailment
public function setUserClassName($className) { try { \Parable\DI\Container::create($className); } catch (\Exception $e) { throw new \Parable\Framework\Exception("Class '{$className}' could not be instantiated."); } $this->userClassName = $className; return $this; }
Set the class name to use for the user. @param string $className @return $this @throws \Parable\Framework\Exception
entailment
public function setUser($user) { if (!($user instanceof $this->userClassName)) { throw new \Parable\Framework\Exception("Invalid object provided, type {$this->userClassName} required."); } $this->user = $user; return $this; }
Set the user and check whether it's of the right type. @param $user @return $this @throws \Parable\Framework\Exception
entailment
public function authenticate($passwordProvided, $passwordHash) { if (password_verify($passwordProvided, $passwordHash)) { $this->setAuthenticated(true); if ($this->getUser() && property_exists($this->getUser(), $this->getUserIdProperty())) { $userId = $this->getUser()->{$this->getUserIdProperty()}; $this->setAuthenticationData(['user_id' => $userId]); } $this->writeToSession([ 'authenticated' => true, 'data' => $this->getAuthenticationData(), ]); } else { $this->revokeAuthentication(); } return $this->isAuthenticated(); }
Check whether the provided password matches the password hash. @param string $passwordProvided @param string $passwordHash @return bool
entailment
protected function isJsonString($data) { if (!is_string($data) && !is_null($data)) { return false; } // We json_encode here to see if there might be a json_last_error json_decode($data, true); if (json_last_error() !== JSON_ERROR_NONE) { return false; } return true; }
Attempt to check whether the provided string is json or not. @param string $data @return bool
entailment
public function getNextTimeDay(array $dayList, $hour, $minute) { $nextTime = PHP_INT_MAX; $currentTimeStamp = $this->getCurrentTimeStamp(); $nDate = date("n", $currentTimeStamp); $yDate = date("Y", $currentTimeStamp); $jDate = date("j", $currentTimeStamp); foreach ($dayList as $day) { if (date('l', $currentTimeStamp) == $day) { if ($currentTimeStamp <= ($time = mktime($hour, $minute, 0, $nDate, $jDate, $yDate))) { $nextTime = $time; break; } } $timeStamp = mktime( $hour, $minute, 0, date('n', strtotime('next ' . $day, $currentTimeStamp)), date('j', strtotime('next ' . $day, $currentTimeStamp)), date('Y', strtotime('next ' . $day, $currentTimeStamp)) ); if ($nextTime > $timeStamp) { $nextTime = $timeStamp; } } return $nextTime; }
@param array $dayList @param integer $hour @param integer $minute @return int
entailment
protected function nextFight(array $hourList, $minute) { sort($hourList); $result = 0; $timeStamp = $this->getCurrentTimeStamp(); $nDate = date("n", $timeStamp); $yDate = date("Y", $timeStamp); $jDate = date("j", $timeStamp); $mDate = date("m", $timeStamp); foreach ($hourList as $hour) { // same day if (($result = mktime($hour, $minute, 0, $nDate, $jDate, $yDate)) >= $timeStamp) { break; } else { $result = 0; } } if (!$result) { // next day foreach ($hourList as $hour) { if (($result = mktime($hour, $minute, 0, $nDate, date('j', strtotime('+1 day', $timeStamp)), $yDate)) >= $timeStamp ) { break; } } } if (!$result) { // next month foreach ($hourList as $hour) { if (($result = mktime($hour, $minute, 0, $mDate + 1, 1, $yDate)) >= $timeStamp) { break; } } } return $result; }
@param array $hourList @param $minute @return int
entailment
protected function setValuesFromConfig() { if ($this->config->get('parable.mail.sender')) { try { $sender = \Parable\DI\Container::create($this->config->get('parable.mail.sender')); $this->setMailSender($sender); } catch (\Exception $e) { throw new \Parable\Framework\Exception('Invalid mail sender set in config.'); } } else { // Use PhPMail sender by default $this->setMailSender(new \Parable\Mail\Sender\PhpMail()); } if ($this->config->get('parable.mail.from.email')) { $this->setFrom( $this->config->get('parable.mail.from.email'), $this->config->get('parable.mail.from.name') ); } return $this; }
Set the following values from config if available: parable.mail.sender - the Mail sender implementation to use (default: PhpMail) parable.mail.from.email - the email to set the from to by default parable.mail.from.name - the name to set the from to by default, optional, only used if from.email is present @return $this @throws \Parable\Framework\Exception
entailment
public function loadTemplate($path) { $path = $this->path->getDir($path); if (!file_exists($path)) { throw new \Parable\Framework\Exception("Email template '{$path}' does not exist."); } $content = $this->view->partial($path); $this->setBody(trim($content)); return $this; }
Load template for this mail. Returns the interpreted output as string. @param string $path @return $this @throws \Parable\Framework\Exception
entailment
public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) { if (strlen($srcToken->getTermText()) < $this->length) { 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
protected function query(string $sql): ResultSet { $sql = preg_replace('/_\?\w{13}\?_/', '?', $sql); if ($sql === null) { throw new \UnexpectedValueException; } return $this->connection->query(...$this->addParams($sql)); }
Call Context::query() with current sql + params
entailment
public function filter(array $filters): void { foreach ($filters as $filter) { if ($filter->isValueSet()) { if ($filter->getConditionCallback() !== null) { $this->sql = call_user_func_array( $filter->getConditionCallback(), [$this->sql, $filter->getValue(), & $this->queryParameters] ); $this->queryHelper->resetQuery($this->sql); } else { if ($filter instanceof FilterText) { $this->applyFilterText($filter); } elseif ($filter instanceof FilterMultiSelect) { $this->applyFilterMultiSelect($filter); } elseif ($filter instanceof FilterSelect) { $this->applyFilterSelect($filter); } elseif ($filter instanceof FilterDate) { $this->applyFilterDate($filter); } elseif ($filter instanceof FilterDateRange) { $this->applyFilterDateRange($filter); } elseif ($filter instanceof FilterRange) { $this->applyFilterRange($filter); } } } } }
{@inheritDoc}
entailment
public function filterOne(array $condition): IDataSource { foreach ($condition as $column => $value) { $this->applyWhere($column, $value); } return $this; }
{@inheritDoc}
entailment
public function setupEntities() { if ($this->registeredEntities->Count() > 0) { return; } if (Config::inst()->get('DocumentationManifest', 'automatic_registration')) { $this->populateEntitiesFromInstall(); } $registered = Config::inst()->get('DocumentationManifest', 'register_entities'); foreach ($registered as $details) { // validate the details provided through the YAML configuration $required = array('Path', 'Title'); foreach ($required as $require) { if (!isset($details[$require])) { throw new Exception("$require is a required key in DocumentationManifest.register_entities"); } } // if path is not an absolute value then assume it is relative from // the BASE_PATH. $path = $this->getRealPath($details['Path']); $key = (isset($details['Key'])) ? $details['Key'] : $details['Title']; if (!$path || !is_dir($path)) { trigger_error($details['Path'] . ' is not a valid documentation directory', E_USER_WARNING); continue; } $version = (isset($details['Version'])) ? $details['Version'] : ''; $versionTitle = isset($details['VersionTitle']) ? $details['VersionTitle'] : $version; $archived = !empty($details['Archived']); $branch = (isset($details['Branch'])) ? $details['Branch'] : ''; $langs = scandir($path); if ($langs) { $possible = i18n::get_common_languages(true); foreach ($langs as $k => $lang) { if (isset($possible[$lang])) { /** * @var DocumentationEntity $entity */ $entity = Injector::inst()->create( 'DocumentationEntity', $key ); $entity->setPath(DocumentationHelper::normalizePath(Controller::join_links($path, $lang, '/'))); $entity->setTitle($details['Title']); $entity->setLanguage($lang); $entity->setVersion($version); $entity->setVersionTitle($versionTitle); $entity->setBranch($branch); $entity->setIsArchived($archived); if (isset($details['Stable'])) { $entity->setIsStable($details['Stable']); } if (isset($details['DefaultEntity'])) { $entity->setIsDefaultEntity($details['DefaultEntity']); if ($entity->getIsDefaultEntity()) { $this->has_default_entity = true; } } $this->registeredEntities->push($entity); } } } } }
Sets up the top level entities. Either manually registered through the YAML syntax or automatically loaded through investigating the file system for `docs` folder.
entailment
public function populateEntitiesFromInstall() { if ($this->automaticallyPopulated) { // already run return; } foreach (scandir(BASE_PATH) as $key => $entity) { if ($key == "themes") { continue; } $dir = DocumentationHelper::normalizePath(Controller::join_links(BASE_PATH, $entity)); if (is_dir($dir)) { // check to see if it has docs $docs = Controller::join_links($dir, 'docs'); if (is_dir($docs)) { $entities[] = array( 'Path' => $docs, 'Title' => DocumentationHelper::clean_page_name($entity), 'Version' => 'master', 'Branch' => 'master', 'Stable' => true ); } } } Config::inst()->update( 'DocumentationManifest', 'register_entities', $entities ); $this->automaticallyPopulated = true; }
Scans the current installation and picks up all the SilverStripe modules that contain a `docs` folder. @return void
entailment
public function getPage($url) { $pages = $this->getPages(); $url = $this->normalizeUrl($url); if (!isset($pages[$url])) { return null; } $record = $pages[$url]; foreach ($this->getEntities() as $entity) { if (strpos($record['filepath'], $entity->getPath()) !== false) { $page = Injector::inst()->create( $record['type'], $entity, $record['basename'], $record['filepath'] ); return $page; } } }
Returns a particular page for the requested URL. @return DocumentationPage
entailment
public function getRedirect($url) { $pages = $this->getRedirects(); $url = $this->normalizeUrl($url); if (isset($pages[$url])) { return $pages[$url]; } }
Get any redirect for the given url @param type $url @return string
entailment
public function regenerate($cache = true) { $finder = new DocumentationManifestFileFinder(); $finder->setOptions( array( 'dir_callback' => array($this, 'handleFolder'), 'file_callback' => array($this, 'handleFile') ) ); $this->redirects = array(); foreach ($this->getEntities() as $entity) { $this->entity = $entity; $this->handleFolder('', $this->entity->getPath(), 0); $finder->find($this->entity->getPath()); } // groupds $grouped = array(); foreach ($this->pages as $url => $page) { if (!isset($grouped[$page['entitypath']])) { $grouped[$page['entitypath']] = array(); } $grouped[$page['entitypath']][$url] = $page; } $this->pages = array(); foreach ($grouped as $entity) { uasort( $entity, function ($a, $b) { // ensure parent directories are first $a['filepath'] = str_replace('index.md', '', $a['filepath']); $b['filepath'] = str_replace('index.md', '', $b['filepath']); if (strpos($b['filepath'], $a['filepath']) === 0) { return -1; } if ($a['filepath'] == $b['filepath']) { return 0; } return ($a['filepath'] < $b['filepath']) ? -1 : 1; } ); $this->pages = array_merge($this->pages, $entity); } if ($cache) { $this->cache->save( array( 'pages' => $this->pages, 'redirects' => $this->redirects ), $this->cacheKey ); } $this->inited = true; }
Regenerates the manifest by scanning the base path. @param bool $cache
entailment
protected function stripLinkBase($link) { // Trim baseURL $link = preg_replace('/^' . preg_quote(Director::baseURL(), '/') .'/', '', $link); // Trim link_base if ($linkBase = Config::inst()->get('DocumentationViewer', 'link_base')) { $link = preg_replace('/^' . preg_quote($linkBase, '/') .'\/?/', '', $link); } return $link; }
Remove the link_base from the start of a link @param string $link @return string
entailment
protected function addRedirect($from, $to) { $fromLink = $this->stripLinkBase($from); $toLink = $this->stripLinkBase($to); // If the redirect "from" is already registered with a "to", don't override it. This ensures // that the first version processed is treated as the canonical version. if (!isset($this->redirects[$fromLink])) { $this->redirects[$fromLink] = $toLink; } }
Add a redirect @param string $from @param string $to
entailment
public function handleFile($basename, $path, $depth) { $page = Injector::inst()->create( 'DocumentationPage', $this->entity, $basename, $path ); // populate any meta data $page->getMarkdown(); // Add main link $fullLink = $page->Link(); $this->addPage($page, $basename, $path); // If this is a stable version, add the short link $shortLink = $page->Link(true); if ($fullLink != $shortLink) { $this->addRedirect($shortLink, $fullLink); } }
Individual files can optionally provide a nice title and a better URL through the use of markdown meta data. This creates a new {@link DocumentationPage} instance for the file. If the markdown does not specify the title in the meta data it falls back to using the file name. @param string $basename @param string $path @param int $depth
entailment
public function generateBreadcrumbs($record, $base) { $output = new ArrayList(); $parts = explode('/', trim($record->getRelativeLink(), '/')); // Add the base link. $output->push( new ArrayData( array( 'Link' => $base->Link(), 'Title' => $base->Title ) ) ); $progress = $base->Link(); foreach ($parts as $part) { if ($part) { $progress = Controller::join_links($progress, $part, '/'); $output->push( new ArrayData( array( 'Link' => $progress, 'Title' => DocumentationHelper::clean_page_name($part) ) ) ); } } return $output; }
Generate an {@link ArrayList} of the pages to the given page. @param DocumentationPage @param DocumentationEntityLanguage @return ArrayList
entailment
protected function buildUrl($url) { return Controller::join_links( Director::baseURL(), Config::inst()->get('DocumentationViewer', 'link_base'), $url, '/' ); }
Create a clean domain-relative URL form a docuetn URL
entailment
public function getNextPage($filepath, $entityBase) { $grabNext = false; $fallback = null; foreach ($this->getPages() as $url => $page) { if ($grabNext && strpos($page['filepath'], $entityBase) !== false) { return new ArrayData( array( 'Link' => $this->buildUrl($url), 'Title' => $page['title'] ) ); } if ($filepath == $page['filepath']) { $grabNext = true; } elseif (!$fallback && strpos($page['filepath'], $filepath) !== false) { $fallback = new ArrayData( array( 'Link' => $this->buildUrl($url), 'Title' => $page['title'], 'Fallback' => true ) ); } } if (!$grabNext) { return $fallback; } return null; }
Determine the next page from the given page. Relies on the fact when the manifest was built, it was generated in order. @param string $filepath @param string $entityBase @return ArrayData
entailment
public function getPreviousPage($filepath, $entityPath) { $previousUrl = $previousPage = null; foreach ($this->getPages() as $url => $page) { if ($filepath == $page['filepath']) { if ($previousUrl) { return new ArrayData( array( 'Link' => $this->buildUrl($previousUrl), 'Title' => $previousPage['title'] ) ); } } if (strpos($page['filepath'], $entityPath) !== false) { $previousUrl = $url; $previousPage = $page; } } return null; }
Determine the previous page from the given page. Relies on the fact when the manifest was built, it was generated in order. @param string $filepath @param string $entityBase @return ArrayData
entailment
public function normalizeUrl($url) { $url = trim($url, '/') .'/'; // if the page is the index page then hide it from the menu if (strpos(strtolower($url), '/index.md/')) { $url = substr($url, 0, strpos($url, "index.md/")); } return $url; }
@param string @return string
entailment
public function getChildrenFor($entityPath, $recordPath = null) { if (!$recordPath) { $recordPath = $entityPath; } $output = new ArrayList(); $entityPath = $this->normalizeUrl($entityPath); $recordPath = $this->normalizeUrl($recordPath); $recordParts = explode('/', trim($recordPath, '/')); $currentRecordPath = end($recordParts); $depth = substr_count($entityPath, '/'); foreach ($this->getPages() as $url => $page) { $pagePath = $this->normalizeUrl($page['filepath']); // check to see if this page is under the given path if (strpos($pagePath, $entityPath) === false) { continue; } // only pull it up if it's one more level depth if (substr_count($pagePath, '/') == ($depth + 1)) { $pagePathParts = explode('/', trim($pagePath, '/')); $currentPagePath = end($pagePathParts); if ($currentPagePath == $currentRecordPath) { $mode = 'current'; } elseif (strpos($recordPath, $pagePath) !== false) { $mode = 'section'; } else { $mode = 'link'; } $children = new ArrayList(); if ($mode == 'section' || $mode == 'current') { $children = $this->getChildrenFor($pagePath, $recordPath); } $output->push( new ArrayData( array( 'Link' => $this->buildUrl($url), 'Title' => $page['title'], 'LinkingMode' => $mode, 'Summary' => $page['summary'], 'Children' => $children ) ) ); } } return $output; }
Return the children of the provided record path. Looks for any pages in the manifest which have one more slash attached. @param string $path @return ArrayList
entailment
public function getAllVersionsOfEntity(DocumentationEntity $entity) { $all = new ArrayList(); foreach ($this->getEntities() as $check) { if ($check->getKey() == $entity->getKey()) { if ($check->getLanguage() == $entity->getLanguage()) { $all->push($check); } } } return $all; }
@param DocumentationEntity @return ArrayList
entailment
public function getStableVersion(DocumentationEntity $entity) { foreach ($this->getEntities() as $check) { if ($check->getKey() == $entity->getKey()) { if ($check->getLanguage() == $entity->getLanguage()) { if ($check->getIsStable()) { return $check; } } } } return $entity; }
@param DocumentationEntity @return DocumentationEntity
entailment
public function getAllVersions() { $versions = array(); foreach ($this->getEntities() as $entity) { if ($entity->getVersion()) { $versions[$entity->getVersion()] = $entity->getVersion(); } else { $versions['0.0'] = _t('DocumentationManifest.MASTER', 'Master'); } } asort($versions); return $versions; }
Returns a sorted array of all the unique versions registered
entailment
public static function fromInteger(int $vat = null): Tax { $mapping = [ 0 => self::VAT0, 10 => self::VAT110, 18 => self::VAT118, ]; if (null === $vat) { return new self(self::NONE); } if (!isset($mapping[$vat])) { throw VatException::becauseUnknownVatValue($vat); } return new self($mapping[$vat]); }
Get tax by integer value. @param int|null $vat @return Tax
entailment
public static function clean_page_name($name) { $name = self::trim_extension_off($name); $name = self::trim_sort_number($name); $name = str_replace(array('-', '_'), ' ', $name); return ucfirst(trim($name)); }
String helper for cleaning a file name to a readable version. @param string $name to convert @return string $name output
entailment
public static function clean_page_url($name) { $name = str_replace(array(' '), '_', $name); $name = self::trim_extension_off($name); $name = self::trim_sort_number($name); if (preg_match('/^[\/]?index[\/]?/', $name)) { return ''; } return strtolower($name); }
String helper for cleaning a file name to a URL safe version. @param string $name to convert @return string $name output
entailment
public static function trim_extension_off($name) { if (strrpos($name, '.') !== false) { return substr($name, 0, strrpos($name, '.')); } return $name; }
Helper function to strip the extension off and return the name without the extension. @param string @return string
entailment
public static function relativePath($path) { $base = self::normalizePath(Director::baseFolder()); return substr($path, strlen($base)); }
Helper function to make normalized paths relative @param string @return string
entailment
private static function _getPrefix($word) { $questionMarkPosition = strpos($word, '?'); $astrericPosition = strpos($word, '*'); if ($questionMarkPosition !== false) { if ($astrericPosition !== false) { return substr($word, 0, min($questionMarkPosition, $astrericPosition)); } return substr($word, 0, $questionMarkPosition); } else if ($astrericPosition !== false) { return substr($word, 0, $astrericPosition); } return $word; }
Get terms prefix @param string $word @return string
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { $this->_matches = array(); if ($this->_pattern->field === null) { // Search through all fields $fields = $index->getFieldNames(true /* indexed fields list */); } else { $fields = array($this->_pattern->field); } $prefix = self::_getPrefix($this->_pattern->text); $prefixLength = strlen($prefix); $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*'), preg_quote($this->_pattern->text, '/')) . '$/'; if ($prefixLength < self::$_minPrefixLength) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard characters are required at the beginning of pattern.'); } /** * @todo check for PCRE unicode support may be performed through Zend_Environment in some future */ if (@preg_match('/\pL/u', 'a') == 1) { // PCRE unicode support is turned on // add Unicode modifier to the match expression $matchExpression .= 'u'; } $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); foreach ($fields as $field) { $index->resetTermsStream(); include_once 'Zend/Search/Lucene/Index/Term.php'; if ($prefix != '') { $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field)); while ($index->currentTerm() !== null && $index->currentTerm()->field == $field && substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) { if (preg_match($matchExpression, $index->currentTerm()->text) === 1) { $this->_matches[] = $index->currentTerm(); if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } } $index->nextTerm(); } } else { $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field)); while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) { if (preg_match($matchExpression, $index->currentTerm()->text) === 1) { $this->_matches[] = $index->currentTerm(); if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } } $index->nextTerm(); } } $index->closeTermsStream(); } if (count($this->_matches) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } else if (count($this->_matches) == 1) { include_once 'Zend/Search/Lucene/Search/Query/Term.php'; return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); } else { include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm(); foreach ($this->_matches as $matchedTerm) { $rewrittenQuery->addTerm($matchedTerm); } return $rewrittenQuery; } }
Re-write query into primitive queries in the context of specified index @param Zend_Search_Lucene_Interface $index @return Zend_Search_Lucene_Search_Query @throws Zend_Search_Lucene_Exception
entailment
protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter) { $words = array(); $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*'), preg_quote($this->_pattern->text, '/')) . '$/'; if (@preg_match('/\pL/u', 'a') == 1) { // PCRE unicode support is turned on // add Unicode modifier to the match expression $matchExpression .= 'u'; } $docBody = $highlighter->getDocument()->getFieldUtf8Value('body'); include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8'); foreach ($tokens as $token) { if (preg_match($matchExpression, $token->getTermText()) === 1) { $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
public function send($recipient, $body, $originator = '') { $result = $this->getSmsSender()->send($this->recipient, $body, $originator); $result['recipient'] = $recipient; return $result; }
{@inheritdoc}
entailment
public function rewrite(Zend_Search_Lucene_Interface $index) { $this->_matches = array(); if ($this->_field === null) { // Search through all fields $fields = $index->getFieldNames(true /* indexed fields list */); } else { $fields = array($this->_field); } include_once 'Zend/Search/Lucene.php'; $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit(); foreach ($fields as $field) { $index->resetTermsStream(); include_once 'Zend/Search/Lucene/Index/Term.php'; if ($this->_lowerTerm !== null) { $lowerTerm = new Zend_Search_Lucene_Index_Term($this->_lowerTerm->text, $field); $index->skipTo($lowerTerm); if (!$this->_inclusive && $index->currentTerm() == $lowerTerm ) { // Skip lower term $index->nextTerm(); } } else { $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field)); } if ($this->_upperTerm !== null) { // Walk up to the upper term $upperTerm = new Zend_Search_Lucene_Index_Term($this->_upperTerm->text, $field); while ($index->currentTerm() !== null && $index->currentTerm()->field == $field && $index->currentTerm()->text < $upperTerm->text) { $this->_matches[] = $index->currentTerm(); if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } $index->nextTerm(); } if ($this->_inclusive && $index->currentTerm() == $upperTerm) { // Include upper term into result $this->_matches[] = $upperTerm; } } else { // Walk up to the end of field data while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) { $this->_matches[] = $index->currentTerm(); if ($maxTerms != 0 && count($this->_matches) > $maxTerms) { include_once 'Zend/Search/Lucene/Exception.php'; throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.'); } $index->nextTerm(); } } $index->closeTermsStream(); } if (count($this->_matches) == 0) { include_once 'Zend/Search/Lucene/Search/Query/Empty.php'; return new Zend_Search_Lucene_Search_Query_Empty(); } else if (count($this->_matches) == 1) { include_once 'Zend/Search/Lucene/Search/Query/Term.php'; return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches)); } else { include_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php'; $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm(); foreach ($this->_matches as $matchedTerm) { $rewrittenQuery->addTerm($matchedTerm); } return $rewrittenQuery; } }
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) { $words = array(); $docBody = $highlighter->getDocument()->getFieldUtf8Value('body'); include_once 'Zend/Search/Lucene/Analysis/Analyzer.php'; $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8'); $lowerTermText = ($this->_lowerTerm !== null)? $this->_lowerTerm->text : null; $upperTermText = ($this->_upperTerm !== null)? $this->_upperTerm->text : null; if ($this->_inclusive) { foreach ($tokens as $token) { $termText = $token->getTermText(); if (($lowerTermText == null || $lowerTermText <= $termText) && ($upperTermText == null || $termText <= $upperTermText) ) { $words[] = $termText; } } } else { foreach ($tokens as $token) { $termText = $token->getTermText(); if (($lowerTermText == null || $lowerTermText < $termText) && ($upperTermText == null || $termText < $upperTermText) ) { $words[] = $termText; } } } $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 outerProduct(Vector $other): Matrix { $literal = []; for ($i = 0; $i < $this->getSize(); $i++) { for ($j = 0; $j < $other->getSize(); $j++) { $literal[$i][$j] = $this->toArray()[$i] * $other->toArray()[$j]; } } return new Matrix($literal); }
| a₀ | | a₀b₀ a₀b₁ a₀b₂ | A ⨂ B = | a₁ | ⨂ |b₀ b₁b₂| = | a₁b₀ a₁b₁ a₁b₂| | a₂ | | a₂b₀ a₂b₁ a₂b₂| @param Vector $other @return Matrix @link https://en.wikipedia.org/wiki/Outer_product
entailment
public function projection(self $other): self { return self::fromMatrix($other->multiplyScalar($this->dotProduct($other) / ($other->l2norm() ** 2))); }
A⋅B projᵇA = --- B |B|² @param self $other @return self @link https://en.wikipedia.org/wiki/Vector_projection#Vector_projection
entailment
public function l1Norm(): float { return array_reduce($this->toArray(), function (float $carry, float $value) { return $carry + abs($value); }, 0); }
|x|₁ = ∑|xᵢ| @return float @link https://en.wikipedia.org/wiki/Norm_(mathematics)#Taxicab_norm_or_Manhattan_norm
entailment
public function l2Norm(): float { return sqrt(array_reduce($this->toArray(), function (float $carry, float $value) { return $carry + pow($value, 2); }, 0)); }
______ |x|₂ = √∑|xᵢ|² Also known as Euclidean norm, Euclidean length, L² distance, ℓ² distance Used to normalize a vector. @return float @link http://mathworld.wolfram.com/L2-Norm.html @link https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm
entailment
public function maxNorm(): float { return array_reduce($this->toArray(), function (float $carry, float $value) { $value = abs($value); return $carry > $value ? $carry : $value; }, -INF); }
|x|∞ = max |x| Max norm (infinity norm) (|x|∞) @return float
entailment