Coverage for Doctrine_Lib

Back to coverage report

1 <?php
2 /*
3  *  $Id: Lib.php 3884 2008-02-22 18:26:35Z jwage $
4  *
5  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16  *
17  * This software consists of voluntary contributions made by many individuals
18  * and is licensed under the LGPL. For more information, see
19  * <http://www.phpdoctrine.org>.
20  */
21
22 /**
23  * Doctrine_Lib has not commonly used static functions, mostly for debugging purposes
24  *
25  * @package     Doctrine
26  * @subpackage  Lib
27  * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
28  * @link        www.phpdoctrine.org
29  * @since       1.0
30  * @version     $Revision: 3884 $
31  * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
32  */
33 class Doctrine_Lib
34 {
35     /**
36      * getRecordStateAsString
37      *
38      * @param integer $state the state of record
39      * @see Doctrine_Record::STATE_* constants
40      * @return string string representation of given state
41      */
42     public static function getRecordStateAsString($state)
43     {
44         switch ($state) {
45             case Doctrine_Record::STATE_PROXY:
46                 return "proxy";
47                 break;
48             case Doctrine_Record::STATE_CLEAN:
49                 return "persistent clean";
50                 break;
51             case Doctrine_Record::STATE_DIRTY:
52                 return "persistent dirty";
53                 break;
54             case Doctrine_Record::STATE_TDIRTY:
55                 return "transient dirty";
56                 break;
57             case Doctrine_Record::STATE_TCLEAN:
58                 return "transient clean";
59                 break;
60         }
61     }
62
63     /**
64      * getRecordAsString
65      *
66      * returns a string representation of Doctrine_Record object
67      *
68      * @param Doctrine_Record $record
69      * @return string
70      */
71     public static function getRecordAsString(Doctrine_Record $record)
72     {
73         $r[] = '<pre>';
74         $r[] = 'Component  : ' . $record->getTable()->getComponentName();
75         $r[] = 'ID         : ' . $record->obtainIdentifier();
76         $r[] = 'References : ' . count($record->getReferences());
77         $r[] = 'State      : ' . Doctrine_Lib::getRecordStateAsString($record->getState());
78         $r[] = 'OID        : ' . $record->getOID();
79         $r[] = 'data       : ' . Doctrine::dump($record->getData(), false);
80         $r[] = '</pre>';
81
82         return implode("\n",$r)."<br />";
83     }
84
85     /**
86      * getConnectionStateAsString
87      *
88      * returns a given connection state as string
89      *
90      * @param integer $state State of the connection as a string
91      */
92     public static function getConnectionStateAsString($state)
93     {
94         switch ($state) {
95             case Doctrine_Transaction::STATE_SLEEP:
96                 return "open";
97                 break;
98             case Doctrine_Transaction::STATE_BUSY:
99                 return "busy";
100                 break;
101             case Doctrine_Transaction::STATE_ACTIVE:
102                 return "active";
103                 break;
104         }
105     }
106
107     /**
108      * getConnectionAsString
109      *
110      * returns a string representation of Doctrine_Connection object
111      *
112      * @param Doctrine_Connection $connection
113      * @return string
114      */
115     public static function getConnectionAsString(Doctrine_Connection $connection)
116     {
117         $r[] = '<pre>';
118         $r[] = 'Doctrine_Connection object';
119         $r[] = 'State               : ' . Doctrine_Lib::getConnectionStateAsString($connection->transaction->getState());
120         $r[] = 'Open Transactions   : ' . $connection->transaction->getTransactionLevel();
121         $r[] = 'Table in memory     : ' . $connection->count();
122         $r[] = 'Driver name         : ' . $connection->getAttribute(Doctrine::ATTR_DRIVER_NAME);
123         $r[] = "</pre>";
124         
125         return implode("\n",$r)."<br>";
126     }
127
128     /**
129      * getTableAsString
130      *
131      * returns a string representation of Doctrine_Table object
132      *
133      * @param Doctrine_Table $table
134      * @return string
135      */
136     public static function getTableAsString(Doctrine_Table $table)
137     {
138         $r[] = "<pre>";
139         $r[] = "Component   : ".$table->getComponentName();
140         $r[] = "Table       : ".$table->getTableName();
141         $r[] = "</pre>";
142         
143         return implode("\n",$r)."<br>";
144     }
145
146     /**
147      * formatSql 
148      * 
149      * @todo: What about creating a config varialbe for the color?
150      * @param mixed $sql 
151      * @return string the formated sql
152      */
153     public static function formatSql($sql)
154     {
155         $e = explode("\n",$sql);
156         $color = "367FAC";
157         $l = $sql;
158         $l = str_replace("SELECT ", "<font color='$color'><b>SELECT </b></font><br \>  ",$l);
159         $l = str_replace("FROM ", "<font color='$color'><b>FROM </b></font><br \>",$l);
160         $l = str_replace(" LEFT JOIN ", "<br \><font color='$color'><b> LEFT JOIN </b></font>",$l);
161         $l = str_replace(" INNER JOIN ", "<br \><font color='$color'><b> INNER JOIN </b></font>",$l);
162         $l = str_replace(" WHERE ", "<br \><font color='$color'><b> WHERE </b></font>",$l);
163         $l = str_replace(" GROUP BY ", "<br \><font color='$color'><b> GROUP BY </b></font>",$l);
164         $l = str_replace(" HAVING ", "<br \><font color='$color'><b> HAVING </b></font>",$l);
165         $l = str_replace(" AS ", "<font color='$color'><b> AS </b></font><br \>  ",$l);
166         $l = str_replace(" ON ", "<font color='$color'><b> ON </b></font>",$l);
167         $l = str_replace(" ORDER BY ", "<font color='$color'><b> ORDER BY </b></font><br \>",$l);
168         $l = str_replace(" LIMIT ", "<font color='$color'><b> LIMIT </b></font><br \>",$l);
169         $l = str_replace(" OFFSET ", "<font color='$color'><b> OFFSET </b></font><br \>",$l);
170         $l = str_replace("  ", "<dd>",$l);
171
172         return $l;
173     }
174
175     /**
176      * getCollectionAsString
177      *
178      * returns a string representation of Doctrine_Collection object
179      *
180      * @param Doctrine_Collection $collection
181      * @return string
182      */
183     public static function getCollectionAsString(Doctrine_Collection $collection)
184     {
185         $r[] = "<pre>";
186         $r[] = get_class($collection);
187         $r[] = 'data : ' . Doctrine::dump($collection->getData(), false);
188         //$r[] = 'snapshot : ' . Doctrine::dump($collection->getSnapshot());
189         $r[] = "</pre>";
190         
191         return implode("\n",$r);
192     }
193
194     // Code from symfony sfToolkit class. See LICENSE
195     // code from php at moechofe dot com (array_merge comment on php.net)
196     /*
197      * arrayDeepMerge
198      *
199      * array arrayDeepMerge ( array array1 [, array array2 [, array ...]] )
200      *
201      * Like array_merge
202      *
203      *  arrayDeepMerge() merges the elements of one or more arrays together so
204      * that the values of one are appended to the end of the previous one. It
205      * returns the resulting array.
206      *  If the input arrays have the same string keys, then the later value for
207      * that key will overwrite the previous one. If, however, the arrays contain
208      * numeric keys, the later value will not overwrite the original value, but
209      * will be appended.
210      *  If only one array is given and the array is numerically indexed, the keys
211      * get reindexed in a continuous way.
212      *
213      * Different from array_merge
214      *  If string keys have arrays for values, these arrays will merge recursively.
215      */
216      public static function arrayDeepMerge()
217      {
218          switch (func_num_args()) {
219              case 0:
220                 return false;
221              case 1:
222                 return func_get_arg(0);
223              case 2:
224                 $args = func_get_args();
225                 $args[2] = array();
226                 
227                 if (is_array($args[0]) && is_array($args[1]))
228                 {
229                     foreach (array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key)
230                     {
231                         $isKey0 = array_key_exists($key, $args[0]);
232                         $isKey1 = array_key_exists($key, $args[1]);
233
234                         if ($isKey0 && $isKey1 && is_array($args[0][$key]) && is_array($args[1][$key]))
235                         {
236                             $args[2][$key] = self::arrayDeepMerge($args[0][$key], $args[1][$key]);
237                         } else if ($isKey0 && $isKey1) {
238                             $args[2][$key] = $args[1][$key];
239                         } else if ( ! $isKey1) {
240                             $args[2][$key] = $args[0][$key];
241                         } else if ( ! $isKey0) {
242                             $args[2][$key] = $args[1][$key];
243                         }
244                     }
245
246                     return $args[2];
247                 } else {
248                     return $args[1];
249                 }
250             default:
251                 $args = func_get_args();
252                 $args[1] = sfToolkit::arrayDeepMerge($args[0], $args[1]);
253                 array_shift($args);
254
255                 return call_user_func_array(array('Doctrine', 'arrayDeepMerge'), $args);
256             break;
257         }
258     }
259
260     // Code from symfony sfToolkit class. See LICENSE
261     /**
262      * stringToArray
263      *
264      * @param string $string 
265      * @return void
266      */
267     public static function stringToArray($string)
268     {
269         preg_match_all('/
270           \s*(\w+)              # key                               \\1
271           \s*=\s*               # =
272           (\'|")?               # values may be included in \' or " \\2
273           (.*?)                 # value                             \\3
274           (?(2) \\2)            # matching \' or " if needed        \\4
275           \s*(?:
276             (?=\w+\s*=) | \s*$  # followed by another key= or the end of the string
277           )
278         /x', $string, $matches, PREG_SET_ORDER);
279
280         $attributes = array();
281         foreach ($matches as $val) {
282             $attributes[$val[1]] = self::literalize($val[3]);
283         }
284
285         return $attributes;
286     }
287
288     /**
289      * Finds the type of the passed value, returns the value as the new type.
290      *
291      * @param  string
292      * @return mixed
293      */
294     public static function literalize($value, $quoted = false)
295     {
296         // lowercase our value for comparison
297         $value  = trim($value);
298         $lvalue = strtolower($value);
299
300         if (in_array($lvalue, array('null', '~', '')))
301         {
302             $value = null;
303         } else if (in_array($lvalue, array('true', 'on', '+', 'yes'))) {
304             $value = true;
305         } else if (in_array($lvalue, array('false', 'off', '-', 'no'))) {
306             $value = false;
307         } else if (ctype_digit($value)) {
308             $value = (int) $value;
309         } else if (is_numeric($value)) {
310             $value = (float) $value;
311         } else {
312             if ($quoted)
313             {
314                 $value = '\''.str_replace('\'', '\\\'', $value).'\'';
315             }
316         }
317
318         return $value;
319     }
320
321     /**
322      * getValidators
323      *
324      * Get available doctrine validators
325      *
326      * @return array $validators
327      */
328     public static function getValidators()
329     {
330         $validators = array();
331
332         $dir = Doctrine::getPath() . DIRECTORY_SEPARATOR . 'Doctrine' . DIRECTORY_SEPARATOR . 'Validator';
333
334         $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY);
335         foreach ($files as $file) {
336             $e = explode('.', $file->getFileName());
337
338             if (end($e) == 'php') {
339                 $name = strtolower($e[0]);
340
341                 $validators[$name] = $name;
342             }
343         }
344
345         return $validators;
346     }
347
348     /**
349      * makeDirectories
350      *
351      * Makes the directories for a path recursively
352      *
353      * @param string $path
354      * @return void
355      */
356     public static function makeDirectories($path, $mode = 0777)
357     {
358         if ( ! $path) {
359           return false;
360         }
361
362         if (is_dir($path) || is_file($path)) {
363           return true;
364         }
365
366         return mkdir($path, $mode, true);
367     }
368
369     /**
370      * removeDirectories
371      *
372      * @param string $folderPath
373      * @return void
374      */
375     public static function removeDirectories($folderPath)
376     {
377         if (is_dir($folderPath))
378         {
379             foreach (scandir($folderPath) as $value)
380             {
381                 if ($value != '.' && $value != '..')
382                 {
383                     $value = $folderPath . "/" . $value;
384
385                     if (is_dir($value)) {
386                         self::removeDirectories($value);
387                     } else if (is_file($value)) {
388                         @unlink($value);
389                     }
390                 }
391             }
392
393             return rmdir ( $folderPath );
394         } else {
395             return false;
396         }
397     }
398
399     public static function copyDirectory($source, $dest)
400     {
401         // Simple copy for a file
402         if (is_file($source)) {
403             return copy($source, $dest);
404         }
405
406         // Make destination directory
407         if ( ! is_dir($dest)) {
408             mkdir($dest);
409         }
410
411         // Loop through the folder
412         $dir = dir($source);
413         while (false !== $entry = $dir->read()) {
414             // Skip pointers
415             if ($entry == '.' || $entry == '..') {
416                 continue;
417             }
418
419             // Deep copy directories
420             if ($dest !== "$source/$entry") {
421                 self::copyDirectory("$source/$entry", "$dest/$entry");
422             }
423         }
424
425         // Clean up
426         $dir->close();
427
428         return true;
429     }
430
431     /**
432      * isValidClassName
433      *
434      * checks for valid class name (uses camel case and underscores)
435      *
436      * @param string $classname
437      * @return boolean
438      */
439     public static function isValidClassName($className)
440     {
441         if (preg_match('~(^[a-z])|(_[a-z])|([\W])|(_{2})~', $className)) {
442             return false;
443         }
444
445         return true;
446     }
447 }