Merge pull request #19273 from eileenmcnaughton/complete
[civicrm-core.git] / CRM / Core / Resources / Strings.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Manage translatable strings on behalf of resource files.
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18 class CRM_Core_Resources_Strings {
19
20 /**
21 * Cache.
22 *
23 * @var CRM_Utils_Cache_Interface|null
24 */
25 private $cache = NULL;
26
27 /**
28 * @param CRM_Utils_Cache_Interface $cache
29 * Localization cache.
30 */
31 public function __construct($cache) {
32 $this->cache = $cache;
33 }
34
35 /**
36 * Flush the cache of translated strings.
37 */
38 public function flush() {
39 $this->cache->flush();
40 }
41
42 /**
43 * Get the strings from a file, using a cache if available.
44 *
45 * @param string $bucket
46 * The name of a cache-row which includes strings for this file.
47 * @param string $file
48 * File path.
49 * @param string $format
50 * Type of file (e.g. 'text/javascript', 'text/html').
51 *
52 * @return array
53 * List of translatable strings.
54 *
55 * @throws \CRM_Core_Exception
56 */
57 public function get($bucket, $file, $format) {
58 // array($file => array(...strings...))
59 $stringsByFile = $this->cache->get($bucket);
60 if (!$stringsByFile) {
61 $stringsByFile = [];
62 }
63 if (!isset($stringsByFile[$file])) {
64 if ($file && is_readable($file)) {
65 $stringsByFile[$file] = $this->extract($file, $format);
66 }
67 else {
68 $stringsByFile[$file] = [];
69 }
70 $this->cache->set($bucket, $stringsByFile);
71 }
72 return $stringsByFile[$file];
73 }
74
75 /**
76 * Extract a list of strings from a file.
77 *
78 * @param string $file
79 * File path.
80 * @param string $format
81 * Type of file (e.g. 'text/javascript', 'text/html').
82 * @return array
83 * List of translatable strings.
84 *
85 * @throws CRM_Core_Exception
86 */
87 public function extract($file, $format) {
88 switch ($format) {
89 case 'text/javascript':
90 return CRM_Utils_JS::parseStrings(file_get_contents($file));
91
92 case 'text/html':
93 // Magic! The JS parser works with HTML! See CRM_Utils_HTMLTest.
94 return CRM_Utils_JS::parseStrings(file_get_contents($file));
95
96 default:
97 throw new CRM_Core_Exception('Cannot extract strings: Unrecognized file type.');
98 }
99 }
100
101 }