sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function search($term, $params = array())
{
$params = $this->getSearchParams($term, $params);
$cacheKey = $this->cacheKey('search', $params);
$cacheDuration = $this->iTunesConfig['cache'];
if ($this->cache->has($cacheKey)) {
return $this->cache->get($cacheKey);
} else {
return $this->cache->remember($cacheKey, $cacheDuration, function () use($term, $params) {
return json_encode(parent::search($term, $params));
});
}
} | Search the API for a term.
@param string $term
@param array $params
@return object | entailment |
public function lookup($id, $value = null, $params = array())
{
$cacheKey = $this->cacheKey('lookup', $this->getLookupParams($id, $value, $params));
$cacheDuration = $this->iTunesConfig['cache'];
if ($this->cache->has($cacheKey)) {
return $this->cache->get($cacheKey);
} else {
return $this->cache->remember($cacheKey, $cacheDuration, function () use($id, $value, $params) {
return json_encode(parent::lookup($id, $value, $params));
});
}
} | Lookup an item in the API.
@param string $item
@param array $params
@return object | entailment |
protected function cacheKey($type, $params)
{
return sprintf('%s:%s:%s', $this->cachePrefix, $type, md5(http_build_query($params)));
} | get a cache key for the given type and params.
@param string $term
@param array $params
@return string | entailment |
protected function loadConfig()
{
parent::loadConfig();
// merge overriding with user-specified configuration.
$this->iTunesConfig = array_merge($this->iTunesConfig, $this->config->get('itunes'));
} | Load the configuration parameters. | entailment |
public function denormalize($data, $class, $format = null, array $context = [])
{
// This is the annotated custom field class defining all custom fields.
if (!isset($this->customFields[$data['namespace']])) {
return new MissingCustomFieldsClass($data['namespace']);
}
$concreteClass = $this->customFields[$data['namespace']]->getClass();
if (!$this->serializer instanceof DenormalizerInterface) {
throw new LogicException(sprintf('Cannot denormalize class "%s" because injected serializer is not a denormalizer', $class));
}
return $this->serializer->denormalize($data['data'], $concreteClass);
} | {@inheritdoc} | entailment |
public static function mpxErrors(): \Closure
{
// Guzzle's built-in middlewares also have this level of nested
// functions, so we follow the same pattern even though it's difficult
// to read.
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
// We only need to process after the request has been sent.
return $handler($request, $options)->then(
function (ResponseInterface $response) use ($request, $handler) {
// While it's not documented, we want to be sure that
// any 4XX or 5XX errors that break through suppression
// are still parsed. In other words, this handler should
// be executed before the normal Guzzle error handler.
// If our response isn't JSON, we can't parse it.
$contentType = $response->getHeaderLine('Content-Type');
if (0 === preg_match('!^(application|text)\/json!', $contentType)) {
return $response;
}
$data = \GuzzleHttp\json_decode($response->getBody(), true);
// Notification responses have a different exception format.
if (isset($data[0]) && isset($data[0]['type']) && 'Exception' == $data[0]['type']) {
throw MpxExceptionFactory::createFromNotificationException($request, $response);
}
if (empty($data['responseCode']) && empty($data['isException'])) {
return $response;
}
throw MpxExceptionFactory::create($request, $response);
}
);
};
};
} | A middleware to check for MPX errors in the body of the response.
@see https://docs.theplatform.com/help/wsf-handling-data-service-exceptions
@return \Closure A middleware function. | entailment |
public function hasNext(): bool
{
return !empty($this->entries) && ($this->getStartIndex() + $this->getItemsPerPage() - 1 < $this->getTotalResults());
} | Return if this object list has a next list to load.
@return bool True if a next list exists, false otherwise. | entailment |
public function nextList()
{
if (!$this->hasNext()) {
return false;
}
if (!isset($this->dataObjectFactory)) {
throw new \LogicException('setDataObjectFactory must be called before calling nextList.');
}
if (!isset($this->objectListQuery)) {
throw new \LogicException('setByFields must be called before calling nextList.');
}
$byFields = clone $this->objectListQuery;
$range = Range::nextRange($this);
$byFields->setRange($range);
return $this->dataObjectFactory->selectRequest($byFields);
} | Return the next object list request, if one exists.
@see \Lullabot\Mpx\DataService\ObjectList::setDataObjectFactory
@return PromiseInterface|bool A promise to the next ObjectList, or false if no list exists. | entailment |
public function yieldLists(): \Generator
{
if (!isset($this->dataObjectFactory)) {
throw new \LogicException('setDataObjectFactory must be called before calling nextList.');
}
if (!isset($this->objectListQuery)) {
throw new \LogicException('setByFields must be called before calling nextList.');
}
// We need to yield ourselves first.
$thisList = new Promise();
$thisList->resolve($this);
yield $thisList;
$ranges = Range::nextRanges($this);
foreach ($ranges as $range) {
$byFields = clone $this->objectListQuery;
$byFields->setRange($range);
yield $this->dataObjectFactory->selectRequest($byFields);
}
} | Yield select requests for all pages of this object list.
@return \Generator A generator returning promises to object lists. | entailment |
public function getClient(): SellsyClient
{
if (!$this->client instanceof SellsyClient) {
$this->client = new SellsyClient(
$this->getTransport(),
$this->apiUrl,
$this->oauthAccessToken,
$this->oauthAccessTokenSecret,
$this->oauthConsumerKey,
$this->oauthConsumerSecret
);
}
return $this->client;
} | Return and configure a sellsy client, on the flow.
@return SellsyClient | entailment |
protected function headerSettings()
{
$this->setPrintHeader(
Config::get('laravel-tcpdf::header_on')
);
$this->setHeaderFont(array(
Config::get('laravel-tcpdf::header_font'),
'',
Config::get('laravel-tcpdf::header_font_size')
));
$this->setHeaderMargin(
Config::get('laravel-tcpdf::header_margin')
);
$this->SetHeaderData(
Config::get('laravel-tcpdf::header_logo'),
Config::get('laravel-tcpdf::header_logo_width'),
Config::get('laravel-tcpdf::header_title'),
Config::get('laravel-tcpdf::header_string')
);
} | Set all the necessary header settings
@author Markus Schober | entailment |
protected function footerSettings()
{
$this->setPrintFooter(
Config::get('laravel-tcpdf::footer_on')
);
$this->setFooterFont(array(
Config::get('laravel-tcpdf::footer_font'),
'',
Config::get('laravel-tcpdf::footer_font_size')
));
$this->setFooterMargin(
Config::get('laravel-tcpdf::footer_margin')
);
} | Set all the necessary footer settings
@author Markus Schober | entailment |
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$data = array(
'calls' => array(),
'error_count' => 0,
'methods' => array(),
'total_time' => 0,
);
/**
* Aggregates global metrics about Guzzle usage
*
* @param array $request
* @param array $response
* @param array $time
* @param bool $error
*/
$aggregate = function ($request, $response, $time, $error) use (&$data) {
$method = $request['method'];
if (!isset($data['methods'][$method])) {
$data['methods'][$method] = 0;
}
$data['methods'][$method]++;
$data['total_time'] += $time['total'];
$data['error_count'] += (int) $error;
};
foreach ($this->profiler as $call) {
$request = $this->collectRequest($call);
$response = $this->collectResponse($call);
$time = $this->collectTime($call);
$error = $call->getResponse()->isError();
$aggregate($request, $response, $time, $error);
$data['calls'][] = array(
'request' => $request,
'response' => $response,
'time' => $time,
'error' => $error
);
}
$this->data = $data;
} | {@inheritdoc} | entailment |
private function collectRequest(GuzzleRequestInterface $request)
{
$body = null;
if ($request instanceof EntityEnclosingRequestInterface) {
$body = (string) $request->getBody();
}
return array(
'headers' => $request->getHeaders(),
'method' => $request->getMethod(),
'scheme' => $request->getScheme(),
'host' => $request->getHost(),
'port' => $request->getPort(),
'path' => $request->getPath(),
'query' => $request->getQuery(),
'body' => $body
);
} | Collect & sanitize data about a Guzzle request
@param Guzzle\Http\Message\RequestInterface $request
@return array | entailment |
private function collectResponse(GuzzleRequestInterface $request)
{
$response = $request->getResponse();
$body = $response->getBody(true);
return array(
'statusCode' => $response->getStatusCode(),
'reasonPhrase' => $response->getReasonPhrase(),
'headers' => $response->getHeaders(),
'body' => $body
);
} | Collect & sanitize data about a Guzzle response
@param Guzzle\Http\Message\RequestInterface $request
@return array | entailment |
private function collectTime(GuzzleRequestInterface $request)
{
$response = $request->getResponse();
return array(
'total' => $response->getInfo('total_time'),
'connection' => $response->getInfo('connect_time')
);
} | Collect time for a Guzzle request
@param Guzzle\Http\Message\RequestInterface $request
@return array | entailment |
public function getColorSchemeId(): \Psr\Http\Message\UriInterface
{
if (!$this->colorSchemeId) {
return new Uri();
}
return $this->colorSchemeId;
} | Returns identifier for the color scheme assigned to this player.
@return \Psr\Http\Message\UriInterface | entailment |
public function getEmbedAdPolicyId(): \Psr\Http\Message\UriInterface
{
if (!$this->embedAdPolicyId) {
return new Uri();
}
return $this->embedAdPolicyId;
} | Returns the identifier for the advertising policy to use when the player is embedded in another site.
@return \Psr\Http\Message\UriInterface | entailment |
public function getEmbedRestrictionId(): \Psr\Http\Message\UriInterface
{
if (!$this->embedRestrictionId) {
return new Uri();
}
return $this->embedRestrictionId;
} | Returns the identifier for the restriction to apply to this player when embedded in another site.
@return \Psr\Http\Message\UriInterface | entailment |
public function getLayoutId(): \Psr\Http\Message\UriInterface
{
if (!$this->layoutId) {
return new Uri();
}
return $this->layoutId;
} | Returns the identifier for the layout assigned to this player.
@return \Psr\Http\Message\UriInterface | entailment |
public function getSkinId(): \Psr\Http\Message\UriInterface
{
if (!$this->skinId) {
return new Uri();
}
return $this->skinId;
} | Returns identifier for the skin object to apply this player.
@return \Psr\Http\Message\UriInterface | entailment |
public function getFieldDataService(): DiscoveredDataService
{
$service = clone $this;
$service->objectType .= '/Field';
$service->schemaVersion = '1.2';
return new DiscoveredDataService(Field::class, $service);
} | Return a discovered data service for custom fields.
Custom fields break the conventions set by all other data services in
that they support CRUD operations, but have paths that are the child of
another object type. As well, they have schemas, but thePlatform has no
documentation of their history. To simplify the implementation, we do
not support discoverable classes for field definitions.
@return DiscoveredDataService A data service suitable for using with a DataObjectFactory. | entailment |
public function createMigration($config, $section, $table, $splitTable, $command)
{
try {
if (!empty($section)) {
$migrationName = 'create_'.str_plural(strtolower(implode('_', $splitTable))).'_table';
$tableName = str_plural(strtolower(implode('_', $splitTable)));
} else {
$migrationName = 'create_'.str_plural(strtolower(snake_case($table))).'_table';
$tableName = str_plural(strtolower(snake_case($table)));
}
$command->callSilent('make:migration', [
'name' => $migrationName,
'--table' => $tableName,
'--create' => true,
'--path' => $this->getMigrationsPath($config, true),
]);
return true;
} catch (Exception $e) {
throw new Exception('Could not create the migration: '.$e->getMessage(), 1);
}
} | Create the migrations.
@param array $config
@param string $section
@param string $table
@param array $splitTable
@param \Grafite\CrudMaker\Console\CrudMaker $command
@return bool | entailment |
public function createSchema($config, $section, $table, $splitTable, $schema)
{
$migrationFiles = $this->filesystem->allFiles($this->getMigrationsPath($config));
if (!empty($section)) {
$migrationName = 'create_'.str_plural(strtolower(implode('_', $splitTable))).'_table';
} else {
$migrationName = 'create_'.str_plural(strtolower(snake_case($table))).'_table';
}
$parsedTable = '';
$definitions = $this->calibrateDefinitions($schema);
foreach ($definitions as $key => $column) {
$columnDefinition = explode(':', $column);
$columnDetails = explode('|', $columnDefinition[1]);
$columnDetailString = $this->createColumnDetailString($columnDetails);
if ($key === 0) {
$parsedTable .= $this->getSchemaString($columnDetails, $columnDefinition, $columnDetailString);
} else {
$parsedTable .= "\t\t\t".$this->getSchemaString($columnDetails, $columnDefinition, $columnDetailString);
}
}
if (isset($config['relationships']) && !is_null($config['relationships'])) {
$relationships = explode(',', $config['relationships']);
foreach ($relationships as $relationship) {
$relation = explode('|', $relationship);
if (isset($relation[2])) {
if (!stristr($parsedTable, "integer('$relation[2]')")) {
$parsedTable .= "\t\t\t\$table->integer('$relation[2]');\n";
}
}
}
}
foreach ($migrationFiles as $file) {
if (stristr($file->getBasename(), $migrationName)) {
$migrationData = $this->filesystem->get($file->getPathname());
$migrationData = str_replace("\$table->increments('id');", $parsedTable, $migrationData);
$this->filesystem->put($file->getPathname(), $migrationData);
}
}
return $parsedTable;
} | Create the Schema.
@param array $config
@param string $section
@param string $table
@param array $splitTable
@return string | entailment |
public function createColumnDetailString($columnDetails)
{
$columnDetailString = '';
if (count($columnDetails) > 1) {
array_shift($columnDetails);
foreach ($columnDetails as $key => $detail) {
if ($key === 0) {
$columnDetailString .= '->';
}
$columnDetailString .= $this->columnDetail($detail);
if ($key != count($columnDetails) - 1) {
$columnDetailString .= '->';
}
}
return $columnDetailString;
}
} | Create a column detail string.
@param array $columnDetails
@return string | entailment |
public function columnDetail($detail)
{
$columnDetailString = '';
if (stristr($detail, '(')) {
$columnDetailString .= $detail;
} else {
$columnDetailString .= $detail.'()';
}
return $columnDetailString;
} | Determine column detail string.
@param array $detail
@return string | entailment |
private function getMigrationsPath($config, $relative = false)
{
$this->fileService->mkdir($config['_path_migrations_'], 0777, true);
if ($relative) {
return str_replace(base_path(), '', $config['_path_migrations_']);
}
return $config['_path_migrations_'];
} | Get the migration path.
@param array $config
@param bool $relative
@return string | entailment |
public function actionView($id)
{
$photos = GalleryPhoto::find()->where(['gallery_id' => $id])->orderBy('name')->all();
return $this->render('view', [
'model' => $this->findModel($id),
'photos' => $photos,
]);
} | Displays a single Gallery model.
@param string $id
@return mixed | entailment |
public function actionCreate()
{
$request = Yii::$app->request;
$model = new Gallery();
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Create Gallery",
'content' => $this->renderPartial('create', [
'model' => $model,
]),
];
} else if ($model->load($request->post()) && $model->validate()) {
$model->name = Html::encode($model->name);
$model->date = date('Y-m-d H:i:s');
if($model->save()) {
$alias = Yii::getAlias('@app/web/img/gallery/' . Translator::rus2translit($model->name));
try {
//если создавать рекурсивно, то работает через раз хз почему.
$old = umask(0);
mkdir($alias, 0777, true);
chmod($alias, 0777);
mkdir($alias . '/thumb', 0777);
chmod($alias . '/thumb', 0777);
umask($old);
} catch (\Exception $e){
return('Не удалось создать директорию ' . $alias . ' - ' . $e->getMessage());
}
return [
'forceReload' => true,
'forceClose' => true,
'hideActionButton' => true,
'title' => "Create Gallery",
'content' => '<span class="text-success">Success!</span>'
];
} else{
return [
'title' => "Create Gallery",
'content' => $this->renderPartial('create', [
'model' => $model,
]),
];
}
} else {
return [
'title' => "Create Gallery",
'content' => $this->renderPartial('create', [
'model' => $model,
]),
];
}
} else {
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->gallery_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
} | Creates a new Gallery model.
For ajax request will return json object
and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
@return mixed | entailment |
public function actionUpdate($id)
{
$request = Yii::$app->request;
$model = $this->findModel($id);
$oldName = $model->name;
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Update Gallery",
'content' => $this->renderPartial('update', [
'model' => $model,
]),
];
} else if ($model->load($request->post()) && $model->validate()) {
$model->name = Html::encode($model->name);
if ($model->save()) {
$oldAlias = Yii::getAlias('@app/web/img/gallery/' . Translator::rus2translit($oldName));
$newAlias = Yii::getAlias('@app/web/img/gallery/' . Translator::rus2translit($model->name));
if($oldAlias != $newAlias) {
try {
rename($oldAlias, $newAlias);
} catch (\Exception $e) {
return('Не удалось переименовать директорию ' . $oldAlias . ' - ' . $e->getMessage());
}
}
return [
'forceReload' => true,
'hideActionButton' => true,
'title' => "Gallery - " . $model->name,
'content' => '<span class="text-success">Success!</span>',
];
} else{
return [
'title' => "Редактирование Галереи - " . $model->name,
'content' => $this->renderPartial('update', [
'model' => $model,
]),
'footer' => Html::button('Закрыть', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Сохранить', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
}else {
return [
'title' => "Gallery Edit - " . $model->name,
'content' => $this->renderPartial('update', [
'model' => $this->findModel($id),
]),
'footer' => Html::button('Закрыть', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Сохранить', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
} else {
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->gallery_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
} | Updates an existing Gallery model.
For ajax request will return json object
and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
@param string $id
@return mixed | entailment |
public function actionDelete($id)
{
$request = Yii::$app->request;
$model = $this->findModel($id);
$galleryId = $model->gallery_id;
$dir = Yii::getAlias('@app/web/img/gallery/' . Translator::rus2translit($model->name));
try{
File::removeDirectory($dir);
} catch (\Exception $e){
echo('Something went wrong... Error: ' . $dir . ' - ' . $e->getMessage());
}
if($model->delete()){
GalleryPhoto::deleteAll(['gallery_id' => $galleryId]);
}
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
return ['forceClose' => false,
'forceReload' => true,
'title' => "Deliting gallery",
'content' => 'Success!',
'hideActionButton' => true
];
} else {
/*
* Process for non-ajax request
*/
return $this->redirect(['index']);
}
} | Delete an existing Gallery model.
For ajax request will return json object
and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
@param string $id
@return mixed | entailment |
public function actionPhotosDelete()
{
$request = Yii::$app->request;
$photoIds = $request->post('ids'); // Array or selected records primary keys
$photoModels = GalleryPhoto::findAll($photoIds);
if(empty($photoModels)) return null;
$galleryModel = $this->findModel($photoModels[0]->gallery_id);
$dir = Yii::getAlias('@app/web/img/gallery/' . Translator::rus2translit($galleryModel->name));
foreach ($photoModels as $photo){
try{
unlink($dir . '/' . $photo->name);
unlink($dir . '/thumb/' . $photo->name);
} catch (\Exception $e){
echo('Не удалось удалить файл ' . $photo->name . ' - ' . $e->getMessage());
}
}
GalleryPhoto::deleteAll(['photo_id' => $photoIds]);
if ($request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return true;
} else {
return $this->redirect(['index']);
}
} | Delete multiple existing Gallery model.
For ajax request will return json object
and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
@return mixed | entailment |
public function validateSchema($command)
{
if ($command->option('schema')) {
$definitions = $this->calibrateDefinitions($command->option('schema'));
foreach ($definitions as $column) {
$columnDefinition = explode(':', $column);
if (!isset($columnDefinition[1])) {
throw new Exception('All schema columns require a column type.', 1);
}
$columnDetails = explode('|', $columnDefinition[1]);
preg_match('('.self::VALID_COLUMN_NAME_REGEX.')', $columnDetails[0], $columnDetailsType);
if (!in_array(camel_case($columnDetailsType[0]), $command->columnTypes)) {
throw new Exception($columnDetailsType[0].' is not in the array of valid column types: '.implode(', ', $command->columnTypes), 1);
}
}
}
return true;
} | Validate the Schema.
@param \Grafite\CrudMaker\Console\CrudMaker $command
@return bool|Exception | entailment |
public function validateOptions($command)
{
if ($command->option('ui') && !in_array($command->option('ui'), ['bootstrap', 'semantic'])) {
throw new Exception('The UI you selected is not suppported. It must be: bootstrap or semantic.', 1);
}
if ((!is_null($command->option('schema')) && !$command->option('migration')) ||
(!is_null($command->option('relationships')) && !$command->option('migration'))
) {
throw new Exception('In order to use Schema or Relationships you need to use Migrations', 1);
}
return true;
} | Validate the options.
@param \Grafite\CrudMaker\Console\CrudMaker $command
@return bool|Exception | entailment |
private function mergeDocuments($other, $pageSize)
{
$numberResults = sizeof($this->response->docs);
if ($numberResults < $pageSize) {
$foundProductIds = array();
foreach ($this->response->docs as $nonFuzzyDoc) {
/* @var $nonFuzzyDoc \Apache_Solr_Document */
$field = $nonFuzzyDoc->getField('product_id');
$foundProductIds[] = $field['value'];
}
$numberDuplicates = 0;
foreach ($other->response->docs as $fuzzyDoc) {
/* @var $fuzzyDoc \Apache_Solr_Document */
$field = $fuzzyDoc->getField('product_id');
if (!in_array($field['value'], $foundProductIds)) {
if ($numberResults++ >= $pageSize) {
continue;
}
$this->response->docs[] = $fuzzyDoc;
} else {
$numberDuplicates++;
}
}
$this->response->numFound = $this->response->numFound
+ $other->response->numFound
- $numberDuplicates;
} else {
$this->response->numFound = max(
$this->response->numFound,
$other->response->numFound
);
}
} | Merge documents from other response, keeping size below $pageSize
@param $other
@param $pageSize | entailment |
private function mergeFacetFieldCounts($other)
{
$facetFields = (array)$other->facet_counts->facet_fields;
foreach($facetFields as $facetName => $facetCounts) {
$facetCounts = (array)$facetCounts;
foreach($facetCounts as $facetId => $facetCount) {
if (isset($this->facet_counts->facet_fields->$facetName->$facetId)) {
$this->facet_counts->facet_fields->$facetName->$facetId = max(
$this->facet_counts->facet_fields->$facetName->$facetId,
$facetCount
);
} else {
$this->facet_counts->facet_fields->$facetName->$facetId = $facetCount;
}
}
}
if (isset($other->facet_counts->facet_ranges)) {
$facetRanges = (array)$other->facet_counts->facet_ranges;
foreach ($facetRanges as $facetName => $facetCounts) {
$facetCounts = (array)$facetCounts->counts;
if (!isset($this->facet_counts)) {
$this->facet_counts = new \stdClass();
}
if (!isset($this->facet_counts->facet_ranges)) {
$this->facet_counts->facet_ranges = new \stdClass();
}
if (!isset($this->facet_counts->facet_ranges->$facetName)) {
$this->facet_counts->facet_ranges->$facetName = new \stdClass();
$this->facet_counts->facet_ranges->$facetName->counts = new \stdClass();
}
foreach ($facetCounts as $facetId => $facetCount) {
if (isset($this->facet_counts->facet_ranges->$facetName->counts->$facetId)) {
$this->facet_counts->facet_ranges->$facetName->counts->$facetId = max(
$this->facet_counts->facet_ranges->$facetName->counts->$facetId,
$facetCount
);
} else {
$this->facet_counts->facet_ranges->$facetName->counts->$facetId = $facetCount;
}
}
}
}
if (isset($other->facet_counts->facet_intervals)) {
$facetIntervals = (array)$other->facet_counts->facet_intervals;
foreach ($facetIntervals as $facetName => $facetCounts) {
$facetCounts = (array)$facetCounts;
if (!isset($this->facet_counts)) {
$this->facet_counts = new \stdClass();
}
if (!isset($this->facet_counts->facet_intervals)) {
$this->facet_counts->facet_intervals = new \stdClass();
}
if (!isset($this->facet_counts->facet_intervals->$facetName)) {
$this->facet_counts->facet_intervals->$facetName = new \stdClass();
}
foreach ($facetCounts as $facetId => $facetCount) {
if (isset($this->facet_counts->facet_intervals->$facetName->$facetId)) {
$this->facet_counts->facet_intervals->$facetName->$facetId = max(
$this->facet_counts->facet_intervals->$facetName->$facetId,
$facetCount
);
} else {
$this->facet_counts->facet_intervals->$facetName->$facetId = $facetCount;
}
}
}
}
} | Merge facet counts from other response
@param $other | entailment |
private function mergePriceData($other)
{
if (!isset($other->stats->stats_fields)) {
return;
}
$statsFields = (array)$other->stats->stats_fields;
foreach($statsFields as $fieldName => $fieldData) {
if (!isset($this->stats)) {
$this->stats = new \stdClass();
}
if (!isset($this->stats->stats_fields)) {
$this->stats->stats_fields = new \stdClass();
}
if (!isset($this->stats->stats_fields->$fieldName)) {
$this->stats->stats_fields->$fieldName = new \stdClass();
}
$fieldData = (array)$fieldData;
if (isset($fieldData['min'])) {
$this->stats->stats_fields->$fieldName->min = $fieldData['min'];
}
if (isset($fieldData['max'])) {
$this->stats->stats_fields->$fieldName->max = $fieldData['max'];
}
}
} | Merge price information (min, max, intervals) from other response
@param $other | entailment |
public function slice($from, $length)
{
$result = clone $this;
$result->response->docs = array_slice($this->response->docs, $from, $length);
return $result;
} | Returns new result with slice from item number $from until item number $from + $length
@param $from
@param $length
@return Response | entailment |
private function sliceResult(SolrResponse $result)
{
$pageSize = $this->getParamsBuilder()->getPageSize();
$firstItemNumber = ($this->getParamsBuilder()->getCurrentPage() - 1) * $pageSize;
$result->slice($firstItemNumber, $pageSize);
return $result;
} | Remove all but last page from multipage result
@param SolrResponse $result
@return SolrResponse | entailment |
public function addReadService($service)
{
if ($service instanceof Apache_Solr_Service)
{
$id = $this->_getServiceId($service->getHost(), $service->getPort(), $service->getPath());
$this->_readableServices[$id] = $service;
}
else if (is_array($service))
{
if (isset($service['host']) && isset($service['port']) && isset($service['path']))
{
$id = $this->_getServiceId((string)$service['host'], (int)$service['port'], (string)$service['path']);
$this->_readableServices[$id] = $service;
}
else
{
throw new Apache_Solr_InvalidArgumentException('A Readable Service description array does not have all required elements of host, port, and path');
}
}
} | Adds a service instance or service descriptor (if it is already
not added)
@param mixed $service
@throws Apache_Solr_InvalidArgumentException If service descriptor is not valid | entailment |
public function addWriteService($service)
{
if ($service instanceof Apache_Solr_Service)
{
$id = $this->_getServiceId($service->getHost(), $service->getPort(), $service->getPath());
$this->_writeableServices[$id] = $service;
}
else if (is_array($service))
{
if (isset($service['host']) && isset($service['port']) && isset($service['path']))
{
$id = $this->_getServiceId((string)$service['host'], (int)$service['port'], (string)$service['path']);
$this->_writeableServices[$id] = $service;
}
else
{
throw new Apache_Solr_InvalidArgumentException('A Writeable Service description array does not have all required elements of host, port, and path');
}
}
} | Adds a service instance or service descriptor (if it is already
not added)
@param mixed $service
@throws Apache_Solr_InvalidArgumentException If service descriptor is not valid | entailment |
protected function _selectReadService($forceSelect = false)
{
if (!$this->_currentReadService || !isset($this->_readableServices[$this->_currentReadService]) || $forceSelect)
{
if ($this->_currentReadService && isset($this->_readableServices[$this->_currentReadService]) && $forceSelect)
{
// we probably had a communication error, ping the current read service, remove it if it times out
if ($this->_readableServices[$this->_currentReadService]->ping($this->_readPingTimeout) === false)
{
$this->removeReadService($this->_currentReadService);
}
}
if (count($this->_readableServices))
{
// select one of the read services at random
$ids = array_keys($this->_readableServices);
$id = $ids[rand(0, count($ids) - 1)];
$service = $this->_readableServices[$id];
if (is_array($service))
{
//convert the array definition to a client object
$service = new Apache_Solr_Service($service['host'], $service['port'], $service['path']);
$this->_readableServices[$id] = $service;
}
$service->setCreateDocuments($this->_createDocuments);
$this->_currentReadService = $id;
}
else
{
throw new Apache_Solr_NoServiceAvailableException('No read services were available');
}
}
return $this->_readableServices[$this->_currentReadService];
} | Iterate through available read services and select the first with a ping
that satisfies configured timeout restrictions (or the default)
@return Apache_Solr_Service
@throws Apache_Solr_NoServiceAvailableException If there are no read services that meet requirements | entailment |
protected function _selectWriteService($forceSelect = false)
{
if($this->_useBackoff)
{
return $this->_selectWriteServiceSafe($forceSelect);
}
if (!$this->_currentWriteService || !isset($this->_writeableServices[$this->_currentWriteService]) || $forceSelect)
{
if ($this->_currentWriteService && isset($this->_writeableServices[$this->_currentWriteService]) && $forceSelect)
{
// we probably had a communication error, ping the current read service, remove it if it times out
if ($this->_writeableServices[$this->_currentWriteService]->ping($this->_writePingTimeout) === false)
{
$this->removeWriteService($this->_currentWriteService);
}
}
if (count($this->_writeableServices))
{
// select one of the read services at random
$ids = array_keys($this->_writeableServices);
$id = $ids[rand(0, count($ids) - 1)];
$service = $this->_writeableServices[$id];
if (is_array($service))
{
//convert the array definition to a client object
$service = new Apache_Solr_Service($service['host'], $service['port'], $service['path']);
$this->_writeableServices[$id] = $service;
}
$this->_currentWriteService = $id;
}
else
{
throw new Apache_Solr_NoServiceAvailableException('No write services were available');
}
}
return $this->_writeableServices[$this->_currentWriteService];
} | Iterate through available write services and select the first with a ping
that satisfies configured timeout restrictions (or the default)
@return Apache_Solr_Service
@throws Apache_Solr_NoServiceAvailableException If there are no write services that meet requirements | entailment |
protected function _selectWriteServiceSafe($forceSelect = false)
{
if (!$this->_currentWriteService || !isset($this->_writeableServices[$this->_currentWriteService]) || $forceSelect)
{
if (count($this->_writeableServices))
{
$backoff = $this->_defaultBackoff;
do {
// select one of the read services at random
$ids = array_keys($this->_writeableServices);
$id = $ids[rand(0, count($ids) - 1)];
$service = $this->_writeableServices[$id];
if (is_array($service))
{
//convert the array definition to a client object
$service = new Apache_Solr_Service($service['host'], $service['port'], $service['path']);
$this->_writeableServices[$id] = $service;
}
$this->_currentWriteService = $id;
$backoff *= $this->_backoffEscalation;
if($backoff > $this->_backoffLimit)
{
throw new Apache_Solr_NoServiceAvailableException('No write services were available. All timeouts exceeded.');
}
} while($this->_writeableServices[$this->_currentWriteService]->ping($backoff) === false);
}
else
{
throw new Apache_Solr_NoServiceAvailableException('No write services were available');
}
}
return $this->_writeableServices[$this->_currentWriteService];
} | Iterate through available write services and select the first with a ping
that satisfies configured timeout restrictions (or the default). The
timeout period will increase until a connection is made or the limit is
reached. This will allow for increased reliability with heavily loaded
server(s).
@return Apache_Solr_Service
@throws Apache_Solr_NoServiceAvailableException If there are no write services that meet requirements | entailment |
public function setCreateDocuments($createDocuments)
{
$this->_createDocuments = (bool) $createDocuments;
// set on current read service
if ($this->_currentReadService)
{
$service = $this->_selectReadService();
$service->setCreateDocuments($createDocuments);
}
} | Set the create documents flag. This determines whether {@link Apache_Solr_Response} objects will
parse the response and create {@link Apache_Solr_Document} instances in place.
@param boolean $createDocuments | entailment |
public function add($rawPost)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->add($rawPost);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Raw Add Method. Takes a raw post body and sends it to the update service. Post body
should be a complete and well formed "add" xml document.
@param string $rawPost
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function addDocument(Apache_Solr_Document $document, $allowDups = false, $overwritePending = true, $overwriteCommitted = true)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->addDocument($document, $allowDups, $overwritePending, $overwriteCommitted);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Add a Solr Document to the index
@param Apache_Solr_Document $document
@param boolean $allowDups
@param boolean $overwritePending
@param boolean $overwriteCommitted
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function addDocuments($documents, $allowDups = false, $overwritePending = true, $overwriteCommitted = true)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->addDocuments($documents, $allowDups, $overwritePending, $overwriteCommitted);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Add an array of Solr Documents to the index all at once
@param array $documents Should be an array of Apache_Solr_Document instances
@param boolean $allowDups
@param boolean $overwritePending
@param boolean $overwriteCommitted
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function delete($rawPost, $timeout = 3600)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->delete($rawPost, $timeout);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Raw Delete Method. Takes a raw post body and sends it to the update service. Body should be
a complete and well formed "delete" xml document
@param string $rawPost
@param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function deleteById($id, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->deleteById($id, $fromPending, $fromCommitted, $timeout);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Create a delete document based on document ID
@param string $id
@param boolean $fromPending
@param boolean $fromCommitted
@param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function deleteByMultipleIds($ids, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->deleteByMultipleId($ids, $fromPending, $fromCommitted, $timeout);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Create and post a delete document based on multiple document IDs.
@param array $ids Expected to be utf-8 encoded strings
@param boolean $fromPending
@param boolean $fromCommitted
@param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function deleteByQuery($rawQuery, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->deleteByQuery($rawQuery, $fromPending, $fromCommitted, $timeout);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Create a delete document based on a query and submit it
@param string $rawQuery
@param boolean $fromPending
@param boolean $fromCommitted
@param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function extract($file, $params = array(), $document = null, $mimetype = 'application/octet-stream')
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->extract($file, $params, $document, $mimetype);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how
to use Solr Cell and what parameters are available.
NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."
as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value
pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also
pass in a document isntance with an "id" field" - the document's value(s) will take precedence).
@param string $file Path to file to extract data from
@param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation)
@param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params)
@param string $mimetype optional mimetype specification (for the file being extracted)
@return Apache_Solr_Response
@throws Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid. | entailment |
public function extractFromString($data, $params = array(), $document = null, $mimetype = 'application/octet-stream')
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->extractFromString($data, $params, $document, $mimetype);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Use Solr Cell to extract document contents. See {@link http://wiki.apache.org/solr/ExtractingRequestHandler} for information on how
to use Solr Cell and what parameters are available.
NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."
as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value
pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also
pass in a document isntance with an "id" field" - the document's value(s) will take precedence).
@param string $data Data that will be passed to Solr Cell
@param array $params optional array of key value pairs that will be sent with the post (see Solr Cell documentation)
@param Apache_Solr_Document $document optional document that will be used to generate post parameters (literal.* and boost.* params)
@param string $mimetype optional mimetype specification (for the file being extracted)
@return Apache_Solr_Response
@throws Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid.
@todo Should be using multipart/form-data to post parameter values, but I could not get my implementation to work. Needs revisisted. | entailment |
public function optimize($waitFlush = true, $waitSearcher = true, $timeout = 3600)
{
$service = $this->_selectWriteService();
do
{
try
{
return $service->optimize($waitFlush, $waitSearcher, $timeout);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectWriteService(true);
} while ($service);
return false;
} | Send an optimize command. Will be synchronous unless both wait parameters are set
to false.
@param boolean $waitFlush
@param boolean $waitSearcher
@param float $timeout Maximum expected duration of the optimize operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function search($query, $offset = 0, $limit = 10, $params = array(), $method = Apache_Solr_Service::METHOD_GET)
{
$service = $this->_selectReadService();
do
{
try
{
return $service->search($query, $offset, $limit, $params, $method);
}
catch (Apache_Solr_HttpTransportException $e)
{
if ($e->getCode() != 0) //IF NOT COMMUNICATION ERROR
{
throw $e;
}
}
$service = $this->_selectReadService(true);
} while ($service);
return false;
} | Simple Search interface
@param string $query The raw query string
@param int $offset The starting offset for result documents
@param int $limit The maximum number of result documents to return
@param array $params key / value pairs for query parameters, use arrays for multivalued parameters
@param string $method The HTTP method (Apache_Solr_Service::METHOD_GET or Apache_Solr_Service::METHOD::POST)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
protected function _getProductData(Product $product, ProductIterator $children)
{
$categoryIds = $this->categoryRepository->getCategoryIds($product);
$productData = new IndexDocument(array(
'id' => $product->getSolrId(), // primary identifier, must be unique
'product_id' => $product->getId(),
'category' => $categoryIds, // @todo get category ids from parent anchor categories as well
'category_name_t_mv' => $this->categoryRepository->getCategoryNames($categoryIds, $product->getStoreId()),
'store_id' => $product->getStoreId(),
'content_type' => self::CONTENT_TYPE,
'is_visible_in_catalog_i' => intval($product->isVisibleInCatalog()),
'is_visible_in_search_i' => intval($product->isVisibleInSearch()),
'has_special_price_i' => intval($product->hasSpecialPrice()),
'is_in_stock_i' => intval($product->isInStock()),
));
$this->_addBoostToProductData($product, $productData);
$this->_addFacetsToProductData($product, $productData, $children);
$this->_addSearchDataToProductData($product, $productData, $children);
$this->_addSortingDataToProductData($product, $productData);
$this->_addResultHtmlToProductData($product, $productData);
$this->_addCategoryProductPositionsToProductData($product, $productData);
$this->eventDispatcher->dispatch('integernet_solr_get_product_data', array(
'product' => $product,
'product_data' => $productData,
'children' => $children,
));
return $productData;
} | Generate single product data for Solr
@param Product $product
@param ProductIterator $children
@return IndexDocument | entailment |
protected function _isInteger($rawValue)
{
$rawValues = explode(',', $rawValue);
foreach ($rawValues as $value) {
if (!is_numeric($value)) {
return false;
}
}
return true;
} | The schema expected for facet attributes integer values
@param string $rawValue
@return bool | entailment |
public function swapCores($restrictToStoreIds)
{
$this->getProgressDispatcher()->start(
'Swap Solr cores' . ($restrictToStoreIds ? ' for stores ' . implode(',', $restrictToStoreIds) : '')
. ' (if swap core is configured)'
);
$this->_getResource()->swapCores($restrictToStoreIds);
$this->getProgressDispatcher()->finish();
} | Swap current core with shadow core (for all given stores)
@param null|int[] $restrictToStoreIds | entailment |
public function getDefaultTimeout()
{
// lazy load the default timeout from the ini settings
if ($this->_defaultTimeout === false)
{
$this->_defaultTimeout = (int) ini_get('default_socket_timeout');
// double check we didn't get 0 for a timeout
if ($this->_defaultTimeout <= 0)
{
$this->_defaultTimeout = 60;
}
}
return $this->_defaultTimeout;
} | Get the current default timeout setting (initially the default_socket_timeout ini setting)
in seconds
@return float | entailment |
public function install(string $path = null, bool $isDevMode = true, int $timeout = null)
{
if ($isDevMode) {
$arguments = ['install'];
} else {
$arguments = ['install', '--production'];
}
if ($timeout === null) {
$timeout = self::DEFAULT_TIMEOUT;
}
$this->executeNpm($arguments, $path, $timeout);
} | Install NPM dependencies for the project at the supplied path.
@param string|null $path The path to the NPM project, or null to use the current working directory.
@param bool $isDevMode True if dev dependencies should be included.
@param int|null $timeout The process timeout, in seconds.
@throws NpmNotFoundException If the npm executable cannot be located.
@throws NpmCommandFailedException If the operation fails. | entailment |
public function update(string $path = null, int $timeout = null)
{
if ($timeout === null) {
$timeout = self::DEFAULT_TIMEOUT;
}
$this->executeNpm(['update'], $path, $timeout);
} | Update NPM dependencies for the project at the supplied path.
@param string|null $path The path to the NPM project, or null to use the current working directory.
@param int $timeout The process timeout, in seconds.
@throws NpmNotFoundException If the npm executable cannot be located.
@throws NpmCommandFailedException If the operation fails. | entailment |
public function setBoost($boost)
{
$boost = (float) $boost;
if ($boost > 0.0)
{
$this->_documentBoost = $boost;
}
else
{
$this->_documentBoost = false;
}
} | Set document boost factor
@param mixed $boost Use false for default boost, else cast to float that should be > 0 or will be treated as false | entailment |
public function addField($key, $value, $boost = false)
{
if (!isset($this->_fields[$key]))
{
// create holding array if this is the first value
$this->_fields[$key] = array();
}
else if (!is_array($this->_fields[$key]))
{
// move existing value into array if it is not already an array
$this->_fields[$key] = array($this->_fields[$key]);
}
if ($this->getFieldBoost($key) === false)
{
// boost not already set, set it now
$this->setFieldBoost($key, $boost);
}
else if ((float) $boost > 0.0)
{
// multiply passed boost with current field boost - similar to SolrJ implementation
$this->_fieldBoosts[$key] *= (float) $boost;
}
// add value to array
$this->_fields[$key][] = $value;
} | Add a value to a multi-valued field
NOTE: the solr XML format allows you to specify boosts
PER value even though the underlying Lucene implementation
only allows a boost per field. To remedy this, the final
field boost value will be the product of all specified boosts
on field values - this is similar to SolrJ's functionality.
<code>
$doc = new Apache_Solr_Document();
$doc->addField('foo', 'bar', 2.0);
$doc->addField('foo', 'baz', 3.0);
// resultant field boost will be 6!
echo $doc->getFieldBoost('foo');
</code>
@param string $key
@param mixed $value
@param mixed $boost Use false for default boost, else cast to float that should be > 0 or will be treated as false | entailment |
public function setMultiValue($key, $value, $boost = false)
{
$this->addField($key, $value, $boost);
} | Handle the array manipulation for a multi-valued field
@param string $key
@param string $value
@param mixed $boost Use false for default boost, else cast to float that should be > 0 or will be treated as false
@deprecated Use addField(...) instead | entailment |
public function getField($key)
{
if (isset($this->_fields[$key]))
{
return array(
'name' => $key,
'value' => $this->_fields[$key],
'boost' => $this->getFieldBoost($key)
);
}
return false;
} | Get field information
@param string $key
@return mixed associative array of info if field exists, false otherwise | entailment |
public function setField($key, $value, $boost = false)
{
$this->_fields[$key] = $value;
$this->setFieldBoost($key, $boost);
} | Set a field value. Multi-valued fields should be set as arrays
or instead use the addField(...) function which will automatically
make sure the field is an array.
@param string $key
@param mixed $value
@param mixed $boost Use false for default boost, else cast to float that should be > 0 or will be treated as false | entailment |
public function getFieldBoost($key)
{
return isset($this->_fieldBoosts[$key]) ? $this->_fieldBoosts[$key] : false;
} | Get the currently set field boost for a document field
@param string $key
@return float currently set field boost, false if one is not set | entailment |
public function setFieldBoost($key, $boost)
{
$boost = (float) $boost;
if ($boost > 0.0)
{
$this->_fieldBoosts[$key] = $boost;
}
else
{
$this->_fieldBoosts[$key] = false;
}
} | Set the field boost for a document field
@param string $key field name for the boost
@param mixed $boost Use false for default boost, else cast to float that should be > 0 or will be treated as false | entailment |
public function fields(array $fields)
{
foreach ($fields as $field) {
if ($field instanceof Mapper) {
$this->addFieldFromMapper($field);
continue;
}
$this->fields[] = $field;
}
return $this;
} | Example:
$query->fields(['name', 'price']);
@param array $fields
@return $this
@throws \ByJG\Serializer\Exception\InvalidArgumentException | entailment |
public function env($key = null)
{
if (isset($_SERVER[$key])) {
return $_SERVER[$key];
} elseif (isset($_ENV[$key])) {
return $_ENV[$key];
} elseif (getenv($key) !== false) {
return getenv($key);
}
return null;
} | Get an environment variable
Query $_SERVER, $_ENV and getenv() in that order
@param string $key
@return mixed | entailment |
public static function map($scheme = null, $adapter = null)
{
if (is_array($scheme)) {
foreach ($scheme as $s => $adapter) {
static::map($s, $adapter);
}
return static::$adapterMap;
}
if ($scheme === null) {
return static::$adapterMap;
}
if ($adapter === null) {
return isset(static::$adapterMap[$scheme]) ? static::$adapterMap[$scheme] : null;
}
if ($adapter === false) {
unset($adapterMap[$scheme]);
return;
}
return static::$adapterMap[$scheme] = $adapter;
} | Read or change the adapter map
For example:
$true = Dsn::map('foo', 'UseThisAdapter');
$dsn = Dsn::parse('foo://....');
$dsn->adapter === 'UseThisAdapter';
$array = ['this' => 'That\Class', 'other' => 'Other\Class', ...];
$fullMap = Dsn::map($array);
$dsn = Dsn::parse('this://....');
$dsn->adapter === 'That\Class';
$dsn = Dsn::parse('other://....');
$dsn->adapter === 'Other\Class';
@param mixed $adapter
@param string $class
@return mixed | entailment |
protected function getDefaultOptions()
{
if (!isset($this->defaultOptions['replacements']['APP_NAME'])) {
$this->defaultOptions['replacements']['APP_NAME'] = $this->env('APP_NAME');
}
return $this->defaultOptions;
} | getDefaultOptions
Return default values including any dynamically added values
@return array | entailment |
protected function mergeDefaultOptions($options = [])
{
$defaults = $this->getDefaultOptions();
foreach (array_keys($defaults) as $key) {
if (!isset($options[$key])) {
$options[$key] = [];
}
$options[$key] += $defaults[$key];
}
return $options;
} | mergeDefaultOptions
Take the default options, merge individual array values
@param array $options
@return array | entailment |
public function getAdapter()
{
$adapter = $this->dsn->adapter;
if ($adapter !== null) {
return $adapter;
}
$scheme = $this->dsn->scheme;
if (isset(static::$adapterMap[$scheme])) {
return static::$adapterMap[$scheme];
}
return null;
} | getAdapter
If the dsn specifies an adatper, it is returned unmodified
If there is an adapter defined via the adapter map - return that
@return string | entailment |
public function toArray()
{
$raw = $this->dsn->toArray();
$allKeys = array_unique(array_merge(static::$mandatoryKeys, array_keys($raw)));
$return = [];
foreach ($allKeys as $key) {
if (isset($this->keyMap[$key])) {
$key = $this->keyMap[$key];
if (!$key) {
continue;
}
}
$val = $this->$key;
if ($val !== null) {
$return[$key] = $val;
}
}
return $return;
} | Return the array representation of this dsn
@return array | entailment |
public function keyMap($keyMap = null)
{
if (!is_null($keyMap)) {
$this->keyMap = $keyMap;
}
return $this->keyMap;
} | Get or set the key map
The key map permits translating the parsed array keys
@param mixed $keyMap
@return array | entailment |
public function replacements($replacements = null)
{
if (!is_null($replacements)) {
$this->replacements = $replacements;
}
return $this->replacements;
} | Get or set replacements
@param mixed $replacements
@return array | entailment |
protected function replace($data, $replacements = null)
{
if (!is_array($data) && !is_string($data)) {
return $data;
}
if (!$replacements) {
$replacements = $this->replacements();
if (!$replacements) {
return $data;
}
}
if (is_array($data)) {
foreach ($data as $key => &$value) {
$value = $this->replace($value, $replacements);
}
return $data;
}
return str_replace(array_keys($replacements), array_values($replacements), $data);
} | perform string replacements on a string
Accepts an array, recusively replacing string values
Does nothing to any scalar that's not string
@param array $data
@param array $replacements
@return mixed | entailment |
public function debug($value = null)
{
if ($value !== null) {
$this->debug = $value;
} elseif ($value === null && $this->debug === null) {
$this->debug = 0;
if (class_exists('\Configure')) {
$this->debug = (int) \Configure::read('debug');
}
}
return $this->debug;
} | debug
Get or set the debug value. The debug value is used to determine the default cache duration
@param mixed $value
@return void | entailment |
protected function getDefaultOptions()
{
parent::getDefaultOptions();
if (!isset($this->defaultOptions['replacements']['DURATION'])) {
$duration = $this->debug() ? '+10 seconds' : '+999 days';
$this->defaultOptions['replacements']['DURATION'] = $duration;
}
return $this->defaultOptions;
} | getDefaultOptions
Add a replacement for DURATION, conditionally set depending on debug,
@return array | entailment |
public function getEngine()
{
$adapter = $this->getAdapter();
if ($adapter) {
return $adapter;
}
return ucfirst($this->dsn->scheme);
} | getEngine
Return the adapter if there is one, else return the scheme
@return string | entailment |
public function getDriver()
{
$adapter = $this->getAdapter();
if ($adapter) {
return $adapter;
}
$engine = $this->dsn->engine;
return 'Cake\Database\Driver\\' . ucfirst($engine);
} | getDriver
Get the engine to use for this dsn. Defaults to `Cake\Database\Driver\Enginename`
@return string | entailment |
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('flows');
$rootNode
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->scalarNode('description')->isRequired()->cannotBeEmpty()->end()
->arrayNode('producer')
->children()
->scalarNode('service')->isRequired()->end()
->end()
->end()
->arrayNode('worker')
->children()
->scalarNode('service')->isRequired()->end()
->integerNode('instances')->min(1)->defaultValue(1)->end()
->integerNode('release_delay')->min(0)->defaultValue(0)->end()
->integerNode('max_retry')->min(1)->defaultValue(5)->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | Generates the configuration tree builder.
@return TreeBuilder The tree builder | entailment |
public function parse($data, $chunkSize = 1024)
{
//Ensure that the $data var is of the right type
if (!is_string($data) && (!is_resource($data) || get_resource_type($data) !== 'stream')) {
throw new Exception('Data must be a string or a stream resource');
}
//Ensure $chunkSize is the right type
if (!is_int($chunkSize)) {
throw new Exception('Chunk size must be an integer');
}
//Initialise the object
$this->init();
//Create the parser and set the parsing flag
$this->parse = TRUE;
$parser = xml_parser_create();
//Set the parser up, ready to stream through the XML
xml_set_object($parser, $this);
//Set up the protected methods _start and _end to deal with the start
//and end tags respectively
xml_set_element_handler($parser, 'start', 'end');
//Set up the _addCdata method to parse any CDATA tags
xml_set_character_data_handler($parser, 'addCdata');
//For general purpose data, use the _addData method
xml_set_default_handler($parser, 'addData');
//If the data is a resource then loop through it, otherwise just parse
//the string
if (is_resource($data)) {
//Not all resources support fseek. For those that don't, suppress
// /the error
@fseek($data, 0);
while ($this->parse && $chunk = fread($data, $chunkSize)) {
$this->parseString($parser, $chunk, feof($data));
}
} else {
$this->parseString($parser, $data, TRUE);
}
//Free up the parser
xml_parser_free($parser);
return $this;
} | Parses the XML provided using streaming and callbacks
@param mixed $data Either a stream resource or string containing XML
@param int $chunkSize The size of data to read in at a time. Only
relevant if $data is a stream
@return Parser
@throws Exception | entailment |
public function registerCallback($path, $callback)
{
//Ensure the path is a string
if (!is_string($path)) {
throw new Exception('Path must be a string');
}
//Ensure that the callback is callable
if (!is_callable($callback)) {
throw new Exception('Callback must be callable');
}
//All tags and paths are lower cased, for consistency
$path = strtolower($path);
if (substr($path, -1, 1) !== '/') {
$path .= '/';
}
//If this is the first callback for this path, initialise the variable
if (!isset($this->callbacks[$path])) {
$this->callback[$path] = array();
}
//Add the callback
$this->callbacks[$path][] = $callback;
return $this;
} | Registers a single callback for a specified XML path
@param string $path The path that the callback is for
@param callable $callback The callback mechanism to use
@return Parser
@throws Exception | entailment |
public function registerCallbacks(Array $pathCallbacks)
{
foreach ($pathCallbacks as $row) {
if (count($row) != 2) {
throw new Exception(
'Each array element in $pathCallbacks must be an array of'
.' 2 elements (the path and the callback)'
);
}
list($path, $callback) = $row;
$this->registerCallback($path, $callback);
}
return $this;
} | Registers multiple callbacks for the specified paths, for example
<code>
$parser->registerCallbacks(array(
array('/path/to/element', 'callback'),
array('/path/to/another/element', array($this, 'callback')),
));
</code>
@param Array $pathCallbacks An array of paths and callbacks
@return Parser
@throws Exception | entailment |
protected function init()
{
$this->namespaces = array();
$this->currentPath = '/';
$this->pathData = array();
$this->parse = FALSE;
} | Initialise the object variables
@return NULL | entailment |
protected function parseString($parser, $data, $isFinal)
{
if (!xml_parse($parser, $data, $isFinal)) {
throw new Exception(
xml_error_string(xml_get_error_code($parser))
.' At line: '.
xml_get_current_line_number($parser)
);
}
return $parser;
} | Parse data using xml_parse
@param resource $parser The XML parser
@param string $data The data to parse
@param boolean $isFinal Whether or not this is the final part to parse
@return NULL
@throws Exception | entailment |
protected function start($parser, $tag, $attributes)
{
//Set the tag as lower case, for consistency
$tag = strtolower($tag);
//Update the current path
$this->currentPath .= $tag.'/';
$this->fireCurrentAttributesCallbacks($attributes);
//Go through each callback and ensure that path data has been
//started for it
foreach ($this->callbacks as $path => $callbacks) {
if ($path === $this->currentPath) {
$this->pathData[$this->currentPath] = '';
}
}
//Generate the tag, with attributes. Attribute names are also lower
//cased, for consistency
$data = '<'.$tag;
foreach ($attributes as $key => $val) {
$options = ENT_QUOTES;
if (defined('ENT_XML1')) {
$options |= ENT_XML1;
}
$val = htmlentities($val, $options, "UTF-8");
$data .= ' '.strtolower($key).'="'.$val.'"';
if (stripos($key, 'xmlns:') !== false) {
$key = strtolower($key);
$key = str_replace('xmlns:', '', $key);
$this->namespaces[strtolower($key)] = $val;
}
}
$data .= '>';
//Add the data to the path data required
$this->addData($parser, $data);
return $parser;
} | Parses the start tag
@param resource $parser The XML parser
@param string $tag The tag that's being started
@param array $attributes The attributes on this tag
@return NULL | entailment |
protected function addData($parser, $data)
{
//Having a path data entry means at least 1 callback is interested in
//the data. Loop through each path here and, if inside that path, add
//the data
foreach ($this->pathData as $key => $val) {
if (strpos($this->currentPath, $key) !== FALSE) {
$this->pathData[$key] .= $data;
}
}
return $parser;
} | Adds data to any paths that require it
@param resource $parser
@param string $data
@return NULL | entailment |
protected function end($parser, $tag)
{
//Make the tag lower case, for consistency
$tag = strtolower($tag);
//Add the data to the paths that require it
$data = '</'.$tag.'>';
$this->addData($parser, $data);
//Loop through each callback and see if the path matches the
//current path
foreach ($this->callbacks as $path => $callbacks) {
//If parsing should continue, and the paths match, then a callback
//needs to be made
if ($this->parse && $this->currentPath === $path) {
if (!$this->fireCallbacks($path, $callbacks)) {
break;
}
}
}
//Unset the path data for this path, as it's no longer needed
unset($this->pathData[$this->currentPath]);
//Update the path with the new path (effectively moving up a directory)
$this->currentPath = substr(
$this->currentPath,
0,
strlen($this->currentPath) - (strlen($tag) + 1)
);
return $parser;
} | Parses the end of a tag
@param resource $parser
@param string $tag
@return NULL | entailment |
protected function fireCallbacks($path, array $callbacks)
{
$namespaceStr = '';
$namespaces = $this->namespaces;
$matches = array();
$pathData = $this->pathData[$path];
$regex = '/xmlns:(?P<namespace>[^=]+)="[^\"]+"/sm';
// Make sure any namespaces already defined in this element are not
// defined again
if (preg_match_all($regex, $pathData, $matches)) {
foreach ($matches['namespace'] as $key => $value) {
unset($namespaces[$value]);
}
}
// Define all remaining namespaces on the root element
foreach ($namespaces as $key => $val) {
$namespaceStr .= ' xmlns:'.$key.'="'.$val.'"';
}
//Build the SimpleXMLElement object. As this is a partial XML
//document suppress any warnings or errors that might arise
//from invalid namespaces
$data = new SimpleXMLElement(
preg_replace('/^(<[^\s>]+)/', '$1'.$namespaceStr, $pathData),
LIBXML_COMPACT | LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NOCDATA
);
//Loop through each callback. If one of them stops the parsing
//then cease operation immediately
foreach ($callbacks as $callback) {
call_user_func_array($callback, array($this, $data));
if (!$this->parse) {
return false;
}
}
return true;
} | Generates a SimpleXMLElement and passes it to each of the callbacks
@param string $path The path to create the SimpleXMLElement from
@param array $callbacks An array of callbacks to be fired.
@return boolean | entailment |
protected function fireCurrentAttributesCallbacks($attributes)
{
foreach ($attributes as $key => $val) {
$path = $this->currentPath . '@' . strtolower($key) . '/';
if (isset($this->callbacks[$path])) {
foreach ($this->callbacks[$path] as $callback) {
call_user_func_array($callback, array($this, $val));
}
}
}
} | Traverses the passed attributes, assuming the currentPath, and invokes registered callbacks,
if there are any
@param array $attributes Key-value map for the current element
@return void | entailment |
public function find(Composer $composer, NpmBridge $bridge): array
{
$packages = $composer->getRepositoryManager()->getLocalRepository()
->getPackages();
$dependantPackages = [];
foreach ($packages as $package) {
if ($bridge->isDependantPackage($package, false)) {
$dependantPackages[] = $package;
}
}
return $dependantPackages;
} | Find all NPM bridge enabled vendor packages.
@param Composer $composer The Composer object for the root project.
@param NpmBridge $bridge The bridge to use.
@return array<integer,PackageInterface> The list of NPM bridge enabled vendor packages. | entailment |
public function translate(array $tokens)
{
$this->operatorStack = new SplStack();
$this->outputQueue = new SplQueue();
foreach($tokens as $token) {
switch ($token->getType()) {
case Token::T_OPERAND:
$this->outputQueue->enqueue($token);
break;
case Token::T_OPERATOR:
$o1 = $token;
while($this->hasOperatorInStack()
&& ($o2 = $this->operatorStack->top())
&& $o1->hasLowerPriority($o2))
{
$this->outputQueue->enqueue($this->operatorStack->pop());
}
$this->operatorStack->push($o1);
break;
case Token::T_LEFT_BRACKET:
$this->operatorStack->push($token);
break;
case Token::T_RIGHT_BRACKET:
while((!$this->operatorStack->isEmpty()) && (Token::T_LEFT_BRACKET != $this->operatorStack->top()->getType())) {
$this->outputQueue->enqueue($this->operatorStack->pop());
}
if($this->operatorStack->isEmpty()) {
throw new InvalidArgumentException(sprintf('Mismatched parentheses: %s', implode(' ',$tokens)));
}
$this->operatorStack->pop();
break;
default:
throw new InvalidArgumentException(sprintf('Invalid token detected: %s', $token));
break;
}
}
while($this->hasOperatorInStack()) {
$this->outputQueue->enqueue($this->operatorStack->pop());
}
if(!$this->operatorStack->isEmpty()) {
throw new InvalidArgumentException(sprintf('Mismatched parenthesis or misplaced number: %s', implode(' ',$tokens)));
}
return iterator_to_array($this->outputQueue);
} | Translate array sequence of tokens from infix to
Reverse Polish notation (RPN) which representing mathematical expression.
@param array $tokens Collection of Token intances
@return array Collection of Token intances
@throws InvalidArgumentException | entailment |
private function hasOperatorInStack()
{
$hasOperatorInStack = false;
if(!$this->operatorStack->isEmpty()) {
$top = $this->operatorStack->top();
if(Token::T_OPERATOR == $top->getType()) {
$hasOperatorInStack = true;
}
}
return $hasOperatorInStack;
} | Determine if there is operator token in operato stack
@return boolean | entailment |
public function createCommitXml($expungeDeletes = false, $waitFlush = true, $waitSearcher = true, $timeout = 3600, $softCommit = false)
{
$expungeValue = $expungeDeletes ? 'true' : 'false';
$searcherValue = $waitSearcher ? 'true' : 'false';
$softCommitValue = $softCommit ? 'true' : 'false';
$rawPost = '<commit expungeDeletes="' . $expungeValue . '" softCommit="' . $softCommitValue . '" waitSearcher="' . $searcherValue . '" />';
return $rawPost;
} | Creates a commit command XML string.
@param boolean $expungeDeletes Defaults to false, merge segments with deletes away
@param boolean $waitFlush Defaults to true, is ignored.
@param boolean $waitSearcher Defaults to true, block until a new searcher is opened and registered as the main query searcher, making the changes visible.
@param float $timeout Maximum expected duration (in seconds) of the commit operation on the server (otherwise, will throw a communication exception). Defaults to 1 hour
@param boolean $softCommit Defaults to false, perform a soft commit instead of a hard commit.
@return string An XML string | entailment |
public function createOptimizeXml($waitFlush = true, $waitSearcher = true)
{
$searcherValue = $waitSearcher ? 'true' : 'false';
$rawPost = '<optimize waitSearcher="' . $searcherValue . '" />';
return $rawPost;
} | Creates an optimize command XML string.
@param boolean $waitFlush Is ignored.
@param boolean $waitSearcher
@param float $timeout Maximum expected duration of the commit operation on the server (otherwise, will throw a communication exception)
@return string An XML string | entailment |
public function createAddDocumentXmlFragment(
$rawDocuments,
$allowDups = false,
$overwritePending = true,
$overwriteCommitted = true,
$commitWithin = 0
) {
$dupValue = !$allowDups ? 'true' : 'false';
$commitWithin = (int) $commitWithin;
$commitWithinString = $commitWithin > 0 ? " commitWithin=\"{$commitWithin}\"" : '';
$addXmlFragment = "<add overwrite=\"{$dupValue}\"{$commitWithinString}>";
$addXmlFragment .= $rawDocuments;
$addXmlFragment .= '</add>';
return $addXmlFragment;
} | Creates an add command XML string
@param string $rawDocuments String containing XML representation of documents.
@param boolean $allowDups
@param boolean $overwritePending
@param boolean $overwriteCommitted
@param integer $commitWithin The number of milliseconds that a document must be committed within,
see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details. If left empty
this property will not be set in the request.
@return string An XML string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.