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\Format;
10
11 use Joomla\Registry\AbstractRegistryFormat;
12
13 /**
14 * PHP class format handler for Registry
15 *
16 * @since 1.0
17 */
18 class Php extends AbstractRegistryFormat
19 {
20 /**
21 * Converts an object into a php class string.
22 * - NOTE: Only one depth level is supported.
23 *
24 * @param object $object Data Source Object
25 * @param array $params Parameters used by the formatter
26 *
27 * @return string Config class formatted string
28 *
29 * @since 1.0
30 */
31 public function objectToString($object, $params = array())
32 {
33 // A class must be provided
34 $class = !empty($params['class']) ? $params['class'] : 'Registry';
35
36 // Build the object variables string
37 $vars = '';
38
39 foreach (get_object_vars($object) as $k => $v)
40 {
41 if (is_scalar($v))
42 {
43 $vars .= "\tpublic $" . $k . " = '" . addcslashes($v, '\\\'') . "';\n";
44 }
45 elseif (is_array($v) || is_object($v))
46 {
47 $vars .= "\tpublic $" . $k . " = " . $this->getArrayString((array) $v) . ";\n";
48 }
49 }
50
51 $str = "<?php\n";
52
53 // If supplied, add a namespace to the class object
54 if (isset($params['namespace']) && $params['namespace'] != '')
55 {
56 $str .= "namespace " . $params['namespace'] . ";\n\n";
57 }
58
59 $str .= "class " . $class . " {\n";
60 $str .= $vars;
61 $str .= "}";
62
63 // Use the closing tag if it not set to false in parameters.
64 if (!isset($params['closingtag']) || $params['closingtag'] !== false)
65 {
66 $str .= "\n?>";
67 }
68
69 return $str;
70 }
71
72 /**
73 * Parse a PHP class formatted string and convert it into an object.
74 *
75 * @param string $data PHP Class formatted string to convert.
76 * @param array $options Options used by the formatter.
77 *
78 * @return object Data object.
79 *
80 * @since 1.0
81 */
82 public function stringToObject($data, array $options = array())
83 {
84 return true;
85 }
86
87 /**
88 * Method to get an array as an exported string.
89 *
90 * @param array $a The array to get as a string.
91 *
92 * @return array
93 *
94 * @since 1.0
95 */
96 protected function getArrayString($a)
97 {
98 $s = 'array(';
99 $i = 0;
100
101 foreach ($a as $k => $v)
102 {
103 $s .= ($i) ? ', ' : '';
104 $s .= '"' . $k . '" => ';
105
106 if (is_array($v) || is_object($v))
107 {
108 $s .= $this->getArrayString((array) $v);
109 }
110 else
111 {
112 $s .= '"' . addslashes($v) . '"';
113 }
114
115 $i++;
116 }
117
118 $s .= ')';
119
120 return $s;
121 }
122 }
123