本文整理汇总了PHP中Drupal\Component\Utility\Unicode::strlen方法的典型用法代码示例。如果您正苦于以下问题:PHP Unicode::strlen方法的具体用法?PHP Unicode::strlen怎么用?PHP Unicode::strlen使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Component\Utility\Unicode
的用法示例。
在下文中一共展示了Unicode::strlen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: _split
protected function _split($lines)
{
$words = array();
$stripped = array();
$first = TRUE;
foreach ($lines as $line) {
// If the line is too long, just pretend the entire line is one big word
// This prevents resource exhaustion problems
if ($first) {
$first = FALSE;
} else {
$words[] = "\n";
$stripped[] = "\n";
}
if (Unicode::strlen($line) > $this::MAX_LINE_LENGTH) {
$words[] = $line;
$stripped[] = $line;
} else {
if (preg_match_all('/ ( [^\\S\\n]+ | [0-9_A-Za-z\\x80-\\xff]+ | . ) (?: (?!< \\n) [^\\S\\n])? /xs', $line, $m)) {
$words = array_merge($words, $m[0]);
$stripped = array_merge($stripped, $m[1]);
}
}
}
return array($words, $stripped);
}
示例2: validateHex
/**
* Validates whether a hexadecimal color value is syntatically correct.
*
* @param $hex
* The hexadecimal string to validate. May contain a leading '#'. May use
* the shorthand notation (e.g., '123' for '112233').
*
* @return bool
* TRUE if $hex is valid or FALSE if it is not.
*/
public static function validateHex($hex)
{
// Must be a string.
$valid = is_string($hex);
// Hash prefix is optional.
$hex = ltrim($hex, '#');
// Must be either RGB or RRGGBB.
$length = Unicode::strlen($hex);
$valid = $valid && ($length === 3 || $length === 6);
// Must be a valid hex value.
$valid = $valid && ctype_xdigit($hex);
return $valid;
}
示例3: testSearchSimplifyUnicode
/**
* Tests that all Unicode characters simplify correctly.
*/
function testSearchSimplifyUnicode()
{
// This test uses a file that was constructed so that the even lines are
// boundary characters, and the odd lines are valid word characters. (It
// was generated as a sequence of all the Unicode characters, and then the
// boundary characters (punctuation, spaces, etc.) were split off into
// their own lines). So the even-numbered lines should simplify to nothing,
// and the odd-numbered lines we need to split into shorter chunks and
// verify that simplification doesn't lose any characters.
$input = file_get_contents(\Drupal::root() . '/core/modules/search/tests/UnicodeTest.txt');
$basestrings = explode(chr(10), $input);
$strings = array();
foreach ($basestrings as $key => $string) {
if ($key % 2) {
// Even line - should simplify down to a space.
$simplified = search_simplify($string);
$this->assertIdentical($simplified, ' ', "Line {$key} is excluded from the index");
} else {
// Odd line, should be word characters.
// Split this into 30-character chunks, so we don't run into limits
// of truncation in search_simplify().
$start = 0;
while ($start < Unicode::strlen($string)) {
$newstr = Unicode::substr($string, $start, 30);
// Special case: leading zeros are removed from numeric strings,
// and there's one string in this file that is numbers starting with
// zero, so prepend a 1 on that string.
if (preg_match('/^[0-9]+$/', $newstr)) {
$newstr = '1' . $newstr;
}
$strings[] = $newstr;
$start += 30;
}
}
}
foreach ($strings as $key => $string) {
$simplified = search_simplify($string);
$this->assertTrue(Unicode::strlen($simplified) >= Unicode::strlen($string), "Nothing is removed from string {$key}.");
}
// Test the low-numbered ASCII control characters separately. They are not
// in the text file because they are problematic for diff, especially \0.
$string = '';
for ($i = 0; $i < 32; $i++) {
$string .= chr($i);
}
$this->assertIdentical(' ', search_simplify($string), 'Search simplify works for ASCII control characters.');
}
示例4: uniquify
/**
* {@inheritdoc}
*/
public function uniquify(&$alias, $source, $langcode)
{
$config = $this->configFactory->get('pathauto.settings');
if (!$this->isReserved($alias, $source, $langcode)) {
return;
}
// If the alias already exists, generate a new, hopefully unique, variant.
$maxlength = min($config->get('max_length'), $this->aliasStorageHelper->getAliasSchemaMaxlength());
$separator = $config->get('separator');
$original_alias = $alias;
$i = 0;
do {
// Append an incrementing numeric suffix until we find a unique alias.
$unique_suffix = $separator . $i;
$alias = Unicode::truncate($original_alias, $maxlength - Unicode::strlen($unique_suffix, TRUE)) . $unique_suffix;
$i++;
} while ($this->isReserved($alias, $source, $langcode));
}
示例5: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, 'data-caption') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//*[@data-caption]') as $node) {
// Read the data-caption attribute's value, then delete it.
$caption = Html::escape($node->getAttribute('data-caption'));
$node->removeAttribute('data-caption');
// Sanitize caption: decode HTML encoding, limit allowed HTML tags; only
// allow inline tags that are allowed by default, plus <br>.
$caption = Html::decodeEntities($caption);
$caption = FilteredMarkup::create(Xss::filter($caption, array('a', 'em', 'strong', 'cite', 'code', 'br')));
// The caption must be non-empty.
if (Unicode::strlen($caption) === 0) {
continue;
}
// Given the updated node and caption: re-render it with a caption, but
// bubble up the value of the class attribute of the captioned element,
// this allows it to collaborate with e.g. the filter_align filter.
$tag = $node->tagName;
$classes = $node->getAttribute('class');
$node->removeAttribute('class');
$node = $node->parentNode->tagName === 'a' ? $node->parentNode : $node;
$filter_caption = array('#theme' => 'filter_caption', '#node' => FilteredMarkup::create($node->C14N()), '#tag' => $tag, '#caption' => $caption, '#classes' => $classes);
$altered_html = drupal_render($filter_caption);
// Load the altered HTML into a new DOMDocument and retrieve the element.
$updated_nodes = Html::load($altered_html)->getElementsByTagName('body')->item(0)->childNodes;
foreach ($updated_nodes as $updated_node) {
// Import the updated node from the new DOMDocument into the original
// one, importing also the child nodes of the updated node.
$updated_node = $dom->importNode($updated_node, TRUE);
$node->parentNode->insertBefore($updated_node, $node);
}
// Finally, remove the original data-caption node.
$node->parentNode->removeChild($node);
}
$result->setProcessedText(Html::serialize($dom))->addAttachments(array('library' => array('filter/caption')));
}
return $result;
}
示例6: formElement
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
{
module_load_include('inc', 'name', 'includes/name.content');
$field_settings = $this->getFieldSettings();
$instance['label'] = 'instance label';
$element += array('#type' => 'name', '#title' => SafeMarkup::checkPlain($instance['label']), '#label' => $instance['label'], '#components' => array(), '#minimum_components' => array_filter($field_settings['minimum_components']), '#allow_family_or_given' => !empty($field_settings['allow_family_or_given']), '#default_value' => isset($items[$delta]) ? $items[$delta]->getValue() : NULL, '#field' => $this, '#credentials_inline' => empty($field_settings['credentials_inline']) ? 0 : 1, '#component_css' => empty($field_settings['component_css']) ? '' : $field_settings['component_css'], '#component_layout' => empty($field_settings['component_layout']) ? 'default' : $field_settings['component_layout'], '#show_component_required_marker' => !empty($field_settings['show_component_required_marker']));
$components = array_filter($field_settings['components']);
foreach (_name_translations() as $key => $title) {
if (isset($components[$key])) {
$element['#components'][$key]['type'] = 'textfield';
$size = !empty($field_settings['size'][$key]) ? $field_settings['size'][$key] : 60;
$title_display = isset($field_settings['title_display'][$key]) ? $field_settings['title_display'][$key] : 'description';
$element['#components'][$key]['title'] = SafeMarkup::checkPlain($field_settings['labels'][$key]);
$element['#components'][$key]['title_display'] = $title_display;
$element['#components'][$key]['size'] = $size;
$element['#components'][$key]['maxlength'] = !empty($field_settings['max_length'][$key]) ? $field_settings['max_length'][$key] : 255;
// Provides backwards compatibility with Drupal 6 modules.
$field_type = $key == 'title' || $key == 'generational' ? 'select' : 'text';
$field_type = isset($field_settings['field_type'][$key]) ? $field_settings['field_type'][$key] : (isset($field_settings[$key . '_field']) ? $field_settings[$key . '_field'] : $field_type);
if ($field_type == 'select') {
$element['#components'][$key]['type'] = 'select';
$element['#components'][$key]['size'] = 1;
$element['#components'][$key]['options'] = $this->optionsProvider->getOptions($this->fieldDefinition, $key);
} elseif ($field_type == 'autocomplete') {
if ($sources = $field_settings['autocomplete_source'][$key]) {
$sources = array_filter($sources);
if (!empty($sources)) {
$element['#components'][$key]['autocomplete'] = array('#autocomplete_route_name' => 'name.autocomplete', '#autocomplete_route_parameters' => array('field_name' => $this->fieldDefinition->getName(), 'entity_type' => $this->fieldDefinition->getTargetEntityTypeId(), 'bundle' => $this->fieldDefinition->getTargetBundle(), 'component' => $key));
}
}
}
if (isset($field_settings['inline_css'][$key]) && Unicode::strlen($field_settings['inline_css'][$key])) {
$element['#components'][$key]['attributes'] = array('style' => $field_settings['inline_css'][$key]);
}
} else {
$element['#components'][$key]['exclude'] = TRUE;
}
}
return $element;
}
示例7: getOptions
public function getOptions(FieldDefinitionInterface $field, $component)
{
$fs = $field->getFieldStorageDefinition()->getSettings();
$options = $fs[$component . '_options'];
foreach ($options as $index => $opt) {
if (preg_match('/^\\[vocabulary:([0-9a-z\\_]{1,})\\]/', trim($opt), $matches)) {
unset($options[$index]);
if ($this->termStorage && $this->vocabularyStorage) {
$vocabulary = $this->vocabularyStorage->load($matches[1]);
if ($vocabulary) {
$max_length = isset($fs['max_length'][$component]) ? $fs['max_length'][$component] : 255;
foreach ($this->termStorage->loadTree($vocabulary->id()) as $term) {
if (Unicode::strlen($term->name) <= $max_length) {
$options[] = $term->name;
}
}
}
}
}
}
// Options could come from multiple sources, filter duplicates.
$options = array_unique($options);
if (isset($fs['sort_options']) && !empty($fs['sort_options'][$component])) {
natcasesort($options);
}
$default = FALSE;
foreach ($options as $index => $opt) {
if (strpos($opt, '--') === 0) {
unset($options[$index]);
$default = trim(Unicode::substr($opt, 2));
}
}
$options = array_map('trim', $options);
$options = array_combine($options, $options);
if ($default !== FALSE) {
$options = array('' => $default) + $options;
}
return $options;
}
示例8: validate
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint)
{
if (!isset($items) || !$items->value) {
$this->context->addViolation($constraint->emptyMessage);
return;
}
$name = $items->first()->value;
if (substr($name, 0, 1) == ' ') {
$this->context->addViolation($constraint->spaceBeginMessage);
}
if (substr($name, -1) == ' ') {
$this->context->addViolation($constraint->spaceEndMessage);
}
if (strpos($name, ' ') !== FALSE) {
$this->context->addViolation($constraint->multipleSpacesMessage);
}
if (preg_match('/[^\\x{80}-\\x{F7} a-z0-9@_.\'-]/i', $name) || preg_match('/[\\x{80}-\\x{A0}' . '\\x{AD}' . '\\x{2000}-\\x{200F}' . '\\x{2028}-\\x{202F}' . '\\x{205F}-\\x{206F}' . '\\x{FEFF}' . '\\x{FF01}-\\x{FF60}' . '\\x{FFF9}-\\x{FFFD}' . '\\x{0}-\\x{1F}]/u', $name)) {
$this->context->addViolation($constraint->illegalMessage);
}
if (Unicode::strlen($name) > USERNAME_MAX_LENGTH) {
$this->context->addViolation($constraint->tooLongMessage, array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}
}
示例9: validateForm
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state)
{
$name = $form_state->getValue('name');
if (Unicode::strlen($name) > 64) {
$form_state->setErrorByName('name', $this->t('The name cannot be longer than 64 characters.'));
}
$phone = $form_state->getValue('phone');
if (Unicode::strlen($phone) > 64) {
$form_state->setErrorByName('phone', $this->t('The phone cannot be longer than 64 characters.'));
} else {
// Validate phone uniqueness amongst all (other) entries.
$query = $this->connection->select('phonebook', 'p')->fields('p', ['pbid']);
$query->condition('phone', $phone);
if ($pbid = $form_state->getValue('pbid')) {
$query->condition('pbid', $pbid, '<>');
}
$result = $query->execute()->fetchObject();
if ($result) {
$form_state->setErrorByName('phone', $this->t('The phone must be unique.'));
}
}
parent::validateForm($form, $form_state);
}
示例10: absoluteMailUrls
/**
* Replaces URLs with absolute URLs.
*/
public static function absoluteMailUrls($match)
{
global $base_url, $base_path;
$regexp =& drupal_static(__FUNCTION__);
$url = $label = '';
if ($match) {
if (empty($regexp)) {
$regexp = '@^' . preg_quote($base_path, '@') . '@';
}
list(, $url, $label) = $match;
$url = strpos($url, '://') ? $url : preg_replace($regexp, $base_url . '/', $url);
// If the link is formed by Drupal's URL filter, we only return the URL.
// The URL filter generates a label out of the original URL.
if (strpos($label, '...') === Unicode::strlen($label) - 3) {
// Remove ellipsis from end of label.
$label = Unicode::substr($label, 0, Unicode::strlen($label) - 3);
}
if (strpos($url, $label) !== FALSE) {
return $url;
}
return $label . ' ' . $url;
}
}
示例11: encrypt
/**
* {@inheritdoc}
*/
public function encrypt($key, $source, $sourcelen = 0)
{
$this->errors = array();
// Convert key into sequence of numbers
$fudgefactor = $this->convertKey($key);
if ($this->errors) {
return;
}
if (empty($source)) {
// Commented out to prevent errors getting logged for use cases that may
// have variable encryption/decryption requirements. -RS
// $this->errors[] = t('No value has been supplied for encryption');
return;
}
while (strlen($source) < $sourcelen) {
$source .= ' ';
}
$target = NULL;
$factor2 = 0;
for ($i = 0; $i < Unicode::strlen($source); $i++) {
$char1 = Unicode::substr($source, $i, 1);
$num1 = strpos(self::$scramble1, $char1);
if ($num1 === FALSE) {
$this->errors[] = t('Source string contains an invalid character (@char)', ['@char' => $char1]);
return;
}
$adj = $this->applyFudgeFactor($fudgefactor);
$factor1 = $factor2 + $adj;
$num2 = round($factor1) + $num1;
$num2 = $this->checkRange($num2);
$factor2 = $factor1 + $num2;
$char2 = substr(self::$scramble2, $num2, 1);
$target .= $char2;
}
return $target;
}
示例12: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (stristr($text, '<img ') !== FALSE) {
$dom = Html::load($text);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src = $image->getAttribute("src");
// The src must be non-empty.
if (Unicode::strlen($src) === 0) {
continue;
}
// The src must not already be an external URL
if (stristr($src, 'http://') !== FALSE || stristr($src, 'https://') !== FALSE) {
continue;
}
$url = Url::fromUri('internal:' . $src, array('absolute' => TRUE));
$url_string = $url->toString();
$image->setAttribute('src', $url_string);
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
示例13: autocomplete
/**
* Retrieves suggestions for block category autocompletion.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
* @param string $token_type
* The token type.
* @param string $filter
* The autocomplete filter.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A JSON response containing autocomplete suggestions.
*/
public function autocomplete($token_type, $filter, Request $request)
{
$filter = substr($filter, strrpos($filter, '['));
$matches = array();
if (!Unicode::strlen($filter)) {
$matches["[{$token_type}:"] = 0;
} else {
$depth = max(1, substr_count($filter, ':'));
$tree = $this->treeBuilder->buildTree($token_type, ['flat' => TRUE, 'depth' => $depth]);
foreach (array_keys($tree) as $token) {
if (strpos($token, $filter) === 0) {
$matches[$token] = levenshtein($token, $filter);
if (isset($tree[$token]['children'])) {
$token = rtrim($token, ':]') . ':';
$matches[$token] = levenshtein($token, $filter);
}
}
}
}
asort($matches);
$keys = array_keys($matches);
$matches = array_combine($keys, $keys);
return new JsonResponse($matches);
}
示例14: _line_hash
/**
* Returns the whole line if it's small enough, or the MD5 hash otherwise.
*/
protected function _line_hash($line)
{
if (Unicode::strlen($line) > $this::MAX_XREF_LENGTH) {
return md5($line);
} else {
return $line;
}
}
示例15: __construct
/**
* Constructs a new EntityType.
*
* @param array $definition
* An array of values from the annotation.
*
* @throws \Drupal\Core\Entity\Exception\EntityTypeIdLengthException
* Thrown when attempting to instantiate an entity type with too long ID.
*/
public function __construct($definition)
{
// Throw an exception if the entity type ID is longer than 32 characters.
if (Unicode::strlen($definition['id']) > static::ID_MAX_LENGTH) {
throw new EntityTypeIdLengthException(String::format('Attempt to create an entity type with an ID longer than @max characters: @id.', array('@max' => static::ID_MAX_LENGTH, '@id' => $definition['id'])));
}
foreach ($definition as $property => $value) {
$this->{$property} = $value;
}
// Ensure defaults.
$this->entity_keys += array('revision' => '', 'bundle' => '');
$this->handlers += array('access' => 'Drupal\\Core\\Entity\\EntityAccessControlHandler');
// Ensure a default list cache tag is set.
if (empty($this->list_cache_tags)) {
$this->list_cache_tags = [$definition['id'] . '_list'];
}
}