sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getWhere($column, $value, array $options = [])
{
$query = $this->createBaseBuilder($options);
$query->where($column, $value);
return $query->get();
} | Get resources by a where clause
@param string $column
@param mixed $value
@param array $options
@return Collection | entailment |
public function getWhereArray(array $clauses, array $options = [])
{
$query = $this->createBaseBuilder($options);
$this->applyWhereArray($query, $clauses);
return $query->get();
} | Get resources by multiple where clauses
@param array $clauses
@param array $options
@deprecated
@return Collection | entailment |
public function getWhereIn($column, array $values, array $options = [])
{
$query = $this->createBaseBuilder($options);
$query->whereIn($column, $values);
return $query->get();
} | Get resources where a column value exists in array
@param string $column
@param array $values
@param array $options
@return Collection | entailment |
public function delete($id)
{
$query = $this->createQueryBuilder();
$query->where($this->getPrimaryKey($query), $id);
$query->delete();
} | Delete a resource by its primary key
@param mixed $id
@return void | entailment |
public function deleteWhere($column, $value)
{
$query = $this->createQueryBuilder();
$query->where($column, $value);
$query->delete();
} | Delete resources by a where clause
@param string $column
@param mixed $value
@return void | entailment |
public function deleteWhereArray(array $clauses)
{
$query = $this->createQueryBuilder();
$this->applyWhereArray($query, $clauses);
$query->delete();
} | Delete resources by multiple where clauses
@param array $clauses
@return void | entailment |
protected function createBaseBuilder(array $options = [])
{
$query = $this->createQueryBuilder();
$this->applyResourceOptions($query, $options);
if (empty($options['sort'])) {
$this->defaultSort($query, $options);
}
return $query;
} | Creates a new query builder with Optimus options set
@param array $options
@return Builder | entailment |
protected function defaultSort(Builder $query, array $options = [])
{
if (isset($this->sortProperty)) {
$direction = $this->sortDirection === 1 ? 'DESC' : 'ASC';
$query->orderBy($this->sortProperty, $direction);
}
} | Order query by the specified sorting property
@param Builder $query
@param array $options
@return void | entailment |
public function get(int $seriesId): Series
{
$json = $this->client->performApiCallWithJsonResponse('get', '/series/' . (int) $seriesId);
return ResponseHandler::create($json, ResponseHandler::METHOD_SERIES)->handle();
} | Returns a series record that contains all information known about a particular series ID.
@param int $seriesId
@return Series
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidJsonInResponseException
@throws InvalidArgumentException | entailment |
public function getActors(int $seriesId): SeriesActors
{
$json = $this->client->performApiCallWithJsonResponse('get', sprintf('/series/%d/actors', (int) $seriesId));
return ResponseHandler::create($json, ResponseHandler::METHOD_SERIES_ACTORS)->handle();
} | Returns actors for the given series ID.
@param int $seriesId
@return SeriesActors
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidJsonInResponseException
@throws InvalidArgumentException | entailment |
public function getEpisodes(int $seriesId, int $page = null): SeriesEpisodes
{
$options = [
'query' => [
'page' => $page === null ? 1 : (int) $page,
],
];
$json = $this->client->performApiCallWithJsonResponse(
'get',
sprintf('/series/%d/episodes', (int) $seriesId),
$options
);
return ResponseHandler::create($json, ResponseHandler::METHOD_SERIES_EPISODES)->handle();
} | All episodes for a given series. Paginated with 100 results per page.
@param int $seriesId
@param int|null $page
@return SeriesEpisodes
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidJsonInResponseException
@throws InvalidArgumentException | entailment |
public function getImagesWithQuery(int $seriesId, array $query): SeriesImageQueryResults
{
$options = [
'query' => $query
];
$json = $this->client->performApiCallWithJsonResponse(
'get',
sprintf('/series/%d/images/query', (int) $seriesId),
$options
);
return ResponseHandler::create($json, ResponseHandler::METHOD_SERIES_IMAGES_QUERY)->handle();
} | E.g.: $query = [
'keyType' => 'fanart',
'resolution' => '1920x1080',
'subKey' => 'graphical'
]
@param int $seriesId
@param array $query
@return SeriesImageQueryResults
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidJsonInResponseException
@throws InvalidArgumentException | entailment |
public function remove($files)
{
foreach ($files as $file) {
try {
$this->filesystem->delete($file);
}
catch (Exception $e) {
// Ignore not found exceptions
}
}
} | Remove an attached file.
@param array $files | entailment |
public function move($source, $target)
{
// Save file
$this->filesystem->put(
$target, file_get_contents($source), $this->media->visibility
);
} | Move an uploaded file to it's intended target.
@param string $source
@param string $target
@return void | entailment |
public function requestHeaders(string $method, string $path, array $options = []): array
{
$options = $this->getDefaultHttpClientOptions($options);
/** @type Response $response */
$response = $this->httpClient->{$method}($path, $options);
return $response->getHeaders();
} | {@inheritdoc} | entailment |
public function performApiCallWithJsonResponse(string $method, string $path, array $options = []): string
{
$response = $this->performApiCall($method, $path, $options);
if ($response->getStatusCode() === 200) {
try {
$contents = $response->getBody()->getContents();
} catch (\RuntimeException $e) {
$contents = '';
}
return $contents;
}
throw new Exception\RequestFailedException(
sprintf(
'Got status code %d from service at path %s',
$response->getStatusCode(),
$path
)
);
} | {@inheritdoc} | entailment |
public function performApiCall(string $method, string $path, array $options = []): Response
{
$options = $this->getDefaultHttpClientOptions($options);
/** @type Response $response */
$response = $this->httpClient->{$method}($path, $options);
if ($response->getStatusCode() === 401) {
throw Exception\UnauthorizedException::invalidToken();
}
if ($response->getStatusCode() === 404) {
$parameters = array_key_exists('query', $options) ? $options['query'] : [];
throw Exception\ResourceNotFoundException::withPath($path, $parameters);
}
return $response;
} | {@inheritdoc} | entailment |
public static function bootHasMediaTrait()
{
static::saved(function ($instance) {
foreach ($instance->getMediaFiles() as $mediaFile) {
$mediaFile->afterSave($instance);
}
});
static::deleting(function ($instance) {
if ($instance->canDeleteMedia()) {
foreach ($instance->getMediaFiles() as $mediaFile) {
$mediaFile->beforeDelete($instance);
}
}
});
static::deleted(function ($instance) {
if ($instance->canDeleteMedia()) {
foreach ($instance->getMediaFiles() as $mediaFile) {
$mediaFile->afterDelete($instance);
}
}
});
} | Register eloquent event handlers.
We'll spin through each of the media file defined on this class
and register callbacks for the events we need to observe in order to
handle file uploads.
@return void | entailment |
public function getQueuedAttachments()
{
$queued = [];
foreach ($this->getMediaFiles() as $name => $attachment) {
if ($attachment->isQueued()) {
$queued[$name] = $attachment;
}
}
return $queued;
} | Return all queued attachments that need processing.
@return array | entailment |
public function getAttribute($key)
{
if (array_key_exists($key, $this->getMediaFiles())) {
return $this->media_files[$key];
}
return parent::getAttribute($key);
} | Handle the dynamic retrieval of media items.
@param string $key
@return mixed | entailment |
public function setAttribute($key, $value)
{
if (array_key_exists($key, $this->getMediaFiles())) {
if ($value) {
$this->media_files[$key]
->setUploadedFile($value, $key);
}
return $this;
}
return parent::setAttribute($key, $value);
} | Handle the dynamic setting of media items.
@param string $key
@param mixed $value
@return $this | entailment |
protected function registerMedia($name, $options)
{
$this->media_files[$name] = new Manager($name, $this->mergeOptions($options));
$this->media_files[$name]->setInstance($this);
} | Register an media type and add the media to the
list of media to be processed during saving.
@param string $name
@param array $options
@return void
@throws Exception | entailment |
protected function mergeOptions($options)
{
$options = array_merge(config('mediasort', []), (array)$options);
$options['styles'] = array_merge((array)$options['styles'], ['original' => '']);
return $options;
} | Merge configuration options.
Here we'll merge user defined options with the MediaSort defaults in a cascading manner.
We start with overall MediaSort options. Next we merge in storage driver specific options.
Finally we'll merge in media specific options on top of that.
@param array $options
@return array | entailment |
public function get($episodeId): Episode
{
$json = $this->client->performApiCallWithJsonResponse('get', '/episodes/' . (int) $episodeId);
return ResponseHandler::create($json, ResponseHandler::METHOD_EPISODE)->handle();
} | Returns the full information for a given episode ID.
@param int $episodeId
@return Episode
@throws RequestFailedException
@throws UnauthorizedException
@throws InvalidJsonInResponseException
@throws InvalidArgumentException | entailment |
public function refresh($class, $media)
{
if (method_exists($class, 'hasMediaFile') === false) {
throw new InvalidClassException("Invalid class: the {$class} class is not currently using MediaSort.", 1);
}
// Get model
$models = app($class)->all();
if ($media) {
$media = explode(',', str_replace(', ', ',', $media));
$this->processSomeFiles($models, $media);
return;
}
$this->processAllFiles($models);
} | Attempt to refresh the defined attachments on a particular model.
@param string $class
@param array $media
@throws \Torann\MediaSort\Exceptions\InvalidClassException | entailment |
protected function processSomeFiles($models, $media)
{
foreach ($models as $model) {
foreach ($model->getMediaFiles() as $file) {
if (in_array($file->name, $media)) {
$file->reprocess();
}
}
}
} | Process a only a specified subset of MediaSort files.
@param array $media
@return void | entailment |
protected function processAllFiles($models)
{
foreach ($models as $model) {
foreach ($model->getMediaFiles() as $file) {
$file->reprocess();
}
}
} | Process all MediaSort attachments defined on a class.
@return void | entailment |
public function setUploadedFile($file)
{
// If set, this just clears the image.
if ($file == MEDIASORT_NULL) {
$this->clear();
return;
}
// Determine if this attachment should be processed
// now or later using queued job.
if ($this->isQueueable()) {
$this->queueUploadedFile($file);
}
// Standard upload, nothing fancy here.
else {
$this->addUploadedFile($file);
}
} | Mutator method for the uploadedFile property.
@param mixed $file
@return void | entailment |
protected function queueUploadedFile($file)
{
// Get the real path of the file
$file = $this->getFileManager()
->make($file)
->getRealPath();
// Create the unique directory name and file to save into
$file_target = $this->joinPaths(
str_replace('.', '-', uniqid(rand(), true)),
basename($file)
);
// Parse the queue path
$queue_path = $this->getInterpolator()->interpolate(
$this->config('queue_path')
);
// Determine if the path is locale and just simple move it,
// otherwise use the disk driver to move the attachment.
if ($local_path = realpath($queue_path)) {
$target = $this->joinPaths($local_path, $file_target);
// Ensure the target directory exists
if (is_dir(dirname($target)) === false) {
mkdir(dirname($target), 0777, true);
}
// Move the file
rename($file, $target);
}
else {
$this->move(
$file, $this->joinPaths($queue_path, $file_target)
);
}
// Save the information for later
$this->instanceWrite('queue_state', self::QUEUE_WAITING);
$this->instanceWrite('queued_file', $file_target);
} | Mutator method for the uploadedFile property.
@param mixed $file
@return void | entailment |
protected function addUploadedFile($file)
{
$this->clear();
$this->uploaded_file = $this->getFileManager()->make($file);
// Get the original values
$filename = $this->uploaded_file->getClientOriginalName();
$content_type = $this->uploaded_file->getMimeType();
// Set model values
$this->instanceWrite('file_name', $filename);
$this->instanceWrite('file_size', $this->uploaded_file->getSize());
$this->instanceWrite('content_type', $content_type);
$this->instanceWrite('updated_at', date('Y-m-d H:i:s'));
$this->instanceWrite('queued_file', null);
// Queue all styles for writing
$this->setQueue('write', $this->styles);
} | Mutator method for the uploadedFile property.
@param mixed $file
@return void | entailment |
public function getDisk()
{
if ($this->disk_instance === null) {
// Create disk class
$class = "\\Torann\\MediaSort\\Disks\\" . ucfirst($this->config('disk'));
// Verify disk
if (class_exists($class) === false) {
throw new InvalidClassException("Disk type \"{$class}\" not found.");
}
// Create disk instance
$this->disk_instance = Container::getInstance()->makeWith($class, ['media' => $this]);
}
return $this->disk_instance;
} | Get disk instance.
@return \Torann\MediaSort\Disks\AbstractDisk
@throws \Torann\MediaSort\Exceptions\InvalidClassException | entailment |
public function setConfig($config)
{
$this->config = $config;
// Sanity check
if (strpos($this->config['url'], '{id}') === false) {
throw new Exception('Invalid Url: an id interpolation is required.', 1);
}
// Set media disk
$this->config['disk'] = Arr::get(
$this->config, 'disk', config('filesystems.default', 'local')
);
} | Mutator method for the config property.
@param array $config
@return void
@throws Exception | entailment |
public function setQueue($queue, $value)
{
// Ensure the value is an array
if (is_array($value) === false) {
$value = [$value];
}
$this->queues[$queue] = array_merge(
$this->getQueue($queue), $value
);
} | Set an item to be queued.
@param string $queue
@param string|array $value | entailment |
public function url($style = '')
{
if ($this->isQueued()) {
return $this->loadingUrl($style);
}
if ($this->getAttribute('filename')) {
if ($path = $this->path($style)) {
return $this->config('prefix_url') . $path;
}
}
return $this->defaultUrl($style);
} | Generates the url to a file upload.
@param string $style
@return string | entailment |
public function toArray($skip_empty = false, $include_original = true)
{
// Skip when no media
if ($skip_empty === true && $this->hasMedia() === false) {
return null;
}
$urls = [];
foreach ($this->styles as $name => $style) {
if ($include_original === false
&& $this->config('default_style') === $name
) {
continue;
}
$urls[$name] = $this->url($name);
}
return $urls;
} | Generates an array of all style urls.
@param bool $skip_empty
@param bool $include_original
@return array|null | entailment |
public function path($style = '')
{
if ($this->getAttribute('filename')) {
return $this->getInterpolator()->interpolate($this->url, $style);
}
return '';
} | Generates the filesystem path to an uploaded file.
@param string $style
@return string | entailment |
public function getAttribute($key)
{
// Sanitize the key
$key = preg_replace('/^_/', '', $key);
// Decoder ring for legacy keys
switch ($key) {
case 'size':
$key = 'file_size';
break;
case 'filename':
case 'original_filename':
$key = 'file_name';
break;
}
return $this->getInstance()
->getAttribute("{$this->name}_{$key}");
} | Return the attachment attribute value.
@param string $key
@return mixed | entailment |
public function getQueuedFilePath()
{
return $this->getInterpolator()->interpolate(
$this->joinPaths(
$this->config('queue_path'),
$this->getAttribute('queued_file')
)
);
} | Get the queued file path.
@return string | entailment |
public function reprocess()
{
if (empty($this->getAttribute('filename'))) {
return;
}
foreach ($this->styles as $name => $style) {
if (empty($file = $this->path($name))) {
continue;
}
$file = $this->getFileManager()->make($file);
if ($style && $file->isImage()) {
$file = $this->getResizer()
->resize($file, $style);
}
else {
$file = $file->getRealPath();
}
$filePath = $this->path($name);
$this->move($file, $filePath);
}
} | Rebuild the images for this attachment.
@return void | entailment |
public function processQueue(Model $instance, $path = null, bool $cleanup = true)
{
$this->setInstance($instance);
// Determine the path to use
$path = $path ?: $this->getQueuedFilePath();
// Set the file for processing
$this->addUploadedFile($path);
// Start processing the file
$this->save();
// Save all updated model attributes
$this->getInstance()->save();
// TODO: also remove non-local files
// Remove queued file locally
if ($cleanup === true && realpath($path) !== false) {
@unlink($path);
@rmdir(dirname($path));
}
} | Trigger queued files for processing.
@param Model $instance
@param string $path
@param bool $cleanup
@return void | entailment |
protected function flushWrites()
{
// Skip this if there is no queued write items
if (count($this->getQueue('write')) === 0) {
return;
}
// Update the state of the queued attachment
$this->updateQueueState(self::QUEUE_WORKING);
foreach ($this->getQueue('write') as $name => $style) {
if ($style && $this->uploaded_file->isImage()) {
$file = $this->getResizer()
->resize($this->uploaded_file, $style);
}
else {
$file = $this->uploaded_file->getRealPath();
}
// Only move it real
if ($filePath = $this->path($name)) {
$this->move($file, $filePath);
}
}
$this->resetQueue('write');
// Update the state of the queued attachment
$this->updateQueueState(self::QUEUE_DONE);
} | Process the queued for writes.
@return void | entailment |
public function getQueuedStateText()
{
switch ((int)$this->getAttribute('queue_state')) {
case self::QUEUE_NA:
return '';
case self::QUEUE_DONE:
return 'done';
case self::QUEUE_WAITING:
return 'waiting';
case self::QUEUE_WORKING:
return 'working';
default:
return 'unknown';
}
} | Get queue state text.
@return string | entailment |
public function updateQueueState(int $state)
{
if ($this->isQueueable()) {
$this->getInstance()
->getConnection()
->table($this->getInstance()->getTable())
->where($this->getInstance()->getQualifiedKeyName(), $this->getInstance()->getKey())
->update([
"{$this->name}_queue_state" => $state,
]);
}
} | Use the model's connecting and table to quickly update the queue state and
bypass the save event in the model to prevent an event loop.
@param int $state
@return void | entailment |
protected function defaultUrl($style = '')
{
if ($this->config('default_url')) {
$url = $this->getInterpolator()->interpolate($this->config('default_url'), $style);
return parse_url($url, PHP_URL_HOST) ? $url : $this->config('prefix_url') . $url;
}
return '';
} | Generates the default url if no file attachment is present.
@param string $style
@return string | entailment |
protected function queueSomeForDeletion($styles)
{
$filePaths = array_map(function ($style) {
return $this->path($style);
}, $styles);
$this->setQueue('deletion', $filePaths);
} | Add a subset (filtered via style) of the uploaded files for this attachment
to the queuedForDeletion queue.
@param array $styles
@return void | entailment |
protected function queueAllForDeletion()
{
if (empty($this->getAttribute('filename'))) {
return;
}
// Remove old files
if ($this->config('preserve_files', false) === false) {
foreach ($this->styles as $name => $style) {
$this->setQueue('deletion', $this->path($name));
}
}
// Set model attributes
$this->instanceWrite('file_name', null);
$this->instanceWrite('file_size', null);
$this->instanceWrite('content_type', null);
$this->instanceWrite('updated_at', null);
$this->instanceWrite('queue_state', self::QUEUE_DONE);
$this->instanceWrite('queued_file', null);
} | Add all uploaded files (across all image styles) to the queuedForDeletion queue.
@return void | entailment |
protected function instanceWrite($property, $value)
{
$field = "{$this->name}_{$property}";
// This is not fillable as it is the one required attribute
if ($property === 'file_name') {
$this->getInstance()->setAttribute($field, $value);
}
// Queue state is optional and outside of the fillable
elseif (preg_match('/^queue(d?)_/', $property)) {
if ($this->isQueueable()) {
$this->getInstance()->setAttribute($field, $value);
}
}
// All other attributes must be fillable to have their values set
else {
if (in_array($field, $this->getInstance()->getFillable())) {
$this->getInstance()->setAttribute($field, $value);
}
}
} | Set an attachment attribute on the underlying model instance.
@param string $property
@param mixed $value
@return void | entailment |
public function getFileManager()
{
if ($this->file_manager_instance === null) {
$this->file_manager_instance = new FileManager($this);
}
return $this->file_manager_instance;
} | Get the file manager instance.
@return FileManager | entailment |
public function getResizer()
{
$options = [
'image_quality' => $this->config('image_quality'),
'auto_orient' => $this->config('auto_orient'),
'color_palette' => $this->config('color_palette'),
];
return new Resizer(
$this->config('image_processor'), $options
);
} | Get the resizer instance.
@return Resizer | entailment |
public function handle()
{
$this->info('Refreshing uploaded images...');
$this->imageRefreshService->refresh($this->argument('class'), $this->option('attachments'));
$this->info('Done!');
} | Execute the console command.
@return void | entailment |
protected function _getCachedOrRender($viewFileName) {
$path = str_replace(APP, '', $viewFileName);
$prefix = Configure::read('Cache.prefix');
if ($prefix) {
$path = $prefix . '_' . $path;
}
$cacheFolder = CACHE . 'views' . DS;
if (Configure::read('debug') && !is_dir($cacheFolder)) {
mkdir($cacheFolder, 0770, true);
}
$cacheFile = $cacheFolder . Inflector::slug($path);
if (file_exists($cacheFile)) {
$cacheContent = $this->extractCacheContent($cacheFile);
$cacheTime = $cacheContent['time'];
if ($cacheTime < time() && $cacheTime !== 0) {
unlink($cacheFile);
} else {
return $cacheContent['content'];
}
}
$content = $this->_render($viewFileName);
$content = $this->_compress($content);
$cacheContent = '<!--cachetime:' . (int)$this->_duration . '-->' . $content;
file_put_contents($cacheFile, $cacheContent);
return $content;
} | @param string $viewFileName
@return string | entailment |
protected function extractCacheContent($file) {
$content = (string)file_get_contents($file);
$cacheTime = 0;
$content = preg_replace_callback('/^\<\!--cachetime\:(\d+)--\>/', function ($matches) use (&$cacheTime) {
$cacheTime = (int)$matches[1];
return '';
}, $content);
if (Configure::read('debug')) {
$modifiedTime = date('Y-m-d H:i:s', filemtime($file));
$content = '<!--created:' . $modifiedTime . '-->' . $content . '<!--end-->';
}
return [
'content' => $content,
'time' => $cacheTime
];
} | @param string $file
@return array | entailment |
public function getOptionParser() {
$parser = parent::getOptionParser();
$infoParser = $parser->toArray();
$infoParser['arguments']['url'] = [
'help' => 'Absolute URL',
'required' => false
];
$parser->description('Cache Shell to cleanup caching of view files.')
->addSubcommand('status', [
'help' => 'Status information about the files',
'parser' => $infoParser,
])
->addSubcommand('clear', [
'help' => 'Clear all or part of the files',
'parser' => $parser
]);
return $parser;
} | Gets the option parser instance and configures it.
@return \Cake\Console\ConsoleOptionParser | entailment |
public function getFile($url, $mustExist = true) {
if ($url === '/') {
$url = '_root';
}
$path = $url;
$prefix = Configure::read('Cache.prefix');
if ($prefix) {
$path = $prefix . '_' . $path;
}
if ($url !== '_root') {
$path = Inflector::slug($path);
}
$folder = CACHE . 'views' . DS;
$file = $folder . $path . '.html';
if ($mustExist && !file_exists($file)) {
return null;
}
return $file;
} | @param string $url
@param bool $mustExist
@return string | entailment |
public function extractCacheInfo(&$content) {
if ($this->_cacheInfo) {
return $this->_cacheInfo;
}
$cacheTime = 0;
$cacheExt = 'html';
$this->_cacheContent = preg_replace_callback('/^\<\!--cachetime\:(\d+);ext\:(\w+)--\>/', function ($matches) use (&$cacheTime, &$cacheExt) {
$cacheTime = $matches[1];
$cacheExt = $matches[2];
return '';
}, $this->_cacheContent);
$this->_cacheInfo = [
'time' => (int)$cacheTime,
'ext' => $cacheExt
];
return $this->_cacheInfo;
} | @param string $content
@return array Time/Ext | entailment |
protected function extractCacheContent($file) {
if ($this->_cacheContent !== null) {
return $this->_cacheContent;
}
$this->_cacheContent = (string)file_get_contents($file);
return $this->_cacheContent;
} | @param string $file
@return string | entailment |
protected function _deliverCacheFile(Request $request, Response $response, $file, $ext) {
$compressionEnabled = $response->compress();
if ($response->type() === $ext) {
$contentType = 'application/octet-stream';
$agent = $request->env('HTTP_USER_AGENT');
if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
$contentType = 'application/octetstream';
}
$response = $response->withType($contentType);
}
if (!$compressionEnabled) {
$response = $response->withHeader('Content-Length', (string)filesize($file));
}
$cacheContent = $this->_cacheContent;
$cacheInfo = $this->_cacheInfo;
$modifiedTime = filemtime($file);
$cacheTime = $cacheInfo['time'];
if (!$cacheTime) {
$cacheTime = $this->config('cacheTime');
}
$response = $response->withCache($modifiedTime, $cacheTime);
$response = $response->withType($cacheInfo['ext']);
if (Configure::read('debug') || $this->config('debug')) {
if ($cacheInfo['ext'] === 'html') {
$cacheContent = '<!--created:' . date('Y-m-d H:i:s', $modifiedTime) . '-->' . $cacheContent;
}
}
$body = $response->getBody();
$body->write($cacheContent);
return $response->withBody($body);
} | Sends an asset file to the client
@param \Cake\Http\ServerRequest $request The request object to use.
@param \Cake\Http\Response $response The response object to use.
@param string $file Path to the asset file in the file system
@param string $ext The extension of the file to determine its mime type
@return \Cake\Http\Response | entailment |
public function beforeDispatch(Event $event) {
if (Configure::read('Cache.check') === false) {
return null;
}
/** @var \Cake\Network\Request $request */
$request = $event->data['request'];
$url = $request->here();
$url = str_replace($request->base, '', $url);
$file = $this->getFile($url);
if ($file === null) {
return null;
}
$cacheContent = $this->extractCacheContent($file);
$cacheInfo = $this->extractCacheInfo($cacheContent);
$cacheTime = $cacheInfo['time'];
if ($cacheTime < time() && $cacheTime != 0) {
unlink($file);
return null;
}
/** @var \Cake\Http\Response $response */
$response = $event->data['response'];
$event->stopPropagation();
$response->modified(filemtime($file));
if ($response->checkNotModified($request)) {
return $response;
}
$pathSegments = explode('.', $file);
$ext = array_pop($pathSegments);
$this->_deliverCacheFile($request, $response, $file, $ext);
return $response;
} | Checks if a requested cache file exists and sends it to the browser
@param \Cake\Event\Event $event containing the request and response object
@return \Cake\Http\Response|null Response if the client is requesting a recognized cache file, null otherwise | entailment |
protected function _deliverCacheFile(Request $request, Response $response, $file, $ext) {
$compressionEnabled = $response->compress();
if ($response->type($ext) === $ext) {
$contentType = 'application/octet-stream';
$agent = $request->env('HTTP_USER_AGENT');
if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
$contentType = 'application/octetstream';
}
$response->type($contentType);
}
if (!$compressionEnabled) {
$response->header('Content-Length', filesize($file));
}
$cacheContent = $this->_cacheContent;
$cacheInfo = $this->_cacheInfo;
$modifiedTime = filemtime($file);
$cacheTime = $cacheInfo['time'];
if (!$cacheTime) {
$cacheTime = $this->_cacheTime;
}
$response->cache($modifiedTime, $cacheTime);
$response->type($cacheInfo['ext']);
if (Configure::read('debug') || $this->config('debug')) {
if ($cacheInfo['ext'] === 'html') {
$cacheContent = '<!--created:' . date('Y-m-d H:i:s', $modifiedTime) . '-->' . $cacheContent;
}
}
$response->body($cacheContent);
} | Sends an asset file to the client
@param \Cake\Network\Request $request The request object to use.
@param \Cake\Http\Response $response The response object to use.
@param string $file Path to the asset file in the file system
@param string $ext The extension of the file to determine its mime type
@return void | entailment |
protected function _writeFile($content, $duration) {
//$cacheTime = date('Y-m-d H:i:s', $timestamp);
$now = time();
if (!$duration) {
$cacheTime = 0;
} elseif (is_numeric($duration)) {
$cacheTime = $now + $duration;
} else {
$cacheTime = strtotime($duration, $now);
}
$url = $this->request->here();
$url = str_replace($this->request->base, '', $url);
if ($url === '/') {
$url = '_root';
}
$cache = $url;
$prefix = Configure::read('Cache.prefix');
if ($prefix) {
$cache = $prefix . '_' . $url;
}
if ($url !== '_root') {
$cache = Inflector::slug($cache);
}
if (empty($cache)) {
return false;
}
$ext = $this->response->mapType($this->response->type());
$content = $this->_compress($content, $ext);
$cache = $cache . '.html';
$content = '<!--cachetime:' . $cacheTime . ';ext:' . $ext . '-->' . $content;
$folder = CACHE . 'views' . DS;
if (Configure::read('debug') && !is_dir($folder)) {
mkdir($folder, 0770, true);
}
$file = $folder . $cache;
return file_put_contents($file, $content);
} | Write a cached version of the file
@param string $content view content to write to a cache file.
@param int|string $duration Duration to set for cache file.
@return bool Success of caching view. | entailment |
protected function _compress($content, $ext) {
$compress = $this->getConfig('compress');
if ($compress === true) {
// Native compressor only supports HTML right now
if ($ext === 'html') {
$Compressor = new Compressor();
$content = $Compressor->compress($content);
}
} elseif (is_callable($compress)) {
$content = $compress($content, $ext);
} elseif ($compress) {
$content = call_user_func($compress, $content, $ext);
}
return $content;
} | Compresses HTML
@param string $content
@param string $ext
@return string Content | entailment |
public function getOptions()
{
if (isset($this->options['id']))
unset($this->options['id']);
$this->registerAnimateCss();
if (ArrayHelper::isIndexed($this->options)) {
$str = '';
foreach ($this->options as $value) {
$str .= '"' . $value . '",';
}
return chop($str, ' ,');
}
return Json::encode($this->options);
} | Get widget options
@return string | entailment |
public function registerAnimateCss()
{
if (isset($this->options['animation']) && $this->options['animation'] === false) {
if (isset($this->options['customClass'])) {
AnimateCssAsset::register($this->view);
}
}
} | Add support Animate.css
@see https://daneden.github.io/animate.css/ | entailment |
public function getTrackInfo($user)
{
$lastFmResponse = $this->makeRequest($user);
if (!isset($lastFmResponse['recenttracks'])) {
throw BadResponse::create($lastFmResponse);
}
if (!count($lastFmResponse['recenttracks'])) {
return false;
};
if (!isset($lastFmResponse['recenttracks']['track'][0])) {
return false;
}
$lastTrack = $lastFmResponse['recenttracks']['track'][0];
if (!isset($lastTrack['@attr']['nowplaying'])) {
return false;
}
if (!$lastTrack['@attr']['nowplaying']) {
return false;
}
return [
'artist' => $lastTrack['artist']['#text'],
'album' => $lastTrack['album']['#text'],
'trackName' => $lastTrack['name'],
'url' => $lastTrack['url'],
'artwork' => $this->getImage($lastTrack, 'extralarge'),
];
} | @param $user
@return array|bool
@throws \Spatie\NowPlaying\Exceptions\BadResponse | entailment |
protected function getSelectMetaModel()
{
if (empty($this->objSelectMetaModel)) {
$this->objSelectMetaModel = $this->factory->getMetaModel($this->getSelectSource());
}
return $this->objSelectMetaModel;
} | Retrieve the linked MetaModel instance.
@return IMetaModel | entailment |
protected function prepareTemplate(Template $objTemplate, $arrRowData, $objSettings)
{
parent::prepareTemplate($objTemplate, $arrRowData, $objSettings);
/** @noinspection PhpUndefinedFieldInspection */
$objTemplate->displayValue = $this->getValueColumn();
} | {@inheritdoc} | entailment |
protected function itemsToValues(IItems $items)
{
$values = [];
foreach ($items as $item) {
/** @var IItem $item */
$valueId = $item->get('id');
$parsedItem = $item->parseValue();
$values[$valueId] = \array_merge(
[self::SELECT_RAW => $parsedItem['raw']],
$parsedItem['text']
);
}
return $values;
} | Convert the item list to values.
@param IItems $items The items to convert.
@return array | entailment |
protected function getValuesById($valueIds, $attrOnly = [])
{
$recursionKey = $this->getMetaModel()->getTableName();
// Prevent recursion.
static $tables = [];
if (isset($tables[$recursionKey])) {
return [];
}
$tables[$recursionKey] = $recursionKey;
$metaModel = $this->getSelectMetaModel();
$filter = $metaModel->getEmptyFilter()->addFilterRule(new StaticIdList($valueIds));
$items = $metaModel->findByFilter($filter, 'id', 0, 0, 'ASC', $attrOnly);
unset($tables[$recursionKey]);
return $this->itemsToValues($items);
} | Retrieve the values with the given ids.
@param string[] $valueIds The ids of the values to retrieve.
@param array $attrOnly The attribute names to obtain.
@return array | entailment |
public function valueToWidget($varValue)
{
$aliasColumn = $this->getIdColumn();
return $varValue[$aliasColumn] ?? $varValue[self::SELECT_RAW][$aliasColumn] ?? null;
} | {@inheritdoc} | entailment |
public function widgetToValue($varValue, $itemId)
{
if (null === $varValue) {
return null;
}
static $cache = [];
$attributeId = $this->get('id');
if (array_key_exists($attributeId, $cache) && array_key_exists($varValue, $cache[$attributeId])) {
return $cache[$attributeId][$varValue];
}
$model = $this->getSelectMetaModel();
$alias = $this->getIdColumn();
if ($model->hasAttribute($alias)) {
$attribute = $model->getAttribute($alias);
// It is an attribute, we may search for it.
$ids = $attribute->searchFor($varValue);
} else {
// Must be a system column then.
$result = $this->connection->createQueryBuilder()
->select('v.id')
->from($this->getSelectSource(), 'v')
->where('v.' . $this->getIdColumn() . '=:value')
->setParameter('value', $varValue)
->execute();
$ids = $result->fetchAll(\PDO::FETCH_COLUMN);
}
// Maybe deleted value?
if ([] === $ids) {
return $cache[$attributeId][$varValue] = null;
}
// Multiple results.
if (null === $ids || \count($ids) > 1) {
throw new \RuntimeException(
\sprintf(
'Multiple values found for %s, are there obsolete values for %s.%s (att_id: %s)?',
\var_export($varValue, true),
$model->getTableName(),
$this->getColName(),
$this->get('id')
)
);
}
$valueId = \array_shift($ids);
$value = $this->getValuesById(
[$valueId],
[$this->getAliasColumn(), $this->getValueColumn(), $this->getIdColumn(), $this->getSortingColumn()]
);
return $cache[$attributeId][$varValue] = $value[$valueId];
} | {@inheritdoc}
@throws \RuntimeException When the value is invalid. | entailment |
public function getFilterOptionsForDcGeneral()
{
if (!$this->isFilterOptionRetrievingPossible(null)) {
return [];
}
$originalLanguage = $GLOBALS['TL_LANGUAGE'];
$GLOBALS['TL_LANGUAGE'] = $this->getMetaModel()->getActiveLanguage();
$filter = $this->getSelectMetaModel()->getEmptyFilter();
$this->buildFilterRulesForFilterSetting($filter);
$objItems = $this->getSelectMetaModel()->findByFilter(
$filter,
$this->getSortingColumn(),
0,
0,
'ASC',
[$this->getValueColumn(), $this->getIdColumn()]
);
$GLOBALS['TL_LANGUAGE'] = $originalLanguage;
return $this->convertItemsToFilterOptions($objItems, $this->getValueColumn(), $this->getIdColumn());
} | {@inheritDoc}
@SuppressWarnings(PHPMD.Superglobals)
@SuppressWarnings(PHPMD.CamelCaseVariableName) | entailment |
public function buildFilterRulesForUsedOnly($filter, $idList = [])
{
$builder = $this->connection->createQueryBuilder()
->select($this->getColName())
->from($this->getMetaModel()->getTableName())
->groupBy($this->getColName());
if (!empty($idList)) {
$builder
->where('id IN (:ids)')
->setParameter('ids', $idList, Connection::PARAM_STR_ARRAY);
}
$arrUsedValues = $builder->execute()->fetchAll(\PDO::FETCH_COLUMN);
$arrUsedValues = \array_filter(
$arrUsedValues,
function ($value) {
return !empty($value);
}
);
$filter->addFilterRule(new StaticIdList($arrUsedValues));
} | Fetch filter options from foreign table taking the given flag into account.
@param IFilter $filter The filter to which the rules shall be added to.
@param array $idList The list of ids of items for which the rules shall be added.
@return void | entailment |
public function buildFilterRulesForFilterSetting($filter)
{
if (!$this->get('select_filter')) {
return;
}
// Set Filter and co.
$filterSettings = $this->filterSettingFactory->createCollection($this->get('select_filter'));
if ($filterSettings) {
$values = $_GET;
$presets = (array) $this->get('select_filterparams');
$presetNames = $filterSettings->getParameters();
$filterParams = \array_keys($filterSettings->getParameterFilterNames());
$processed = [];
// We have to use all the preset values we want first.
foreach ($presets as $presetName => $preset) {
if (\in_array($presetName, $presetNames)) {
$processed[$presetName] = $preset['value'];
}
}
// Now we have to use all FrontEnd filter params, that are either:
// * not contained within the presets
// * or are overridable.
foreach ($filterParams as $parameter) {
// Unknown parameter? - next please.
if (!\array_key_exists($parameter, $values)) {
continue;
}
// Not a preset or allowed to override? - use value.
if ((!\array_key_exists($parameter, $presets)) || $presets[$parameter]['use_get']) {
$processed[$parameter] = $values[$parameter];
}
}
$filterSettings->addRules($filter, $processed);
}
} | Fetch filter options from foreign table taking the given flag into account.
@param IFilter $filter The filter to which the rules shall be added to.
@return void
@SuppressWarnings(PHPMD.Superglobals)
@SuppressWarnings(PHPMD.CamelCaseVariableName) | entailment |
protected function convertItemsToFilterOptions($items, $displayValue, $aliasColumn, &$count = null, $idList = null)
{
if (null !== $count) {
$this->determineCount($items, $count, $idList);
}
$result = [];
foreach ($items as $item) {
$textValue = $this->tryParseAttribute($displayValue, $item);
$aliasValue = $this->tryParseAttribute($aliasColumn, $item);
$result[$aliasValue] = $textValue;
// Clean the count array if alias is different from id value.
if (null !== $count && isset($count[$item->get('id')]) && $aliasValue !== $item->get('id')) {
$count[$aliasValue] = $count[$item->get('id')];
unset($count[$item->get('id')]);
}
}
return $result;
} | Convert a collection of items into a proper filter option list.
@param IItems|IItem[] $items The item collection to convert.
@param string $displayValue The name of the attribute to use as value.
@param string $aliasColumn The name of the attribute to use as alias.
@param null|string[] $count The counter array.
@param null|array $idList A list for the current Items to use.
@return array | entailment |
private function tryParseAttribute($displayValue, IItem $item)
{
$parsedValue = $item->parseAttribute($displayValue);
if (isset($parsedValue['text'])) {
return $parsedValue['text'];
}
return $item->get($displayValue);
} | Parse a column as text or return the native value if that failed.
@param string $displayValue The attribute to parse.
@param IITem $item The item to extract the value from.
@return mixed | entailment |
private function determineCount($items, &$count, $idList)
{
$usedOptionsIdList = \array_unique(\array_filter(\array_map(
function ($item) {
/** @var IItem $item */
return $item->get('id');
},
\iterator_to_array($items)
)));
if (empty($usedOptionsIdList)) {
return;
}
$valueCol = $this->getColName();
$query = $this->connection->createQueryBuilder()
->select($this->getColName())
->addSelect(\sprintf('COUNT(%s) AS count', $this->getColName()))
->from($this->getMetaModel()->getTableName())
->where($this->getColName() . ' IN (:ids)')
->groupBy($this->getColName())
->setParameter('ids', $usedOptionsIdList, Connection::PARAM_STR_ARRAY);
if ($idList !== null && !empty($idList)) {
$query
->andWhere('id IN (:idList)')
->setParameter('idList', $idList, Connection::PARAM_STR_ARRAY);
}
$query = $query->execute();
while ($row = $query->fetch(\PDO::FETCH_ASSOC)) {
$count[$row->{$valueCol}] = $row->count;
}
} | Determine the option count for the passed items.
@param IItems|IItem[] $items The item collection to convert.
@param null|string[] $count The counter array.
@param array $idList The id list for the subselect.
@return void | entailment |
public function getFilterOptions($idList, $usedOnly, &$arrCount = null)
{
if (!$this->isFilterOptionRetrievingPossible($idList)) {
return [];
}
$strDisplayValue = $this->getValueColumn();
$strSortingValue = $this->getSortingColumn();
$strCurrentLanguage = null;
// Change language.
if (TL_MODE == 'BE') {
$strCurrentLanguage = $GLOBALS['TL_LANGUAGE'];
$GLOBALS['TL_LANGUAGE'] = $this->getMetaModel()->getActiveLanguage();
}
$filter = $this->getSelectMetaModel()->getEmptyFilter();
$this->buildFilterRulesForFilterSetting($filter);
// Add some more filter rules.
if ($usedOnly || ($idList && \is_array($idList))) {
$this->buildFilterRulesForUsedOnly($filter, $idList ?: []);
}
$objItems = $this->getSelectMetaModel()->findByFilter($filter, $strSortingValue);
// Reset language.
if (TL_MODE == 'BE') {
$GLOBALS['TL_LANGUAGE'] = $strCurrentLanguage;
}
return $this->convertItemsToFilterOptions(
$objItems,
$strDisplayValue,
$this->getAliasColumn(),
$arrCount,
$idList
);
} | {@inheritdoc}
Fetch filter options from foreign table.
@SuppressWarnings(PHPMD.Superglobals)
@SuppressWarnings(PHPMD.CamelCaseVariableName) | entailment |
public function sortIds($idList, $strDirection)
{
$metaModel = $this->getSelectMetaModel();
$myColName = $this->getColName();
$statement = $this->connection->createQueryBuilder()
->select('id,' . $myColName)
->from($this->getMetaModel()->getTableName())
->where('id IN (:ids)')
->setParameter('ids', $idList, Connection::PARAM_STR_ARRAY)
->execute();
$valueIds = [];
$valueMap = [];
while ($values = $statement->fetch(\PDO::FETCH_OBJ)) {
$itemId = $values->id;
$value = $values->$myColName;
$valueIds[$itemId] = $value;
$valueMap[$value][] = $itemId;
}
$filter =
$metaModel->getEmptyFilter()->addFilterRule(new StaticIdList(\array_unique(\array_values($valueIds))));
$value = $this->getValueColumn();
$items = $metaModel->findByFilter($filter, $value, 0, 0, $strDirection, [$value]);
$result = [];
foreach ($items as $item) {
$result = \array_merge($result, $valueMap[$item->get('id')]);
}
$diff = \array_diff($idList, $result);
return \array_merge($result, $diff);
} | {@inheritdoc}
This implementation does a complete sorting by the referenced MetaModel. | entailment |
public function getDataFor($arrIds)
{
if (!$this->isProperlyConfigured()) {
return [];
}
$result = [];
$valueColumn = $this->getColName();
// First pass, load database rows.
$statement = $this->connection->createQueryBuilder()
->select($valueColumn . ', id')
->from($this->getMetaModel()->getTableName())
->where('id IN (:ids)')
->setParameter('ids', $arrIds, Connection::PARAM_STR_ARRAY)
->execute();
$valueIds = [];
while ($rows = $statement->fetch(\PDO::FETCH_OBJ)) {
/** @noinspection PhpUndefinedFieldInspection */
$valueIds[$rows->id] = $rows->$valueColumn;
}
$values = $this->getValuesById($valueIds);
foreach ($valueIds as $itemId => $valueId) {
if (empty($valueId)) {
$result[$itemId] = null;
continue;
}
$result[$itemId] = $values[$valueId];
}
return $result;
} | {@inheritdoc} | entailment |
public function setDataFor($arrValues)
{
if (!($this->getSelectSource() && $this->getValueColumn())) {
return;
}
$query = \sprintf(
// @codingStandardsIgnoreStart - We want to keep the numbers as comment at the end of the following lines.
'UPDATE %1$s SET %2$s=:val WHERE %1$s.id=:id',
$this->getMetaModel()->getTableName(), // 1
$this->getColName() // 2
// @codingStandardsIgnoreEnd
);
foreach ($arrValues as $itemId => $value) {
if (\is_array($value) && isset($value[self::SELECT_RAW]['id'])) {
$this->connection->prepare($query)->execute([
'val' => (int) $value[self::SELECT_RAW]['id'],
'id' => $itemId
]);
} elseif (\is_numeric($itemId) && (\is_numeric($value) || $value === null)) {
$this->connection->prepare($query)->execute(['val' => (int) $value, 'id' => $itemId]);
} else {
throw new \RuntimeException(
'Invalid values encountered, itemId: ' .
\var_export($value, true) .
' value: ' . \var_export($value, true)
);
}
}
} | {@inheritdoc}
@throws \RuntimeException When invalid data is encountered. | entailment |
public function convertValuesToValueIds($values)
{
$strColNameAlias = $this->getAliasColumn();
$strColNameId = $this->getIdColumn();
if ($strColNameId === $strColNameAlias) {
return $values;
}
$attribute = $this->getSelectMetaModel()->getAttribute($strColNameAlias);
if (!$attribute) {
// If not an attribute, perform plain SQL translation. See #32, 34.
return parent::convertValuesToValueIds($values);
}
$sanitizedValues = [];
foreach ($values as $value) {
$valueIds = $attribute->searchFor($value);
if ($valueIds === null) {
return null;
}
$sanitizedValues = \array_merge($valueIds, $sanitizedValues);
}
return \array_unique($sanitizedValues);
} | {@inheritdoc} | entailment |
public function href($service, $url = null, array $options = [])
{
// Get the URL, get the current full path if a URL hasn't been specified.
$url = Router::url($url, true);
$SocialShareUrl = new SocialShareUrl();
return $SocialShareUrl->getUrl($service, $url, $options);
} | Creates a share URL.
### Options
- `text` Text to be passed to service relating to the shared content(e.g. page title).
- `image` URL of image for sharing (used by Pinterest).
For other options see HtmlHelper::link().
@param string $service Social Media service to create share link for.
@param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
@param array $options Array of options.
@return string|null URL. | entailment |
public function link($service, $text, $url = null, array $attributes = [])
{
$defaults = [
'target' => $this->_config['target']
];
$attributes += $defaults;
$options = [];
if (!empty($attributes['text'])) {
$options['text'] = $attributes['text'];
unset($attributes['text']);
}
if (!empty($attributes['image'])) {
$options['image'] = $attributes['image'];
unset($attributes['image']);
}
return $this->Html->link(
$text,
$this->href($service, $url, $options),
$attributes
);
} | Creates an HTML link to share a URL.
@param string $service Social Media service to create share link for.
@param string $text The content to be wrapped by <a> tags.
@param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
@param array $attributes Array of options and HTML attributes.
@return string An `<a />` element. | entailment |
public function fa($service, $url = null, array $options = [])
{
$defaults = [
'target' => $this->_config['target']
];
$options += $defaults;
$options['escape'] = false;
$icon = $this->icon($service, $options);
unset($options['icon_class']);
$attributes = $options;
unset($attributes['text']);
unset($attributes['image']);
return $this->Html->link(
$icon,
$this->href($service, $url, $options),
$attributes
);
} | Creates an HTML link to share a URL using a Font Awesome icon.
### Options
- `icon_class` Class name of icon for overriding defaults.
See HtmlHelper::link().
@param string $service Social Media service to create share link for.
@param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
@param array $options Array of options.
@return string URL. | entailment |
public function icon($service, array $options = [])
{
$class = 'fa ' . (!empty($this->_fa[$service]) ? $this->_fa[$service] : $this->_config['default_fa']);
if (!empty($options['icon_class'])) {
$class = $options['icon_class'];
}
return '<i class="' . $class . '"></i>';
} | Creates an icon
### Options
- `icon_class` Class name of icon for overriding defaults.
@param string $service Social Media service to create icon for
@param array $options Icon options
@return string | entailment |
public function handle()
{
$class = config(
'auth.providers.' . config(
'auth.guards.' . config(
'auth.defaults.guard'
) . '.provider'
) . '.model'
);
$user = new $class;
$fillables = $user->getFillable();
foreach($fillables as $key => $fillable) {
if ($fillable == 'password') {
$user->password = \Hash::make($this->secret(($key+1) . "/" . count($fillables) . " User $fillable"));
} else {
$user->$fillable = $this->ask(($key+1) . "/" . count($fillables) . " User $fillable");
}
}
if ($this->confirm("Do you want to create the user?", true)) {
$user->save();
$this->info("User created (id: {$user->id})");
}
return true;
} | Execute the console command.
@return mixed | entailment |
public function getMatchingIds()
{
$values = $this->objAttribute->convertValuesToValueIds(\explode(',', $this->value));
if (empty($values)) {
return $values;
}
$matches = $this->connection->createQueryBuilder()
->select('id')
->from($this->objAttribute->getMetaModel()->getTableName())
->where($this->objAttribute->getColName() . ' IN (:ids)')
->setParameter('ids', $values, Connection::PARAM_STR_ARRAY)
->execute();
return $matches->fetchAll(\PDO::FETCH_COLUMN);
} | {@inheritdoc} | entailment |
public function scopeSorted(Builder $builder, $query = [])
{
$query = (array)($query ?: Input::input($this->_getSortParameterName(), $this->_getDefaultSortCriteria()));
if (empty($query)) {
$query = $this->_getDefaultSortCriteria();
}
//unwrap sorting criteria array (for backwards compatibility)
if (is_array($query) && array_key_exists($this->_getSortParameterName(), $query)) {
$query = (array)$query[$this->_getSortParameterName()];
}
$criteria = $this->getCriteria($builder, $query);
$this->applyCriteria($builder, $criteria);
} | Applies filters.
@param Builder $builder query builder
@param array|string $query query parameters to use for sorting - $request[$this->_getSortParameterName()] is used by default
with fallback to $this->defaultSortCriteria if $this->_getSortParameterName() parameter is missing
in the request parameters | entailment |
protected function getCriteria(Builder $builder, array $query)
{
$criteria = [];
foreach ($query as $value) {
$criterion = Criterion::make($value, $this->_getDefaultSortOrder());
if ($this->isFieldSortable($builder, $criterion->getField())) {
$criteria[] = $criterion;
}
}
return $criteria;
} | Builds sort criteria based on model's sortable fields and query parameters.
@param Builder $builder query builder
@param array $query query parameters
@return array | entailment |
protected function isFieldSortable(Builder $builder, $field)
{
$sortable = $this->_getSortableAttributes($builder);
return in_array($field, $sortable) || in_array('*', $sortable);
} | Check if field is sortable for given model.
@param Builder $builder query builder
@param string $field field name
@return bool | entailment |
protected function applyCriteria(Builder $builder, array $criteria)
{
foreach ($criteria as $criterion) {
$criterion->apply($builder);
}
} | Applies criteria to query
@param Builder $builder query builder
@param Criterion[] $criteria sorting criteria | entailment |
protected function _getSortableAttributes(Builder $builder)
{
if (method_exists($builder->getModel(), 'getSortableAttributes')) {
return $builder->getModel()->getSortableAttributes();
}
if (property_exists($builder->getModel(), 'sortable')) {
return $builder->getModel()->sortable;
}
throw new RuntimeException(sprintf('Model %s must either implement getSortableAttributes() or have $sortable property set', get_class($builder->getModel())));
} | @param Builder $builder
@return array list of sortable attributes | entailment |
public function translate(
$text,
$to,
$from = null,
$category = null,
$contentType = ApiCall\Translate::CONTENT_TYPE_TEXT
)
{
$apiCall = new ApiCall\Translate($text, $to, $from, $category, $contentType);
return $this->call($apiCall);
} | Translates a given text or html to the given language
The language of the given text or html is optional, and will be auto-detected
The category will default to "general"
@param string $text
@param string $to
@param string|null $from
@param string $contentType
@param string|null $category
@return string | entailment |
public function translateArray(array $texts, $to, $from = null)
{
$apiCall = new ApiCall\TranslateArray($texts, $to, $from);
return $this->call($apiCall);
} | Translates an array of texts
@see MicrosoftTranslator::translate()
@param array $texts
@param string $to
@param string|null $from
@return array An array of translated strings | entailment |
public function breakSentences($text, $language)
{
$apiCall = new ApiCall\BreakSentences($text, $language);
return $this->call($apiCall);
} | Break a given text into the sentences it contains
@param string $text
@param string $language
@return array An array of strings | entailment |
public function getLanguageNames(array $languageCodes, $locale)
{
$apiCall = new ApiCall\GetLanguageNames($languageCodes, $locale);
return $this->call($apiCall);
} | Get a list of language names for the given language codes readable for the given locale
@param array $languageCodes
@param string $locale
@return array An array of language names | entailment |
public function createInstance($information, $metaModel)
{
if (substr($information['select_table'], 0, 3) === 'mm_') {
return new MetaModelSelect(
$metaModel,
$information,
$this->connection,
$this->tableManipulator,
$this->factory,
$this->filterSettingFactory
);
}
return new Select($metaModel, $information, $this->connection, $this->tableManipulator);
} | {@inheritdoc} | entailment |
public function send(RequestInterface $request, MessageInterface $response)
{
$cacheKey = $this->generateCacheKeyForRequest($request);
if ($this->cache->contains($cacheKey)) {
$this->hits++;
$cachedResponse = unserialize($this->cache->fetch($cacheKey));
/* @var $cachedResponse \Buzz\Message\Response */
$response->setContent($cachedResponse->getContent());
$response->setHeaders($cachedResponse->getHeaders());
return;
}
$this->misses++;
$this->client->send($request, $response);
$this->cache->save($cacheKey, serialize($response), $this->lifetime);
} | Populates the supplied response with the response for the supplied request.
@param RequestInterface $request A request object
@param MessageInterface $response A response object | entailment |
private function generateCacheKeyForRequest(RequestInterface $request)
{
$normalizedRequest = $this->getNormalizedRequest($request);
return md5($normalizedRequest->__toString());
} | Generate a unique key for the given request
The request is made invariant by sorting the headers alphabetically and by
removing headers that are to be ignored.
@see CachedClient::__construct()
@param \Buzz\Message\RequestInterface $request
@return string | entailment |
private function getNormalizedRequest(RequestInterface $request)
{
$normalizedRequest = clone $request;
$headers = $request->getHeaders();
$normalizedHeaders = $this->normalizeHeaders($headers);
asort($normalizedHeaders);
$normalizedRequest->setHeaders($normalizedHeaders);
return $normalizedRequest;
} | Reduces the request to its normal form
Which means: strip all information that does not contribute to its uniqueness
This will prevent cache misses, when effectively indifferent requests are made
@param \Buzz\Message\RequestInterface $request
@return \Buzz\Message\RequestInterface | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.