Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
10 / 10 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| UserRealnamePreloadService | |
100.00% |
10 / 10 |
|
100.00% |
2 / 2 |
7 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| preload | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
6 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Drupal\name\Service; |
| 6 | |
| 7 | use Drupal\Core\Config\ConfigFactoryInterface; |
| 8 | use Drupal\Core\Entity\EntityTypeManagerInterface; |
| 9 | use Drupal\Core\Session\AccountInterface; |
| 10 | use Drupal\field\Entity\FieldConfig; |
| 11 | |
| 12 | /** |
| 13 | * Loads full user when user_format_name_alter needs preferred name field data. |
| 14 | * |
| 15 | * @internal |
| 16 | */ |
| 17 | class UserRealnamePreloadService implements UserRealnamePreloadInterface { |
| 18 | |
| 19 | /** |
| 20 | * Whether a preload operation is in progress (recursion guard). |
| 21 | */ |
| 22 | private bool $inPreload = FALSE; |
| 23 | |
| 24 | public function __construct( |
| 25 | private readonly ConfigFactoryInterface $configFactory, |
| 26 | private readonly EntityTypeManagerInterface $entityTypeManager, |
| 27 | ) {} |
| 28 | |
| 29 | /** |
| 30 | * Preloads user entity where configured; mirrors legacy global behavior. |
| 31 | * |
| 32 | * Recursion check in place after RealName module issue queue suggested that |
| 33 | * there were issues with token based recursion on load. |
| 34 | */ |
| 35 | public function preload(AccountInterface $account): void { |
| 36 | $should_preload = (!$this->inPreload && !isset($account->realname)); |
| 37 | if ($should_preload) { |
| 38 | $field_name = $this->configFactory->get('name.settings')->get('user_preferred'); |
| 39 | $field_exists = ($field_name && FieldConfig::loadByName('user', 'user', $field_name)); |
| 40 | if ($field_exists) { |
| 41 | $this->inPreload = TRUE; |
| 42 | $user_id = $account->id(); |
| 43 | $account = $user_id ? $this->entityTypeManager->getStorage('user')->load($user_id) : 'unknown'; |
| 44 | $this->inPreload = FALSE; |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | } |