/[cvs]/nfo/php/libs/org.netfrag.glib/php_extensions.php
ViewVC logotype

Annotation of /nfo/php/libs/org.netfrag.glib/php_extensions.php

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.2 - (hide annotations)
Wed Mar 5 11:58:49 2003 UTC (21 years, 5 months ago) by joko
Branch: MAIN
Changes since 1.1: +10 -7 lines
modified is_hash, mkInstance and others

1 joko 1.1 <?php
2    
3     /**
4     * This file contains some core functions extending php.
5     *
6     * @author Andreas Motl <andreas.motl@ilo.de>
7     * @package org.netfrag.glib
8     * @module php
9     *
10     */
11    
12     /**
13 joko 1.2 * $Id: php_extensions.php,v 1.1 2003/03/03 21:08:21 joko Exp $
14     *
15     * $Log: php_extensions.php,v $
16     * Revision 1.1 2003/03/03 21:08:21 joko
17     * refactored from flib/utils
18 joko 1.1 *
19     *
20     */
21    
22    
23     /**
24     * --- php extension functions
25     *
26     * x php::Dumper
27     * x php::session_register_safe
28     * x php::array_init
29     * x php::is_hash
30     * x php::array_join_merge
31     * o php::merge
32     * o php::merge_to
33     * x php::loadModule
34     * x php::mkInstance
35     *
36     * @author Andreas Motl <andreas.motl@ilo.de>
37     * @copyright (c) 2003 - All Rights reserved.
38     * @license GNU LGPL (GNU Lesser General Public License)
39     *
40     * @author-url http://www.netfrag.org/~joko/
41     * @license-url http://www.gnu.org/licenses/lgpl.txt
42     *
43     * @package org.netfrag.glib
44     * @module php
45     *
46     */
47    
48     /**
49     * Todo:
50     * o establish mkInstance here (move from DesignPattern::Object::mkObject)
51     * o establish loadModule here (move from DesignPattern::Object::loadModule)
52     *
53     * Ideas:
54     * o php::create_redirector_function('func', array( type => 'lamba|function|method', name => 'Abc::do_xyz') )
55     * o php::create_redirector_method('class|obj_ref', 'method', $target)
56     * o php::export_symbol(from, to) (maybe solves above two)
57     *
58     */
59    
60    
61    
62     /**
63     * --- shortcut functions
64     * Is there a mechanism in php to 'export' these methods
65     * to the global symbol table automagically?
66     * We wouldn't require declaring these shortcuts below and
67     * could also do some nice stuff at runtime.
68     * (maybe resembling CPAN's Exporter)
69     *
70     * Okay, 'eval' and 'create_function' are alternatives, but i'm
71     * still looking for something that would let us manipulate the
72     * symbol table.... (would also be a nice-to-have feature for
73     * mungling "other" symbol table entries, like variables
74     * and/or object references etc.)
75     *
76     * TODO: $php::EXPORT_OK = array('Dumper', 'session_register_safe', 'mkObject', 'is_hash', 'merge_to');
77     *
78     */
79    
80     // this is (and will probably always be) required by the "Exporter"
81     function &Dumper() {
82     $args = func_get_args();
83     // shrink array to single item?
84     //if (sizeof($args) == 1) { $args = $args[0]; }
85     php::array_shrink($args);
86     return php::Dumper($args);
87     }
88    
89     // these could be refactore using Exporter proposal below,
90     // which just does this code at runtime via eval
91     //function &session_register_safe() { return php::session_register_safe(func_get_args()); }
92     //function &is_hash() { return php::is_hash(func_get_args()); }
93     //function &loadModule() { return php::loadModule(func_get_args()); }
94     //function &mkObject() { return php::mkInstance(func_get_args()); }
95    
96    
97     //exit;
98    
99     // yes!
100     php::export_symbols();
101    
102    
103    
104     /**
105     * --- php extension functions lying in the php:: namespace
106     *
107     */
108    
109    
110     class php {
111    
112    
113     // Exporter proposal
114    
115     // does (e.g.) Exporter::export_symbol('php', 'loadModule', array( php_function => 'loadModule' ));
116     // (or) Exporter::export_symbol('php', 'mkInstance', array( php_function => 'mkObject' ));
117     // -> just all from EXPORT_OK
118    
119     function export_symbols() {
120    
121     $symbols = func_get_args();
122     php::array_shrink($symbols);
123    
124     global $PHP_EXTENSIONS_EXPORT;
125     //print Dumper($PHP_EXTENSIONS_EXPORT);
126     //exit;
127    
128     if (is_array($PHP_EXTENSIONS_EXPORT)) {
129     //if (defined('EXPORT_OK')) {
130     //print EXPORT_OK . "<br/>";
131     //$symbols = split(' ', EXPORT_OK);
132     //foreach ($php->EXPORT_OK as $symbol) {
133     /*
134     foreach (EXPORT_OK as $symbol) {
135     print "exporting: $symbol<br/>";
136     Exporter::export_symbol('php', $symbol, array( php_function => $symbol ));
137     }
138     */
139    
140     $symbols = php::array_join_merge($PHP_EXTENSIONS_EXPORT, $symbols);
141    
142     php::loadModule('Exporter');
143     if (class_exists('Exporter')) {
144     Exporter::export_symbols('php', $symbols);
145     }
146    
147     }
148    
149     }
150    
151     function Dumper() {
152     $arg_list = func_get_args();
153     $count = 1;
154    
155     // build dump by catching output of php's 'print_r'
156     // using php's output buffering functions
157     ob_start();
158     foreach ($arg_list as $arg) {
159     print_r($arg);
160     if (is_string($arg)) {
161     print "\n";
162     }
163     $count++;
164     }
165     $var_dump = ob_get_contents();
166     ob_end_clean();
167    
168     //print "mode: " . $this->Dumper_mode . "<br/>";
169     //if ($this->Dumper_mode == HTML) {
170     $var_dump = str_replace("\n", '<br/>', $var_dump);
171     $var_dump = str_replace(" ", '&nbsp;', $var_dump);
172     //}
173    
174     //if (sizeof($args) == 1) { $var_dump .= '<br/>'; }
175    
176     return $var_dump;
177     }
178    
179     function session_register_safe($varname) {
180     if (!session_is_registered($varname)) {
181     session_register($varname);
182     return 1;
183     }
184     }
185    
186     // -------------------------------------------------
187     // array initializer
188     // initializes passed variable (taken by reference) with an empty array
189     // does this only if it doesn't exist yet or initialization is explicitely requested ($clear = 1)
190     function array_init(&$var, $clear = 0) {
191     if (!is_array($var) || $clear) { $var = array(); }
192     }
193    
194     // from: php.net - http://www.php.net/manual/en/function.array-merge-recursive.php
195 joko 1.2 function is_hash( $var = null ) {
196 joko 1.1 if( is_array( $var ) ) {
197     $keys = array_keys( $var );
198     $all_num = true;
199     for( $i=0; $i<count($keys); $i++ )
200     if( is_string($keys[$i] ) ) return true;
201     }
202     return false;
203     }
204    
205     // from: php.net - http://www.php.net/manual/en/function.array-merge-recursive.php
206     function array_join_merge( $arr1, $arr2 ) {
207     if( is_array( $arr1 ) and is_array( $arr2 ) ) {
208     // the same -> merge
209     $new_array = array();
210    
211     if( php::is_hash( $arr1 ) and php::is_hash( $arr2 ) ) {
212     // hashes -> merge based on keys
213     $keys = array_merge( array_keys( $arr1 ), array_keys( $arr2 ) );
214     foreach( $keys as $key ) {
215     $new_array[$key] = php::array_join_merge( $arr1[$key], $arr2[$key] );
216     }
217     } else {
218     // two real arrays -> merge
219     $new_array =
220     array_reverse(array_unique(array_reverse(array_merge($arr1,$arr2))));
221     }
222    
223     return $new_array;
224     } else {
225     // not the same ... take new one if defined, else the old one stays
226     return $arr2 ? $arr2 : $arr1;
227     }
228     }
229    
230    
231     // TODO:
232     // o refactor to the php:: namespace?
233     // o PEAR::???
234     // x rename mkObject to mkInstance
235     // x rename loadModule? let it like is.... (suggestions? loadPackage?)
236     // o enhance loadModule: make it possible to load packages from anywhere?! #?)&%$
237    
238     function namespace2filename($nsName) {
239     if ($filename = str_replace('::', '/', $nsName)) {
240     return $filename;
241     }
242     }
243    
244     function loadModule($namespacedClassname, $options = null) {
245    
246     if (DEBUG_PHP_EXTENSIONS == 1) {
247     print "php::loadModule: " . Dumper($namespacedClassname);
248     }
249     if (LOG_PHP_EXTENSIONS == 1) {
250     php::append_log( "php::loadModule( $namespacedClassname )" );
251     }
252    
253     if ($filename = php::namespace2filename($namespacedClassname)) {
254    
255     if (is_array($options)) {
256     $extension = $options[extension];
257     } elseif ($options) {
258     $extension = $options;
259     } else {
260     $extension = 'php';
261     }
262    
263     $filename .= ".$extension";
264    
265     // V1: just require
266     //require_once($filename);
267    
268     // V2: check file for existance (didn't work!!! problem with path-style conversion regarding platform running on?)
269     /*
270     if (file_exists($filename)) {
271     require_once($filename);
272     } else {
273     //user_error("Could not load module '$namespacedClassname', file '$filename' does not exist.");
274     }
275     */
276    
277     // V3: wrapped through eval (weird)
278     /*
279     $evalstring = "return include_once('$filename');";
280     $result = eval($evalstring);
281     if (!$result) {
282     user_error("DesignPattern::Object: Could not load module '$namespacedClassname', file '$filename' does not exist.");
283     return;
284     }
285     */
286    
287     // V4: just include
288     //define ("WARNING", E_USER_NOTICE);
289     //error_reporting(E_USER_WARNING);
290     //error_reporting(E_ALL);
291     //error_reporting(E_CORE_ERROR);
292     //set_error_handler(array('php::error_handler_2'));
293    
294     //set_error_handler('php_error_handler');
295     // TODO: do stack-backtracing here to determine function called two or three levels before!!!
296     //print "file: $filename<br/>";
297     if (!include_once($filename)) {
298     $msg = "php::loadModule error: Could not load module '$namespacedClassname', file '$filename' does not exist.";
299     user_error($msg);
300     php::append_log($msg, PEAR_LOG_ERR);
301     //trigger_error($msg);
302     //print "msg: $msg<br/>";
303     return;
304     }
305     //restore_error_handler();
306    
307     //exit;
308    
309     return 1;
310     }
311     }
312    
313    
314     function &mkComponent() {
315    
316     // argument handling - perl style
317 joko 1.2 $arg_list = &func_get_args();
318 joko 1.1
319     // trace
320     //print "php::mkInstance: " . Dumper($arg_list);
321     //exit;
322    
323     // patch arglist if all arguments are passed in as a single array
324     if (sizeof($arg_list) == 1 && is_array($arg_list[0])) {
325 joko 1.2 $arg_list = &$arg_list[0];
326 joko 1.1 }
327    
328     //print "arg_list: $arg_list<br/>";
329     $namespacedClassname = array_shift($arg_list);
330    
331     // debug
332     if (DEBUG_PHP_EXTENSIONS == 1) {
333     print "php::mkComponent: $namespacedClassname<br/>";
334     }
335     if (LOG_PHP_EXTENSIONS == 1) {
336     php::append_log( "php::mkComponent( $namespacedClassname )" );
337     }
338    
339     $classname = $namespacedClassname;
340     $filename = $namespacedClassname;
341     $load_module_options = null;
342    
343     if (strstr($namespacedClassname, '_')) {
344     //print "mkObject: unallowed character in namespaced classname: '_' ($namespacedClassname)<br/>";
345     //return;
346     }
347    
348     if (strstr($namespacedClassname, '.')) {
349     //print "mkObject: unallowed character in namespaced classname: '_' ($namespacedClassname)<br/>";
350     //return;
351     $parts = split('\.', $namespacedClassname);
352     $filename = $parts[0];
353     $extension = $parts[sizeof($parts) - 1];
354     $load_module_options = array( extension => $extension );
355     }
356    
357    
358     // trace
359     //print "mkObject: $classname<br>";
360     //print "file: $filename<br>";
361    
362     // build native class name from namespaced one
363     $classname = str_replace('::', '_', $classname);
364     $classname = str_replace('/', '_', $classname);
365    
366     // load class-file
367     if (!class_exists($classname)) {
368     php::loadModule($filename, $load_module_options);
369     }
370    
371     // instantiate object
372     $attributes = $arg_list;
373     // V0:
374     //$obj = new $classname($attributes);
375     // V1:
376     //$obj = new DesignPattern_Bridge($classname, $attributes);
377     // V2:
378     $obj = php::mkInstance($classname, $attributes);
379    
380     // constructor autocall - if possible
381     // FIXME: take care for side-effects!!!
382     /*
383     if (method_exists($obj, 'constructor')) {
384     $obj->constructor();
385     }
386     */
387    
388     // return instance
389     return $obj;
390    
391     }
392    
393     // from: http://www.php.net/manual/en/function.method-exists.php
394     function class_has_method($className, $methodName) {
395     $bool_exists = (in_array(strtolower($methodName), get_class_methods($className)));
396     return $bool_exists;
397     }
398    
399     // down: array( item ) => item
400     function &array_shrink(&$array) {
401     // shrink array to single item? yes!
402     if (is_array($array) && !php::is_hash($array) && (sizeof($array) == 1)) { $array = $array[0]; }
403     return $array;
404     }
405    
406     function append_log($message, $level = PEAR_LOG_DEBUG) {
407     static $Class_Logger_loaded;
408     static $Class_Logger_instance;
409     if (!$Class_Logger_loaded) {
410     $Class_Logger_loaded++;
411     //print "LOAD<br/>";
412     php::loadModule('Class::Logger');
413     }
414     if (class_exists('Class_Logger')) {
415     //$Class_Logger_instance = new Class_Logger();
416     $Class_Logger_instance = php::mkComponent('Class::Logger');
417     //print "YAI<br/>";
418     //Class_Logger::log($message);
419     $Class_Logger_instance->log($message, $level);
420     } else {
421     // FIXME! pre-logger log-messages (two or three):
422     // [PEAR_LOG_DEBUG] php::loadModule( Class::Logger )
423     // [PEAR_LOG_DEBUG] php::loadModule( DesignPattern::AbstractClass )
424     //print "[$level] $message" . "<br/>";
425     }
426     }
427    
428 joko 1.2 function &mkInstance($classname, $attributes = array()) {
429 joko 1.1
430     $oo = is_object($this);
431    
432     // autocall constructor?
433     if ($oo) {
434     //print Dumper($this);
435     //exit;
436     //print "this: $this<br/>";
437     //print "parent: $parent<br/>";
438     // V1:
439     //parent::constructor();
440     // V2:
441     //call_user_func('parent::constructor');
442     // V3:
443     //call_user_func(array($this, 'constructor'));
444     if (method_exists($this, 'constructor')) {
445     //print "YAI<br/>";
446     //call_user_func(array($this, 'constructor'));
447     }
448     }
449    
450     if ($oo) {
451     //$this->log( get_class($this) . "->mkInstance( classname $classname )" );
452     //Class_Logger::log( get_class($this) . "->mkInstance( classname $classname )" );
453     } else {
454     //php::append_log( "php::mkInstance( classname $classname )" );
455     }
456    
457     if (isset($attributes)) {
458     //print Dumper($attributes);
459    
460     /*
461     // pass single argument 1:1
462     if (count($attributes) == 1) {
463     $attributes_merged = $attributes[0];
464    
465    
466    
467     // pass hash 1:1
468     } elseif (is_hash($attributes)) {
469     $attributes_merged = $attributes;
470    
471     } else {
472     $attributes_merged = $attributes;
473     }
474     */
475    
476     $args_pass = array();
477     for ($i=0; $i<=count($attributes); $i++) {
478 joko 1.2 array_push($args_pass, '&$attributes[' . $i . ']');
479 joko 1.1 }
480    
481     $arg_string = join(', ', $args_pass);
482    
483     /*
484     // merge entries of numerical indexed arrays together into one hash
485     } else {
486     $attributes_merged = array();
487     foreach ($attributes as $entry) {
488     $attributes_merged = array_merge($attributes_merged, $entry);
489     }
490     }
491     */
492    
493     if (!class_exists($classname)) {
494     user_error("Class '$classname' doesn't exist.");
495     return;
496     }
497    
498     //print Dumper($attributes_merged);
499     //print Dumper($attributes);
500     //$instance = new $classname($attributes_merged);
501     //$instance = new $classname($attributes[0]);
502     $evalstr = 'return new $classname(' . $arg_string . ');';
503    
504     //print "eval: $evalstr<br/>";
505    
506     $instance = eval($evalstr);
507     //print $evalstr . "<br>";
508     } else {
509     $instance = new $classname;
510     }
511     //$this->log("ok");
512     return $instance;
513     }
514    
515     // up: string -> array
516     function array_cast_safe(&$array_or_not) {
517     if (!is_array($array_or_not)) {
518     $array_or_not = array($array_or_not);
519     //print Dumper($array_or_not);
520     //exit;
521     }
522     }
523    
524     // To return all ancestors class of an object
525     // from: http://www.php.net/manual/en/function.get-parent-class.php
526     function get_ancestors_class($classname) {
527     $father = get_parent_class($classname);
528     if ($father != "") {
529     $ancestors = php::get_ancestors_class($father);
530     $ancestors[] = $father;
531     }
532     return $ancestors;
533     }
534    
535     // ------ override/expand php's 'include_path' setting ------
536     function add_libpath($paths) {
537    
538     if (!is_array($paths)) {
539     $paths = array($paths);
540     }
541     array_push($paths, ini_get("include_path"));
542    
543     // determine OS
544     $os = 'linux';
545     if (stristr($_SERVER["SERVER_SOFTWARE"], 'win32')) {
546     $os = 'windows';
547     }
548    
549     $path_delimiter = ':';
550     // change path-delimiter for win32
551     if ($os == 'windows') { $path_delimiter = ';'; }
552     // build new 'include_path'-string
553     $path_new = join($path_delimiter, $paths);
554     ini_set("include_path", $path_new);
555     }
556    
557     // from: http://www.php.net/manual/en/function.is-subclass-of.php
558     function is_subclass($child, $parent) {
559     if (is_string($child)) {
560     do {
561     $child = get_parent_class($child);
562     if (!$child) return false;
563     //} while ($child == $parent);
564     } while ($child != $parent);
565     return true;
566     } else {
567     return is_subclass_of($child, $parent);
568     }
569     }
570    
571    
572     }
573    
574     //function error_handler($errno, $errstr, $errfile, $errline) {
575     function php_error_handler() {
576     //print "ERROR!<br/>";
577     $error_raw = func_get_args();
578    
579     //print Dumper($error_raw);
580    
581     $error = array(
582     'level' => $error_raw[0],
583     'message' => $error_raw[1],
584     'file' => $error_raw[2],
585     'line' => $error_raw[3],
586     'context' => &$error_raw[4],
587     'object_context' => &$error_raw[4][this],
588     );
589     $error[component] = $error[object_context]->_component_name;
590    
591     //$output_order = array( 'message', 'component', 'file', 'line', 'level' );
592     $output_order = array( 'message', 'file', 'line' );
593    
594     /*
595     $level = $error[0];
596     $context = &$error[4];
597     $cc = &$context['this'];
598     */
599    
600    
601     //print Dumper($context);
602     //print Dumper($cc);
603     //print Dumper($cc->_component_name);
604    
605     // by level
606     //$do_trace = ($level <= 5);
607    
608     //$c_name = $context['this']['_component_name'];
609    
610     //print "c_error: $c_name<br/>";
611    
612     // if component
613     //$do_trace = isset($context[this][_component_name]);
614     //$do_trace = isset($context->this[_component_name]);
615     //$do_trace = isset($cc->_component_name);
616     $do_trace = isset($error[component]);
617    
618     //$do_trace = 1;
619    
620     //print Dumper($context);
621    
622     if ($do_trace) {
623    
624     //print php::Dumper($error);
625     //exit;
626    
627     //print "<hr/><b><font color=\"red\">ERROR:</font></b><br/>";
628     print "<b><font color=\"red\">ERROR:</font></b><br/> ";
629    
630     foreach ($output_order as $key) {
631     print "<b>$key:</b> $error[$key]<br/>";
632     }
633    
634     }
635    
636     }
637    
638    
639     ?>

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed