Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 8 | use SilverStripe\i18n\i18n; |
||
| 9 | use SilverStripe\ORM\DataObject; |
||
| 10 | use SilverStripe\Translatable\Model\Translatable; |
||
| 11 | |||
| 12 | /** |
||
| 13 | * An extension to dropdown field, pre-configured to list languages. |
||
| 14 | * The languages already used in the site will be on top. |
||
| 15 | * |
||
| 16 | * @package translatable |
||
| 17 | */ |
||
| 18 | class LanguageDropdownField extends GroupedDropdownField |
||
| 19 | { |
||
| 20 | private static $allowed_actions = array( |
||
| 21 | 'getLocaleForObject' |
||
| 22 | ); |
||
| 23 | |||
| 24 | /** |
||
| 25 | * Create a new LanguageDropdownField |
||
| 26 | * @param string $name |
||
| 27 | * @param string $title |
||
| 28 | * @param array $excludeLocales List of locales that won't be included |
||
| 29 | * @param string $translatingClass Name of the class with translated instances |
||
| 30 | * where to look for used languages |
||
| 31 | * @param string $list Indicates the source language list. |
||
| 32 | * Can be either Common-English or Locale-English (default) |
||
| 33 | */ |
||
| 34 | public function __construct( |
||
| 93 | |||
| 94 | public function Type() |
||
| 98 | |||
| 99 | public function getAttributes() |
||
| 106 | |||
| 107 | /** |
||
| 108 | * Get the locale for an object that has the Translatable extension. |
||
| 109 | * |
||
| 110 | * @return locale |
||
| 111 | */ |
||
| 112 | public function getLocaleForObject() |
||
| 113 | { |
||
| 114 | $id = (int)$this->getRequest()->requestVar('id'); |
||
| 115 | $class = Convert::raw2sql($this->getRequest()->requestVar('class')); |
||
| 116 | $locale = Translatable::get_current_locale(); |
||
| 117 | if ($id && $class && class_exists($class) && $class::has_extension(Translatable::class)) { |
||
| 118 | // temporarily disable locale filter so that we won't filter out the object |
||
| 119 | Translatable::disable_locale_filter(); |
||
| 120 | $object = DataObject::get_by_id($class, $id); |
||
| 121 | Translatable::enable_locale_filter(); |
||
| 129 |