sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function validateObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
{
$contentObjectAttributeID = $contentObjectAttribute->attribute( 'id' );
$keywordString = trim( $http->postVariable( $base . '_eztags_data_text_' . $contentObjectAttributeID, '' ) );
$parentString = trim( $http->postVariable( $base . '_eztags_data_text2_' . $contentObjectAttributeID, '' ) );
$idString = trim( $http->postVariable( $base . '_eztags_data_text3_' . $contentObjectAttributeID, '' ) );
$localeString = trim( $http->postVariable( $base . '_eztags_data_text4_' . $contentObjectAttributeID, '' ) );
return $this->validateObjectAttribute( $contentObjectAttribute, $idString, $keywordString, $parentString, $localeString );
} | Validates the input and returns true if the input was valid for this datatype
@param eZHTTPTool $http
@param string $base
@param eZContentObjectAttribute $contentObjectAttribute
@return bool | entailment |
public function fetchObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
{
$contentObjectAttributeID = $contentObjectAttribute->attribute( 'id' );
if ( !$http->hasPostVariable( $base . '_eztags_data_text_' . $contentObjectAttributeID ) )
return false;
if ( !$http->hasPostVariable( $base . '_eztags_data_text2_' . $contentObjectAttributeID ) )
return false;
if ( !$http->hasPostVariable( $base . '_eztags_data_text3_' . $contentObjectAttributeID ) )
return false;
if ( !$http->hasPostVariable( $base . '_eztags_data_text4_' . $contentObjectAttributeID ) )
return false;
$keywordString = trim( $http->postVariable( $base . '_eztags_data_text_' . $contentObjectAttributeID ) );
$parentString = trim( $http->postVariable( $base . '_eztags_data_text2_' . $contentObjectAttributeID ) );
$idString = trim( $http->postVariable( $base . '_eztags_data_text3_' . $contentObjectAttributeID ) );
$localeString = trim( $http->postVariable( $base . '_eztags_data_text4_' . $contentObjectAttributeID ) );
$eZTags = eZTags::createFromStrings( $contentObjectAttribute, $idString, $keywordString, $parentString, $localeString );
$contentObjectAttribute->setContent( $eZTags );
return true;
} | Fetches the HTTP POST input and stores it in the data instance
@param eZHTTPTool $http
@param string $base
@param eZContentObjectAttribute $contentObjectAttribute
@return bool | entailment |
public function storeObjectAttribute( $attribute )
{
/** @var $eZTags eZTags */
$eZTags = $attribute->content();
if ( $eZTags instanceof eZTags )
$eZTags->store( $attribute );
} | Stores the object attribute
@param eZContentObjectAttribute $attribute | entailment |
public function validateClassAttributeHTTPInput( $http, $base, $attribute )
{
$classAttributeID = $attribute->attribute( 'id' );
$maxTags = trim( $http->postVariable( $base . self::MAX_TAGS_VARIABLE . $classAttributeID, '' ) );
if ( ( !is_numeric( $maxTags ) && !empty( $maxTags ) ) || (int) $maxTags < 0 )
return eZInputValidator::STATE_INVALID;
$subTreeLimit = (int) $http->postVariable( $base . self::SUBTREE_LIMIT_VARIABLE . $classAttributeID, -1 );
if ( $subTreeLimit < 0 )
return eZInputValidator::STATE_INVALID;
if ( $subTreeLimit > 0 )
{
$tag = eZTagsObject::fetchWithMainTranslation( $subTreeLimit );
if ( !$tag instanceof eZTagsObject || $tag->attribute( 'main_tag_id' ) > 0 )
return eZInputValidator::STATE_INVALID;
}
return eZInputValidator::STATE_ACCEPTED;
} | Validates class attribute HTTP input
@param eZHTTPTool $http
@param string $base
@param eZContentClassAttribute $attribute
@return bool | entailment |
public function fetchClassAttributeHTTPInput( $http, $base, $attribute )
{
$classAttributeID = $attribute->attribute( 'id' );
$subTreeLimit = (int) $http->postVariable( $base . self::SUBTREE_LIMIT_VARIABLE . $classAttributeID, -1 );
$maxTags = (int) trim( $http->postVariable( $base . self::MAX_TAGS_VARIABLE . $classAttributeID, -1 ) );
if ( $subTreeLimit < 0 || $maxTags < 0 )
return false;
$hideRootTag = (int) $http->hasPostVariable( $base . self::HIDE_ROOT_TAG_VARIABLE . $classAttributeID );
$editView = trim( $http->postVariable( $base . self::EDIT_VIEW_VARIABLE . $classAttributeID, self::EDIT_VIEW_DEFAULT_VALUE ) );
$eZTagsIni = eZINI::instance( 'eztags.ini' );
$availableEditViews = $eZTagsIni->variable( 'EditSettings', 'AvailableViews' );
if ( !in_array( $editView, array_keys( $availableEditViews ) ) )
return false;
$attribute->setAttribute( self::SUBTREE_LIMIT_FIELD, $subTreeLimit );
$attribute->setAttribute( self::HIDE_ROOT_TAG_FIELD, $hideRootTag );
$attribute->setAttribute( self::MAX_TAGS_FIELD, $maxTags );
$attribute->setAttribute( self::EDIT_VIEW_FIELD, $editView );
return true;
} | Fetches class attribute HTTP input and stores it
@param eZHTTPTool $http
@param string $base
@param eZContentClassAttribute $attribute
@return bool | entailment |
public function unserializeContentClassAttribute( $classAttribute, $attributeNode, $attributeParametersNode )
{
/** @var $domNodes DOMNodeList */
$subTreeLimit = 0;
$domNodes = $attributeParametersNode->getElementsByTagName( 'subtree-limit' );
if ( $domNodes->length > 0 )
$subTreeLimit = (int) $domNodes->item( 0 )->textContent;
$maxTags = 0;
$domNodes = $attributeParametersNode->getElementsByTagName( 'max-tags' );
if ( $domNodes->length > 0 )
$maxTags = (int) $domNodes->item( 0 )->textContent;
$hideRootTag = 0;
$domNodes = $attributeParametersNode->getElementsByTagName( 'hide-root-tag' );
if ( $domNodes->length > 0 && $domNodes->item( 0 )->textContent === 'true' )
$hideRootTag = 1;
$editView = self::EDIT_VIEW_DEFAULT_VALUE;
$domNodes = $attributeParametersNode->getElementsByTagName( 'edit-view' );
if ( $domNodes->length > 0 )
{
$domNodeContent = trim( $domNodes->item( 0 )->textContent );
if ( !empty( $domNodeContent ) )
{
$editView = $domNodeContent;
}
}
$classAttribute->setAttribute( self::SUBTREE_LIMIT_FIELD, $subTreeLimit );
$classAttribute->setAttribute( self::MAX_TAGS_FIELD, $maxTags );
$classAttribute->setAttribute( self::HIDE_ROOT_TAG_FIELD, $hideRootTag );
$classAttribute->setAttribute( self::EDIT_VIEW_FIELD, $editView );
} | Extracts values from the attribute parameters and sets it in the class attribute.
@param eZContentClassAttribute $classAttribute
@param DOMElement $attributeNode
@param DOMElement $attributeParametersNode | entailment |
public function serializeContentClassAttribute( $classAttribute, $attributeNode, $attributeParametersNode )
{
$dom = $attributeParametersNode->ownerDocument;
$subTreeLimit = (string) $classAttribute->attribute( self::SUBTREE_LIMIT_FIELD );
$domNode = $dom->createElement( 'subtree-limit' );
$domNode->appendChild( $dom->createTextNode( $subTreeLimit ) );
$attributeParametersNode->appendChild( $domNode );
$maxTags = (string) $classAttribute->attribute( self::MAX_TAGS_FIELD );
$domNode = $dom->createElement( 'max-tags' );
$domNode->appendChild( $dom->createTextNode( $maxTags ) );
$attributeParametersNode->appendChild( $domNode );
$hideRootTag = ( (int) $classAttribute->attribute( self::HIDE_ROOT_TAG_FIELD ) ) > 0 ? 'true' : 'false';
$domNode = $dom->createElement( 'hide-root-tag' );
$domNode->appendChild( $dom->createTextNode( $hideRootTag ) );
$attributeParametersNode->appendChild( $domNode );
$editView = (string) $classAttribute->attribute( self::EDIT_VIEW_FIELD );
$domNode = $dom->createElement( 'edit-view' );
$domNode->appendChild( $dom->createTextNode( $editView ) );
$attributeParametersNode->appendChild( $domNode );
} | Adds the necessary DOM structure to the attribute parameters
@param eZContentClassAttribute $classAttribute
@param DOMNode $attributeNode
@param DOMNode $attributeParametersNode | entailment |
public function metaData( $attribute )
{
/** @var $eZTags eZTags */
$eZTags = $attribute->content();
if ( !$eZTags instanceof eZTags )
return '';
$indexSynonyms = eZINI::instance( 'eztags.ini' )->variable( 'SearchSettings', 'IndexSynonyms' ) === 'enabled';
$keywords = array();
$tags = $eZTags->attribute( 'tags' );
/** @var eZTagsObject $tag */
foreach ( $tags as $tag )
{
if ( !$indexSynonyms && $tag->isSynonym() )
$tag = $tag->getMainTag();
if ( $tag instanceof eZTagsObject )
{
$keyword = $tag->getKeyword( $attribute->attribute( 'language_code' ) );
if ( !$keyword )
{
//fall back to main language
/** @var eZContentLanguage $mainLanguage */
$mainLanguage = eZContentLanguage::fetch( $tag->attribute( 'main_language_id') );
if ( $mainLanguage instanceof eZContentLanguage )
$keyword = $tag->getKeyword( $mainLanguage->attribute( 'locale' ) );
}
if ( $keyword )
$keywords[] = $keyword;
}
}
return implode( ', ', array_unique( $keywords ) );
} | Returns the meta data used for storing search indices
@param eZContentObjectAttribute $attribute
@return string | entailment |
public function deleteStoredObjectAttribute( $contentObjectAttribute, $version = null )
{
$contentObjectAttributeID = $contentObjectAttribute->attribute( 'id' );
eZTagsAttributeLinkObject::removeByAttribute( $contentObjectAttributeID, $version );
} | Delete stored object attribute
@param eZContentObjectAttribute $contentObjectAttribute
@param eZContentObjectVersion $version | entailment |
public function hasObjectAttributeContent( $contentObjectAttribute )
{
/** @var $eZTags eZTags */
$eZTags = $contentObjectAttribute->content();
if ( !$eZTags instanceof eZTags )
return false;
$tagsCount = $eZTags->attribute( 'tags_count' );
return $tagsCount > 0;
} | Returns true if content object attribute has content
@param eZContentObjectAttribute $contentObjectAttribute
@return bool | entailment |
public function toString( $contentObjectAttribute )
{
/** @var $eZTags eZTags */
$eZTags = $contentObjectAttribute->content();
if ( !$eZTags instanceof eZTags )
return '';
$returnArray = array();
$returnArray[] = $eZTags->attribute( 'id_string' );
$returnArray[] = $eZTags->attribute( 'keyword_string' );
$returnArray[] = $eZTags->attribute( 'parent_string' );
$returnArray[] = $eZTags->attribute( 'locale_string' );
return implode( '|#', $returnArray );
} | Returns string representation of a content object attribute
@param eZContentObjectAttribute $contentObjectAttribute
@return string | entailment |
public function fromString( $contentObjectAttribute, $string )
{
$idString = '';
$keywordString = '';
$parentString = '';
$localeString = '';
$string = trim( $string );
if ( !empty( $string ) )
{
$itemsArray = explode( '|#', $string );
if ( !is_array( $itemsArray ) || empty( $itemsArray ) || count( $itemsArray ) % 4 != 0 )
return false;
$tagsCount = count( $itemsArray ) / 4;
$idArray = array_slice( $itemsArray, 0, $tagsCount );
$keywordArray = array_slice( $itemsArray, $tagsCount, $tagsCount );
$parentArray = array_slice( $itemsArray, $tagsCount * 2, $tagsCount );
$localeArray = array_slice( $itemsArray, $tagsCount * 3, $tagsCount );
$idString = implode( '|#', $idArray );
$keywordString = implode( '|#', $keywordArray );
$parentString = implode( '|#', $parentArray );
$localeString = implode( '|#', $localeArray );
}
$validationResult = $this->validateObjectAttribute( $contentObjectAttribute, $idString, $keywordString, $parentString, $localeString );
if ( $validationResult != eZInputValidator::STATE_ACCEPTED )
return false;
$eZTags = eZTags::createFromStrings( $contentObjectAttribute, $idString, $keywordString, $parentString, $localeString );
$contentObjectAttribute->setContent( $eZTags );
return true;
} | Creates the content object attribute content from the input string
Valid string value is list of ids, followed by list of keywords,
followed by list of parent ids, followed by list of locales
all together separated by '|#'
for example "1|#2|#3|#first tag|#second tag|#third tag|#12|#13|#14|#eng-GB|#eng-GB|#eng-GB"
@param eZContentObjectAttribute $contentObjectAttribute
@param string $string
@return bool | entailment |
public function serializeContentObjectAttribute( $package, $objectAttribute )
{
$node = $this->createContentObjectAttributeDOMNode( $objectAttribute );
/** @var $eZTags eZTags */
$eZTags = $objectAttribute->content();
if ( !$eZTags instanceof eZTags )
return $node;
$dom = $node->ownerDocument;
$idStringNode = $dom->createElement( 'id-string' );
$idStringNode->appendChild( $dom->createTextNode( $eZTags->attribute( 'id_string' ) ) );
$node->appendChild( $idStringNode );
$keywordStringNode = $dom->createElement( 'keyword-string' );
$keywordStringNode->appendChild( $dom->createTextNode( $eZTags->attribute( 'keyword_string' ) ) );
$node->appendChild( $keywordStringNode );
$parentStringNode = $dom->createElement( 'parent-string' );
$parentStringNode->appendChild( $dom->createTextNode( $eZTags->attribute( 'parent_string' ) ) );
$node->appendChild( $parentStringNode );
$localeStringNode = $dom->createElement( 'locale-string' );
$localeStringNode->appendChild( $dom->createTextNode( $eZTags->attribute( 'locale_string' ) ) );
$node->appendChild( $localeStringNode );
return $node;
} | Serializes the content object attribute
@param eZPackage $package
@param eZContentObjectAttribute $objectAttribute
@return DOMNode | entailment |
public function unserializeContentObjectAttribute( $package, $objectAttribute, $attributeNode )
{
$idString = $attributeNode->getElementsByTagName( 'id-string' )->item( 0 )->textContent;
$keywordString = $attributeNode->getElementsByTagName( 'keyword-string' )->item( 0 )->textContent;
$parentString = $attributeNode->getElementsByTagName( 'parent-string' )->item( 0 )->textContent;
$localeString = $attributeNode->getElementsByTagName( 'locale-string' )->item( 0 )->textContent;
$validationResult = $this->validateObjectAttribute( $objectAttribute, $idString, $keywordString, $parentString, $localeString );
if ( $validationResult == eZInputValidator::STATE_ACCEPTED )
{
$eZTags = eZTags::createFromStrings( $objectAttribute, $idString, $keywordString, $parentString, $localeString );
$objectAttribute->setContent( $eZTags );
}
} | Unserializes the content object attribute from provided DOM node
@param eZPackage $package
@param eZContentObjectAttribute $objectAttribute
@param DOMElement $attributeNode | entailment |
private function isEmptyLine(array $tokensInLine): bool
{
if (count($tokensInLine) > 1) {
return false;
}
$firstToken = $tokensInLine[0];
return $firstToken->getType() === TokenInterface::TYPE_WHITESPACE && $firstToken->getValue() === "\n";
} | Checks if a stream of tokens is an empty line.
@param TokenInterface[] $tokensInLine
@return bool | entailment |
private function reduceIndentationLevel(int $indentationLevel, array $tokensInLine): int
{
$raisingIndentation = [
TokenInterface::TYPE_BRACE_CLOSE,
];
if ($this->indentConditions) {
$raisingIndentation[] = TokenInterface::TYPE_CONDITION_END;
}
foreach ($tokensInLine as $token) {
if (in_array($token->getType(), $raisingIndentation)) {
if ($token->getType() === TokenInterface::TYPE_CONDITION_END) {
$this->insideCondition = false;
}
return $indentationLevel - 1;
}
}
return $indentationLevel;
} | Check whether indentation should be reduced by one level, for current line.
Checks tokens in current line, and whether they will reduce the indentation by one.
@param int $indentationLevel The current indentation level
@param TokenInterface[] $tokensInLine
@return int The new indentation level | entailment |
private function raiseIndentationLevel(int $indentationLevel, array $tokensInLine): int
{
$raisingIndentation = [
TokenInterface::TYPE_BRACE_OPEN,
];
if ($this->indentConditions && $this->insideCondition === false) {
$raisingIndentation[] = TokenInterface::TYPE_CONDITION;
}
foreach ($tokensInLine as $token) {
if (in_array($token->getType(), $raisingIndentation)) {
if ($token->getType() === TokenInterface::TYPE_CONDITION) {
$this->insideCondition = true;
}
return $indentationLevel + 1;
}
}
return $indentationLevel;
} | Check whether indentation should be raised by one level, for current line.
Checks tokens in current line, and whether they will raise the indentation by one.
@param int $indentationLevel The current indentation level
@param TokenInterface[] $tokensInLine
@return int The new indentation level | entailment |
public function execute(EntityInterface $entity = NULL, array &$normalized = NULL, array $context = NULL) {
$config = $this->getConfiguration();
$drupal_predicate = $config[self::URI_PREDICATE];
if (!is_null($drupal_predicate) && !empty($drupal_predicate)) {
$url = $entity
->toUrl('canonical', ['absolute' => TRUE])
->setRouteParameter('_format', 'jsonld')
->toString();
if ($context['needs_jsonldcontext'] === FALSE) {
$drupal_predicate = NormalizerBase::escapePrefix($drupal_predicate, $context['namespaces']);
}
if (isset($normalized['@graph']) && is_array($normalized['@graph'])) {
foreach ($normalized['@graph'] as &$graph) {
if (isset($graph['@id']) && $graph['@id'] == $url) {
if ($entity instanceof MediaInterface) {
$file = $this->mediaSource->getSourceFile($entity);
$url = $file->url('canonical', ['absolute' => TRUE]);
}
if (isset($graph[$drupal_predicate])) {
if (!is_array($graph[$drupal_predicate])) {
if ($graph[$drupal_predicate] == $url) {
// Don't add it if it already exists.
return;
}
$tmp = $graph[$drupal_predicate];
$graph[$drupal_predicate] = [$tmp];
}
elseif (array_search($url, array_column($graph[$drupal_predicate], '@value'))) {
// Don't add it if it already exists.
return;
}
}
else {
$graph[$drupal_predicate] = [];
}
$graph[$drupal_predicate][] = ["@value" => $url];
return;
}
}
}
}
} | {@inheritdoc} | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$config = $this->getConfiguration();
$form[self::URI_PREDICATE] = [
'#type' => 'textfield',
'#title' => $this->t('Drupal URI predicate'),
'#description' => $this->t("The Drupal object's URI will be added to the resource with this predicate. Must use a defined prefix."),
'#default_value' => isset($config[self::URI_PREDICATE]) ? $config[self::URI_PREDICATE] : '',
'#size' => 35,
];
return $form;
} | {@inheritdoc} | entailment |
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
$drupal_predicate = $form_state->getValue(self::URI_PREDICATE);
if (!is_null($drupal_predicate) and !empty($drupal_predicate)) {
if (preg_match('/^https?:\/\//', $drupal_predicate)) {
// Can't validate all URIs so we have to trust them.
return;
}
elseif (preg_match('/^([^\s:]+):/', $drupal_predicate, $matches)) {
$predicate_prefix = $matches[1];
$rdf = rdf_get_namespaces();
$rdf_prefixes = array_keys($rdf);
if (!in_array($predicate_prefix, $rdf_prefixes)) {
$form_state->setErrorByName(
self::URI_PREDICATE,
$this->t('Namespace prefix @prefix is not registered.',
['@prefix' => $predicate_prefix]
)
);
}
}
else {
$form_state->setErrorByName(
self::URI_PREDICATE,
$this->t('Predicate must use a defined prefix or be a full URI')
);
}
}
parent::validateConfigurationForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->setConfiguration([self::URI_PREDICATE => $form_state->getValue(self::URI_PREDICATE)]);
} | {@inheritdoc} | entailment |
public function field($fieldName, $fieldValue = '', $fieldBoost = null) {
if(empty($fieldName)) {
throw new \InvalidArgumentException('Please provide a fieldname');
}
$field = array(
'name'=> $fieldName,
'value' => $fieldValue
);
if(!empty($fieldBoost)) {
$field['boost'] = $fieldBoost;
}
$this->fields[] = $field;
return $this;
} | Add a 'field' entry for this document
@param String $fieldName
@param String $fieldValue
@param int $fieldBoost
@throws \InvalidArgumentException | entailment |
public function getField($fieldName) {
if(empty($fieldName)) {
throw new \InvalidArgumentException('Please provide a fieldname');
}
$values = array();
foreach($this->fields as $field) {
if($field['name'] == $fieldName) {
$values[] = $field['value'];
}
}
return $values;
} | Return value(s) for one field
@param String $fieldName | entailment |
protected function init($curlOptions)
{
$client = new Curl;
$client->setVerifyPeer(false);
$client->setTimeout(60000);
foreach($curlOptions as $option => $value) {
$client->setOption($option, $value);
}
$this->client = $client;
$this->browser = new Browser($client);
} | Initialise | entailment |
private function buildUrl($request) {
return $this->options['url'] . $request->getUrlPrefix() . $request->getPath() . '?' . $this->getUrlPartParameters($request);
} | Build final URL to call
@param OpenSearchServer\Request $request | entailment |
public function submit(Request $request)
{
try {
$response = $this->browser->call(
$this->buildUrl($request),
$request->getMethod(),
$request->getHeaders(),
$request->getData()
);
$response = ResponseFactory::createResponse($response, $request);
return $response;
} catch(\Exception $e) {
throw new Exception\OpenSearchServerException('Error while connecting to OpenSearchServer: ' . $e->getMessage(), 1);
}
} | Submit a request to the API.
@param OpenSearchServer\Request $request
@return object | entailment |
public function submitFile(RequestFile $requestOSS, array $options = array()) {
$request = curl_init($this->buildUrl($requestOSS));
($requestOSS->getMethod() == 'PUT') ?
curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'PUT') :
curl_setopt($request, CURLOPT_POST, true);
$args['file'] = new \CurlFile($requestOSS->getFilePath());
curl_setopt($request, CURLOPT_POSTFIELDS, $args);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
//send
$content = curl_exec ( $request );
//build BuzzResponse
$errmsg = curl_error ( $request );
$headers = curl_getinfo ( $request );
$httpCode = curl_getinfo ( $request, CURLINFO_HTTP_CODE );
//build header for BuzzResponse to parse HTTP code properly
$newHeader = 'HTTP ' . $httpCode . ' ';
$newHeader .= ($errmsg) ? $errmsg : '-';
array_unshift($headers, $newHeader);
$response = new BuzzResponse();
$response->setContent($content);
$response->setHeaders($headers);
//force parsing of first header
$response->getStatusCode();
curl_close($request);
//build and return an OpenSearchServer\Response
return new \OpenSearchServer\Response\Response($response, $requestOSS);
} | Submit a PUT or POST request to the API, sending a file using CURL directly.
@param OpenSearchServer\RequestFile $requestOSS
@param array $options | entailment |
public function attribute( $name )
{
if ( !$this->hasAttribute( $name ) )
{
eZDebug::writeError( "Attribute '$name' does not exist", __METHOD__ );
return null;
}
if ( $name == 'tags' )
return $this->tags();
else if ( $name == 'tags_count' )
return $this->tagsCount();
else if ( $name == 'permission_array' )
return $this->getPermissionArray();
else if ( $name == 'tag_ids' )
return $this->IDArray;
else if ( $name == 'keywords' )
return $this->KeywordArray;
else if ( $name == 'parent_ids' )
return $this->ParentArray;
else if ( $name == 'locales' )
return $this->LocaleArray;
else if ( $name == 'id_string' )
return $this->idString();
else if ( $name == 'keyword_string' )
return $this->keywordString();
else if ( $name == 'meta_keyword_string' )
return $this->metaKeywordString();
else if ( $name == 'parent_string' )
return $this->parentString();
else if ( $name == 'locale_string' )
return $this->localeString();
return null;
} | Returns the specified attribute
@param string $name
@return mixed | entailment |
static public function createFromStrings( eZContentObjectAttribute $attribute, $idString, $keywordString, $parentString, $localeString )
{
$idArray = explode( '|#', $idString );
$keywordArray = explode( '|#', $keywordString );
$parentArray = explode( '|#', $parentString );
$localeArray = explode( '|#', $localeString );
$wordArray = array();
foreach ( array_keys( $idArray ) as $key )
{
$wordArray[] = trim( $idArray[$key] ) . "|#" . trim( $keywordArray[$key] ) . "|#" . trim( $parentArray[$key] ) . "|#" . trim( $localeArray[$key] );
}
$idArray = array();
$keywordArray = array();
$parentArray = array();
$localeArray = array();
$db = eZDB::instance();
$wordArray = array_unique( $wordArray );
foreach ( $wordArray as $wordKey )
{
$word = explode( '|#', $wordKey );
if ( $word[0] != '' )
{
$idArray[] = (int) $word[0];
$keywordArray[] = trim( $word[1] );
$parentArray[] = (int) $word[2];
$localeArray[] = trim( $word[3] );
}
}
return new self( $attribute, $idArray, $keywordArray, $parentArray, $localeArray );
} | Initializes the tags
@static
@param eZContentObjectAttribute $attribute
@param string $idString
@param string $keywordString
@param string $parentString
@param string $localeString
@return eZTags The newly created eZTags object | entailment |
static public function createFromAttribute( eZContentObjectAttribute $attribute, $locale = null )
{
$idArray = array();
$keywordArray = array();
$parentArray = array();
$localeArray = array();
if ( !is_numeric( $attribute->attribute( 'id' ) ) || !is_numeric( $attribute->attribute( 'version' ) ) )
return new self( $attribute, $idArray, $keywordArray, $parentArray, $localeArray );
if ( $locale === null || !is_string( $locale ) )
$locale = $attribute->attribute( 'language_code' );
// First fetch IDs of tags translated to defined locale
$db = eZDB::instance();
$words = $db->arrayQuery( "SELECT
eztags.id
FROM eztags_attribute_link, eztags, eztags_keyword
WHERE eztags_attribute_link.keyword_id = eztags.id AND
eztags.id = eztags_keyword.keyword_id AND eztags_keyword.locale = '" .
$db->escapeString( $locale ) . "' AND
eztags_keyword.status = " . eZTagsKeyword::STATUS_PUBLISHED . " AND
eztags_attribute_link.objectattribute_id = " . (int) $attribute->attribute( 'id' ) . " AND
eztags_attribute_link.objectattribute_version = " . (int) $attribute->attribute( 'version' ) );
$foundIdArray = array();
foreach ( $words as $word )
{
$foundIdArray[] = (int) $word['id'];
}
// Next, fetch all tags with help from IDs found before in the second part of the clause
$dbString = '';
if ( !empty( $foundIdArray ) )
$dbString = $db->generateSQLINStatement( $foundIdArray, 'eztags.id', true, true, 'int' ) . ' AND ';
$words = $db->arrayQuery( "SELECT DISTINCT
eztags.id,
eztags_keyword.keyword,
eztags.parent_id,
eztags_keyword.locale,
eztags_attribute_link.priority
FROM eztags_attribute_link, eztags, eztags_keyword
WHERE eztags_attribute_link.keyword_id = eztags.id AND
eztags.id = eztags_keyword.keyword_id AND eztags_keyword.locale = '" .
$db->escapeString( $locale ) . "' AND
eztags_keyword.status = " . eZTagsKeyword::STATUS_PUBLISHED . " AND
eztags_attribute_link.objectattribute_id = " . (int) $attribute->attribute( 'id' ) . " AND
eztags_attribute_link.objectattribute_version = " . (int) $attribute->attribute( 'version' ) . "
UNION
SELECT DISTINCT
eztags.id,
eztags_keyword.keyword,
eztags.parent_id,
eztags_keyword.locale,
eztags_attribute_link.priority
FROM eztags_attribute_link, eztags, eztags_keyword
WHERE eztags_attribute_link.keyword_id = eztags.id AND
eztags.id = eztags_keyword.keyword_id AND
eztags.main_language_id + MOD( eztags.language_mask, 2 ) = eztags_keyword.language_id AND
eztags_keyword.status = " . eZTagsKeyword::STATUS_PUBLISHED . " AND $dbString
eztags_attribute_link.objectattribute_id = " . (int) $attribute->attribute( 'id' ) . " AND
eztags_attribute_link.objectattribute_version = " . (int) $attribute->attribute( 'version' ) . "
ORDER BY priority ASC, id ASC" );
foreach ( $words as $word )
{
$idArray[] = $word['id'];
$keywordArray[] = $word['keyword'];
$parentArray[] = $word['parent_id'];
$localeArray[] = $word['locale'];
}
return new self( $attribute, $idArray, $keywordArray, $parentArray, $localeArray );
} | Fetches the tags for the given attribute and locale
@static
@param eZContentObjectAttribute $attribute
@param string|null $locale
@return eZTags The newly created eZTags object | entailment |
public function store( eZContentObjectAttribute $attribute )
{
$this->Attribute = $attribute;
if( !is_numeric( $this->Attribute->attribute( 'id' ) ) || !is_numeric( $this->Attribute->attribute( 'version' ) ) )
return;
$db = eZDB::instance();
$db->begin();
// first remove all links in this version, allows emptying the attribute and storing
eZTagsAttributeLinkObject::removeByAttribute( $this->Attribute->attribute( 'id' ), $this->Attribute->attribute( 'version' ) );
if ( empty( $this->IDArray ) )
{
$db->commit();
return;
}
// if for some reason already existing tags are added with ID = 0 with fromString
// check to see if they really exist, so we can link to them
// locale doesn't matter here, since we don't allow storing tags under the same
// parent that have any of translations same as any other translation from another tag
foreach ( array_keys( $this->IDArray ) as $key )
{
if ( $this->IDArray[$key] == 0 )
{
$results = $db->arrayQuery( "SELECT eztags.id
FROM eztags, eztags_keyword
WHERE eztags.id = eztags_keyword.keyword_id AND
eztags.parent_id = " . (int) $this->ParentArray[$key] . " AND
eztags_keyword.keyword LIKE '" . $db->escapeString( $this->KeywordArray[$key] ) . "'",
array( 'offset' => 0, 'limit' => 1 ) );
if ( is_array( $results ) && !empty( $results ) )
$this->IDArray[$key] = (int) $results[0]['id'];
}
}
// first check if user can really add tags, considering policies
// and subtree limits
$permissionArray = $this->getPermissionArray();
$priority = 0;
foreach ( array_keys( $this->IDArray ) as $key )
{
if ( $this->IDArray[$key] == 0 && $permissionArray['can_add'] )
{
$pathString = '/';
$depth = 0;
$parentTag = eZTagsObject::fetchWithMainTranslation( $this->ParentArray[$key] );
if ( $parentTag instanceof eZTagsObject )
{
$pathString = $parentTag->attribute( 'path_string' );
$depth = (int) $parentTag->attribute( 'depth' );
}
//and then for each tag check if user can save in one of the allowed locations
if ( self::canSave( $pathString, $permissionArray['allowed_locations'] ) )
{
self::createAndLinkTag( $this->Attribute,
$this->ParentArray[$key],
$pathString,
$depth,
$this->KeywordArray[$key],
$this->LocaleArray[$key],
$priority );
$priority++;
}
}
else if ( $this->IDArray[$key] > 0 )
{
$tagObject = eZTagsObject::fetchWithMainTranslation( $this->IDArray[$key] );
if ( !$tagObject instanceof eZTagsObject )
continue;
if ( $permissionArray['subtree_limit'] == 0 || ( $permissionArray['subtree_limit'] > 0 &&
strpos( $tagObject->attribute( 'path_string' ), '/' . $permissionArray['subtree_limit'] . '/' ) !== false ) )
{
self::linkTag( $this->Attribute, $tagObject, $this->KeywordArray[$key], $this->LocaleArray[$key], $priority );
$priority++;
}
}
}
$db->commit();
} | Stores the tags to database
@param eZContentObjectAttribute $attribute | entailment |
private function getPermissionArray()
{
$permissionArray = array(
'can_add' => false,
'subtree_limit' => $this->Attribute->contentClassAttribute()->attribute( eZTagsType::SUBTREE_LIMIT_FIELD ),
'allowed_locations' => array(),
'allowed_locations_tags' => false );
$userLimitations = eZTagsTemplateFunctions::getSimplifiedUserAccess( 'tags', 'add' );
if ( $userLimitations['accessWord'] == 'no' )
return $permissionArray;
$userLimitations = isset( $userLimitations['simplifiedLimitations']['Tag'] ) ? $userLimitations['simplifiedLimitations']['Tag'] : array();
$limitTag = eZTagsObject::fetchWithMainTranslation( $permissionArray['subtree_limit'] );
if ( empty( $userLimitations ) )
{
if ( $permissionArray['subtree_limit'] == 0 || $limitTag instanceof eZTagsObject )
{
$permissionArray['allowed_locations'] = array( $permissionArray['subtree_limit'] );
if ( $limitTag instanceof eZTagsObject )
$permissionArray['allowed_locations_tags'] = array( $limitTag );
}
}
else if ( $permissionArray['subtree_limit'] == 0 )
{
$permissionArray['allowed_locations_tags'] = array();
/** @var eZTagsObject[] $userLimitations */
$userLimitations = eZTagsObject::fetchList( array( 'id' => array( $userLimitations ) ), null, null, true );
if ( is_array( $userLimitations ) && !empty( $userLimitations ) )
{
foreach ( $userLimitations as $limitation )
{
$permissionArray['allowed_locations'][] = $limitation->attribute( 'id' );
$permissionArray['allowed_locations_tags'][] = $limitation;
}
}
}
else if ( $limitTag instanceof eZTagsObject )
{
/** @var eZTagsObject[] $userLimitations */
$userLimitations = eZTagsObject::fetchList( array( 'id' => array( $userLimitations ) ), null, null, true );
if ( is_array( $userLimitations ) && !empty( $userLimitations ) )
{
$pathString = $limitTag->attribute( 'path_string' );
foreach ( $userLimitations as $limitation )
{
if ( strpos( $pathString, '/' . $limitation->attribute( 'id' ) . '/' ) !== false )
{
$permissionArray['allowed_locations'] = array( $permissionArray['subtree_limit'] );
$permissionArray['allowed_locations_tags'] = array( $limitTag );
break;
}
}
}
}
if ( !empty( $permissionArray['allowed_locations'] ) )
$permissionArray['can_add'] = true;
return $permissionArray;
} | Returns the array with permission info for linking tags to current content object attribute
@return array | entailment |
static private function canSave( $pathString, array $allowedLocations )
{
foreach ( $allowedLocations as $location )
{
if ( $location == 0 || strpos( $pathString, '/' . $location . '/' ) !== false )
return true;
}
return false;
} | Checks if tags can be saved below tag with provided path string,
taking into account allowed locations for tag placement
@static
@param string $pathString
@param array $allowedLocations
@return bool | entailment |
static private function createAndLinkTag( eZContentObjectAttribute $attribute, $parentID, $parentPathString, $parentDepth, $keyword, $locale, $priority )
{
$languageID = eZContentLanguage::idByLocale( $locale );
if ( $languageID === false )
return;
$ini = eZINI::instance( 'eztags.ini' );
$alwaysAvailable = $ini->variable( 'GeneralSettings', 'DefaultAlwaysAvailable' );
$alwaysAvailable = $alwaysAvailable === 'true' ? 1 : 0;
$tagObject = new eZTagsObject( array(
'parent_id' => $parentID,
'main_tag_id' => 0,
'depth' => $parentDepth + 1,
'path_string' => $parentPathString,
'main_language_id' => $languageID,
'language_mask' => $languageID + $alwaysAvailable ), $locale );
$tagObject->store();
$tagKeywordObject = new eZTagsKeyword( array(
'keyword_id' => $tagObject->attribute( 'id' ),
'language_id' => $languageID + $alwaysAvailable,
'keyword' => $keyword,
'locale' => $locale,
'status' => eZTagsKeyword::STATUS_PUBLISHED ) );
$tagKeywordObject->store();
$tagObject->setAttribute( 'path_string', $tagObject->attribute( 'path_string' ) . $tagObject->attribute( 'id' ) . '/' );
$tagObject->store();
$tagObject->updateModified();
$linkObject = new eZTagsAttributeLinkObject( array(
'keyword_id' => $tagObject->attribute( 'id' ),
'objectattribute_id' => $attribute->attribute( 'id' ),
'objectattribute_version' => $attribute->attribute( 'version' ),
'object_id' => $attribute->attribute( 'contentobject_id' ),
'priority' => $priority ) );
$linkObject->store();
if ( class_exists( 'ezpEvent', false ) )
{
ezpEvent::getInstance()->filter(
'tag/add',
array(
'tag' => $tagObject,
'parentTag' => $tagObject->getParent( true )
)
);
}
} | Creates a new tag and links it to provided content object attribute
@static
@param eZContentObjectAttribute $attribute
@param int $parentID
@param string $parentPathString
@param int $parentDepth
@param string $keyword
@param string $locale | entailment |
static private function linkTag( eZContentObjectAttribute $attribute, eZTagsObject $tagObject, $keyword, $locale, $priority )
{
$languageID = eZContentLanguage::idByLocale( $locale );
if ( $languageID === false )
return;
if ( $locale == $attribute->attribute( 'language_code' ) )
{
if ( !$tagObject->hasTranslation( $locale ) )
{
$tagKeywordObject = new eZTagsKeyword( array(
'keyword_id' => $tagObject->attribute( 'id' ),
'language_id' => $languageID,
'keyword' => $keyword,
'locale' => $locale,
'status' => eZTagsKeyword::STATUS_PUBLISHED ) );
$tagKeywordObject->store();
$tagObject->updateLanguageMask();
}
}
$linkObject = new eZTagsAttributeLinkObject( array(
'keyword_id' => $tagObject->attribute( 'id' ),
'objectattribute_id' => $attribute->attribute( 'id' ),
'objectattribute_version' => $attribute->attribute( 'version' ),
'object_id' => $attribute->attribute( 'contentobject_id' ),
'priority' => $priority ) );
$linkObject->store();
} | Links the content object attribute and tag
@static
@param eZContentObjectAttribute $attribute
@param eZTagsObject $tagObject
@param string $keyword
@param string $locale | entailment |
public function tags()
{
if ( !is_array( $this->IDArray ) || empty( $this->IDArray ) )
return array();
$tags = array();
foreach ( eZTagsObject::fetchList( array( 'id' => array( $this->IDArray ) ) ) as $item )
{
$tags[array_search( $item->attribute( 'id' ), $this->IDArray )] = $item;
}
ksort( $tags );
return $tags;
} | Returns tags within this instance
@return eZTagsObject[] | entailment |
public function tagsCount()
{
if ( !is_array( $this->IDArray ) || empty( $this->IDArray ) )
return 0;
return eZTagsObject::fetchListCount( array( 'id' => array( $this->IDArray ) ) );
} | Returns the count of tags within this instance
@return int | entailment |
public function metaKeywordString()
{
$tagKeywords = array_map(
function( $tag )
{
/** @var eZTagsObject $tag */
return $tag->attribute( 'keyword' );
},
$this->tags()
);
return !empty( $tagKeywords ) ? implode( ', ', $tagKeywords ) : '';
} | Returns the keywords as a string
@return string | entailment |
public function up()
{
Schema::table('messages', function (Blueprint $table) {
$table->dropForeign('messages_thread_id_foreign');
$table->dropForeign('messages_user_id_foreign');
});
Schema::table('participants', function (Blueprint $table) {
$table->dropForeign('participants_thread_id_foreign');
$table->dropForeign('participants_user_id_foreign');
});
} | Run the migrations.
@return void | entailment |
public function generateEvent(EntityInterface $entity, UserInterface $user, array $data) {
$user_url = $user->toUrl()->setAbsolute()->toString();
if ($entity instanceof FileInterface) {
$entity_url = $entity->url();
$mimetype = $entity->getMimeType();
}
else {
$entity_url = $entity->toUrl()->setAbsolute()->toString();
$mimetype = 'text/html';
}
$event = [
"@context" => "https://www.w3.org/ns/activitystreams",
"actor" => [
"type" => "Person",
"id" => "urn:uuid:{$user->uuid()}",
"url" => [
[
"name" => "Canonical",
"type" => "Link",
"href" => "$user_url",
"mediaType" => "text/html",
"rel" => "canonical",
],
],
],
"object" => [
"id" => "urn:uuid:{$entity->uuid()}",
"url" => [
[
"name" => "Canonical",
"type" => "Link",
"href" => $entity_url,
"mediaType" => $mimetype,
"rel" => "canonical",
],
],
],
];
$entity_type = $entity->getEntityTypeId();
$event_type = $data["event"];
if ($data["event"] == "Generate Derivative") {
$event["type"] = "Activity";
$event["summary"] = $data["event"];
}
else {
$event["type"] = ucfirst($data["event"]);
$event["summary"] = ucfirst($data["event"]) . " a " . ucfirst($entity_type);
}
// Add REST links for non-file entities.
if ($entity_type != 'file') {
$event['object']['url'][] = [
"name" => "JSON",
"type" => "Link",
"href" => "$entity_url?_format=json",
"mediaType" => "application/json",
"rel" => "alternate",
];
$event['object']['url'][] = [
"name" => "JSONLD",
"type" => "Link",
"href" => "$entity_url?_format=jsonld",
"mediaType" => "application/ld+json",
"rel" => "alternate",
];
}
unset($data["event"]);
unset($data["queue"]);
if (!empty($data)) {
$event["attachment"] = [
"type" => "Object",
"content" => $data,
"mediaType" => "application/json",
];
}
return json_encode($event);
} | {@inheritdoc} | entailment |
public function execute(EntityInterface $entity = NULL, array &$normalized = NULL, array $context = NULL) {
$config = $this->getConfiguration();
// Use a pre-configured field as the source of the additional @type.
if (($entity->hasField($config['source_field'])) &&
(!empty($entity->get($config['source_field'])->getValue()))) {
if (isset($normalized['@graph']) && is_array($normalized['@graph'])) {
foreach ($normalized['@graph'] as &$graph) {
foreach ($entity->get($config['source_field'])->getValue() as $type) {
// If the configured field is using an entity reference,
// we will see if it uses the core config's field_external_uri.
if (array_key_exists('target_id', $type)) {
$target_type = $entity->get($config['source_field'])->getFieldDefinition()->getSetting('target_type');
$referenced_entity = \Drupal::entityTypeManager()->getStorage($target_type)->load($type['target_id']);
if ($referenced_entity->hasField('field_external_uri') &&
!empty($referenced_entity->get('field_external_uri')->getValue())) {
foreach ($referenced_entity->get('field_external_uri')->getValue() as $value) {
$graph['@type'][] = $value['uri'];
}
}
}
else {
$graph['@type'][] = NormalizerBase::escapePrefix($type['value'], $context['namespaces']);
}
}
}
}
}
} | {@inheritdoc} | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$options = [];
$fieldsArray = \Drupal::service('entity_field.manager')->getFieldMap();
foreach ($fieldsArray as $entity_type => $entity_fields) {
foreach ($entity_fields as $field => $field_properties) {
$options[$field] = $this->t('@field (@bundles)', [
'@field' => $field,
'@bundles' => implode(', ', array_keys($field_properties['bundles'])),
]);
}
}
$config = $this->getConfiguration();
$form['source_field'] = [
'#type' => 'select',
'#title' => $this->t('Source Field'),
'#options' => $options,
'#description' => $this->t("Select the field containing the type predicates."),
'#default_value' => isset($config['source_field']) ? $config['source_field'] : '',
];
return $form;
} | {@inheritdoc} | entailment |
protected function generateData(EntityInterface $entity) {
$data = parent::generateData($entity);
$data['source_field'] = $this->mediaSource->getSourceFieldName($entity->bundle());
return $data;
} | {@inheritdoc} | entailment |
public function evaluate() {
if (empty($this->configuration['uri']) && !$this->isNegated()) {
return TRUE;
}
$media = $this->getContextValue('media');
if (!$media) {
return FALSE;
}
return $this->evaluateEntity($media);
} | {@inheritdoc} | entailment |
protected function _fixVersionTables(Event $event)
{
if (!preg_match('/Versions$/', $event->subject->viewVars['name'])) {
return;
}
unset($event->subject->viewVars['rulesChecker']['version_id']);
foreach ($event->subject->viewVars['associations']['belongsTo'] as $i => $association) {
if ($association['alias'] === 'Versions' && $association['foreignKey'] === 'version_id') {
unset($event->subject->viewVars['associations']['belongsTo'][$i]);
}
}
} | Removes unnecessary associations
@param Event $event An Event instance
@return void | entailment |
protected function _checkAssociation(Event $event, $tableSuffix)
{
$subject = $event->subject;
$connection = ConnectionManager::get($subject->viewVars['connection']);
$schema = $connection->getSchemaCollection();
$versionTable = sprintf('%s_%s', Hash::get($event->subject->viewVars, 'table'), $tableSuffix);
if (!in_array($versionTable, $schema->listTables())) {
return false;
}
$event->subject->viewVars['behaviors']['Josegonzalez/Version.Version'] = [
sprintf("'versionTable' => '%s'", $versionTable),
];
$event->subject->viewVars['associations']['belongsTo'] = $this->_modifyBelongsTo($event);
$event->subject->viewVars['rulesChecker'] = $this->_modifyRulesChecker($event);
return true;
} | Attaches the behavior and modifies associations as necessary
@param Event $event An Event instance
@param string $tableSuffix a suffix for the primary table
@return bool true if modified, false otherwise | entailment |
protected function _modifyBelongsTo(Event $event)
{
$belongsTo = $event->subject->viewVars['associations']['belongsTo'];
foreach ($belongsTo as $i => $association) {
if ($association['alias'] !== 'Versions' || $association['foreignKey'] !== 'version_id') {
continue;
}
unset($belongsTo[$i]);
}
return $belongsTo;
} | Removes unnecessary belongsTo associations
@param Event $event An Event instance
@return array | entailment |
protected function _modifyRulesChecker(Event $event)
{
$rulesChecker = $event->subject->viewVars['rulesChecker'];
foreach ($rulesChecker as $key => $config) {
if (Hash::get($config, 'extra') !== 'Versions' || $key !== 'version_id') {
continue;
}
unset($rulesChecker[$key]);
}
return $rulesChecker;
} | Removes unnecessary rulesChecker entries
@param Event $event An Event instance
@return array | entailment |
public function writeReport(Report $report): void
{
$xml = new \DOMDocument('1.0', 'UTF-8');
$root = $xml->createElement('checkstyle');
$root->setAttribute('version', APP_NAME . '-' . APP_VERSION);
foreach ($report->getFiles() as $file) {
$xmlFile = $xml->createElement('file');
$xmlFile->setAttribute('name', $file->getFilename());
foreach ($file->getIssues() as $issue) {
$xmlWarning = $xml->createElement('error');
$xmlWarning->setAttribute('line', "" . $issue->getLine());
$xmlWarning->setAttribute('severity', $issue->getSeverity());
$xmlWarning->setAttribute('message', $issue->getMessage());
$xmlWarning->setAttribute('source', $issue->getSource());
if ($issue->getColumn() !== null) {
$xmlWarning->setAttribute('column', "" . $issue->getColumn());
}
$xmlFile->appendChild($xmlWarning);
}
$root->appendChild($xmlFile);
}
$xml->appendChild($root);
$xml->formatOutput = true;
$this->output->write($xml->saveXML());
} | Writes a report in checkstyle XML format.
@param Report $report The report to print.
@return void | entailment |
public function sort($field, $direction = self::SORT_DESC) {
if(empty($this->data['sorts'])) {
$this->data['sorts'] = array();
}
$this->data['sorts'][] = array(
'field' => $field,
'direction' => $direction
);
return $this;
} | Add one level of sorting
@return OpenSearchServer\Search\Search | entailment |
public function collapsing($field, $max, $mode = self::COLLAPSING_MODE_OFF, $type = self::COLLAPSING_TYPE_FULL) {
if(empty($this->data['collapsing'])) {
$this->data['collapsing'] = array();
}
$this->data['collapsing'] = array(
'field' => $field,
'mode' => $mode,
'type' => $type,
'max' => $max
);
return $this;
} | Configure collapsing
@return OpenSearchServer\Search\Search | entailment |
public function facet($field, $min = 0, $multi = false, $postCollapsing = false) {
if(empty($this->data['facets'])) {
$this->data['facets'] = array();
}
$this->data['facets'][] = array(
'field' => $field,
'minCount' => $min,
'multivalued' => $multi,
'postCollapsing' => $postCollapsing
);
return $this;
} | Add a facet to search results
@return OpenSearchServer\Search\Search | entailment |
public function snippet($field, $tag = 'b', $separator = '...', $maxSize = 200, $maxNumber = 1, $fragmenter = self::SNIPPET_NO_FRAGMENTER) {
if(empty($this->data['snippets'])) {
$this->data['snippets'] = array();
}
$this->data['snippets'][] = array(
'field' => $field,
'tag' => $tag,
'separator' => $separator,
'maxSize' => $maxSize,
'maxNumber' => $maxNumber,
'fragmenter' => $fragmenter,
);
return $this;
} | Add one snippet
@return OpenSearchServer\Search\Search | entailment |
public function scoring($field = null, $weight = 1, $ascending = false, $type = self::SCORING_FIELD_ORDER) {
if(empty($this->data['scorings'])) {
$this->data['scorings'] = array();
}
$newScoring = array(
'ascending' => (boolean) $ascending,
'type' => $type,
'weight' => $weight
);
if(!empty($field)) {
$newScoring['field'] = $field;
}
$this->data['scorings'][] = $newScoring;
return $this;
} | Add one level of scoring
@return OpenSearchServer\Search\Search | entailment |
public function boostingQuery($query, $boost = 1) {
if(empty($this->data['boostingQueries'])) {
$this->data['boostingQueries'] = array();
}
$newBoosting = array(
'patternQuery' => $query,
'boost' => $boost
);
$this->data['boostingQueries'][] = $newBoosting;
return $this;
} | Add one boosting query
@return OpenSearchServer\Search\Search | entailment |
public function join($indexName, $queryTemplate, $queryString, $localField, $foreignField, $type = self::JOIN_INNER, $returnFields = true, $returnScores = false, $returnFacets = false) {
if(empty($this->data['joins'])) {
$this->data['joins'] = array();
}
$this->data['joins'][] = array(
'indexName' => $indexName,
'queryTemplate' => $queryTemplate,
'queryString' => $queryString,
'localField' => $localField,
'foreignField' => $foreignField,
'type' => $type,
'returnFields' => $returnFields,
'returnScores' => $returnScores,
'returnFacets' => $returnFacets
);
return $this;
} | Add one join
@return OpenSearchServer\Search\Search | entailment |
public function sorts($sorts, $direction = self::SORT_DESC) {
foreach($sorts as $sort) {
$this->sort($sort, $direction);
}
return $this;
} | Helper method: add several sorts
@return OpenSearchServer\Search\Search | entailment |
public function evaluate() {
if (empty($this->configuration['uri']) && !$this->isNegated()) {
return TRUE;
}
$media = $this->getContextValue('media');
if (!$media) {
return FALSE;
}
$node = $this->utils->getParentNode($media);
if (!$node) {
return FALSE;
}
return $this->evaluateEntity($node);
} | {@inheritdoc} | entailment |
public function modify( $tpl, $operatorName, $operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters )
{
switch ( $operatorName )
{
case 'eztagscloud':
{
$searchEngine = eZINI::instance()->variable( 'SearchSettings', 'SearchEngine' );
if ( class_exists( 'eZSolr' ) && $searchEngine == 'ezsolr'
&& eZINI::instance( 'eztags.ini' )->variable( 'GeneralSettings', 'TagCloudOverSolr' ) === 'enabled' )
{
$tagCloud = $this->solrTagCloud( $namedParameters['params'] );
}
else
{
$tagCloud = $this->tagCloud( $namedParameters['params'] );
}
$tpl = eZTemplate::factory();
$tpl->setVariable( 'tag_cloud', $tagCloud );
$operatorValue = $tpl->fetch( 'design:tagcloud.tpl' );
} break;
}
} | Executes the PHP function for the operator cleanup and modifies $operatorValue.
@param eZTemplate $tpl
@param string $operatorName
@param array $operatorParameters
@param string $rootNamespace
@param string $currentNamespace
@param mixed $operatorValue
@param array $namedParameters | entailment |
private function tagCloud( $params )
{
$parentNodeID = 0;
$classIdentifier = '';
$classIdentifierSQL = '';
$pathString = '';
$parentNodeIDSQL = '';
$dbParams = array();
$orderBySql = 'ORDER BY eztags.keyword ASC';
if ( isset( $params['class_identifier'] ) )
$classIdentifier = $params['class_identifier'];
if ( isset( $params['parent_node_id'] ) )
$parentNodeID = $params['parent_node_id'];
if ( isset( $params['limit'] ) )
$dbParams['limit'] = $params['limit'];
if ( isset( $params['offset'] ) )
$dbParams['offset'] = $params['offset'];
if ( isset( $params['sort_by'] ) && is_array( $params['sort_by'] ) && !empty( $params['sort_by'] ) )
{
$orderBySql = 'ORDER BY ';
$orderArr = is_string( $params['sort_by'][0] ) ? array( $params['sort_by'] ) : $params['sort_by'];
foreach ( $orderArr as $key => $order )
{
if ( $key !== 0 ) $orderBySql .= ', ';
$direction = isset( $order[1] ) ? $order[1] : false;
switch( $order[0] )
{
case 'keyword':
{
$orderBySql .= 'eztags.keyword ' . ( $direction ? 'ASC' : 'DESC' );
}break;
case 'count':
{
$orderBySql .= 'keyword_count ' . ( $direction ? 'ASC' : 'DESC' );
}break;
}
}
}
$db = eZDB::instance();
if ( $classIdentifier )
{
$classID = eZContentObjectTreeNode::classIDByIdentifier( $classIdentifier );
$classIdentifierSQL = "AND ezcontentobject.contentclass_id = '" . $classID . "'";
}
if ( $parentNodeID )
{
$node = eZContentObjectTreeNode::fetch( $parentNodeID );
if ( $node )
$pathString = "AND ezcontentobject_tree.path_string like '" . $node->attribute( 'path_string' ) . "%'";
$parentNodeIDSQL = "AND ezcontentobject_tree.node_id != " . (int) $parentNodeID;
}
$showInvisibleNodesCond = eZContentObjectTreeNode::createShowInvisibleSQLString( true, false );
$limitation = false;
$limitationList = eZContentObjectTreeNode::getLimitationList( $limitation );
$sqlPermissionChecking = eZContentObjectTreeNode::createPermissionCheckingSQL( $limitationList );
$languageFilter = 'AND ' . eZContentLanguage::languagesSQLFilter( 'ezcontentobject' );
$languageFilter .= 'AND ' . eZContentLanguage::languagesSQLFilter( 'ezcontentobject_attribute', 'language_id' );
$rs = $db->arrayQuery( "SELECT eztags.id, eztags.keyword, COUNT(DISTINCT ezcontentobject.id) AS keyword_count
FROM eztags_attribute_link
LEFT JOIN ezcontentobject_attribute
ON eztags_attribute_link.objectattribute_id = ezcontentobject_attribute.id
AND eztags_attribute_link.objectattribute_version = ezcontentobject_attribute.version
LEFT JOIN ezcontentobject
ON ezcontentobject_attribute.contentobject_id = ezcontentobject.id
LEFT JOIN ezcontentobject_tree
ON ezcontentobject_attribute.contentobject_id = ezcontentobject_tree.contentobject_id
LEFT JOIN eztags
ON eztags.id = eztags_attribute_link.keyword_id
LEFT JOIN eztags_keyword
ON eztags.id = eztags_keyword.keyword_id
$sqlPermissionChecking[from]
WHERE " . eZContentLanguage::languagesSQLFilter( 'eztags' ) . "
AND " . eZContentLanguage::sqlFilter( 'eztags_keyword', 'eztags' ) . "
AND ezcontentobject.status = " . eZContentObject::STATUS_PUBLISHED . "
AND ezcontentobject_attribute.version = ezcontentobject.current_version
AND ezcontentobject_tree.main_node_id = ezcontentobject_tree.node_id
$pathString
$parentNodeIDSQL
$classIdentifierSQL
$showInvisibleNodesCond
$sqlPermissionChecking[where]
$languageFilter
GROUP BY eztags.id, eztags.keyword
$orderBySql", $dbParams );
$tagsCountList = array();
foreach( $rs as $row )
{
$tagsCountList[$row['id']] = $row['keyword_count'];
}
if ( empty( $tagsCountList ) )
return array();
/** @var eZTagsObject[] $tagObjects */
$tagObjects = eZTagsObject::fetchList( array( 'id' => array( array_keys( $tagsCountList ) ) ) );
if ( !is_array( $tagObjects ) || empty( $tagObjects ) )
return array();
$tagSortArray = array();
$tagKeywords = array();
$tagCounts = array();
foreach ( $tagObjects as $tag )
{
$tagKeyword = $tag->attribute( 'keyword' );
$tagCount = $tagsCountList[$tag->attribute( 'id' )];
$tagSortArray[] = array(
'keyword' => $tagKeyword,
'count' => $tagCount,
'tag' => $tag
);
$tagKeywords[] = $tagKeyword;
$tagCounts[] = $tagCount;
}
if ( isset( $params['post_sort_by'] ) )
{
if ( $params['post_sort_by'] === 'keyword' )
array_multisort( $tagKeywords, SORT_ASC, SORT_LOCALE_STRING, $tagSortArray );
else if ( $params['post_sort_by'] === 'keyword_reverse' )
array_multisort( $tagKeywords, SORT_DESC, SORT_LOCALE_STRING, $tagSortArray );
else if ( $params['post_sort_by'] === 'count' )
array_multisort( $tagCounts, SORT_ASC, SORT_NUMERIC, $tagSortArray );
else if ( $params['post_sort_by'] === 'count_reverse' )
array_multisort( $tagCounts, SORT_DESC, SORT_NUMERIC, $tagSortArray );
}
$this->normalizeTagCounts( $tagSortArray, $tagCounts );
return $tagSortArray;
} | Returns the tag cloud for specified parameters using eZ Publish database
@param array $params
@return array | entailment |
private function solrTagCloud( $params )
{
$offset = 0;
if( isset( $params['offset'] ) && is_numeric( $params['offset'] ) )
$offset = (int) $params['offset'];
// It seems that Solr doesn't like PHP_INT_MAX constant on 64bit operating systems
$limit = 1000000;
if( isset( $params['limit'] ) && is_numeric( $params['limit'] ) )
$limit = (int) $params['limit'];
$searchFilter = array();
if ( isset( $params['class_identifier'] ) )
{
if ( !is_array( $params['class_identifier'] ) )
$params['class_identifier'] = array( $params['class_identifier'] );
if ( !empty( $params['class_identifier'] ) )
$searchFilter['meta_class_identifier_ms'] = '(' . implode( ' OR ', $params['class_identifier'] ) . ')';
}
if ( isset( $params['parent_node_id'] ) )
$searchFilter['meta_path_si'] = (int) $params['parent_node_id'];
$solrSearch = new eZSolr();
$solrParams = array(
'SearchOffset' => 0,
// It seems that Solr doesn't like PHP_INT_MAX constant on 64bit operating systems
'SearchLimit' => 1000000,
'Facet' => array(
// We don't want to limit max facet result number since we limit it later anyways
array( 'field' => 'ezf_df_tag_ids', 'limit' => 1000000 )
),
'Filter' => $searchFilter,
'QueryHandler' => 'ezpublish',
'AsObjects' => false
);
$searchResult = $solrSearch->search( '*:*', $solrParams );
if ( !isset( $searchResult['SearchExtras'] ) || !$searchResult['SearchExtras'] instanceof ezfSearchResultInfo )
return array();
$facetResult = $searchResult['SearchExtras']->attribute( 'facet_fields' );
if ( !is_array( $facetResult ) || empty( $facetResult[0]['countList'] ) )
return array();
$tagsCountList = $facetResult[0]['countList'];
/** @var eZTagsObject[] $tags */
$tags = eZTagsObject::fetchList( array( 'id' => array( array_keys( $tagsCountList ) ) ) );
if ( !is_array( $tags ) || empty( $tags ) )
return array();
$tagSortArray = array();
$tagKeywords = array();
$tagCounts = array();
foreach ( $tags as $tag )
{
$tagKeyword = $tag->attribute( 'keyword' );
$tagCount = $tagsCountList[(int) $tag->attribute( 'id' )];
$tagSortArray[] = array(
'keyword' => $tagKeyword,
'count' => $tagCount,
'tag' => $tag
);
$tagKeywords[] = $tagKeyword;
$tagCounts[] = $tagCount;
}
// calling call_user_func_array requires all arguments to be references
// this is the reason for $sortFlags array and $sortArgs[] = &....
$sortArgs = array();
$sortFlags = array( SORT_ASC, SORT_DESC, SORT_LOCALE_STRING, SORT_NUMERIC );
if ( isset( $params['sort_by'] ) && is_array( $params['sort_by'] ) && !empty( $params['sort_by'] ) )
{
$params['sort_by'] = is_string( $params['sort_by'][0] ) ? array( $params['sort_by'] ) : $params['sort_by'];
foreach ( $params['sort_by'] as $sortItem )
{
if ( is_array( $sortItem ) && !empty( $sortItem ) )
{
switch ( $sortItem[0] )
{
case 'keyword':
$sortArgs[] = &$tagKeywords;
if ( isset( $sortItem[1] ) && $sortItem[1] )
$sortArgs[] = &$sortFlags[0];
else
$sortArgs[] = &$sortFlags[1];
$sortArgs[] = &$sortFlags[2];
break;
case 'count':
$sortArgs[] = &$tagCounts;
if ( isset( $sortItem[1] ) && $sortItem[1] )
$sortArgs[] = &$sortFlags[0];
else
$sortArgs[] = &$sortFlags[1];
$sortArgs[] = &$sortFlags[3];
break;
}
}
}
}
if ( empty( $sortArgs ) )
{
$sortArgs[] = &$tagKeywords;
$sortArgs[] = &$sortFlags[0];
}
$sortArgs[] = &$tagSortArray;
call_user_func_array( 'array_multisort', $sortArgs );
$tagSortArray = array_slice( $tagSortArray, $offset, $limit );
if ( empty( $tagSortArray ) )
return array();
$tagKeywords = array_slice( $tagKeywords, $offset, $limit );
$tagCounts = array_slice( $tagCounts, $offset, $limit );
if ( isset( $params['post_sort_by'] ) )
{
if ( $params['post_sort_by'] === 'keyword' )
array_multisort( $tagKeywords, SORT_ASC, SORT_LOCALE_STRING, $tagSortArray );
else if ( $params['post_sort_by'] === 'keyword_reverse' )
array_multisort( $tagKeywords, SORT_DESC, SORT_LOCALE_STRING, $tagSortArray );
else if ( $params['post_sort_by'] === 'count' )
array_multisort( $tagCounts, SORT_ASC, SORT_NUMERIC, $tagSortArray );
else if ( $params['post_sort_by'] === 'count_reverse' )
array_multisort( $tagCounts, SORT_DESC, SORT_NUMERIC, $tagSortArray );
}
$this->normalizeTagCounts( $tagSortArray, $tagCounts );
return $tagSortArray;
} | Returns the tag cloud for specified parameters using eZ Find
@param array $params
@return array | entailment |
private function normalizeTagCounts( &$tagsArray, $tagCounts )
{
$maxFontSize = 200;
$minFontSize = 100;
$maxCount = max( $tagCounts );
$minCount = min( $tagCounts );
$spread = $maxCount - $minCount;
if ( $spread == 0 )
$spread = 1;
$step = ( $maxFontSize - $minFontSize ) / ( $spread );
foreach ( $tagsArray as $index => $tagItem )
{
$tagsArray[$index]['font_size'] = $minFontSize + ( ( $tagItem['count'] - $minCount ) * $step );
}
} | Normalizes the count of tags to be able to be displayed properly on the page
@param array $tagsArray
@param array $tagCounts | entailment |
public function connect($host, $ssl = false, $port = 21, $timeout = 90)
{
if ($ssl) {
$this->connection = @ftp_ssl_connect($host, $port, $timeout);
} else {
$this->connection = @ftp_connect($host, $port, $timeout);
}
if ($this->connection == null) {
throw new Exception('Unable to connect');
} else {
return $this;
}
} | Opens a FTP connection
@param string $host
@param bool $ssl
@param int $port
@param int $timeout
@return FTPClient | entailment |
public function login($username = 'anonymous', $password = '')
{
$result = @ftp_login($this->connection, $username, $password);
if ($result === false) {
throw new Exception('Login incorrect');
} else {
// set passive mode
if (!is_null($this->passive)) {
$this->passive($this->passive);
}
return $this;
}
} | Logins to FTP Server
@param string $username
@param string $password
@return FTPClient | entailment |
public function passive($passive = true)
{
$this->passive = $passive;
if ($this->connection) {
$result = ftp_pasv($this->connection, $passive);
if ($result === false) {
throw new Exception('Unable to change passive mode');
}
}
return $this;
} | Changes passive mode,,,
@param bool $passive
@return FTPClient, | entailment |
public function changeDirectory($directory)
{
$result = @ftp_chdir($this->connection, $directory);
if ($result === false) {
throw new Exception('Unable to change directory');
}
return $this;
} | Changes the current directory to the specified one
@return FTPClient | entailment |
public function createDirectory($directory)
{
$result = @ftp_mkdir($this->connection, $directory);
if ($result === false) {
throw new Exception('Unable to create directory');
}
return $this;
} | Creates a directory
@param string $directory
@return FTPClient | entailment |
public function removeDirectory($directory)
{
$result = @ftp_rmdir($this->connection, $directory);
if ($result === false) {
throw new Exception('Unable to remove directory');
}
return $this;
} | Removes a directory
@param string $directory
@return FTPClient | entailment |
public function listDirectory($directory)
{
$result = @ftp_nlist($this->connection, $directory);
if ($result === false) {
throw new Exception('Unable to list directory');
}
asort($result);
return $result;
} | Returns a list of files in the given directory
@param string $directory
@return array | entailment |
public function rawlistDirectory($parameters, $recursive = false)
{
$result = @ftp_rawlist($this->connection, $parameters, $recursive);
if ($result === false) {
throw new Exception('Unable to list directory');
}
return $result;
} | @param string $parameters
@param bool $recursive
@return array
@throws \Exception | entailment |
public function delete($path)
{
$result = @ftp_delete($this->connection, $path);
if ($result === false) {
throw new Exception('Unable to get parent folder');
}
return $this;
} | Deletes a file on the FTP server
@param string $path
@return FTPClient | entailment |
public function size($remoteFile)
{
$size = @ftp_size($this->connection, $remoteFile);
if ($size === -1) {
throw new Exception('Unable to get file size');
}
return $size;
} | Returns the size of the given file.
Return -1 on error
@param string $remoteFile
@return int | entailment |
public function modifiedTime($remoteFile, $format = null)
{
$time = ftp_mdtm($this->connection, $remoteFile);
if ( $time !== -1 && $format !== null ) {
return date($format, $time);
} else {
return $time;
}
} | Returns the last modified time of the given file.
Return -1 on error
@param string $remoteFile
@return int | entailment |
public function rename($currentName, $newName)
{
$result = @ftp_rename($this->connection, $currentName, $newName);
return $result;
} | Renames a file or a directory on the FTP server
@param string $currentName
@param string $newName
@return bool | entailment |
public function get($localFile, $remoteFile, $resumePosision = 0)
{
$mode = $this->getMode();
$result = @ftp_get($this->connection, $localFile, $remoteFile, $mode, $resumePosision);
if ($result === false)
{
throw new Exception(sprintf('Unable to get or save file "%s" from %s', $localFile, $remoteFile));
}
return $this;
} | Downloads a file from the FTP server
@param string $localFile
@param string $remoteFile
@param int $mode
@param int $resumepos
@return FTPClient | entailment |
public function put($remoteFile, $localFile, $startPosision = 0)
{
$mode = $this->getMode();
$result = @ftp_put($this->connection, $remoteFile, $localFile, $mode, $startPosision);
if ($result === false) {
throw new Exception('Unable to put file');
}
return $this;
} | Uploads from an open file to the FTP server
@param string $remoteFile
@param string $localFile
@param int $mode
@param int $startPosision
@return FTPClient | entailment |
public function fget($handle, $remoteFile, $resumePosision = 0)
{
$mode = $this->getMode();
$result = @ftp_fget($this->connection, $handle, $remoteFile, $mode, $resumePosision);
if ($result === false) {
throw new Exception('Unable to get file');
}
return $this;
} | Downloads a file from the FTP server and saves to an open file
@param resource $handle
@param string $remoteFile
@param int $mode
@param int $resumepos
@return FTPClient | entailment |
public function fput($remoteFile, $handle, $startPosision = 0)
{
$mode = $this->getMode();
$result = @ftp_fput($this->connection, $remoteFile, $handle, $mode, $startPosision);
if ($result === false) {
throw new Exception('Unable to put file');
}
return $this;
} | Uploads from an open file to the FTP server
@param string $remoteFile
@param resource $handle
@param int $mode
@param int $startPosision
@return FTPClient | entailment |
public function getOption($option)
{
switch ($option) {
case FTPClient::TIMEOUT_SEC:
case FTPClient::AUTOSEEK:
$result = @ftp_get_option($this->connection, $option);
return $result;
break;
default:
throw new Exception('Unsupported option');
break;
}
} | Retrieves various runtime behaviours of the current FTP stream
TIMEOUT_SEC | AUTOSEEK
@param mixed $option
@return mixed | entailment |
public function setOption($option, $value)
{
switch ($option) {
case FTPClient::TIMEOUT_SEC:
if ($value <= 0) {
throw new Exception('Timeout value must be greater than zero');
}
break;
case FTPClient::AUTOSEEK:
if (!is_bool($value)) {
throw new Exception('Autoseek value must be boolean');
}
break;
default:
throw new Exception('Unsupported option');
break;
}
return @ftp_set_option($this->connection, $option, $value);
} | Set miscellaneous runtime FTP options
TIMEOUT_SEC | AUTOSEEK
@param mixed $option
@param mixed $value
@return mixed | entailment |
public function allocate($filesize)
{
$result = @ftp_alloc($this->connection, $filesize);
if ($result === false) {
throw new Exception('Unable to allocate');
}
return $this;
} | Allocates space for a file to be uploaded
@param int $filesize
@return FTPClient | entailment |
public function chmod($mode, $filename)
{
$result = @ftp_chmod($this->connection, $mode, $filename);
if ($result === false) {
throw new Exception('Unable to change permissions');
}
return $this;
} | Set permissions on a file via FTP
@param int $mode
@param string $filename
@return FTPClient | entailment |
public function exec($command)
{
$result = @ftp_exec($this->connection, $command);
if ($result === false) {
throw new Exception('Unable to exec command');
}
return $this;
} | Requests execution of a command on the FTP server
@param string $command
@return FTPClient | entailment |
public function find($key)
{
if (isset($this->payload[$key])) {
return $this->payload[$key];
}
return null;
} | Find a value from array with given key.
@param $key
@return mixed | entailment |
protected function execute(InputInterface $input, OutputInterface $output): void
{
$configFilesOption = $input->getOption('config');
$outputOption = $input->getOption('output');
$formatOption = $input->getOption('format');
'@phan-var string $configFilesOption';
'@phan-var string $outputOption';
'@phan-var string $formatOption';
$configFiles = $this->getPossibleConfigFiles($configFilesOption);
$configuration = $this->linterConfigurationLocator->loadConfiguration($configFiles);
$paths = $input->getArgument('paths') ?: $configuration->getPaths();
$outputTarget = $input->getOption('output');
$exitWithExitCode = $input->getOption('exit-code') || $input->getOption('fail-on-warnings');
'@phan-var string[] $paths';
if (false == $outputTarget) {
throw new BadOutputFileException('Bad output file.');
}
if ($outputOption === '-') {
$reportOutput = $output;
} else {
$fileHandle = fopen($outputOption, 'w');
if ($fileHandle === false) {
throw new \Exception("could not open file '${outputOption}' for writing");
}
$reportOutput = new StreamOutput($fileHandle);
}
$logger = $this->loggerBuilder->createLogger($formatOption, $reportOutput, $output);
$report = new Report();
$patterns = $configuration->getFilePatterns();
$files = $this->finder->getFilenames($paths, $patterns, new CallbackFinderObserver(function ($name) use ($logger) {
$logger->notifyFileNotFound($name);
}));
$logger->notifyFiles($files);
foreach ($files as $filename) {
$logger->notifyFileStart($filename);
$fileReport = $this->linter->lintFile($filename, $report, $configuration, $logger);
$logger->notifyFileComplete($filename, $fileReport);
}
$logger->notifyRunComplete($report);
$exitCode = 0;
if ($report->countIssuesBySeverity(Issue::SEVERITY_ERROR) > 0) {
$exitCode = 2;
} else if ($exitWithExitCode && $report->countIssues() > 0) {
$exitCode = 2;
}
$this->eventDispatcher->addListener(
ConsoleEvents::TERMINATE,
function (ConsoleTerminateEvent $event) use ($exitCode) {
$event->setExitCode($exitCode);
}
);
} | Executes this command.
@param InputInterface $input Input options.
@param OutputInterface $output Output stream.
@return void
@throws BadOutputFileException | entailment |
public function getIssues(): array
{
usort(
$this->issues,
function (Issue $a, Issue $b) {
return $a->getLine() - $b->getLine();
}
);
return $this->issues;
} | Gets all issues for this file. The issues will be sorted by line
numbers, not by order of addition to this report.
@return Issue[] The issues for this file. | entailment |
public function getIssuesBySeverity(string $severity): array
{
return array_values(array_filter($this->getIssues(), function(Issue $i) use ($severity) {
return $i->getSeverity() === $severity;
}));
} | Gets all issues for this file that have a certain severity.
@param string $severity The severity. Should be one of the Issue class' SEVERITY_* constants
@return Issue[] All issues with the given severity | entailment |
public function merge(File $other): self
{
$new = new static($this->filename);
$new->issues = array_merge($this->issues, $other->issues);
return $new;
} | Merges this file report with another file report
@param File $other The file report to merge this report with
@return File The merged report | entailment |
public function execute()
{
$methods = array_values($this->implementedEvents());
foreach ($methods as $method) {
$this->dispatchEvent(sprintf('Bake.%s', $method), null, $this->event->subject);
}
} | Dispatches all the attached events
@return void | entailment |
public function isType($type)
{
$template = sprintf('Bake/%s.ctp', $type);
return strpos($this->event->getData('0'), $template) !== false;
} | Check whether or not a bake call is a certain type.
@param string|array $type The type of file you want to check.
@return bool Whether or not the bake template is the type you are checking. | entailment |
public function implementedEvents()
{
$methodMap = [
'config/routes' => 'beforeRenderRoutes',
'Controller/component' => 'beforeRenderComponent',
'Controller/controller' => 'beforeRenderController',
'Model/behavior' => 'beforeRenderBehavior',
'Model/entity' => 'beforeRenderEntity',
'Model/table' => 'beforeRenderTable',
'Shell/shell' => 'beforeRenderShell',
'View/cell' => 'beforeRenderCell',
'View/helper' => 'beforeRenderHelper',
'tests/test_case' => 'beforeRenderTestCase',
];
$events = [];
foreach ($methodMap as $template => $method) {
if ($this->isType($template) && method_exists($this, $method)) {
$events[sprintf('Bake.%s', $method)] = $method;
}
}
return $events;
} | Get the callbacks this class is interested in.
@return array | entailment |
public function boot(Router $router)
{
Storage::extend('cloudinary', function ($app, $config) {
return new Filesystem(new CloudinaryAdapter($config));
});
} | Bootstrap the application services.
@return void | entailment |
public function execute(EntityInterface $entity = NULL) {
$config = $this->getConfiguration();
$action_ids = $config['actions'];
foreach ($action_ids as $action_id) {
$action = $this->actionStorage->load($action_id);
$action->execute([$entity]);
}
} | {@inheritdoc} | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$actions = $this->actionStorage->loadMultiple();
foreach ($actions as $action) {
$options[ucfirst($action->getType())][$action->id()] = $action->label();
}
$config = $this->getConfiguration();
$form['actions'] = [
'#title' => $this->t('Actions'),
'#description' => $this->t('Pre-configured actions to execute. Multiple actions may be selected by shift or ctrl clicking.'),
'#type' => 'select',
'#multiple' => TRUE,
'#options' => $options,
'#default_value' => isset($config['actions']) ? $config['actions'] : '',
'#size' => 15,
];
return $form;
} | {@inheritdoc} | entailment |
public function version($versionId, $reset = false)
{
$versions = $this->versions($reset);
if (empty($versions[$versionId])) {
return null;
}
return $versions[$versionId];
} | Retrieves a specified version for the current entity
@param int $versionId The version number to retrieve
@param bool $reset If true, will re-retrieve the related version collection
@return \Cake\ORM\Entity|null | entailment |
public function versions($reset = false)
{
if ($reset === false && $this->has('_versions')) {
return $this->get('_versions');
}
/*
* @var \Josegonzalez\Version\Model\Behavior\VersionBehavior $table
* @var \Cake\Datasource\EntityInterface $this
*/
$table = TableRegistry::get($this->getSource());
$versions = $table->getVersions($this);
$this->set('_versions', $versions);
return $this->get('_versions');
} | Retrieves the related versions for the current entity
@param bool $reset If true, will re-retrieve the related version collection
@return \Cake\Collection\CollectionInterface | entailment |
public function getData()
{
if(!empty($this->jsonText)) {
return $this->jsonText;
}elseif(!empty($this->jsonValues)) {
return json_encode($this->jsonValues);
} elseif(!empty($this->data)) {
return json_encode($this->data);
}
return null;
} | {@inheritdoc} | entailment |
public static function create(ConfigFactoryInterface $config) {
// Get broker url from config.
$settings = $config->get(IslandoraSettingsForm::CONFIG_NAME);
$brokerUrl = $settings->get(IslandoraSettingsForm::BROKER_URL);
// Try a sensible default if one hasn't been configured.
if (empty($brokerUrl)) {
$brokerUrl = "tcp://localhost:61613";
}
$client = new Client($brokerUrl);
return new StatefulStomp($client);
} | Factory function.
@param \Drupal\Core\Config\ConfigFactoryInterface $config
Config.
@return \Stomp\StatefulStomp
Stomp client. | entailment |
protected function generateData(EntityInterface $entity) {
$uri = $entity->getFileUri();
$scheme = $this->fileSystem->uriScheme($uri);
$flysystem_config = Settings::get('flysystem');
$data = parent::generateData($entity);
if (isset($flysystem_config[$scheme]) && $flysystem_config[$scheme]['driver'] == 'fedora') {
// Fdora $uri for files may contain ':///' so we need to replace
// the three / with two.
if (strpos($uri, $scheme . ':///') !== FALSE) {
$uri = str_replace($scheme . ':///', $scheme . '://', $uri);
}
$data['fedora_uri'] = str_replace("$scheme://", $flysystem_config[$scheme]['config']['root'], $uri);
}
return $data;
} | {@inheritdoc} | entailment |
public function getSourceFieldName($media_type) {
$bundle = $this->entityTypeManager->getStorage('media_type')->load($media_type);
if (!$bundle) {
throw new NotFoundHttpException("Bundle $media_type does not exist");
}
$type_configuration = $bundle->get('source_configuration');
if (!isset($type_configuration['source_field'])) {
return NULL;
}
return $type_configuration['source_field'];
} | Gets the name of a source field for a Media.
@param string $media_type
Media bundle whose source field you are searching for.
@return string|null
Field name if it exists in configuration, else NULL. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.