33namespace Xhgui \Profiler ;
44
55use ArrayAccess ;
6+ use Xhgui \Profiler \Exception \ProfilerException ;
67
78class Config implements ArrayAccess
89{
910 /** @var array */
10- private $ config ;
11+ private $ config = array () ;
1112
1213 public function __construct (array $ config = array ())
1314 {
14- $ this ->config = $ this -> getDefaultConfig ();
15+ $ this ->loadDefaultConfig ();
1516 if ($ config ) {
1617 $ this ->merge ($ config );
1718 }
@@ -25,6 +26,37 @@ public function toArray()
2526 return $ this ->config ;
2627 }
2728
29+ /**
30+ * Create config from defaults, and merge config/config.php if the file exists
31+ *
32+ * @return Config
33+ */
34+ public static function create ()
35+ {
36+ $ configDir = dirname (__DIR__ ) . '/config ' ;
37+ $ config = new self ();
38+ if (file_exists ($ file = $ configDir . '/config.php ' )) {
39+ $ config ->load ($ file );
40+ }
41+
42+ return $ config ;
43+ }
44+
45+ /**
46+ * Load a config file, merge with the currently loaded configuration.
47+ */
48+ public function load ($ filename )
49+ {
50+ if (!file_exists ($ filename )) {
51+ throw new ProfilerException ("File does not exist: $ filename " );
52+ }
53+ $ config = require $ filename ;
54+ if ($ config === 1 ) {
55+ throw new ProfilerException ("Config did not return an array: $ filename " );
56+ }
57+ $ this ->merge ($ config );
58+ }
59+
2860 private function merge (array $ config )
2961 {
3062 $ this ->config = array_replace ($ this ->config , $ config );
@@ -50,38 +82,8 @@ public function offsetUnset($offset)
5082 unset($ this ->config [$ offset ]);
5183 }
5284
53- /**
54- * @return array
55- */
56- private function getDefaultConfig ()
85+ private function loadDefaultConfig ()
5786 {
58- return array (
59- 'save.handler ' => Profiler::SAVER_STACK ,
60- 'save.handler.stack ' => array (
61- 'savers ' => array (
62- Profiler::SAVER_UPLOAD ,
63- Profiler::SAVER_FILE ,
64- ),
65- 'saveAll ' => false ,
66- ),
67- 'save.handler.file ' => array (
68- 'filename ' => sys_get_temp_dir () . '/xhgui.data.jsonl ' ,
69- ),
70- 'profiler.enable ' => function () {
71- return true ;
72- },
73- 'profiler.flags ' => array (
74- ProfilingFlags::CPU ,
75- ProfilingFlags::MEMORY ,
76- ProfilingFlags::NO_BUILTINS ,
77- ProfilingFlags::NO_SPANS ,
78- ),
79- 'profiler.options ' => array (),
80- 'profiler.exclude-env ' => array (),
81- 'profiler.simple_url ' => function ($ url ) {
82- return preg_replace ('/=\d+/ ' , '' , $ url );
83- },
84- 'profiler.replace_url ' => null ,
85- );
87+ $ this ->load (__DIR__ . '/../config/config.default.php ' );
8688 }
8789}
0 commit comments