1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 3.0.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\I18n;
16:
17: use Aura\Intl\Package;
18: use RuntimeException;
19:
20: /**
21: * Wraps multiple message loaders calling them one after another until
22: * one of them returns a non-empty package.
23: */
24: class ChainMessagesLoader
25: {
26:
27: /**
28: * The list of callables to execute one after another for loading messages
29: *
30: * @var callable[]
31: */
32: protected $_loaders = [];
33:
34: /**
35: * Receives a list of callable functions or objects that will be executed
36: * one after another until one of them returns a non-empty translations package
37: *
38: * @param callable[] $loaders List of callables to execute
39: */
40: public function __construct(array $loaders)
41: {
42: $this->_loaders = $loaders;
43: }
44:
45: /**
46: * Executes this object returning the translations package as configured in
47: * the chain.
48: *
49: * @return \Aura\Intl\Package
50: * @throws \RuntimeException if any of the loaders in the chain is not a valid callable
51: */
52: public function __invoke()
53: {
54: foreach ($this->_loaders as $k => $loader) {
55: if (!is_callable($loader)) {
56: throw new RuntimeException(sprintf(
57: 'Loader "%s" in the chain is not a valid callable',
58: $k
59: ));
60: }
61:
62: $package = $loader();
63: if (!$package) {
64: continue;
65: }
66:
67: if (!($package instanceof Package)) {
68: throw new RuntimeException(sprintf(
69: 'Loader "%s" in the chain did not return a valid Package object',
70: $k
71: ));
72: }
73:
74: return $package;
75: }
76:
77: return new Package();
78: }
79: }
80: