sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getRuntimeContexts(array $unqualified_context_ids) {
$context_definition = new ContextDefinition('entity:node', NULL, FALSE);
$context = new Context($context_definition, $this->node);
return ['@node.node_route_context:node' => $context];
} | {@inheritdoc} | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$schemes = $this->utils->getFilesystemSchemes();
$options = array_combine($schemes, $schemes);
$form['filesystems'] = [
'#title' => $this->t('Filesystems'),
'#type' => 'checkboxes',
'#options' => $options,
'#default_value' => $this->configuration['filesystems'],
];
return parent::buildConfigurationForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['filesystems'] = array_filter($form_state->getValue('filesystems'));
parent::submitConfigurationForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function evaluate() {
if (empty($this->configuration['filesystems']) && !$this->isNegated()) {
return TRUE;
}
$file = $this->getContextValue('file');
return $this->evaluateFile($file);
} | {@inheritdoc} | entailment |
protected function evaluateFile(FileInterface $file) {
$uri = $file->getFileUri();
$scheme = $this->fileSystem->uriScheme($uri);
return !empty($this->configuration['filesystems'][$scheme]);
} | The actual evaluate function.
@param \Drupal\file\FileInterface $file
File.
@return bool
TRUE on success. | entailment |
public function index()
{
$currentUserId = Auth::user()->id;
// All threads, ignore deleted/archived participants
$threads = Thread::getAllLatest()->get();
// All threads that user is participating in
// $threads = Thread::forUser($currentUserId)->latest('updated_at')->get();
// All threads that user is participating in, with new messages
// $threads = Thread::forUserWithNewMessages($currentUserId)->latest('updated_at')->get();
return view('chat.index', compact('threads', 'currentUserId'));
} | Show all of the message threads to the user
@return mixed | entailment |
public function show($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect('message');
}
// show current user in list if not a current participant
// $users = User::whereNotIn('id', $thread->participantsUserIds())->get();
// don't show the current user in list
$userId = Auth::user()->id;
$users = User::whereNotIn('id', $thread->participantsUserIds($userId))->get();
$thread->markAsRead($userId);
return view('chat.show', compact('thread', 'users'));
} | Shows a message thread
@param $id
@return mixed | entailment |
public function store()
{
$input = Input::all();
$thread = Thread::create(
[
'subject' => $input['subject'],
]
);
// Message
Message::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
'body' => $input['message'],
]
);
// Sender
Participant::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
'last_read' => new Carbon
]
);
// Recipients
if (Input::has('recipients')) {
$thread->addParticipants($input['recipients']);
}
return redirect('message');
} | Stores a new message thread
@return mixed | entailment |
public function getRuntimeContexts(array $unqualified_context_ids) {
$result = [];
$context_definition = new ContextDefinition('entity:media', NULL, FALSE);
$value = NULL;
// Hack the media out of the route.
$route_object = $this->routeMatch->getRouteObject();
if ($route_object) {
$route_contexts = $route_object->getOption('parameters');
if ($route_contexts && isset($route_contexts['media'])) {
$media = $this->routeMatch->getParameter('media');
if ($media) {
$value = $media;
}
}
elseif ($this->routeMatch->getRouteName() == 'entity.media.add_form') {
$media_type = $this->routeMatch->getParameter('media_type');
$value = Media::create(['bundle' => $media_type->id()]);
}
}
$cacheability = new CacheableMetadata();
$cacheability->setCacheContexts(['route']);
$context = new Context($context_definition, $value);
$context->addCacheableDependency($cacheability);
return ['media' => $context];
} | {@inheritdoc} | entailment |
public function participantsUserIds($userId = null)
{
$users = $this->participants()->lists('user_id');
if ($userId) {
$users[] = $userId;
}
return $users;
} | Returns an array of user ids that are associated with the thread
@param null $userId
@return array | entailment |
public function scopeForUserWithNewMessages($query, $userId)
{
return $query->join('participants', 'threads.id', '=', 'participants.thread_id')
->where('participants.user_id', $userId)
->where(function ($query) {
$query->where('threads.updated_at', '>', $this->getConnection()->raw($this->getConnection()->getTablePrefix() . 'participants.last_read'))
->orWhereNull('participants.last_read');
})
->select('threads.*');
} | Returns threads with new messages that the user is associated with
@param $query
@param $userId
@return mixed | entailment |
public function scopeBetween($query, array $participants)
{
$query->whereHas('participants', function ($query) use ($participants) {
$query->whereIn('user_id', $participants)
->groupBy('thread_id')
->havingRaw('COUNT(thread_id)='.count($participants));
});
} | Returns threads between given user ids
@param $query
@param $participants
@return mixed | entailment |
public function addParticipants(array $participants)
{
if (count($participants)) {
foreach ($participants as $user_id) {
Participant::firstOrCreate([
'user_id' => $user_id,
'thread_id' => $this->id,
]);
}
}
} | Adds users to this thread
@param array $participants list of all participants
@return void | entailment |
public function markAsRead($userId)
{
try {
$participant = $this->getParticipantFromUser($userId);
$participant->last_read = new Carbon;
$participant->save();
} catch (ModelNotFoundException $e) {
// do nothing
}
} | Mark a thread as read for a user
@param integer $userId | entailment |
public function isUnread($userId)
{
try {
$participant = $this->getParticipantFromUser($userId);
if ($this->updated_at > $participant->last_read) {
return true;
}
} catch (ModelNotFoundException $e) {
// do nothing
}
return false;
} | See if the current thread is unread by the user
@param integer $userId
@return bool | entailment |
public function participantsString($userId=null, $columns=['first_name'])
{
$selectString = $this->createSelectString($columns);
$participantNames = $this->getConnection()->table($this->getUsersTable())
->join('participants', $this->getUsersTable() . '.id', '=', 'participants.user_id')
->where('participants.thread_id', $this->id)
->select($this->getConnection()->raw($selectString));
if ($userId !== null) {
$participantNames->where($this->getUsersTable() . '.id', '!=', $userId);
}
$userNames = $participantNames->lists($this->getUsersTable() . '.name');
return implode(', ', $userNames);
} | Generates a string of participant information
@param null $userId
@param array $columns
@return string | entailment |
protected function createSelectString($columns)
{
$dbDriver = $this->getConnection()->getDriverName();
switch ($dbDriver) {
case 'pgsql':
case 'sqlite':
$columnString = implode(" || ' ' || " . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . ".", $columns);
$selectString = "(" . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . "." . $columnString . ") as name";
break;
case 'sqlsrv':
$columnString = implode(" + ' ' + " . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . ".", $columns);
$selectString = "(" . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . "." . $columnString . ") as name";
break;
default:
$columnString = implode(", ' ', " . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . ".", $columns);
$selectString = "concat(" . $this->getConnection()->getTablePrefix() . $this->getUsersTable() . "." . $columnString . ") as name";
}
return $selectString;
} | Generates a select string used in participantsString()
@param $columns
@return string | entailment |
private function getUsersTable()
{
if ($this->usersTable !== null) {
return $this->usersTable;
}
$userModel = Config::get('chat.user_model');
return $this->usersTable = (new $userModel)->getTable();
} | Returns the "users" table name to use in manual queries
@return string | entailment |
public function addSynonyms($list) {
$this->data = array_unique(array_merge($this->data, (array)$list));
return $this;
} | Add synonyms
@param string/array $list One array entry for each group of synonyms. The synonyms within a group are separated by commas.
Example: couch,sofa,divan | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['types'] = [
'#title' => $this->t('Content Entity Types'),
'#type' => 'checkboxes',
'#options' => [
'node' => $this->t('Node'),
'media' => $this->t('Media'),
'file' => $this->t('File'),
'taxonomy_term' => $this->t('Taxonomy Term'),
],
'#default_value' => $this->configuration['types'],
];
return parent::buildConfigurationForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function evaluate() {
if (empty($this->configuration['types']) && !$this->isNegated()) {
return TRUE;
}
foreach ($this->configuration['types'] as $type) {
if ($this->getContext($type)->hasContextValue()) {
$entity = $this->getContextValue($type);
if ($entity && $entity->getEntityTypeId() == $type) {
return TRUE;
}
}
}
return FALSE;
} | {@inheritdoc} | entailment |
public function summary() {
if (count($this->configuration['types']) > 1) {
$types = $this->configuration['types'];
$last = array_pop($types);
$types = implode(', ', $types);
return $this->t(
'The content entity is a @types or @last',
[
'@types' => $types,
'@last' => $last,
]
);
}
$type = reset($this->configuration['types']);
return $this->t(
'The content entity is a @type',
[
'@type' => $type,
]
);
} | {@inheritdoc} | entailment |
public function relativeDateFilter($field, $fromUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $fromInterval, $toUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $toInterval = 0, $dateFormat = self::RELATIVE_DATE_FILTER_DATEFORMAT, $isNegative = false) {
$parameters = array(
'fromUnit' => $fromUnit,
'fromInterval' => $fromInterval,
'toUnit' => $toUnit,
'toInterval' => $toInterval,
'dateFormat' => $dateFormat,
'field' => $field
);
$this->addFilter(null, self::RELATIVE_DATE_FILTER, $isNegative, $parameters);
return $this;
} | Add a RelativeDateFilter on request
@return OpenSearchServer\Search | entailment |
public function negativeRelativeDateFilter($field, $fromUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $fromInterval, $toUnit = self::RELATIVE_DATE_FILTER_UNIT_MINUTES, $toInterval = 0, $dateFormat = self::RELATIVE_DATE_FILTER_DATEFORMAT, $isNegative = false) {
return $this->relativeDateFilter($field, $fromUnit, $fromInterval, $toUnit, $toInterval, $dateFormat, true);
} | Add a negative RelativeDateFilter on request
@return OpenSearchServer\Search | entailment |
public function geoFilter($shape = self::GEO_FILTER_SQUARED, $unit = self::GEO_FILTER_KILOMETERS, $distance, $isNegative = false) {
$parameters = array(
'shape' => $shape,
'unit' => $unit,
'distance' => $distance
);
$this->addFilter(null, self::GEO_FILTER, $isNegative, $parameters);
return $this;
} | Add a GeoFilter on request
@return OpenSearchServer\Search | entailment |
public function negativeGeoFilter($shape = self::GEO_FILTER_SQUARED, $unit = self::GEO_FILTER_KILOMETERS, $distance) {
return $this->geoFilter(null, $shape, $unit, $distance, true);
} | Add a negative GeoFilter on request
@return OpenSearchServer\Search | entailment |
public function returnedFields($fields) {
if(empty($this->data['returnedFields'])) {
$this->data['returnedFields'] = array();
}
$this->data['returnedFields'] = array_unique(array_merge($this->data['returnedFields'], (array)$fields));
return $this;
} | Configure fields to return
@param array or string $fields
@return OpenSearchServer\Search | entailment |
function filterField($field, $filter, $join = self::OPERATOR_OR, $addQuotes = false) {
$quotes = ($addQuotes) ? '"' : '';
if(is_array($filter)) {
$filterString = $field . ':'.$quotes.'' . implode(''.$quotes.' '.$join.' '.$field.':'.$quotes.'', $filter ) .''.$quotes.'';
}
else {
$filterString = $field . ':'.$quotes.'' . $filter .''.$quotes.'';
}
return $this->queryFilter($filterString);
} | Helper method: set a QueryFilter by specifying field and value.
Value can be an array of values, that will be joined with $join
@param string $field Field on which filter.
@param string $filter Value of the filter.
@param string $join Type of join. Default is OR.
@param string $addQuotes Whether or not add quotes around values. | entailment |
private function addFilter($value = null, $type, $isNegative, $parameters = array()) {
if(empty($this->data['filters'])) {
$this->data['filters'] = array();
}
$newFilter = array(
'type' => $type,
'negative' => (boolean)$isNegative,
);
//add options depending on type of filter
switch($type) {
case self::GEO_FILTER:
$newFilter['shape'] = $parammeters['shape'];
$newFilter['unit'] = $parammeters['unit'];
$newFilter['distance'] = $parammeters['distance'];
break;
case self::QUERY_FILTER:
$newFilter['query'] = $value;
break;
case self::RELATIVE_DATE_FILTER:
$newFilter['from'] = array(
'unit' => $parameters['fromUnit'],
'interval' => $parameters['fromInterval'],
);
$newFilter['to'] = array(
'unit' => $parameters['toUnit'],
'interval' => $parameters['toInterval'],
);
$newFilter['field'] = $parameters['field'];
$newFilter['dateFormat'] = $parameters['dateFormat'];
break;
}
$this->data['filters'][] = $newFilter;
} | ****************************
PRIVATE METHODS
**************************** | entailment |
static public function fetch( $tagID, $locale, $includeDrafts = false )
{
$fetchParams = array( 'keyword_id' => $tagID, 'locale' => $locale );
if ( !$includeDrafts )
$fetchParams['status'] = self::STATUS_PUBLISHED;
return parent::fetchObject( self::definition(), null, $fetchParams );
} | Returns eZTagsKeyword object for given tag ID and locale
@static
@param int $tagID
@param string $locale
@param bool $includeDrafts
@return eZTagsKeyword | entailment |
static public function fetchByTagID( $tagID )
{
$tagKeywordList = parent::fetchObjectList( self::definition(), null, array( 'keyword_id' => $tagID ) );
if ( is_array( $tagKeywordList ) )
return $tagKeywordList;
return array();
} | Returns eZTagsKeyword list for given tag ID
@static
@param int $tagID
@return eZTagsKeyword[] | entailment |
public function languageName()
{
/** @var eZContentLanguage $language */
$language = eZContentLanguage::fetchByLocale( $this->attribute( 'locale' ) );
if ( $language instanceof eZContentLanguage )
return array( 'locale' => $language->attribute( 'locale' ), 'name' => $language->attribute( 'name' ) );
return false;
} | Returns array with language name and locale for this instance
@return array | entailment |
public function searchField($field, $mode = self::SEARCH_MODE_PATTERN, $boost = 1, $phraseBoost = 1) {
if(empty($this->data['searchFields'])) {
$this->data['searchFields'] = array();
}
$this->data['searchFields'][] = array(
'field' => $field,
'mode' => $mode,
'boost' => $boost,
'phraseBoost' => $phraseBoost
);
return $this;
} | Add a field to search into
@return OpenSearchServer\Search\Search | entailment |
public function searchFields(array $fields, $mode = self::SEARCH_MODE_PATTERN, $boost = 1, $phraseBoost = 2) {
foreach($fields as $field) {
$this->searchField($field, $mode, $boost, $phraseBoost);
}
return $this;
} | Helper method: add several searchFields with same parameters | entailment |
public function getFilenames(array $fileOrDirectoryNames, array $filePatterns = [], FinderObserver $observer = null): array
{
$finder = clone $this->finder;
$finder->files();
$observer = $observer ?: new CallbackFinderObserver(function() {});
if (count($filePatterns) > 0) {
$finder->filter(function(SplFileInfo $fileInfo) use ($filePatterns) {
if ($fileInfo->isDir()) {
return true;
}
foreach ($filePatterns as $pattern) {
if (fnmatch($pattern, $fileInfo->getFilename())) {
return true;
}
}
return false;
});
}
$filenames = [];
foreach ($fileOrDirectoryNames as $fileOrDirectoryName) {
$subFinder = clone $finder;
$resolvedFileOrDirectoryName = $fileOrDirectoryName;
if ($fileOrDirectoryName{0} !== '/' && substr($fileOrDirectoryName, 0, 6) !== 'vfs://') {
$resolvedFileOrDirectoryName = realpath($fileOrDirectoryName);
if ($resolvedFileOrDirectoryName === false) {
$observer->onEntryNotFound($fileOrDirectoryName);
continue;
}
}
if (file_exists($resolvedFileOrDirectoryName) === false) {
$observer->onEntryNotFound($resolvedFileOrDirectoryName);
continue;
}
$fileInfo = $this->filesystem->openFile($resolvedFileOrDirectoryName);
if ($fileInfo->isFile()) {
$filenames[] = $resolvedFileOrDirectoryName;
} else {
$subFinder->in($resolvedFileOrDirectoryName);
/** @var SymfonySplFileInfo $subFileInfo */
foreach ($subFinder as $subFileInfo) {
$filenames[] = $subFileInfo->getPathname();
}
}
}
return $filenames;
} | Generates a list of file names from a list of file and directory names.
@param string[] $fileOrDirectoryNames A list of file and directory names.
@param string[] $filePatterns Glob patterns that filenames should match
@param FinderObserver|null $observer
@return string[] A list of file names. | entailment |
public function getPath()
{
$this->checkPathIndexNeeded();
$path = rawurlencode($this->options['index']).'/morelikethis';
return (!empty($this->options['template'])) ? $path.'/template/'.rawurlencode($this->options['template']) : $path;
} | {@inheritdoc} | entailment |
public function getField($fieldName, $returnFirstValueOnly = true) {
if(!empty($this->fields[$fieldName]) && count($this->fields[$fieldName] > 0)) {
return ($returnFirstValueOnly) ? $this->fields[$fieldName][0] : $this->fields[$fieldName];
}
} | Return value of a field
@param string $fieldName
@param boolean $returnFirstValueOnly Return every values (useful for a multivalued field), or only
first value (useful for most of the cases when there is only one value).
Default value: true. | entailment |
public function getSnippet($fieldName, $returnFirstValueOnly = true) {
if(!empty($this->snippets[$fieldName]) && count($this->snippets[$fieldName] > 0)) {
return ($returnFirstValueOnly) ? $this->snippets[$fieldName][0] : $this->snippets[$fieldName];
}
} | Return value of a snippet
@param string $fieldName
@param boolean $returnFirstValueOnly Return every values (useful for a multivalued snippets), or only
first value (useful for most of the cases when there is only one value).
Default value: true. | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
// Build up options array.
$entity_types = $this->entityTypeManager->getDefinitions();
$view_modes = $this->entityTypeManager->getStorage('entity_view_mode')->loadMultiple();
$options = [];
foreach ($view_modes as $view_mode) {
$exploded = explode('.', $view_mode->id());
$entity_type_label = $entity_types[$exploded[0]]->getLabel()->render();
$options[$entity_type_label][$view_mode->id()] = $view_mode->label();
}
// Provide a select to choose display mode.
$config = $this->getConfiguration();
$form[self::MODE] = [
'#title' => $this->t('View Mode'),
'#description' => $this->t("The selected view mode will be used if conditions are met."),
'#type' => 'select',
'#options' => $options,
'#default_value' => isset($config[self::MODE]) ? $config[self::MODE] : '',
];
return $form;
} | {@inheritdoc} | entailment |
public function initialize(array $config)
{
if ($this->_config['referenceName'] == null) {
$this->_config['referenceName'] = $this->_referenceName();
}
$this->setupFieldAssociations($this->_config['versionTable']);
} | Constructor hook method.
Implement this method to avoid having to overwrite
the constructor and call parent.
@param array $config The configuration settings provided to this behavior.
@return void | entailment |
public function setupFieldAssociations($table)
{
$options = [
'table' => $table
];
foreach ($this->_fields() as $field) {
$this->versionAssociation($field, $options);
}
$this->versionAssociation(null, $options);
} | Creates the associations between the bound table and every field passed to
this method.
Additionally it creates a `version` HasMany association that will be
used for fetching all versions for each record in the bound table
@param string $table the table name to use for storing each field version
@return void | entailment |
public function versionAssociation($field = null, $options = [])
{
$name = $this->_associationName($field);
if (!$this->_table->associations()->has($name)) {
$model = $this->_config['referenceName'];
$options += [
'className' => $this->_config['versionTable'],
'foreignKey' => $this->_config['foreignKey'],
'strategy' => 'subquery',
'dependent' => true
];
if ($field) {
$options += [
'conditions' => [
$name . '.model' => $model,
$name . '.field' => $field,
],
'propertyName' => $field . '_version'
];
} else {
$options += [
'conditions' => [
$name . '.model' => $model
],
'propertyName' => '__version'
];
}
$this->_table->hasMany($name, $options);
}
return $this->_table->getAssociation($name);
} | Returns association object for all versions or single field version.
@param string|null $field Field name for per-field association.
@param array $options Association options.
@return \Cake\ORM\Association | entailment |
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
{
$association = $this->versionAssociation();
$name = $association->getName();
$newOptions = [$name => ['validate' => false]];
$options['associated'] = $newOptions + $options['associated'];
$fields = $this->_fields();
$values = $entity->extract($fields, $this->_config['onlyDirty']);
$primaryKey = (array)$this->_table->getPrimaryKey();
$versionField = $this->_config['versionField'];
if (isset($options['versionId'])) {
$versionId = $options['versionId'];
} else {
$versionId = $this->getVersionId($entity) + 1;
}
$created = new DateTime();
$new = [];
$entityClass = TableRegistry::get($this->_config['versionTable'])->getEntityClass();
foreach ($values as $field => $content) {
if (in_array($field, $primaryKey) || $field == $versionField) {
continue;
}
$converted = $this->_convertFieldsToType([$field => $content], 'toDatabase');
$data = [
'version_id' => $versionId,
'model' => $this->_config['referenceName'],
'field' => $field,
'content' => $converted[$field],
'created' => $created,
] + $this->_extractForeignKey($entity);
$event = new Event('Model.Version.beforeSave', $this, $options);
$userData = EventManager::instance()->dispatch($event);
if (isset($userData->result) && is_array($userData->result)) {
$data = array_merge($data, $userData->result);
}
$new[$field] = new $entityClass($data, [
'useSetters' => false,
'markNew' => true
]);
}
$entity->set($association->getProperty(), $new);
if (!empty($versionField) && in_array($versionField, $this->_table->getSchema()->columns())) {
$entity->set($this->_config['versionField'], $versionId);
}
} | Modifies the entity before it is saved so that versioned fields are persisted
in the database too.
@param \Cake\Event\Event $event The beforeSave event that was fired
@param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
@param \ArrayObject $options the options passed to the save method
@return void | entailment |
public function afterSave(Event $event, EntityInterface $entity)
{
$property = $this->versionAssociation()->getProperty();
$entity->unsetProperty($property);
} | Unsets the temporary `__version` property after the entity has been saved
@param \Cake\Event\Event $event The beforeSave event that was fired
@param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
@return void | entailment |
public function getVersionId(EntityInterface $entity)
{
$table = TableRegistry::get($this->_config['versionTable']);
$preexistent = $table->find()
->select(['version_id'])
->where([
'model' => $this->_config['referenceName']
] + $this->_extractForeignKey($entity))
->order(['id desc'])
->limit(1)
->enableHydration(false)
->toArray();
return Hash::get($preexistent, '0.version_id', 0);
} | return the last version id
@param \Cake\Datasource\EntityInterface $entity Entity.
@return int | entailment |
public function findVersions(Query $query, array $options)
{
$association = $this->versionAssociation();
$name = $association->getName();
return $query
->contain([$name => function (Query $q) use ($name, $options, $query) {
if (!empty($options['primaryKey'])) {
$foreignKey = (array)$this->_config['foreignKey'];
$aliasedFK = [];
foreach ($foreignKey as $field) {
$aliasedFK[] = "$name.$field";
}
$conditions = array_combine($aliasedFK, (array)$options['primaryKey']);
$q->where($conditions);
}
if (!empty($options['versionId'])) {
$q->where(["$name.version_id IN" => $options['versionId']]);
}
$q->where(["$name.field IN" => $this->_fields()]);
return $q;
}])
->formatResults([$this, 'groupVersions'], $query::PREPEND);
} | Custom finder method used to retrieve all versions for the found records.
Versioned values will be found for each entity under the property `_versions`.
### Example:
{{{
$article = $articles->find('versions')->first();
$firstVersion = $article->get('_versions')[1];
}}}
@param \Cake\ORM\Query $query The original query to modify
@param array $options Options
@return \Cake\ORM\Query | entailment |
public function groupVersions($results)
{
$property = $this->versionAssociation()->getProperty();
return $results->map(function (EntityInterface $row) use ($property) {
$versionField = $this->_config['versionField'];
$versions = (array)$row->get($property);
$grouped = new Collection($versions);
$result = [];
foreach ($grouped->combine('field', 'content', 'version_id') as $versionId => $keys) {
$entityClass = $this->_table->getEntityClass();
$versionData = [
$versionField => $versionId
];
$keys = $this->_convertFieldsToType($keys, 'toPHP');
/* @var \Cake\Datasource\EntityInterface $versionRow */
$versionRow = $grouped->match(['version_id' => $versionId])->first();
foreach ($this->_config['additionalVersionFields'] as $mappedField => $field) {
if (!is_string($mappedField)) {
$mappedField = 'version_' . $field;
}
$versionData[$mappedField] = $versionRow->get($field);
}
$version = new $entityClass($keys + $versionData, [
'markNew' => false,
'useSetters' => false,
'markClean' => true
]);
$result[$versionId] = $version;
}
$options = ['setter' => false, 'guard' => false];
$row->set('_versions', $result, $options);
unset($row[$property]);
$row->clean();
return $row;
});
} | Modifies the results from a table find in order to merge full version records
into each entity under the `_versions` key
@param \Cake\Datasource\ResultSetInterface $results Results to modify.
@return \Cake\Collection\CollectionInterface | entailment |
public function getVersions(EntityInterface $entity)
{
$primaryKey = (array)$this->_table->getPrimaryKey();
$query = $this->_table->find('versions');
$pkValue = $entity->extract($primaryKey);
$conditions = [];
foreach ($pkValue as $key => $value) {
$field = current($query->aliasField($key));
$conditions[$field] = $value;
}
$entities = $query->where($conditions)->all();
if (empty($entities)) {
return new Collection([]);
}
$entity = $entities->first();
return $entity->get('_versions');
} | Returns the versions of a specific entity.
@param \Cake\Datasource\EntityInterface $entity Entity.
@return \Cake\Collection\CollectionInterface | entailment |
protected function _fields()
{
$schema = $this->_table->getSchema();
$fields = $schema->columns();
if ($this->_config['fields'] !== null) {
$fields = array_intersect($fields, (array)$this->_config['fields']);
}
return $fields;
} | Returns an array of fields to be versioned.
@return array | entailment |
protected function _extractForeignKey($entity)
{
$foreignKey = (array)$this->_config['foreignKey'];
$primaryKey = (array)$this->_table->getPrimaryKey();
$pkValue = $entity->extract($primaryKey);
return array_combine($foreignKey, $pkValue);
} | Returns an array with foreignKey value.
@param \Cake\Datasource\EntityInterface $entity Entity.
@return array | entailment |
protected function _associationName($field = null)
{
$alias = Inflector::singularize($this->_table->getAlias());
if ($field) {
$field = Inflector::camelize($field);
}
return $alias . $field . 'Version';
} | Returns default version association name.
@param string $field Field name.
@return string | entailment |
protected function _referenceName()
{
$table = $this->_table;
$name = namespaceSplit(get_class($table));
$name = substr(end($name), 0, -5);
if (empty($name)) {
$name = $table->getTable() ?: $table->getAlias();
$name = Inflector::camelize($name);
}
return $name;
} | Returns reference name for identifying this model's records in version table.
@return string | entailment |
protected function _convertFieldsToType(array $fields, $direction)
{
if (!in_array($direction, ['toPHP', 'toDatabase'])) {
throw new InvalidArgumentException(sprintf('Cannot convert type, Cake\Database\Type::%s does not exist', $direction));
}
$driver = $this->_table->getConnection()->getDriver();
foreach ($fields as $field => $content) {
$column = $this->_table->getSchema()->getColumn($field);
$type = Type::build($column['type']);
$fields[$field] = $type->{$direction}($content, $driver);
}
return $fields;
} | Converts fields to the appropriate type to be stored in the version, and
to be converted from the version record to the entity
@param array $fields Fields to convert
@param string $direction Direction (toPHP or toDatabase)
@return array | entailment |
public function indexed($indexed) {
if($indexed === true or $indexed === false) {
$this->data['indexed'] = ($indexed) ? 'YES' : 'NO';
} else {
$this->data['indexed'] = $indexed;
}
return $this;
} | Tell whether this field must be indexed or not
@param boolean $indexed
@return OpenSearchServer\Field\Create | entailment |
public function stored($stored) {
if($stored === true or $stored === false) {
$this->data['stored'] = ($stored) ? 'YES' : 'NO';
} else {
$this->data['stored'] = $stored;
}
return $this;
} | Tell whether this field must be stored or not
@param string $stored
@return OpenSearchServer\Field\Create | entailment |
public function onResponse(FilterResponseEvent $event) {
$response = $event->getResponse();
$media = $this->getObject($response, 'media');
if ($media === FALSE) {
return;
}
$links = array_merge(
$this->generateEntityReferenceLinks($media),
$this->generateRestLinks($media),
$this->generateMediaLinks($media)
);
// Add the link headers to the response.
if (empty($links)) {
return;
}
$response->headers->set('Link', $links, FALSE);
} | {@inheritdoc} | entailment |
protected function generateMediaLinks(MediaInterface $media) {
$media_type = $this->entityTypeManager->getStorage('media_type')->load($media->bundle());
$type_configuration = $media_type->get('source_configuration');
$links = [];
$update_route_name = 'islandora.media_source_update';
$update_route_params = ['media' => $media->id()];
if ($this->accessManager->checkNamedRoute($update_route_name, $update_route_params, $this->account)) {
$edit_media_url = Url::fromRoute($update_route_name, $update_route_params)
->setAbsolute()
->toString();
$links[] = "<$edit_media_url>; rel=\"edit-media\"";
}
if (!isset($type_configuration['source_field'])) {
return $links;
}
$source_field = $type_configuration['source_field'];
if (empty($source_field) ||
!$media->hasField($source_field)
) {
return $links;
}
// Collect file links for the media.
foreach ($media->get($source_field)->referencedEntities() as $referencedEntity) {
if ($referencedEntity->access('view')) {
$file_url = $referencedEntity->url('canonical', ['absolute' => TRUE]);
$links[] = "<$file_url>; rel=\"describes\"; type=\"{$referencedEntity->getMimeType()}\"";
}
}
return $links;
} | Generates link headers for the described file and source update routes.
@param \Drupal\media\MediaInterface $media
Media to generate link headers.
@return string[]
Array of link headers | entailment |
public function evaluateContexts(array $provided = []) {
$this->activeContexts = [];
/** @var \Drupal\context\ContextInterface $context */
foreach ($this->getContexts() as $context) {
if ($this->evaluateContextConditions($context, $provided) && !$context->disabled()) {
$this->activeContexts[$context->id()] = $context;
}
}
$this->contextConditionsEvaluated = TRUE;
} | Evaluate all context conditions.
@param \Drupal\Core\Plugin\Context\Context[] $provided
Additional provided (core) contexts to apply to Conditions. | entailment |
public function evaluateContextConditions(ContextInterface $context, array $provided = []) {
$conditions = $context->getConditions();
// Apply context to any context aware conditions.
$this->applyContexts($conditions, $provided);
// Set the logic to use when validating the conditions.
$logic = $context->requiresAllConditions()
? 'and'
: 'or';
// Of there are no conditions then the context will be
// applied as a site wide context.
if (!count($conditions)) {
$logic = 'and';
}
return $this->resolveConditions($conditions, $logic);
} | Evaluate a contexts conditions.
@param \Drupal\context\ContextInterface $context
The context to evaluate conditions for.
@param \Drupal\Core\Plugin\Context\Context[] $provided
Additional provided (core) contexts to apply to Conditions.
@return bool
TRUE if conditions pass | entailment |
protected function applyContexts(ConditionPluginCollection &$conditions, array $provided = []) {
foreach ($conditions as $condition) {
if ($condition instanceof ContextAwarePluginInterface) {
try {
if (empty($provided)) {
$contexts = $this->contextRepository->getRuntimeContexts(array_values($condition->getContextMapping()));
}
else {
$contexts = $provided;
}
$this->contextHandler->applyContextMapping($condition, $contexts);
}
catch (ContextException $e) {
return FALSE;
}
}
}
return TRUE;
} | Apply context to all the context aware conditions in the collection.
@param \Drupal\Core\Condition\ConditionPluginCollection $conditions
A collection of conditions to apply context to.
@param \Drupal\Core\Plugin\Context\Context[] $provided
Additional provided (core) contexts to apply to Conditions.
@return bool
TRUE if conditions pass | entailment |
public function variables(array $variables) {
foreach($variables as $name => $value) {
$this->variable($name, $value);
}
return $this;
} | ****************************
HELPER METHOD
**************************** | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
// Build up options array.
$entity_types = $this->entityTypeManager->getDefinitions();
$form_displays = $this->entityTypeManager->getStorage('entity_form_display')->loadMultiple();
$options = [];
foreach ($form_displays as $form_display) {
$entity_type = $form_display->getTargetEntityTypeId();
$entity_type_label = $entity_types[$entity_type]->getLabel()->render();
$mode = $form_display->getMode();
$options[$entity_type_label]["$entity_type.$mode"] = ucfirst($mode);
}
// Provide a select to choose display mode.
$config = $this->getConfiguration();
$form[self::MODE] = [
'#title' => $this->t('Form Mode'),
'#description' => $this->t("The selected form mode will be used if conditions are met."),
'#type' => 'select',
'#options' => $options,
'#default_value' => isset($config[self::MODE]) ? $config[self::MODE] : '',
];
return $form;
} | {@inheritdoc} | entailment |
public function writeStream($path, $resource, Config $config)
{
$path = pathinfo($path)['filename'];
$resource_metadata = stream_get_meta_data($resource);
$uploaded_metadata = Uploader::upload($resource_metadata['uri'], ['public_id' => $path, 'resource_type' => 'auto']);
return $uploaded_metadata;
} | Write a new file using a stream.
@param string $path
@param resource $resource
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
public function write($path, $resource, Config $config)
{
$path = pathinfo($path)['filename'];
return parent::write($path, $resource, $config);
} | Write a new file.
@param string $path
@param resource $resource
@param Config $config Config object
@return array|false false on failure file meta data on success | entailment |
protected function getObject(Response $response, $object_type) {
if ($object_type != 'node'
&& $object_type != 'media'
) {
return FALSE;
}
// Exit early if the response is already cached.
if ($response->headers->get('X-Drupal-Dynamic-Cache') == 'HIT') {
return FALSE;
}
if (!$response->isOk()) {
return FALSE;
}
// Hack the node out of the route.
$route_object = $this->routeMatch->getRouteObject();
if (!$route_object) {
return FALSE;
}
$methods = $route_object->getMethods();
$is_get = in_array('GET', $methods);
$is_head = in_array('HEAD', $methods);
if (!($is_get || $is_head)) {
return FALSE;
}
$route_contexts = $route_object->getOption('parameters');
if (!$route_contexts) {
return FALSE;
}
if (!isset($route_contexts[$object_type])) {
return FALSE;
}
$object = $this->routeMatch->getParameter($object_type);
if (!$object) {
return FALSE;
}
return $object;
} | Get the Node | Media | File.
@param \Symfony\Component\HttpFoundation\Response $response
The current response object.
@param string $object_type
The type of entity to look for.
@return Drupal\Core\Entity\ContentEntityBase|bool
A node or media entity or FALSE if we should skip out. | entailment |
protected function generateEntityReferenceLinks(EntityInterface $entity) {
// Use the node to add link headers for each entity reference.
$entity_type = $entity->getEntityType()->id();
$bundle = $entity->bundle();
// Get all fields for the entity.
$fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);
// Strip out everything but entity references that are not base fields.
$entity_reference_fields = array_filter($fields, function ($field) {
return $field->getFieldStorageDefinition()->isBaseField() == FALSE && $field->getType() == "entity_reference";
});
// Collect links for referenced entities.
$links = [];
foreach ($entity_reference_fields as $field_name => $field_definition) {
foreach ($entity->get($field_name)->referencedEntities() as $referencedEntity) {
// Headers are subject to an access check.
if ($referencedEntity->access('view')) {
// Taxonomy terms are written out as
// <url>; rel="tag"; title="Tag Name"
// where url is defined in field_same_as.
// If field_same_as doesn't exist or is empty,
// it becomes the taxonomy term's local uri.
if ($referencedEntity->getEntityTypeId() == 'taxonomy_term') {
$rel = "tag";
$entity_url = $referencedEntity->url('canonical', ['absolute' => TRUE]);
if ($referencedEntity->hasField('field_external_uri')) {
$external_uri = $referencedEntity->get('field_external_uri')->getValue();
if (!empty($external_uri) && isset($external_uri[0]['uri'])) {
$entity_url = $external_uri[0]['uri'];
}
}
$title = $referencedEntity->label();
}
else {
// If it's not a taxonomy term, referenced entity link
// headers take the form
// <url>; rel="related"; title="Field Label"
// and the url is the local uri.
$rel = "related";
$entity_url = $referencedEntity->url('canonical', ['absolute' => TRUE]);
$title = $field_definition->label();
}
$links[] = "<$entity_url>; rel=\"$rel\"; title=\"$title\"";
}
}
}
return $links;
} | Generates link headers for each referenced entity.
@param \Drupal\Core\Entity\EntityInterface $entity
Entity that has reference fields.
@return string[]
Array of link headers | entailment |
protected function generateRestLinks(EntityInterface $entity) {
$rest_resource_config_storage = $this->entityTypeManager->getStorage('rest_resource_config');
$entity_type = $entity->getEntityType()->id();
$rest_resource_config = $rest_resource_config_storage->load("entity.$entity_type");
$current_format = $this->requestStack->getCurrentRequest()->query->get('_format');
$links = [];
$route_name = $this->routeMatch->getRouteName();
if ($rest_resource_config) {
$formats = $rest_resource_config->getFormats("GET");
foreach ($formats as $format) {
if ($format == $current_format) {
continue;
}
switch ($format) {
case 'json':
$mime = 'application/json';
break;
case 'jsonld':
$mime = 'application/ld+json';
break;
case 'hal_json':
$mime = 'application/hal+json';
break;
case 'xml':
$mime = 'application/xml';
break;
default:
continue;
}
$meta_route_name = "rest.entity.$entity_type.GET";
$route_params = [$entity_type => $entity->id()];
if (!$this->accessManager->checkNamedRoute($meta_route_name, $route_params, $this->account)) {
continue;
}
$meta_url = Url::fromRoute($meta_route_name, $route_params)
->setAbsolute()
->toString();
$links[] = "<$meta_url?_format=$format>; rel=\"alternate\"; type=\"$mime\"";
}
}
return $links;
} | Generates link headers for REST endpoints.
@param \Drupal\Core\Entity\EntityInterface $entity
Entity that has reference fields.
@return string[]
Array of link headers | entailment |
public function threadsWithNewMessages()
{
$threadsWithNewMessages = [];
$participants = Participant::where('user_id', $this->id)->lists('last_read', 'thread_id');
/**
* @todo: see if we can fix this more in the future.
* Illuminate\Foundation is not available through composer, only in laravel/framework which
* I don't want to include as a dependency for this package...it's overkill. So let's
* exclude this check in the testing environment.
*/
if (getenv('APP_ENV') == 'testing' || !str_contains(\Illuminate\Foundation\Application::VERSION, '5.0')) {
$participants = $participants->all();
}
if ($participants) {
$threads = Thread::whereIn('id', array_keys($participants))->get();
foreach ($threads as $thread) {
if ($thread->updated_at > $participants[$thread->id]) {
$threadsWithNewMessages[] = $thread->id;
}
}
}
return $threadsWithNewMessages;
} | Returns all threads with new messages
@return array | entailment |
public function getConfigTreeBuilder(): TreeBuilder
{
if (method_exists(TreeBuilder::class, 'getRootNode')) {
$treeBuilder = new TreeBuilder('typoscript-lint');
$root = $treeBuilder->getRootNode();
} else {
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('typoscript-lint');
}
$root
->children()
->arrayNode('paths')
->prototype('scalar')->end()
->end()
->arrayNode('filePatterns')
->prototype('scalar')->end()
->end()
->arrayNode('sniffs')
->isRequired()
->useAttributeAsKey('class')
->prototype('array')
->children()
->scalarNode('class')->end()
->variableNode('parameters')->end()
->booleanNode('disabled')->defaultValue(false)->end()
->end()
->end()
->end();
return $treeBuilder;
} | Generates the configuration tree builder.
@return TreeBuilder The tree builder
@codeCoverageIgnore FU, I'm not going to test this one!
@suppress PhanParamTooMany, PhanUndeclaredMethod | entailment |
public function execute($entity = NULL) {
if (!$entity) {
return;
}
$transaction = $this->connection->startTransaction();
try {
// Delete all the source files and then the media.
$source_field = $this->mediaSourceService->getSourceFieldName($entity->bundle());
foreach ($entity->get($source_field)->referencedEntities() as $file) {
$file->delete();
}
$entity->delete();
}
catch (\Exception $e) {
$transaction->rollBack();
$this->logger->error("Cannot delete media and its files. Rolling back transaction: @msg", ["@msg" => $e->getMessage()]);
}
} | {@inheritdoc} | entailment |
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
return $object->access('delete', $account, $return_as_object);
} | {@inheritdoc} | entailment |
public function summary() {
if (count($this->configuration['filesystems']) > 1) {
$filesystems = $this->configuration['filesystems'];
$last = array_pop($filesystems);
$filesystems = implode(', ', $filesystems);
return $this->t(
'The media uses @filesystems or @last',
[
'@filesystems' => $filesystems,
'@last' => $last,
]
);
}
$filesystem = reset($this->configuration['filesystems']);
return $this->t(
'The media uses @filesystem',
[
'@filesystem' => $filesystem,
]
);
} | {@inheritdoc} | entailment |
public function evaluate() {
if (empty($this->configuration['filesystems']) && !$this->isNegated()) {
return TRUE;
}
$media = $this->getContextValue('media');
$file = $this->mediaSource->getSourceFile($media);
if (!$file) {
return FALSE;
}
return $this->evaluateFile($file);
} | {@inheritdoc} | entailment |
private function buildFacetsArray($facetsJson) {
foreach($facetsJson as $facetObj) {
//build array of term with <term> => <number of occurences>
$terms = array();
foreach($facetObj->terms as $termObj) {
$terms[$termObj->term] = $termObj->count;
}
$this->facets[$facetObj->fieldName] = $terms;
}
} | Build array of facets based on JSON results
@param array $facetsJson Array of JSON values for facets | entailment |
public function addStopWords($list) {
$this->data = array_unique(array_merge($this->data, (array)$list));
return $this;
} | Add synonyms
@param string/array $list One array entry for each stop word | entailment |
public function validateUser(CommandData $commandData) {
$userid = $commandData->input()->getOption('userid');
if ($userid) {
$account = User::load($userid);
if (!$account) {
throw new \Exception("User ID does not match an existing user.");
}
}
} | Validate the provided userid.
@hook validate migrate:import | entailment |
public function preImport(CommandData $commandData) {
$userid = $commandData->input()->getOption('userid');
if ($userid) {
$account = User::load($userid);
$accountSwitcher = \Drupal::service('account_switcher');
$userSession = new UserSession([
'uid' => $account->id(),
'name' => $account->getUsername(),
'roles' => $account->getRoles(),
]);
$accountSwitcher->switchTo($userSession);
$this->logger()->notice(
dt(
'Now acting as user ID @id',
['@id' => \Drupal::currentUser()->id()]
)
);
}
} | Switch the active user account to perform the import.
@hook pre-command migrate:import | entailment |
public function postImport($result, CommandData $commandData) {
if ($commandData->input()->getOption('userid')) {
$accountSwitcher = \Drupal::service('account_switcher');
$this->logger()->notice(dt(
'Switching back from user @uid.',
['@uid' => \Drupal::currentUser()->id()]
));
$accountSwitcher->switchBack();
}
} | Switch the user back once the migration is complete.
@hook post-command migrate:import | entailment |
protected function getSpecialOffset(\Imagick $original, $targetWidth, $targetHeight)
{
return $this->getEntropyOffsets($original, $targetWidth, $targetHeight);
} | get special offset for class
@param \Imagick $original
@param int $targetWidth
@param int $targetHeight
@return array | entailment |
protected function getEntropyOffsets(\Imagick $original, $targetWidth, $targetHeight)
{
$measureImage = clone($original);
// Enhance edges
$measureImage->edgeimage(1);
// Turn image into a grayscale
$measureImage->modulateImage(100, 0, 100);
// Turn everything darker than this to pitch black
$measureImage->blackThresholdImage("#070707");
// Get the calculated offset for cropping
return $this->getOffsetFromEntropy($measureImage, $targetWidth, $targetHeight);
} | Get the topleftX and topleftY that will can be passed to a cropping method.
@param \Imagick $original
@param int $targetWidth
@param int $targetHeight
@return array | entailment |
protected function getOffsetFromEntropy(\Imagick $originalImage, $targetWidth, $targetHeight)
{
// The entropy works better on a blured image
$image = clone $originalImage;
$image->blurImage(3, 2);
$size = $image->getImageGeometry();
$originalWidth = $size['width'];
$originalHeight = $size['height'];
$leftX = $this->slice($image, $originalWidth, $targetWidth, 'h');
$topY = $this->slice($image, $originalHeight, $targetHeight, 'v');
return array('x' => $leftX, 'y' => $topY);
} | Get the offset of where the crop should start
@param \Imagick $image
@param int $targetHeight
@param int $targetHeight
@param int $sliceSize
@return array | entailment |
protected function slice($image, $originalSize, $targetSize, $axis)
{
$aSlice = null;
$bSlice = null;
// Just an arbitrary size of slice size
$sliceSize = ceil(($originalSize - $targetSize) / 25);
$aBottom = $originalSize;
$aTop = 0;
// while there still are uninvestigated slices of the image
while ($aBottom - $aTop > $targetSize) {
// Make sure that we don't try to slice outside the picture
$sliceSize = min($aBottom - $aTop - $targetSize, $sliceSize);
// Make a top slice image
if (!$aSlice) {
$aSlice = clone $image;
if ($axis === 'h') {
$aSlice->cropImage($sliceSize, $originalSize, $aTop, 0);
} else {
$aSlice->cropImage($originalSize, $sliceSize, 0, $aTop);
}
}
// Make a bottom slice image
if (!$bSlice) {
$bSlice = clone $image;
if ($axis === 'h') {
$bSlice->cropImage($sliceSize, $originalSize, $aBottom - $sliceSize, 0);
} else {
$bSlice->cropImage($originalSize, $sliceSize, 0, $aBottom - $sliceSize);
}
}
// calculate slices potential
$aPosition = ($axis === 'h' ? 'left' : 'top');
$bPosition = ($axis === 'h' ? 'right' : 'bottom');
$aPot = $this->getPotential($aPosition, $aTop, $sliceSize);
$bPot = $this->getPotential($bPosition, $aBottom, $sliceSize);
$canCutA = ($aPot <= 0);
$canCutB = ($bPot <= 0);
// if no slices are "cutable", we force if a slice has a lot of potential
if (!$canCutA && !$canCutB) {
if ($aPot * self::POTENTIAL_RATIO < $bPot) {
$canCutA = true;
} elseif ($aPot > $bPot * self::POTENTIAL_RATIO) {
$canCutB = true;
}
}
// if we can only cut on one side
if ($canCutA xor $canCutB) {
if ($canCutA) {
$aTop += $sliceSize;
$aSlice = null;
} else {
$aBottom -= $sliceSize;
$bSlice = null;
}
} elseif ($this->grayscaleEntropy($aSlice) < $this->grayscaleEntropy($bSlice)) {
// bSlice has more entropy, so remove aSlice and bump aTop down
$aTop += $sliceSize;
$aSlice = null;
} else {
$aBottom -= $sliceSize;
$bSlice = null;
}
}
return $aTop;
} | slice
@param mixed $image
@param mixed $originalSize
@param mixed $targetSize
@param mixed $axis h=horizontal, v = vertical
@access protected
@return void | entailment |
protected function getPotential($position, $top, $sliceSize)
{
$safeZoneList = $this->getSafeZoneList();
$safeRatio = 0;
if ($position == 'top' || $position == 'left') {
$start = $top;
$end = $top + $sliceSize;
} else {
$start = $top - $sliceSize;
$end = $top;
}
for ($i = $start; $i < $end; $i++) {
foreach ($safeZoneList as $safeZone) {
if ($position == 'top' || $position == 'bottom') {
if ($safeZone['top'] <= $i && $safeZone['bottom'] >= $i) {
$safeRatio = max($safeRatio, ($safeZone['right'] - $safeZone['left']));
}
} else {
if ($safeZone['left'] <= $i && $safeZone['right'] >= $i) {
$safeRatio = max($safeRatio, ($safeZone['bottom'] - $safeZone['top']));
}
}
}
}
return $safeRatio;
} | getPotential
@param mixed $position
@param mixed $top
@param mixed $sliceSize
@access protected
@return void | entailment |
protected function grayscaleEntropy(\Imagick $image)
{
// The histogram consists of a list of 0-254 and the number of pixels that has that value
$histogram = $image->getImageHistogram();
return $this->getEntropy($histogram, $this->area($image));
} | Calculate the entropy for this image.
A higher value of entropy means more noise / liveliness / color / business
@param \Imagick $image
@return float
@see http://brainacle.com/calculating-image-entropy-with-python-how-and-why.html
@see http://www.mathworks.com/help/toolbox/images/ref/entropy.html | entailment |
protected function colorEntropy(\Imagick $image)
{
$histogram = $image->getImageHistogram();
$newHistogram = array();
// Translates a color histogram into a bw histogram
$colors = count($histogram);
for ($idx = 0; $idx < $colors; $idx++) {
$colors = $histogram[$idx]->getColor();
$grey = $this->rgb2bw($colors['r'], $colors['g'], $colors['b']);
if (!isset($newHistogram[$grey])) {
$newHistogram[$grey] = $histogram[$idx]->getColorCount();
} else {
$newHistogram[$grey] += $histogram[$idx]->getColorCount();
}
}
return $this->getEntropy($newHistogram, $this->area($image));
} | Find out the entropy for a color image
If the source image is in color we need to transform RGB into a grayscale image
so we can calculate the entropy more performant.
@param \Imagick $image
@return float | entailment |
public static function createFromParseError(ParseError $parseError): self
{
return new self(
$parseError->getSourceLine(),
0,
"Parse error: " . $parseError->getMessage(),
self::SEVERITY_ERROR,
get_class($parseError)
);
} | Creates a new warning from a parse error.
@param ParseError $parseError The parse error to convert into a warning.
@return Issue The converted warning. | entailment |
public static function createFromTokenizerError(TokenizerException $tokenizerException): self
{
return new self(
$tokenizerException->getSourceLine(),
0,
"Tokenization error: " . $tokenizerException->getMessage(),
self::SEVERITY_ERROR,
get_class($tokenizerException)
);
} | Creates a new warning from a tokenizer error.
@param TokenizerException $tokenizerException The tokenizer error to convert into a warning.
@return Issue The converted warning. | entailment |
public function getPath()
{
$this->checkPathIndexNeeded();
if(empty($this->parameters['name'])) {
throw new \Exception('Method "name($name)" must be called before submitting request.');
}
return rawurlencode($this->options['index']).'/replication/run';
} | {@inheritdoc} | entailment |
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/lastfm.php', 'lastfm');
$this->app->bind(Lastfm::class, function () {
return new Lastfm(new \GuzzleHttp\Client(), config('lastfm.api_key'));
});
} | Register any package services. | entailment |
public function getConfig()
{
$config = [];
foreach ($this->providers as $key => $provider) {
$config[$key] = $provider->getConfig();
}
return $config;
} | Aggregates the config from the providers, and returns a hash with the namespace as the key, and the config
as the value.
@return array | entailment |
public function createCommand($name)
{
$startTimestamp = time();
#######################
# Build Paths #
#######################
$basePath = $this->getStashEntryPath($name);
$databaseDestination = $basePath . '/database.sql';
$persistentDestination = $basePath . '/persistent/';
FileUtils::createDirectoryRecursively($basePath);
#######################
# Check Configuration #
#######################
$this->checkConfiguration();
##################
# Define Secrets #
##################
$this->addSecret($this->databaseConfiguration['user']);
$this->addSecret($this->databaseConfiguration['password']);
######################
# Write Manifest #
######################
$this->renderHeadLine('Write Manifest');
$presetName = $this->configurationService->getCurrentPreset();
$presetConfiguration = $this->configurationService->getCurrentConfiguration();
$cloneTimestamp = $this->configurationService->getMostRecentCloneTimeStamp();
$stashTimestamp = time();
$this->writeStashEntryManifest($name, [
'preset' => [
'name' => $presetName,
'configuration' => $presetConfiguration
],
'cloned_at' => $cloneTimestamp,
'stashed_at' => $stashTimestamp
]);
######################
# Backup Database #
######################
$this->renderHeadLine('Backup Database');
$this->executeLocalShellCommand(
'mysqldump --single-transaction --add-drop-table --host="%s" --user="%s" --password="%s" %s > %s',
[
$this->databaseConfiguration['host'],
$this->databaseConfiguration['user'],
$this->databaseConfiguration['password'],
$this->databaseConfiguration['dbname'],
$databaseDestination
]
);
###############################
# Backup Persistent Resources #
###############################
$this->renderHeadLine('Backup Persistent Resources');
$this->executeLocalShellCommand(
'cp -al %s %s',
[
FLOW_PATH_ROOT . 'Data/Persistent',
$persistentDestination
]
);
#################
# Final Message #
#################
$endTimestamp = time();
$duration = $endTimestamp - $startTimestamp;
$this->renderHeadLine('Done');
$this->renderLine('Successfuly stashed %s in %s seconds', [$name, $duration]);
} | Creates a new stash entry with the given name.
@param string $name The name for the new stash entry
@return void | entailment |
public function listCommand()
{
$head = ['Name', 'Stashed At', 'From Preset', 'Cloned At'];
$rows = [];
$basePath = sprintf(FLOW_PATH_ROOT . 'Data/MagicWandStash');
if (!is_dir($basePath)) {
$this->renderLine('Stash is empty.');
$this->quit(1);
}
$baseDir = new \DirectoryIterator($basePath);
$anyEntry = false;
foreach ($baseDir as $entry) {
if (!in_array($entry, ['.', '..'])) {
$stashEntryName = $entry->getFilename();
$manifest = $this->readStashEntryManifest($stashEntryName) ?: [];
$rows[] = [
$stashEntryName,
$manifest['stashed_at'] ? date('Y-m-d H:i:s', $manifest['stashed_at']) : 'N/A',
isset($manifest['preset']['name']) ? $manifest['preset']['name'] : 'N/A',
$manifest['cloned_at'] ? date('Y-m-d H:i:s', $manifest['cloned_at']) : 'N/A',
];
$anyEntry = true;
}
}
if (!$anyEntry) {
$this->renderLine('Stash is empty.');
$this->quit(1);
}
$this->output->outputTable($rows, $head);
} | Lists all entries
@return void | entailment |
public function clearCommand()
{
$startTimestamp = time();
$path = FLOW_PATH_ROOT . 'Data/MagicWandStash';
FileUtils::removeDirectoryRecursively($path);
#################
# Final Message #
#################
$endTimestamp = time();
$duration = $endTimestamp - $startTimestamp;
$this->renderHeadLine('Done');
$this->renderLine('Cleanup successful in %s seconds', [$duration]);
} | Clear the whole stash
@return void | entailment |
public function restoreCommand($name, $yes = false, $keepDb = false)
{
$basePath = $this->getStashEntryPath($name);
$this->restoreStashEntry($basePath, $name, $yes, true, $keepDb);
} | Restores stash entries
@param string $name The name of the stash entry that will be restored
@param boolean $yes confirm execution without further input
@param boolean $keepDb skip dropping of database during sync
@return void | entailment |
public function removeCommand($name, $yes = false)
{
$directory = FLOW_PATH_ROOT . 'Data/MagicWandStash/' . $name;
if (!is_dir($directory)) {
$this->renderLine('<error>%s does not exist</error>', [$name]);
$this->quit(1);
}
if (!$yes) {
$this->renderLine("Are you sure you want to do this? Type 'yes' to continue: ");
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
if (trim($line) != 'yes') {
$this->renderLine('exit');
$this->quit(1);
} else {
$this->renderLine();
$this->renderLine();
}
}
###############
# Start Timer #
###############
$startTimestamp = time();
FileUtils::removeDirectoryRecursively($directory);
#################
# Final Message #
#################
$endTimestamp = time();
$duration = $endTimestamp - $startTimestamp;
$this->renderHeadLine('Done');
$this->renderLine('Cleanup removed stash %s in %s seconds', [$name, $duration]);
} | Remove a named stash entry
@param string $name The name of the stash entry that will be removed
@param boolean $yes confirm execution without further input
@return void | entailment |
protected function restoreStashEntry($source, $name, $force = false, $preserve = true, $keepDb = false)
{
if (!is_dir($source)) {
$this->renderLine('<error>%s does not exist</error>', [$name]);
$this->quit(1);
}
#################
# Are you sure? #
#################
if (!$force) {
$this->renderLine("Are you sure you want to do this? Type 'yes' to continue: ");
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
if (trim($line) != 'yes') {
$this->renderLine('exit');
$this->quit(1);
} else {
$this->renderLine();
$this->renderLine();
}
}
######################
# Measure Start Time #
######################
$startTimestamp = time();
#######################
# Check Configuration #
#######################
$this->checkConfiguration();
##################
# Define Secrets #
##################
$this->addSecret($this->databaseConfiguration['user']);
$this->addSecret($this->databaseConfiguration['password']);
########################
# Drop and Recreate DB #
########################
if ($keepDb == false) {
$this->renderHeadLine('Drop and Recreate DB');
$emptyLocalDbSql = 'DROP DATABASE `'
. $this->databaseConfiguration['dbname']
. '`; CREATE DATABASE `'
. $this->databaseConfiguration['dbname']
. '` collate utf8_unicode_ci;';
$this->executeLocalShellCommand(
'echo %s | mysql --host=%s --user=%s --password=%s',
[
escapeshellarg($emptyLocalDbSql),
$this->databaseConfiguration['host'],
$this->databaseConfiguration['user'],
$this->databaseConfiguration['password']
]
);
} else {
$this->renderHeadLine('Skipped (Drop and Recreate DB)');
}
######################
# Restore Database #
######################
$this->renderHeadLine('Restore Database');
$this->executeLocalShellCommand(
'mysql --host="%s" --user="%s" --password="%s" %s < %s',
[
$this->databaseConfiguration['host'],
$this->databaseConfiguration['user'],
$this->databaseConfiguration['password'],
$this->databaseConfiguration['dbname'],
$source . '/database.sql'
]
);
################################
# Restore Persistent Resources #
################################
$this->renderHeadLine('Restore Persistent Resources');
$this->executeLocalShellCommand(
'rm -rf %s && cp -al %s %1$s',
[
FLOW_PATH_ROOT . 'Data/Persistent',
$source . '/persistent'
]
);
if (!$preserve) {
FileUtils::removeDirectoryRecursively($source);
}
################
# Clear Caches #
################
$this->renderHeadLine('Clear Caches');
$this->executeLocalFlowCommand('flow:cache:flush');
##############
# Migrate DB #
##############
$this->renderHeadLine('Migrate DB');
$this->executeLocalFlowCommand('doctrine:migrate');
#####################
# Publish Resources #
#####################
$this->renderHeadLine('Publish Resources');
$this->executeLocalFlowCommand('resource:publish');
#############################
# Restore Clone Information #
#############################
if($manifest = $this->readStashEntryManifest($name)) {
$this->configurationService->setCurrentStashEntry($name, $manifest);
}
#################
# Final Message #
#################
$endTimestamp = time();
$duration = $endTimestamp - $startTimestamp;
$this->renderHeadLine('Done');
$this->renderLine('Successfuly restored %s in %s seconds', [$name, $duration]);
} | Actual restore logic
@param string $source
@param string $name
@param boolean $force
@param boolean $keepDb
@return void | entailment |
public function fillFieldWithValue($field, $value = '')
{
$fieldNode = $this->spin(
function () use ($field) {
$fieldNode = $this->getSession()->getPage()->findField($field);
if ($fieldNode == null) {
throw new \Exception('Field not found');
}
return $fieldNode;
}
);
$this->spin(
function () use ($fieldNode, $field, $value) {
// make sure any autofocus elements don't mis-behave when setting value
$fieldNode->blur();
usleep(10 * 1000);
$fieldNode->focus();
usleep(10 * 1000);
// setting value on pre-filled inputs can cause issues, clearing before
$fieldNode->setValue('');
$fieldNode->setValue($value);
// verication that the field was really filled in correctly
$this->sleep();
$check = $this->getSession()->getPage()->findField($field)->getValue();
if ($check != $value) {
throw new \Exception('Failed to set the field value: ' . $check);
}
return true;
}
);
} | @When I fill in :field with :value
@When I set :field as empty
Spin function make it possible to retry in case of failure | entailment |
public function clickEditActionBar($button)
{
$actionBarElements = $this->findAllWithWait('.ez-editactionbar-container .ez-action .action-label');
foreach ($actionBarElements as $element) {
if ($element->isVisible() && $element->getText() === $button) {
$element->click();
$this->waitWhileLoading();
return;
}
}
throw new \Exception("Couldn't click element {$button}");
} | @Given I click (on) the edit action bar button :button
Click on a PlatformUI edit action bar
@param string $button Text of the element to click | entailment |
public function goToContentWithPath($path)
{
$this->clickNavigationZone('Content');
$this->clickNavigationItem('Content structure');
$this->clickOnBrowsePath($path);
$this->confirmSelection();
} | Opens a content in PlatformUi. | entailment |
public function load(array $configs, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$container->getDefinition('prezent_doctrine_translatable.listener')
->addMethodCall('setCurrentLocale', array($config['fallback_locale']))
->addMethodCall('setFallbackLocale', array($config['fallback_locale']));
$this->loadSonata($container, $loader);
} | {@inheritdoc} | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.