LocaleLookup.php 2.29 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php

/**
 * @file
 * Definition of LocaleLookup
 */

namespace Drupal\locale;

use Drupal\Core\Utility\CacheArray;
11
12
use Drupal\locale\SourceString;
use Drupal\locale\TranslationString;
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

/**
 * Extends CacheArray to allow for dynamic building of the locale cache.
 */
class LocaleLookup extends CacheArray {

  /**
   * A language code.
   * @var string
   */
  protected $langcode;

  /**
   * The msgctxt context.
   * @var string
   */
  protected $context;

31
32
33
34
35
36
37
  /**
   * The locale storage
   *
   * @var Drupal\locale\StringStorageInterface
   */
  protected $stringStorage;

38
39
40
  /**
   * Constructs a LocaleCache object.
   */
41
  public function __construct($langcode, $context, $stringStorage) {
42
43
    $this->langcode = $langcode;
    $this->context = (string) $context;
44
    $this->stringStorage = $stringStorage;
45
46
47
48
49

    // Add the current user's role IDs to the cache key, this ensures that, for
    // example, strings for admin menu items and settings forms are not cached
    // for anonymous users.
    $rids = implode(':', array_keys($GLOBALS['user']->roles));
50
    parent::__construct("locale:$langcode:$context:$rids", 'cache', array('locale' => TRUE));
51
52
53
  }

  /**
54
   * Implements CacheArray::resolveCacheMiss().
55
56
   */
  protected function resolveCacheMiss($offset) {
57
58
59
60
61
62
    $translation = $this->stringStorage->findTranslation(array(
      'language' => $this->langcode,
      'source' => $offset,
      'context' => $this->context
    ));

63
64
65
66
67
68
    if ($translation) {
      $value = !empty($translation->translation) ? $translation->translation : TRUE;
    }
    else {
      // We don't have the source string, update the {locales_source} table to
      // indicate the string is not translated.
69
70
71
72
      $this->stringStorage->createString(array(
        'source' => $offset,
        'context' => $this->context,
        'version' => VERSION
73
      ))->addLocation('path', request_uri())->save();
74
      $value = TRUE;
75
76
77
78
79
80
81
82
83
84
85
86
    }
    $this->storage[$offset] = $value;
    // Disabling the usage of string caching allows a module to watch for
    // the exact list of strings used on a page. From a performance
    // perspective that is a really bad idea, so we have no user
    // interface for this. Be careful when turning this option off!
    if (variable_get('locale_cache_strings', 1)) {
      $this->persist($offset);
    }
    return $value;
  }
}