Completed
Pull Request — 8.x-3.x (#550)
by Philipp
02:06
created

GraphQLLanguageContext::executeInLanguageContext()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 3
nop 2
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Drupal\graphql;
4
5
use Drupal\Core\Language\LanguageManagerInterface;
6
7
/**
8
 * Simple service that stores the current GraphQL language state.
9
 */
10
class GraphQLLanguageContext {
11
12
  /**
13
   * Indicates if the GraphQL context language is currently active.
14
   *
15
   * @var bool
16
   */
17
  protected $isActive;
18
19
  /**
20
   * The current language context.
21
   *
22
   * @var string
23
   */
24
  protected $currentLanguage;
25
26
  /**
27
   * The language manager service.
28
   *
29
   * @var \Drupal\Core\Language\LanguageManagerInterface
30
   */
31
  protected $languageManager;
32
33
  /**
34
   * GraphQLLanguageContext constructor.
35
   *
36
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
37
   *   The language manager service.
38
   */
39
  public function __construct(LanguageManagerInterface $languageManager) {
40
    $this->languageManager = $languageManager;
41
  }
42
43
  /**
44
   * Retrieve the current language.
45
   *
46
   * @return string|null
47
   *   The current language code, or null if the context is not active.
48
   */
49
  public function getCurrentLanguage() {
50
    return $this->isActive
51
      ? ($this->currentLanguage ?: $this->languageManager->getDefaultLanguage()->getId())
52
      : NULL;
53
  }
54
55
  /**
56
   * Executes a callable in a defined language context.
57
   *
58
   * @param callable $callable
59
   *   The callable to be executed.
60
   * @param string $language
61
   *   The langcode to be set.
62
   *
63
   * @return mixed
64
   *   The callables result.
65
   *
66
   * @throws \Exception
67
   *   Any exception caught while executing the callable.
68
   */
69
  public function executeInLanguageContext(callable $callable, $language) {
70
    $this->currentLanguage = $language;
71
    $this->isActive = TRUE;
72
    $this->languageManager->reset();
73
    // Extract the result array.
74
    try {
75
      return call_user_func($callable);
76
    }
77
    catch (\Exception $exc) {
78
      throw $exc;
79
    }
80
    finally {
81
      // In any case, set the language context back to null.
82
      $this->currentLanguage = NULL;
83
      $this->isActive = FALSE;
84
      $this->languageManager->reset();
85
    }
86
  }
87
88
}
89