sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function setCurrentParams() { $this->_current['plugin'] = $this->Controller->request->params['plugin']; $this->_current['controller'] = $this->Controller->request->params['controller']; $this->_current['action'] = $this->Controller->request->params['action']; return $this->_current; }
setCurrentParams Setter for the current propperty. @return array
entailment
public function action($actions, $function) { if (!is_array($actions)) { $actions = [$actions]; } $controller = $this->_current['controller']; foreach ($actions as $action) { $path = $controller . '.' . $action; self::$_data = Hash::insert(self::$_data, $path, [ 'function' => $function, 'roles' => [], ]); $this->_runFunction($action); } }
Sets authorization per action. The action variable can be a string or array of strings ``` $this->Authorizer->action(["My action"], function($auth) { // authorization for the chosen actions }); ``` @param string|array $actions An array or string to run the function on. @param callable $function Function to authorize with. @return void
entailment
public function allowRole($roles) { if (!is_array($roles)) { $roles = [$roles]; } $controller = $this->_current['controller']; $action = $this->_selected['action']; $path = $controller . '.' . $action . '.roles.'; foreach ($roles as $role) { self::$_data = Hash::insert(self::$_data, $path . $role, true); } }
allowRole This method is used inside the action-method to allow a role to the selected actions ``` $this->Authorizer->action(["My action"], function($auth) { $auth->allowRole(1); }); ``` The role-variable can be an integer or array with integers. @param int|array $roles Array or integer with the roles to allow. @return void
entailment
public function denyRole($roles) { if (!is_array($roles)) { $roles = [$roles]; } $controller = $this->_current['controller']; $action = $this->_selected['action']; $path = $controller . '.' . $action . '.roles.'; foreach ($roles as $role) { self::$_data = Hash::insert(self::$_data, $path . $role, false); } }
denyRole This method is used inside the action-method to deny a role from the selected actions ``` $this->Authorizer->action(["My action"], function($auth) { $auth->denyRole(2); }); ``` The role-variable can be an integer or array with integers. @param int|array $roles Array or integer with the roles to allow. @return void
entailment
public function setRole($roles, $value) { if (!is_array($roles)) { $roles = [$roles]; } $controller = $this->_current['controller']; $action = $this->_selected['action']; $path = $controller . '.' . $action . '.roles.'; foreach ($roles as $role) { self::$_data = Hash::insert(self::$_data, $path . $role, $value); } }
setRole This method is used inside the action-method to set a custom boolean to the selected role for the selected action ``` $this->Authorizer->action(["My action"], function($auth) { $auth->setRole(2, $this->customMethod()); }); ``` The role-variable can be an integer or array with integers. The value is an boolean. @param int|array $roles Array or integer with the roles to allow. @param boole $value The value to set to the selected role(s). @return void
entailment
public function authorize() { $user = $this->Controller->Auth->user(); $role = $user[$this->config('roleField')]; $controller = $this->_current['controller']; $action = $this->_current['action']; $path = $controller . '.' . $action . '.roles.' . $role; $state = $this->_getState($action, $role); return $state; }
authorize The final method who will authorize the current request. Use the following in the isAuthorized-method to return if the user is authorized: ``` public function isAuthorized($user) { // your autorization with the action-method return $this->Authorizer->authorize(); } ``` @return bool
entailment
protected function _getState($action, $role) { $controller = $this->_current['controller']; $path = $controller . '.' . $action . '.roles.' . $role; $state = Hash::get(self::$_data, $path); if ($state == null) { $action = '*'; $path = $controller . '.' . $action . '.roles.' . $role; $state = Hash::get(self::$_data, $path); } if (!is_bool($state)) { $state = false; } return $state; }
_getState Checks if the role is allowed to the action. @param string $action Is the action-name. @param int $role Is the role-id. @return bool
entailment
protected function _runFunction($action) { $controller = $this->_current['controller']; $path = $controller . '.' . $action . '.function'; $function = Hash::get(self::$_data, $path); $this->_selected['action'] = $action; if ($function) { $function($this, $this->Controller); } }
_runFunction Runs the given function from the action-method. @param string $action Action name. @return void
entailment
public function setTimeout($timeout = null) { if ($timeout === null) { $timeout = 30000; } if (!is_int($timeout)) { throw new \InvalidArgumentException('Parameter is not an integer'); } if ($timeout < 0) { throw new \InvalidArgumentException( 'Parameter is negative. Only positive timeouts accepted.' ); } $this->timeout = $timeout; return $this; }
Setting the timeout will define how long Diffbot will keep trying to fetch the API results. A timeout can happen for various reasons, from Diffbot's failure, to the site being crawled being exceptionally slow, and more. @param int|null $timeout Defaults to 30000 even if not set @return $this
entailment
protected function getValueArray($name, $value = null) { // Looks for the values in "old" if (!$this->oldInputIsEmpty()) { if (is_null($this->session->getOldInput($name))) { // we have old input, but none for this name return []; } else { return $this->session->getOldInput($name); } } // Looks for the values in the Request if (isset($this->request) and $this->request->input($name)) { return $this->request->input($name); } // Returns the default value return empty($value) ? [] : $value; }
Gets the array of values that must be set on page load. In order, these are: 1 - "old" session values 2 - $request values 3 - default values, passed as $selected 4 - empty array. @param string $key @param array $value @return array
entailment
protected function option($display, $value, array $attributes = []) { $options = ['value' => $value] + $attributes; return $this->toHtmlString('<option'.$this->attributes($options).'>'.e($display).'</option>'); }
Generates a single option for the select dropdown. @param string $display @param string $value @param array $attributes @return \Illuminate\Support\HtmlString
entailment
public function autocomplete( $name, $list = [], $selected = [], array $inputAttributes = [], array $spanAttributes = [], $inputOnly = false ) { // Forces the ID attribute $inputAttributes['id'] = $name.'-ms'; if (!isset($inputAttributes['class'])) { $inputAttributes['class'] = 'multiselect'; } // We will concatenate the span html unless $selectOnly is passed as false $spanHtml = $inputOnly ? '' : $this->span($name, $list, $selected, $spanAttributes); $inputAttributes = $this->attributes($inputAttributes); return $this->toHtmlString($spanHtml."<input type=\"text\"{$inputAttributes}>"); }
Create the multi-select autocomplete field and optionally the already selected span field. This method interface mimicks LaravelCollective\html select method. @param string $name The name of the select element. Will be used by the JS to add hidden inputs @param array $list A Laravel collection or list of key => values @param array $selected A laravel collection or list of keys @param array $inputAttributes @param array $spanAttributes @param bool $inputOnly @return \Illuminate\Support\HtmlString
entailment
public function scripts( $name, $url, array $params = [] ) { $inputName = $name.'-ms'; return $this->toHtmlString( '<script>$(document).ready(function() {'. '$("#'.$inputName.'").lmsAutocomplete("'. $url.'", '. json_encode($params, JSON_FORCE_OBJECT). ');'. '});</script>'); }
Create the javaScript scripts required for the multi-select autocomplete plugin. Notice that this should be called *after* jQuery has been imported. @param string $name the name of the select element @param string $url The URL to be used for getting the autocomplete responses @param array $params Further parameters to be passed to devbridgeAutocomplete @return \Illuminate\Support\HtmlString
entailment
public function select( $name, $list = [], $selected = [], array $selectAttributes = [], array $optionsAttributes = [], array $spanAttributes = [], $selectOnly = false ) { // Forces the ID attribute $selectAttributes['id'] = $name.'-ms'; if (!isset($selectAttributes['class'])) { $selectAttributes['class'] = 'multiselect'; } // We will concatenate the span html unless $selectOnly is passed as false $spanHtml = $selectOnly ? '' : $this->span($name, $list, $selected, $spanAttributes); // Here, we generate the list of options $html = []; if (isset($selectAttributes['placeholder'])) { $html[] = $this->option($selectAttributes['placeholder'], ''); unset($selectAttributes['placeholder']); } else { $html[] = $this->option('&nbsp;', ''); } foreach ($list as $value => $display) { $optionAttributes = isset($optionsAttributes[$value]) ? $optionsAttributes[$value] : []; $html[] = $this->option($display, $value, $optionAttributes); } $list = implode('', $html); $selectAttributes = $this->attributes($selectAttributes); return $this->toHtmlString($spanHtml."<select{$selectAttributes}>{$list}</select>"); }
Create the multi-select select box field and optionally the already selected span field. This method interface mimicks LaravelCollective\html select method. @param string $name The name of the select element. Will be used by the JS to add hidden inputs @param array $list A Laravel collection or list of key => values @param array $selected A laravel collection or list of keys @param array $selectAttributes @param array $optionsAttributes @param array $spanAttributes @param bool $selectOnly @return \Illuminate\Support\HtmlString
entailment
public function span( $name, $list = [], $default = [], array $spanAttributes = [], $strict = false ) { // Forces the ID attribute $spanAttributes['id'] = $name.'-span'; // Here, we generate the list of already selected options considering "old" values $html = []; $selected = $this->getValueArray($name, $default); foreach ($selected as $value) { // This block avoids Undefined Offsets if (isset($list[$value])) { $html[] = $this->spanElement($name, $list[$value], $value); } else { // Undefined offset! What to do now depends on the value of parameter $strict if ($strict) { throw new MultiselectException("Undefined offset $value!"); } else { $html[] = $this->spanElement($name, 'Undefined', $value); } } } $spanAttributes = $this->attributes($spanAttributes); $list = implode('', $html); return $this->toHtmlString("<span{$spanAttributes}>{$list}</span>"); }
Create the multi-select span with the already selected values. This method is called from Multiselect::select by default, but you may wish to call it elsewhere in your html. If you call it explicitly, remember to pass $selectOnly = false to the select Multiselect::select method. @param string $name The name of the select element. Will be used by the JS to add elements under this @param array $list A Laravel collection or list of elements @param array $default A laravel collection or list of elements @param array $spanAttributes @param bool $strict If true, will throw a Undefined Offset exception in case a value in $default is not present in $list. If false, the item is generated with an "Undefined" label @return \Illuminate\Support\HtmlString
entailment
public function spanElement($name, $display, $value) { $options = ['onClick' => '$(this).remove();', 'class' => 'multiselector']; return $this->toHtmlString( '<span'.$this->attributes($options).'>'. '<input type="hidden" name="'.$name.'[]" value="'.$value.'">' .e($display). '</span>'); }
Generates a single span with pre-selected options with relevant options. @param string $name @param string $display @param string $value @return \Illuminate\Support\HtmlString
entailment
public function say($text) { $message = $this->getSpeechBubble($text); return str_replace( '{{bubble}}', $message, $this->character ); }
Make the animal speak. @param $text string A string you want the animal says @return string The animal speaks...
entailment
public function extendBubble($message) { $characterLength = $this->getMaxLineLength($this->character); $exploded_message = explode("\n", $message); $padded_message = array_map( function ($line) use ($characterLength) { return str_pad($line, $characterLength, ' '); },$exploded_message); return implode("\n",$padded_message); }
Used to pad the bubble to fit at least the size of the animal with empty spaces. @param $message @return string
entailment
public function getMessageLines($text) { $message = $text; $wrapLength = 40; // wrap the message to max chars $message = wordwrap($message, $wrapLength - 2); // split into array of lines return explode("\n", $message); }
Obtain the message as array wrapping the text @param $text @return array
entailment
public function getMaxLineLength($lines) { if (!is_array($lines)) { $lines = explode("\n", $lines); } $lineLength = 0; // find the longest line foreach ($lines as $line) { $currentLineLength = strlen($line); if ($currentLineLength > $lineLength) { $lineLength = $currentLineLength; } } return $lineLength; }
Find the longest line and get the line length @param array $lines @return int
entailment
public function getSpeechBubble($text) { $lines = $this->getMessageLines($text); $lineLength = $this->getMaxLineLength($lines); $text = ''; $numberOfLines = count($lines); $firstLine = str_pad(array_shift($lines), $lineLength); if ($numberOfLines === 1) { $text = "< {$firstLine} >"; } else { $lastLine = str_pad(array_pop($lines), $lineLength); $text = "/ {$firstLine} \\\n"; foreach ($lines as $line) { $line = str_pad($line, $lineLength); $text .= "| {$line} |\n"; } $text .= "\\ {$lastLine} /"; } $text = $this->extendBubble($text); return $text; }
Obtain the speech bubble. @param $text @return string
entailment
public function defineModelClasses($modelClasses = []) { $this->modelMap = ArrayHelper::merge( $this->getDefaultModels(), $this->modelMap, $modelClasses ); }
Merges the default and user defined model classes Also let's the developer to set new ones with the parameter being those the ones with most preference. @param array $modelClasses
entailment
protected function getDefaultModels() { return [ 'Comment' => Comments\models\Comment::className(), 'CommentQuery' => Comments\models\queries\CommentQuery::className(), 'CommentCreateForm' => Comments\forms\CommentCreateForm::className(), ]; }
Get default model classes
entailment
public function model($name, $config = []) { $modelData = $this->modelMap[ucfirst($name)]; if (!empty($config)) { if (is_string($modelData)) { $modelData = ['class' => $modelData]; } $modelData = ArrayHelper::merge( $modelData, $config ); } return $modelData; }
Get defined className of model Returns an string or array compatible with the Yii::createObject method. @param string $name @param array $config // You should never send an array with a key defined as "class" since this will // overwrite the main className defined by the system. @return string|array
entailment
public static function createFromFile($file) { $jsonConfig = json_decode(file_get_contents($file), true); return self::createFromConfig($jsonConfig); }
Creates a Gitkit client from a config file (json format). @param string $file file name of the json config file @return Gitkit_Client created Gitkit client
entailment
public static function createFromConfig($config, $rpcHelper = null) { $clientId = $config['clientId']; $projectId = $config['projectId']; if (!isset($clientId) && !isset($projectId)) { throw new Gitkit_ClientException("Missing projectId or clientId in server configuration."); } if (!isset($config['widgetUrl'])) { throw new Gitkit_ClientException("\"widgetUrl\" should be configured"); } if (isset($config["cookieName"])) { $cookieName = $config['cookieName']; } else { $cookieName = self::$DEFAULT_COOKIE_NAME; } if (!$rpcHelper) { if (!isset($config['serviceAccountEmail'])) { throw new Gitkit_ClientException( "\"serviceAccountEmail\" should be configured"); } if (!isset($config['serviceAccountPrivateKeyFile'])) { throw new Gitkit_ClientException( "\"serviceAccountPrivateKeyFile\" should be configured"); } $p12Key = file_get_contents($config["serviceAccountPrivateKeyFile"]); if ($p12Key === false) { throw new Gitkit_ClientException( "Can not read file " . $config["serviceAccountPrivateKeyFile"]); } if (isset($config['serverApiKey'])) { $serverApiKey = $config['serverApiKey']; } else { $serverApiKey = null; } $rpcHelper = new Gitkit_RpcHelper( $config["serviceAccountEmail"], $p12Key, self::$GITKIT_API_BASE, new Google_Auth_OAuth2(new Google_Client()), $serverApiKey); } return new Gitkit_Client($clientId, $config['widgetUrl'], $cookieName, $rpcHelper, $projectId); }
Creates a Gitkit client from the config array. @param array $config config parameters @param null|Gitkit_RpcHelper $rpcHelper Gitkit Rpc helper object @return Gitkit_Client created Gitkit client @throws Gitkit_ClientException if required config is missing
entailment
public function validateToken($gitToken) { if ($gitToken) { $loginTicket = null; $auds = array_filter( array($this->projectId, $this->clientId), function($x) { return isset($x); }); foreach ($auds as $aud) { try { $loginTicket = $this->oauth2Client->verifySignedJwtWithCerts( $gitToken, $this->getCerts(), $aud, self::$GTIKIT_TOKEN_ISSUER, 180 * 86400)->getAttributes(); break; } catch (Google_Auth_Exception $e) { if (strpos($e->getMessage(), "Wrong recipient") === false) { throw $e; } } } if (!isset($loginTicket)) { throw new Google_Auth_Exception( "Gitkit token audience doesn't match projectId or clientId in server configuration."); } $jwt = $loginTicket["payload"]; if ($jwt) { $user = new Gitkit_Account(); $user->setUserId($jwt["user_id"]); $user->setEmail($jwt["email"]); if (isset($jwt["provider_id"])) { $user->setProviderId($jwt["provider_id"]); } else { $user->setProviderId(null); } $user->setEmailVerified($jwt["verified"]); if (isset($jwt["display_name"])) { $user->setDisplayName($jwt["display_name"]); } if (isset($jwt["photo_url"])) { $user->setPhotoUrl($jwt["photo_url"]); } return $user; } } return null; }
Validates a Gitkit token. User info is extracted from the token only. @param string $gitToken token to be checked @return Gitkit_Account|null Gitkit user corresponding to the token, null for invalid token
entailment
public function getUserInRequest() { if (isset($_COOKIE[$this->cookieName])) { $user = $this->validateToken($_COOKIE[$this->cookieName], $this->clientId); if ($user) { $accountInfo = $this->getUserById($user->getUserId()); $accountInfo->setProviderId($user->getProviderId()); return $accountInfo; } } return null; }
Gets GitkitUser for the http request. Complete user info is retrieved from Gitkit server. @return Gitkit_Account|null Gitkit user at Gitkit server, null for invalid token
entailment
public function uploadUsers($hashAlgorithm, $hashKey, $accounts, $rounds = null, $memoryCost = null) { $this->rpcHelper->uploadAccount($hashAlgorithm, $hashKey, $this->toJsonRequest($accounts), $rounds, $memoryCost); }
Uploads multiple accounts info to Gitkit server. @param string $hashAlgorithm password hash algorithm. See Gitkit doc for supported names. @param string $hashKey raw key for the algorithm @param array $accounts array of Gitkit_Account to be uploaded @param null|int $rounds Rounds of the hash function @param null|int $memoryCost Memory cost of the hash function @throws Gitkit_ServerException if error happens
entailment
public function getOobResults($param = null, $user_ip = null, $gitkit_token = null) { if (!$param) { $param = $_POST; } if (!$user_ip) { $user_ip = $_SERVER['REMOTE_ADDR']; } if (!$gitkit_token) { $gitkit_token = $this->getTokenString(); } if (isset($param['action'])) { try { if ($param['action'] == 'resetPassword') { $oob_link = $this->buildOobLink( $this->passwordResetRequest($param, $user_ip), $param['action']); return $this->passwordResetResponse($oob_link, $param); } else if ($param['action'] == 'changeEmail') { if (!$gitkit_token) { return $this->failureOobMsg('login is required'); } $oob_link = $this->buildOobLink( $this->changeEmailRequest($param, $user_ip, $gitkit_token), $param['action']); return $this->emailChangeResponse($oob_link, $param); } } catch (Gitkit_ClientException $error) { return $this->failureOobMsg($error->getMessage()); } } return $this->failureOobMsg('unknown action type'); }
Gets out-of-band results for ResetPassword, ChangeEmail operations etc. @param null|array $param http post body @param null|string $user_ip end user IP address @param null|string $gitkit_token Gitkit token in the request @return array out-of-band results: array( 'email' => email of the user, 'oldEmail' => old email (for ChangeEmail only), 'newEmail' => new email (for ChangeEmail only), 'oobLink' => url for user click to finish the operation, 'action' => 'RESET_PASSWORD', or 'CHANGE_EMAIL', 'response_body' => http response to be sent back to Gitkit widget )
entailment
private function toJsonRequest($accounts) { $jsonUsers = array(); foreach($accounts as $account) { $user = array( 'email' => $account->getEmail(), 'localId' => $account->getUserId(), 'emailVerified' => $account->isEmailVerified(), 'displayName' => $account->getDisplayName(), 'passwordHash' => Google_Utils::urlSafeB64Encode( $account->getPasswordHash()), 'salt' => Google_Utils::urlSafeB64Encode($account->getSalt()) ); array_push($jsonUsers, $user); } return $jsonUsers; }
Converts Gitkit account array to json request. @param array $accounts Gitkit account array @return array json request
entailment
private function buildOobLink($param, $action) { $code = $this->rpcHelper->getOobCode($param); $separator = parse_url($this->widgetUrl, PHP_URL_QUERY) ? '&' : '?'; return $this->widgetUrl . $separator . http_build_query(array('mode' => $action, 'oobCode' => $code)); }
Builds the url of out-of-band confirmation. @param array $param oob request param @param string $action 'RESET_PASSWORD' or 'CHANGE_EMAIL' @return string the oob url
entailment
protected function setNullableFields() { foreach ($this->nullableFromArray($this->getAttributes()) as $key => $value) { $this->attributes[$key] = $this->nullIfEmpty($value, $key); } }
Set empty nullable fields to null. @since 1.1.0 @return void
entailment
public function nullIfEmpty($value, $key = null) { if (! is_null($key)) { $value = $this->fetchValueForKey($key, $value); } if (is_array($value)) { return $this->nullIfEmptyArray($key, $value); } if (is_bool($value)) { return $value; } return trim($value) === '' ? null : $value; }
If value is empty, return null, otherwise return the original input. @param string $value @param null $key @return null|string
entailment
protected function nullableFromArray(array $attributes = []) { if (is_array($this->nullable) && count($this->nullable) > 0) { return array_intersect_key($attributes, array_flip($this->nullable)); } // Assume no fields are nullable return []; }
Get the nullable attributes of a given array. @param array $attributes @return array
entailment
private function getJsonCastValue($value) { return method_exists($this, 'fromJson') ? $this->fromJson($value) : json_decode($value, true); }
Return value of the json-encoded value as a native PHP type @param mixed $value @return string
entailment
private function fetchValueForKey($key, $value) { if (in_array($key, $this->getDates())) { return trim($value) === '' ? null : $value; } if (! $this->hasSetMutator($key)) { $value = $this->getAttribute($key); } if ($this->isJsonCastable($key) && ! is_null($value)) { $value = is_string($value) ? $this->getJsonCastValue($value) : $value; } return $value; }
For the given key and value pair, determine the actual value, depending on whether or not a mutator or cast is in use. @param string $key @param mixed $value @return mixed
entailment
private function nullIfEmptyArray($key, $value) { if ($this->isJsonCastable($key) && ! empty($value)) { return $this->setJsonCastValue($value); } return empty($value) ? null : $value; }
Determine whether an array value is empty, taking into account casting. @param string $key @param array $value @return mixed
entailment
public function inherit() { if ((bool)Config::getOption("plugins.dataInheritance.enabled")) { $storeData = Data::get(); $storePatternData = PatternData::get(); foreach ($storePatternData as $patternStoreKey => $patternData) { if (isset($patternData["lineages"]) && (count($patternData["lineages"]) > 0)) { $dataLineage = array(); foreach($patternData["lineages"] as $lineage) { // merge the lineage data with the lineage store. newer/higher-level data is more important. $lineageKey = $lineage["lineagePattern"]; $lineageData = isset($storeData["patternSpecific"][$lineageKey]) && isset($storeData["patternSpecific"][$lineageKey]["data"]) ? $storeData["patternSpecific"][$lineageKey]["data"] : array(); if (!empty($lineageData)) { $dataLineage = array_replace_recursive($dataLineage, $lineageData); } } // merge the lineage data with the pattern data. pattern data is more important. $dataPattern = isset($storeData["patternSpecific"][$patternStoreKey]) && isset($storeData["patternSpecific"][$patternStoreKey]["data"]) ? $storeData["patternSpecific"][$patternStoreKey]["data"] : array(); $dataPattern = array_replace_recursive($dataLineage, $dataPattern); if (!empty($dataPattern)) { $storeData["patternSpecific"][$patternStoreKey]["data"] = $dataPattern; } } } Data::replaceStore($storeData); } }
Look up data in lineages, update pattern store data, replace store
entailment
public function getGitkitCerts() { $certUrl = $this->gitkitApisUrl . 'publicKeys'; if ($this->apiKey) { // try server-key first return $this->oauth2Client->retrieveCertsFromLocation( $certUrl . '?key=' . $this->apiKey); } else { // fallback to service account $httpRequest = new Google_Http_Request($certUrl); $response = $this->oauth2Client->authenticatedRequest($httpRequest) ->getResponseBody(); return json_decode($response); } }
Downloads Gitkit public certs. @return array|string certs
entailment
public function updateAccount($gitkitAccount) { $data = array( 'email' => $gitkitAccount->getEmail(), 'localId' => $gitkitAccount->getUserId(), 'displayName' => $gitkitAccount->getDisplayName(), 'emailVerified' => $gitkitAccount->isEmailVerified(), 'photoUrl' => $gitkitAccount->getPhotoUrl() ); return $this->invokeGitkitApiWithServiceAccount('setAccountInfo', $data); }
Invokes the SetAccountInfo API. @param Gitkit_Account $gitkitAccount account info to be updated @return array updated account info
entailment
public function uploadAccount($hashAlgorithm, $hashKey, $accounts, $rounds, $memoryCost) { $data = array( 'hashAlgorithm' => $hashAlgorithm, 'signerKey' => Google_Utils::urlSafeB64Encode($hashKey), 'users' => $accounts ); if ($rounds) { $data['rounds'] = $rounds; } if ($memoryCost) { $data['memoryCost'] = $memoryCost; } $this->invokeGitkitApiWithServiceAccount('uploadAccount', $data); }
Invokes the UploadAccount API. @param string $hashAlgorithm password hash algorithm. See Gitkit doc for supported names. @param string $hashKey raw key for the algorithm @param array $accounts array of account info to be uploaded @param null|int $rounds Rounds of the hash function @param null|int $memoryCost Memory cost of the hash function
entailment
public function downloadAccount($nextPageToken = null, $maxResults = 10) { $data = array(); if ($nextPageToken) { $data['nextPageToken'] = $nextPageToken; } $data['maxResults'] = $maxResults; return $this->invokeGitkitApiWithServiceAccount('downloadAccount', $data); }
Invokes the DownloadAccount API. @param string|null $nextPageToken next page token to download the next pagination. @param int $maxResults max results per request @return array of accounts info and nextPageToken
entailment
public function getOobCode($param) { $response = $this->invokeGitkitApiWithServiceAccount( 'getOobConfirmationCode', $param); if (isset($response['oobCode'])) { return $response['oobCode']; } else { throw new Gitkit_ClientException("can not get oob-code"); } }
Invokes the GetOobConfirmationCode API. @param array $param parameters for the request @return string the out-of-band code @throws Gitkit_ClientException
entailment
public function invokeGitkitApiWithServiceAccount($method, $data) { $httpRequest = new Google_Http_Request( $this->gitkitApisUrl . $method, 'POST', null, json_encode($data)); $contentTypeHeader = array(); $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8'; $httpRequest->setRequestHeaders($contentTypeHeader); $response = $this->oauth2Client->authenticatedRequest($httpRequest) ->getResponseBody(); return $this->checkGitkitError(json_decode($response, true)); }
Sends the authenticated request to Gitkit API. The request contains an OAuth2 access_token generated from service account. @param string $method the API method name @param array $data http post data for the api @return array server response @throws Gitkit_ClientException if input is invalid @throws Gitkit_ServerException if there is server error
entailment
public function checkGitkitError($response) { if (isset($response['error'])) { $error = $response['error']; if (!isset($error['code'])) { throw new Gitkit_ServerException('null error code from Gitkit server'); } else { $code = $error['code']; if (strpos($code, '4') === 0) { throw new Gitkit_ClientException($error['message']); } else { throw new Gitkit_ServerException($error['message']); } } } else { return $response; } }
Checks the error in the response. @param array $response server response to be checked @return array the response if there is no error @throws Gitkit_ClientException if input is invalid @throws Gitkit_ServerException if there is server error
entailment
public function addProvider($name, ReindexProviderInterface $provider) { if (isset($this->providers[$name])) { throw new \InvalidArgumentException(sprintf( 'Reindex provider with name "%s" has already been registered.', $name )); } $this->providers[$name] = $provider; }
Add a reindex provider to the registry. @param string $name @param ReindexProviderInterface $provider @throws \InvalidArgumentException
entailment
public function getProvider($name) { if (!isset($this->providers[$name])) { throw new \InvalidArgumentException(sprintf( 'Unknown provider "%s", registered reindex providers: "%s"', $name, implode('", "', array_keys($this->providers)) )); } return $this->providers[$name]; }
Return a specific provider.
entailment
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $container->setAlias('massive_search.factory', $config['services']['factory']); $loader->load('command.xml'); $this->loadSearch($config, $loader, $container); $this->loadMetadata($config['metadata'], $loader, $container); $this->loadPersistence($config['persistence'], $loader); }
{@inheritdoc}
entailment
public function getMetadataForObject($object) { $metadata = $this->metadataFactory->getMetadataForClass(get_class($object)); if (null === $metadata) { return; } return $metadata->getOutsideClassMetadata(); }
{@inheritdoc}
entailment
public function getAllMetadata() { $classNames = $this->metadataFactory->getAllClassNames(); $metadatas = []; foreach ($classNames as $className) { $metadatas[] = $this->metadataFactory->getMetadataForClass($className)->getOutsideClassMetadata(); } return $metadatas; }
{@inheritdoc}
entailment
public function getMetadataForDocument(Document $document) { $className = $document->getClass(); $metadata = $this->metadataFactory->getMetadataForClass($className); if (null === $metadata) { return; } return $metadata->getOutsideClassMetadata(); }
{@inheritdoc}
entailment
public function diffAgainstCollection(MappingCollection $complementCollection) { $returnMappings = new MappingCollection(); foreach ($this as $entityMapping) { /** @var $entityMapping Mapping */ $mapping = new Mapping(clone $entityMapping->getType()); $saveMapping = false; foreach ($entityMapping->getProperties() as $propertyName => $propertySettings) { foreach ($propertySettings as $entitySettingKey => $entitySettingValue) { $backendSettingValue = $complementCollection->getMappingSetting($entityMapping, $propertyName, $entitySettingKey); if ($entitySettingValue !== $backendSettingValue) { $mapping->setPropertyByPath([$propertyName, $entitySettingKey], $entitySettingValue); $saveMapping = true; } } } if ($saveMapping) { $returnMappings->add($mapping); } } return $returnMappings; }
Returns a new collection of mappings of this collection that are not member of the $complementCollection. @param MappingCollection $complementCollection @return MappingCollection
entailment
public function getMappingSetting(Mapping $inquirerMapping, $propertyName, $settingKey) { foreach ($this as $memberMapping) { /** @var $memberMapping Mapping */ if ($inquirerMapping->getType()->getName() === $memberMapping->getType()->getName() && $inquirerMapping->getType()->getIndex()->getName() === $memberMapping->getType()->getIndex()->getName() ) { return $memberMapping->getPropertyByPath([$propertyName, $settingKey]); } } return null; }
Tells whether a member of this collection has a specific index/type/property settings value @param Mapping $inquirerMapping @param string $propertyName @param string $settingKey @return mixed
entailment
public function execute(InputInterface $input, OutputInterface $output) { $formatterHelper = new FormatterHelper(); $output->writeln( $formatterHelper->formatBlock(sprintf( 'DEPRECATED: The `%s` command is deprecated, use `massive:search:reindex` instead.', $this->getName() ), 'comment', true) ); return parent::execute($input, $output); }
{@inheritdoc}
entailment
public function getClassFqns() { $metadataFactory = $this->entityManager->getMetadataFactory(); $classFqns = []; foreach ($metadataFactory->getAllMetadata() as $classMetadata) { if (null === $this->searchMetadataFactory->getMetadataForClass($classMetadata->name)) { continue; } $classFqns[] = $classMetadata->name; } return $classFqns; }
{@inheritdoc}
entailment
public function provide($classFqn, $offset, $maxResults) { if (!empty($this->cachedEntities)) { return $this->sliceEntities($offset, $maxResults); } $repository = $this->entityManager->getRepository($classFqn); $metadata = $this->searchMetadataFactory->getMetadataForClass($classFqn); $repositoryMethod = $metadata->getOutsideClassMetadata()->getReindexRepositoryMethod(); $queryBuilder = $repository->createQueryBuilder('d'); if ($repositoryMethod) { $result = $repository->$repositoryMethod($queryBuilder); if (is_array($result)) { @trigger_error('Reindex repository methods should NOT return anything. Use the passed query builder instead.'); $this->cachedEntities = $result; return $this->sliceEntities($offset, $maxResults); } } $queryBuilder->setFirstResult($offset); $queryBuilder->setMaxResults($maxResults); return $queryBuilder->getQuery()->execute(); }
BC Note: Previous versions of the MassiveSearchBundle expected a collection of entities to be returned from the repository via. a custom repository method. The expected behavior now is that a query builder will be passed and NOTHING should be returned. {@inheritdoc}
entailment
public function getCount($classFqn) { $repository = $this->entityManager->getRepository($classFqn); $metadata = $this->searchMetadataFactory->getMetadataForClass($classFqn); $repositoryMethod = $metadata->getOutsideClassMetadata()->getReindexRepositoryMethod(); $queryBuilder = $repository->createQueryBuilder('d'); if ($repositoryMethod) { $result = $repository->$repositoryMethod($queryBuilder); if ($result) { @trigger_error( 'Reindex repository methods should NOT return anything. Use the passed query builder instead.' ); $queryBuilder = $this->entityManager->createQueryBuilder() ->from($classFqn, 'd'); } } $queryBuilder->select('count(d.id)'); return $queryBuilder->getQuery()->getSingleScalarResult(); }
{@inheritdoc}
entailment
public function execute(InputInterface $input, OutputInterface $output) { $query = $input->getArgument('query'); $indexes = $input->getOption('index'); $locale = $input->getOption('locale'); $start = microtime(true); $hits = $this->searchManager->createSearch($query)->indexes($indexes)->locale($locale)->execute(); $timeElapsed = microtime(true) - $start; $table = new Table($output); $table->setHeaders(['Score', 'ID', 'Title', 'Description', 'Url', 'Image', 'Class']); foreach ($hits as $hit) { $document = $hit->getDocument(); $table->addRow([ $hit->getScore(), $document->getId(), $document->getTitle(), $this->truncate($document->getDescription(), 50), $document->getUrl(), $document->getImageUrl(), $document->getClass(), ]); } $table->render(); $output->writeln(sprintf('%s result(s) in %fs', count($hits), $timeElapsed)); }
{@inheritdoc}
entailment
private function truncate($text, $length, $suffix = '...') { $computedLength = $length - strlen($suffix); return strlen($text) > $computedLength ? substr($text, 0, $computedLength) . $suffix : $text; }
Truncate the given string. See: https://github.com/symfony/symfony/issues/11977 @param string $text Text to truncate @param int $length Length @param string $suffix Suffix to append @return string
entailment
public function getMetadata($object) { if (!is_object($object)) { throw new \InvalidArgumentException( sprintf( 'You must pass an object to the %s method, you passed: %s', __METHOD__, var_export($object, true) ) ); } $metadata = $this->metadataProvider->getMetadataForObject($object); if (null === $metadata) { throw new MetadataNotFoundException( sprintf( 'There is no search mapping for object with class "%s"', get_class($object) ) ); } return $metadata; }
{@inheritdoc}
entailment
public function deindex($object) { $metadata = $this->getMetadata($object); foreach ($metadata->getIndexMetadatas() as $indexMetadata) { $indexName = $this->fieldEvaluator->getValue($object, $indexMetadata->getIndexName()); $this->markIndexToFlush($indexName); $indexNames = $this->getDecoratedIndexNames($indexName); foreach ($indexNames as $indexName) { $document = $this->converter->objectToDocument($indexMetadata, $object); $this->adapter->deindex($document, $indexName); } } }
{@inheritdoc}
entailment
public function index($object) { $indexMetadata = $this->getMetadata($object); foreach ($indexMetadata->getIndexMetadatas() as $indexMetadata) { $document = $this->converter->objectToDocument($indexMetadata, $object); $indexName = $this->indexNameDecorator->decorate($indexMetadata, $object, $document); $this->markIndexToFlush($indexName); $evaluator = $this->converter->getFieldEvaluator(); $this->eventDispatcher->dispatch( SearchEvents::PRE_INDEX, new PreIndexEvent($object, $document, $indexMetadata, $evaluator) ); $this->adapter->index($document, $indexName); } }
{@inheritdoc}
entailment
public function search(SearchQuery $query) { $this->validateQuery($query); $this->expandQueryIndexes($query); // At this point the indexes should have been expanded to potentially // include all indexes managed by massive search, if it is empty then // there is nothing to search for. // // See: https://github.com/massiveart/MassiveSearchBundle/issues/38 if (0 === count($query->getIndexes())) { return new SearchResult([], 0); } $this->eventDispatcher->dispatch( SearchEvents::SEARCH, new SearchEvent($query) ); $hits = $this->adapter->search($query); /** @var QueryHit $hit */ foreach ($hits as $hit) { $document = $hit->getDocument(); // only throw events for existing documents if (!class_exists($document->getClass())) { continue; } $metadata = $this->metadataProvider->getMetadataForDocument($document); $this->eventDispatcher->dispatch( SearchEvents::HIT, new HitEvent($hit, $metadata) ); } return $hits; }
{@inheritdoc}
entailment
public function getStatus() { $data = ['Adapter' => get_class($this->adapter)]; $data += $this->adapter->getStatus() ?: []; return $data; }
{@inheritdoc}
entailment
public function purge($indexName) { $this->markIndexToFlush($indexName); $indexes = $this->getDecoratedIndexNames($indexName); foreach ($indexes as $indexName) { $this->adapter->purge($indexName); } }
{@inheritdoc}
entailment
public function getIndexNames() { return array_unique( array_filter( array_map( function ($indexName) { $undecoratedIndexName = $this->indexNameDecorator->undecorate($indexName); if (!$this->indexNameDecorator->isVariant($undecoratedIndexName, $indexName)) { return; } return $undecoratedIndexName; }, $this->adapter->listIndexes() ) ) ); }
{@inheritdoc}
entailment
private function getDecoratedIndexNames($indexName, $locale = null) { $adapterIndexNames = $this->adapter->listIndexes(); $indexNames = []; foreach ($adapterIndexNames as $adapterIndexName) { if ($this->indexNameDecorator->isVariant($indexName, $adapterIndexName, ['locale' => $locale])) { $indexNames[] = $adapterIndexName; } } return $indexNames; }
Retrieve all the index names including localized names (i.e. variants) for the given index name, optionally limiting to the given locale. @param string $indexName @param string $locale @return string[]
entailment
private function expandQueryIndexes(SearchQuery $query) { $expandedIndexes = []; foreach ($query->getIndexes() as $index) { foreach ($this->getDecoratedIndexNames($index, $query->getLocale()) as $expandedIndex) { $expandedIndexes[$expandedIndex] = $expandedIndex; } } $query->setIndexes($expandedIndexes); }
Add additional indexes to the Query object. If the query object has no indexes, then add all indexes (including variants), otherwise expand the indexes the query does have to include all of their variants. @param SearchQuery $query
entailment
private function validateQuery(SearchQuery $query) { $indexNames = $this->getIndexNames(); $queryIndexNames = $query->getIndexes(); foreach ($queryIndexNames as $queryIndexName) { if (!in_array($queryIndexName, $indexNames)) { $unknownIndexes[] = $queryIndexName; } } if (false === empty($unknownIndexes)) { throw new Exception\SearchException( sprintf( 'Search indexes "%s" not known. Known indexes: "%s"', implode('", "', $queryIndexNames), implode('", "', $indexNames) ) ); } }
If query has indexes, ensure that they are known. @throws Exception\SearchException @param SearchQuery $query
entailment
public function store() { if ($this->id !== null) { $method = 'PUT'; $path = '/' . $this->id; } else { $method = 'POST'; $path = ''; } $response = $this->request($method, $path, [], json_encode($this->data)); $treatedContent = $response->getTreatedContent(); $this->id = $treatedContent['_id']; $this->version = $treatedContent['_version']; $this->dirty = false; }
Stores this document. If ID is given, PUT will be used; else POST @throws ElasticSearchException @return void
entailment
public function getField($fieldName, $silent = false) { if (!array_key_exists($fieldName, $this->data) && $silent === false) { throw new ElasticSearchException(sprintf('The field %s was not present in data of document in %s/%s.', $fieldName, $this->type->getIndex()->getName(), $this->type->getName()), 1340274696); } return $this->data[$fieldName]; }
Gets a specific field's value from this' data @param string $fieldName @param boolean $silent @return mixed @throws ElasticSearchException
entailment
public function onIndex(IndexEvent $event) { try { $this->searchManager->index($event->getSubject()); } catch (MetadataNotFoundException $ex) { // no metadata found => do nothing } }
Index subject from event. @param IndexEvent $event
entailment
public function request($method, $path = null, array $arguments = [], $content = null) { return $this->requestService->request($method, $this, $path, $arguments, $content); }
Passes a request through to the request service @param string $method @param string $path @param array $arguments @param string|array $content @return Response
entailment
public function setLanguage($language) { if (!array_key_exists($language, $this->allowedlanguages)) { throw new InvalidArgumentException("Invalid language ISO code"); } $this->parameters['language'] = $language; }
ISO code eg nl_BE
entailment
public function decorate(IndexMetadataInterface $indexMetadata, $object, Document $document) { return $this->fieldEvaluator->getValue($object, $indexMetadata->getIndexName()); }
{@inheritdoc}
entailment
public function buildMappingInformation() { $mappings = new MappingCollection(MappingCollection::TYPE_ENTITY); foreach ($this->indexInformer->getClassesAndAnnotations() as $className => $annotation) { $mappings->add($this->buildMappingFromClassAndAnnotation($className, $annotation)); } return $mappings; }
Builds a Mapping collection from the annotation sources that are present @return MappingCollection<Mapping>
entailment
protected function extractShaSign(array $parameters) { if (!array_key_exists(self::SHASIGN_FIELD, $parameters) || $parameters[self::SHASIGN_FIELD] == '') { throw new InvalidArgumentException('SHASIGN parameter not present in parameters.'); } return $parameters[self::SHASIGN_FIELD]; }
Set Ogone SHA sign @param array $parameters @throws \InvalidArgumentException
entailment
public function isValid(ShaComposer $shaComposer) { if (function_exists('hash_equals')) { return hash_equals($shaComposer->compose($this->parameters), $this->shaSign); } else { return $shaComposer->compose($this->parameters) == $this->shaSign; } }
Checks if the response is valid @return bool
entailment
public function buildMappingInformation() { if (!$this->client instanceof Model\Client) { throw new ElasticSearchException('No client was given for mapping retrieval. Set a client BackendMappingBuilder->setClient().', 1339678111); } $this->indicesWithoutTypeInformation = []; $response = $this->client->request('GET', '/_mapping'); $mappingInformation = new MappingCollection(MappingCollection::TYPE_BACKEND); $mappingInformation->setClient($this->client); $indexNames = $this->indexInformer->getAllIndexNames(); foreach ($response->getTreatedContent() as $indexName => $indexSettings) { if (!in_array($indexName, $indexNames)) { continue; } $index = new Model\Index($indexName); if (empty($indexSettings)) { $this->indicesWithoutTypeInformation[] = $indexName; } foreach ($indexSettings as $typeName => $typeSettings) { $type = new Model\GenericType($index, $typeName); $mapping = new Model\Mapping($type); if (isset($typeSettings['properties'])) { foreach ($typeSettings['properties'] as $propertyName => $propertySettings) { foreach ($propertySettings as $key => $value) { $mapping->setPropertyByPath([$propertyName, $key], $value); } } } $mappingInformation->add($mapping); } } return $mappingInformation; }
Builds a Mapping collection from the annotation sources that are present @return MappingCollection<Model\Mapping> @throws ElasticSearchException
entailment
public function addIndexMetadata($contextName, IndexMetadata $indexMetadata) { if (isset($this->indexMetadatas[$contextName])) { throw new \InvalidArgumentException(sprintf( 'Context name "%s" has already been registered', $contextName )); } $indexMetadata->setName($this->name); $indexMetadata->setClassMetadata($this); $this->indexMetadatas[$contextName] = $indexMetadata; }
Add an index metadata for the given context name. @param mixed $contextName @param IndexMetadata $indexMetadata
entailment
public function getIndexMetadata($contextName) { if (!isset($this->indexMetadatas[$contextName])) { throw new \InvalidArgumentException(sprintf( 'Context name "%s" not known, known contexts: "%s"', $contextName, implode('", "', array_keys($this->indexMetadatas)) )); } return $this->indexMetadatas[$contextName]; }
Return the indexmetadata for the given context. @param string $contextName @return IndexMetadata
entailment
public function serialize() { $data = parent::serialize(); return serialize([$data, serialize($this->indexMetadatas), $this->repositoryMethod]); }
{@inheritdoc}
entailment
public function unserialize($data) { list($data, $indexMetadata, $this->repositoryMethod) = unserialize($data); parent::unserialize($data); $this->indexMetadatas = unserialize($indexMetadata); }
{@inheritdoc}
entailment
public function process(Request $request, Handler $handler): Response { try { return $handler->handle($request); } catch (\Exception $e) { return WhoopsRunner::handle($e, $request); } }
Process an incoming server request and return a response, optionally delegating response creation to a handler.
entailment
public static function getPreferredFormat(ServerRequestInterface $request) { $acceptTypes = $request->getHeader('accept'); if (count($acceptTypes) > 0) { $acceptType = $acceptTypes[0]; // As many formats may match for a given Accept header, let's try to find the one that fits the best $counters = []; foreach (self::$formats as $format => $values) { foreach ($values as $value) { $counters[$format] = isset($counters[$format]) ? $counters[$format] : 0; $counters[$format] += intval(strpos($acceptType, $value) !== false); } } // Sort the array to retrieve the format that best matches the Accept header asort($counters); end($counters); return key($counters); } return 'html'; }
Returns the preferred format based on the Accept header @param ServerRequestInterface $request @return string
entailment
public static function getAllProcessors($objectManager) { /** @var ReflectionService $reflectionService */ $reflectionService = $objectManager->get(ReflectionService::class); $processorClassNames = $reflectionService->getAllImplementationClassNamesForInterface(IndexSettingProcessorInterface::class); $processors = []; foreach ($processorClassNames as $processorClassName) { $processors[$processorClassName] = [ 'priority' => $processorClassName::getPriority(), 'className' => $processorClassName ]; } return array_reverse( (new PositionalArraySorter($processors, 'priority'))->toArray() ); }
Returns all class names implementing the IndexSettingProcessorInterface. @Flow\CompileStatic @param ObjectManagerInterface $objectManager @return array
entailment
public static function buildIndexClassesAndProperties($objectManager) { /** @var ReflectionService $reflectionService */ $reflectionService = $objectManager->get(ReflectionService::class); $indexAnnotations = []; $annotationClassName = Indexable::class; foreach ($reflectionService->getClassNamesByAnnotation($annotationClassName) as $className) { if ($reflectionService->isClassAbstract($className)) { throw new ElasticSearchException(sprintf('The class with name "%s" is annotated with %s, but is abstract. Indexable classes must not be abstract.', $className, $annotationClassName), 1339595182); } $indexAnnotations[$className]['annotation'] = $reflectionService->getClassAnnotation($className, $annotationClassName); // if no single properties are set to be indexed, consider all properties to be indexed. $annotatedProperties = $reflectionService->getPropertyNamesByAnnotation($className, $annotationClassName); if (!empty($annotatedProperties)) { $indexAnnotations[$className]['properties'] = $annotatedProperties; } else { foreach ($reflectionService->getClassPropertyNames($className) as $propertyName) { $indexAnnotations[$className]['properties'][] = $propertyName; } } } return $indexAnnotations; }
Creates the source array of what classes and properties have to be annotated. The returned array consists of class names, with a sub-key having both 'annotation' and 'properties' set. The annotation contains the class's annotation, while properties contains each property that has to be indexed. Each property might either have TRUE as value, or also an annotation instance, if given. @param ObjectManagerInterface $objectManager @return array @throws ElasticSearchException
entailment
public function getAllIndexNames() { $indexes = []; foreach ($this->getClassesAndAnnotations() as $configuration) { /** @var Indexable $configuration */ $indexes[$configuration->indexName] = $configuration->indexName; } return array_keys($indexes); }
Returns all indexes name deplared in class annotations @return array
entailment
public function getClassesAndAnnotations() { static $classesAndAnnotations; if ($classesAndAnnotations === null) { $classesAndAnnotations = []; foreach (array_keys($this->indexAnnotations) as $className) { $classesAndAnnotations[$className] = $this->indexAnnotations[$className]['annotation']; } } return $classesAndAnnotations; }
Returns the to-index classes and their annotation @return array
entailment
protected function getSearchManager() { return new SearchManager( $this->kernel->getContainer()->get($this->adapterId), $this->kernel->getContainer()->get('massive_search_test.metadata.provider.chain'), $this->kernel->getContainer()->get('massive_search_test.object_to_document_converter'), $this->kernel->getContainer()->get('event_dispatcher'), $this->kernel->getContainer()->get('massive_search_test.index_name_decorator.default'), $this->kernel->getContainer()->get('massive_search_test.metadata.field_evaluator') ); }
Return the search manager using the configured adapter ID.
entailment
public function boot(Bootstrap $bootstrap) { $dispatcher = $bootstrap->getSignalSlotDispatcher(); $package = $this; $dispatcher->connect(Sequence::class, 'afterInvokeStep', function (Step $step) use ($package, $bootstrap) { if ($step->getIdentifier() === 'neos.flow:objectmanagement:runtime') { $package->prepareRealtimeIndexing($bootstrap); } }); }
Invokes custom PHP code directly after the package manager has been initialized. @param Bootstrap $bootstrap The current bootstrap @return void
entailment
public function onIndexRebuild(IndexRebuildEvent $event) { foreach ($this->adapter->listIndexes() as $indexName) { if (!$this->indexNameDecorator->isVariant($this->indexNameDecorator->undecorate($indexName), $indexName)) { continue; } $event->getOutput()->writeln(sprintf('<info>Optimizing zend lucene index:</info> %s', $indexName)); $this->adapter->optimize($indexName); } }
Optimize the search indexes after the index rebuild event has been fired. Should have a priority low enough in order for it to be executed after all the actual index builders. @param IndexRebuildEvent $event
entailment
public function showStatusCommand($clientName = null) { $entityMappingCollection = $this->entityMappingBuilder->buildMappingInformation(); $entityMappingCollection = $this->buildArrayFromMappingCollection($entityMappingCollection); $client = $this->clientFactory->create($clientName); $this->backendMappingBuilder->setClient($client); $backendMappingCollection = $this->backendMappingBuilder->buildMappingInformation(); $backendMappingCollection = $this->buildArrayFromMappingCollection($backendMappingCollection); $this->printLegend(); $this->outputFormatted('<b>Mapping status:</b>'); $this->outputFormatted('<b>---------------</b>'); $mergedMappingCollection = array_merge_recursive($entityMappingCollection, $backendMappingCollection); foreach ($mergedMappingCollection as $indexName => $typeSet) { $this->outputFormatted('index %s:', [$this->markupDiffValue(isset($entityMappingCollection[$indexName]) ? $indexName : null, isset($backendMappingCollection[$indexName]) ? $indexName : null)]); foreach ($typeSet as $typeName => $mappingSet) { $propertiesSet = $mappingSet['properties']; $this->outputFormatted('type %s:', [$this->markupDiffValue(isset($entityMappingCollection[$indexName][$typeName]) ? $typeName : null, isset($backendMappingCollection[$indexName][$typeName]) ? $typeName : null)], 4); foreach ($propertiesSet as $propertyName => $properties) { $entityProperties = Arrays::getValueByPath($entityMappingCollection, [ $indexName, $typeName, 'properties', $propertyName, ]); $backendProperties = Arrays::getValueByPath($backendMappingCollection, [ $indexName, $typeName, 'properties', $propertyName, ]); $this->outputFormatted('property %s:', [$this->markupDiffValue($entityProperties ? $propertyName : null, $backendProperties ? $propertyName : null)], 8); foreach ($properties as $key => $value) { $keyMarkup = $this->markupDiffValue(isset($entityProperties[$key]) ? $key : null, isset($backendProperties[$key]) ? $key : null); $valueMarkup = $this->markupDiffValue(isset($entityProperties[$key]) ? $entityProperties[$key] : null, isset($backendProperties[$key]) ? $backendProperties[$key] : null); $this->outputFormatted("%s : %s", [$keyMarkup, $valueMarkup], 12); } } $this->outputLine(); } $this->outputLine(); } if (count($indicesWithoutTypeInformation = $this->backendMappingBuilder->getIndicesWithoutTypeInformation())) { $this->outputFormatted("\x1b[43mNotice:\x1b[0m The following indices are present in the backend's mapping but having no type configuration, can hence be regarded as garbage:"); foreach ($indicesWithoutTypeInformation as $indexName) { $this->outputFormatted('* %s', [$indexName], 4); } } }
Shows the status of the current mapping... @param string $clientName The client name for the configuration. Defaults to the default client configured. @return void
entailment
protected function buildArrayFromMappingCollection(MappingCollection $mappingCollection) { $return = []; /** @var $mappingInformation Mapping */ foreach ($mappingCollection as $mappingInformation) { $indexName = $mappingInformation->getType()->getIndex()->getName(); $typeName = $mappingInformation->getType()->getName(); if (isset($return[$indexName][$typeName])) { throw new ElasticSearchException('There was more than one mapping present in index %s with type %s, which must not happen.', 1339758480); } $return[$indexName][$typeName]['mappingInstance'] = $mappingInformation; $return[$indexName][$typeName]['properties'] = $mappingInformation->getProperties(); } return $return; }
Traverses through mappingInformation array and aggregates by index and type names @param MappingCollection $mappingCollection @throws ElasticSearchException @return array with index names as keys, second level type names as keys
entailment
public function convergeCommand($clientName = null) { $client = $this->clientFactory->create($clientName); $entityMappingCollection = $this->entityMappingBuilder->buildMappingInformation(); $this->backendMappingBuilder->setClient($client); $backendMappingCollection = $this->backendMappingBuilder->buildMappingInformation(); $additiveMappings = $entityMappingCollection->diffAgainstCollection($backendMappingCollection); /** @var $mapping Mapping */ foreach ($additiveMappings as $mapping) { $index = $mapping->getType()->getIndex(); $index->setClient($client); if (!$index->exists()) { $this->outputFormatted('Index <b>%s</b> does not exist', [$index->getName()]); continue; } $this->outputLine('Attempt to apply properties to %s/%s: %s... ', [ $index->getName(), $mapping->getType()->getName(), print_r($mapping->getProperties(), true), ]); $response = $mapping->apply(); if ($response->getStatusCode() === 200) { $this->outputFormatted('<b>OK</b>'); } else { $this->outputFormatted('<b>NOT OK</b>, response code was %d, response body was: %s', [ $response->getStatusCode(), $response->getOriginalResponse()->getContent(), ], 4); } } if ($additiveMappings->count() === 0) { $this->outputLine('No mappings were to be applied.'); } }
This command will adjust the backend's mapping to the mapping the entity status prescribes. @param string $clientName The client name for the configuration. Defaults to the default client configured. @return void
entailment
public function objectToDocument(IndexMetadata $metadata, $object) { $indexNameField = $metadata->getIndexName(); $idField = $metadata->getIdField(); $urlField = $metadata->getUrlField(); $titleField = $metadata->getTitleField(); $descriptionField = $metadata->getDescriptionField(); $imageUrlField = $metadata->getImageUrlField(); $localeField = $metadata->getLocaleField(); $fieldMapping = $metadata->getFieldMapping(); $document = $this->factory->createDocument(); $document->setIndex($this->fieldEvaluator->getValue($object, $indexNameField)); $document->setId($this->fieldEvaluator->getValue($object, $idField)); $document->setClass($metadata->getName()); if ($urlField) { $url = $this->fieldEvaluator->getValue($object, $urlField); if ($url) { $document->setUrl($url); } } if ($titleField) { $title = $this->fieldEvaluator->getValue($object, $titleField); if ($title) { $document->setTitle($title); } } if ($descriptionField) { $description = $this->fieldEvaluator->getValue($object, $descriptionField); if ($description) { $document->setDescription($description); } } if ($imageUrlField) { $imageUrl = $this->fieldEvaluator->getValue($object, $imageUrlField); $document->setImageUrl($imageUrl); } if ($localeField) { $locale = $this->fieldEvaluator->getValue($object, $localeField); $document->setLocale($locale); } $this->populateDocument($document, $object, $fieldMapping); return $document; }
Map the given object to a new document using the given metadata. @param IndexMetadata $metadata @param object $object @return Document
entailment
private function populateDocument($document, $object, $fieldMapping, $prefix = '') { foreach ($fieldMapping as $fieldName => $mapping) { $requiredMappings = ['field', 'type']; foreach ($requiredMappings as $requiredMapping) { if (!isset($mapping[$requiredMapping])) { throw new \RuntimeException( sprintf( 'Mapping for "%s" does not have "%s" key', get_class($document), $requiredMapping ) ); } } $mapping = array_merge( [ 'stored' => true, 'aggregate' => false, 'indexed' => true, ], $mapping ); if ('complex' == $mapping['type']) { if (!isset($mapping['mapping'])) { throw new \InvalidArgumentException( sprintf( '"complex" field mappings must have an additional array key "mapping" ' . 'which contains the mapping for the complex structure in mapping: %s', print_r($mapping, true) ) ); } $childObjects = $this->fieldEvaluator->getValue($object, $mapping['field']); if (null === $childObjects) { continue; } foreach ($childObjects as $i => $childObject) { $this->populateDocument( $document, $childObject, $mapping['mapping']->getFieldMapping(), $prefix . $fieldName . $i ); } continue; } $type = $mapping['type']; $value = $this->fieldEvaluator->getValue($object, $mapping['field']); if (Field::TYPE_STRING !== $type && Field::TYPE_ARRAY !== $type) { $value = $this->converterManager->convert($value, $type); if (is_null($value)) { $type = Field::TYPE_NULL; } elseif (is_array($value)) { $type = Field::TYPE_ARRAY; } else { $type = Field::TYPE_STRING; } } if (null !== $value && false === is_scalar($value) && false === is_array($value)) { throw new \InvalidArgumentException( sprintf( 'Search field "%s" resolved to not supported type "%s". Only scalar (single) or array values can be indexed.', $fieldName, gettype($value) ) ); } if ('complex' !== $mapping['type']) { $document->addField( $this->factory->createField( $prefix . $fieldName, $value, $type, $mapping['stored'], $mapping['indexed'], $mapping['aggregate'] ) ); continue; } foreach ($value as $key => $itemValue) { $document->addField( $this->factory->createField( $prefix . $fieldName . $key, $itemValue, $mapping['type'], $mapping['stored'], $mapping['indexed'], $mapping['aggregate'] ) ); } } }
Populate the Document with the actual values from the object which is being indexed. @param Document $document @param mixed $object @param array $fieldMapping @param string $prefix Prefix the document field name (used when called recursively) @throws \InvalidArgumentException
entailment
public function setPropertyByPath($path, $value) { $this->properties = Arrays::setValueByPath($this->properties, $path, $value); }
Gets a property setting by its path @param array|string $path @param string $value @return void
entailment
public function asArray() { return [ $this->type->getName() => Arrays::arrayMergeRecursiveOverrule([ 'dynamic_templates' => $this->getDynamicTemplates(), 'properties' => $this->getProperties(), ], $this->fullMapping), ]; }
Return the mapping which would be sent to the server as array @return array
entailment