Commit afd9bc5d authored by jian he's avatar jian he

Initial commit.

parents
name: Pinyin Short Code
type: module
description: 'Generate pinyin short code(拼音简码).'
core: 8.x
<?php
/**
* Implements hook_field_formatter_info_alter().
*/
function pinyin_field_formatter_info_alter(array &$info) {
$info['string']['field_types'][] = 'pinyin_shortcode';
}
/**
* Implements hook_field_widget_info_alter().
*/
function pinyin_field_widget_info_alter(array &$info) {
$info['string_textfield']['field_types'][] = 'pinyin_shortcode';
}
services:
pinyin.shortcode:
class: Drupal\pinyin\PinyinShortcode
arguments: [null, '@module_handler']
<?php
namespace Drupal\pinyin;
use Drupal\Component\Transliteration\PhpTransliteration;
/**
* Implements pinyin short code.
*/
class PinyinShortcode extends PhpTransliteration {
/**
* {@inheritdoc}
*/
public function transliterate($string, $langcode = 'en', $unknown_character = '?', $max_length = NULL) {
$result = '';
$length = 0;
// Split into Unicode characters and transliterate each one.
foreach (preg_split('//u', $string, 0, PREG_SPLIT_NO_EMPTY) as $character) {
$code = self::ordUTF8($character);
if ($code != -1) {
$to_add = $this->replace($code, $langcode, $unknown_character);
// Check if this exceeds the maximum allowed length.
if (isset($max_length)) {
$length += 1;
if ($length > $max_length) {
return $result;
}
}
$result .= $to_add[0];
}
}
return $result;
}
}
<?php
namespace Drupal\pinyin\Plugin\Field\FieldType;
use Drupal\Core\Field\Plugin\Field\FieldType\StringItem;
/**
* Defines the "pinyin_shortcode" entity field type.
*
* @FieldType(
* id = "pinyin_shortcode",
* label = @Translation("Pinyin short code"),
* description = @Translation("A field containing pinyin short code value."),
* default_widget = "string_textfield",
* default_formatter = "string"
* )
*/
class PinyinShortcodeItem extends StringItem {
/**
* {@inheritdoc}
*/
public function applyDefaultValue($notify = TRUE) {
parent::applyDefaultValue($notify);
// Field preSave is only called if have values in field.
$this->setValue(['value' => 'pinyin'], $notify);
return $this;
}
/**
* {@inheritdoc}
*/
public function preSave() {
parent::preSave();
$entity = $this->getEntity();
if (!$entity->isNew()) {
if ($entity->label() == $entity->original->label()) {
return;
}
}
$this->value = \Drupal::service('pinyin.shortcode')
->transliterate($entity->label(), 'en', '?', $this->getSetting('max_length'));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment