1 <?php
2 /**
3 * Part of the Joomla Framework Registry Package
4 *
5 * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
6 * @license GNU General Public License version 2 or later; see LICENSE
7 */
8
9 namespace Joomla\Registry;
10
11 /**
12 * Factory class to fetch Registry objects
13 *
14 * @since 1.5.0
15 */
16 class Factory
17 {
18 /**
19 * Format instances container - for backward compatibility with AbstractRegistryFormat::getInstance().
20 *
21 * @var FormatInterface[]
22 * @since 1.5.0
23 * @deprecated 2.0 Object caching will no longer be supported
24 */
25 protected static $formatInstances = array();
26
27 /**
28 * Returns an AbstractRegistryFormat object, only creating it if it doesn't already exist.
29 *
30 * @param string $type The format to load
31 * @param array $options Additional options to configure the object
32 *
33 * @return FormatInterface Registry format handler
34 *
35 * @since 1.5.0
36 * @throws \InvalidArgumentException
37 */
38 public static function getFormat($type, array $options = array())
39 {
40 // Sanitize format type.
41 $type = strtolower(preg_replace('/[^A-Z0-9_]/i', '', $type));
42
43 /*
44 * Only instantiate the object if it doesn't already exist.
45 * @deprecated 2.0 Object caching will no longer be supported, a new instance will be returned every time
46 */
47 if (!isset(self::$formatInstances[$type]))
48 {
49 $localNamespace = __NAMESPACE__ . '\\Format';
50 $namespace = isset($options['format_namespace']) ? $options['format_namespace'] : $localNamespace;
51 $class = $namespace . '\\' . ucfirst($type);
52
53 if (!class_exists($class))
54 {
55 // Were we given a custom namespace? If not, there's nothing else we can do
56 if ($namespace === $localNamespace)
57 {
58 throw new \InvalidArgumentException(sprintf('Unable to load format class for type "%s".', $type), 500);
59 }
60
61 $class = $localNamespace . '\\' . ucfirst($type);
62
63 if (!class_exists($class))
64 {
65 throw new \InvalidArgumentException(sprintf('Unable to load format class for type "%s".', $type), 500);
66 }
67 }
68
69 self::$formatInstances[$type] = new $class;
70 }
71
72 return self::$formatInstances[$type];
73 }
74 }
75