Container.php 25.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
<?php
// +---------------------------------------------------------------------+
// | PHP Version 4                                                       |
// +---------------------------------------------------------------------+
// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group            |
// +---------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,      |
// | that is bundled with this package in the file LICENSE, and is       |
// | available at through the world-wide-web at                          |
// | http://www.php.net/license/2_02.txt.                                |
// | If you did not receive a copy of the PHP license and are unable to  |
// | obtain it through the world-wide-web, please send a note to         |
// | license@php.net so we can mail you a copy immediately.              |
// +---------------------------------------------------------------------+
// | Author: Bertrand Mansion <bmansion@mamasam.com>                     |
// +---------------------------------------------------------------------+
//
// $Id$

require_once 'Config.php';

/**
* Interface for Config containers
*
* @author   Bertrand Mansion <bmansion@mamasam.com>
* @package  Config
*/
class Config_Container {

    /**
    * Container object type
    * Ex: section, directive, comment, blank
    * @var  string
    */
    var $type;

    /**
    * Container object name
    * @var  string
    */
    var $name = '';

    /**
    * Container object content
    * @var  string
    */
    var $content = '';

    /**
    * Container object children
    * @var  array
    */
    var $children = array();

    /**
    * Reference to container object's parent
    * @var  object
    */
    var $parent;
    
    /**
    * Array of attributes for this item
    * @var  array
    */
    var $attributes;

    /**
    * Unique id to differenciate nodes
    *
    * This is used to compare nodes
    * Will not be needed anymore when this class will use ZendEngine 2
    *
    * @var  int
    */
    var $_id;

    /**
    * Constructor
    *
    * @param  string  $type       Type of container object
    * @param  string  $name       Name of container object
    * @param  string  $content    Content of container object
    * @param  array   $attributes Array of attributes for container object
    */
    function Config_Container($type = 'section', $name = '', $content = '', $attributes = null)
    {
        $this->type       = $type;
        $this->name       = $name;
        $this->content    = $content;
        $this->attributes = $attributes;
        $this->parent     = null;
        $this->_id        = uniqid($name.$type, true);
    } // end constructor

    /**
    * Create a child for this item.
    * @param  string  $type       type of item: directive, section, comment, blank...
    * @param  mixed   $item       item name
    * @param  string  $content    item content
    * @param  array   $attributes item attributes
    * @param  string  $where      choose a position 'bottom', 'top', 'after', 'before'
    * @param  object  $target     needed if you choose 'before' or 'after' for where
    * @return object  reference to new item or Pear_Error
    */
    function &createItem($type, $name, $content, $attributes = null, $where = 'bottom', $target = null)
    {
        $item =& new Config_Container($type, $name, $content, $attributes);
        $result =& $this->addItem($item, $where, $target);
        return $result;
    } // end func &createItem
    
    /**
    * Adds an item to this item.
    * @param  object   $item      a container object
    * @param  string   $where     choose a position 'bottom', 'top', 'after', 'before'
    * @param  object   $target    needed if you choose 'before' or 'after' in $where
    * @return mixed    reference to added container on success, Pear_Error on error
    */
    function &addItem(&$item, $where = 'bottom', $target = null)
    {
        if ($this->type != 'section') {
            return PEAR::raiseError('Config_Container::addItem must be called on a section type object.', null, PEAR_ERROR_RETURN);
        }
        if (is_null($target)) {
            $target =& $this;
        }
        if (strtolower(get_class($target)) != 'config_container') {
            return PEAR::raiseError('Target must be a Config_Container object in Config_Container::addItem.', null, PEAR_ERROR_RETURN);
        }

        switch ($where) {
            case 'before':
                $index = $target->getItemIndex();
                break;
            case 'after':
                $index = $target->getItemIndex()+1;
                break;
            case 'top':
                $index = 0;
                break;
            case 'bottom':
                $index = -1;
                break;
            default:
                return PEAR::raiseError('Use only top, bottom, before or after in Config_Container::addItem.', null, PEAR_ERROR_RETURN);
        }
        if (isset($index) && $index >= 0) {
            array_splice($this->children, $index, 0, 'tmp');
        } else {
            $index = count($this->children);
        }
        $this->children[$index] =& $item;
        $this->children[$index]->parent =& $this;

        return $item;
    } // end func addItem

    /**
    * Adds a comment to this item.
    * This is a helper method that calls createItem
    *
    * @param  string    $content        Object content
    * @param  string    $where          Position : 'top', 'bottom', 'before', 'after'
    * @param  object    $target         Needed when $where is 'before' or 'after'
    * @return object  reference to new item or Pear_Error
    */
    function &createComment($content = '', $where = 'bottom', $target = null)
    {
        return $this->createItem('comment', null, $content, null, $where, $target);
    } // end func &createComment

    /**
    * Adds a blank line to this item.
    * This is a helper method that calls createItem
    *
    * @return object  reference to new item or Pear_Error
    */
    function &createBlank($where = 'bottom', $target = null)
    {
        return $this->createItem('blank', null, null, null, $where, $target);
    } // end func &createBlank

    /**
    * Adds a directive to this item.
    * This is a helper method that calls createItem
    *
    * @param  string    $name           Name of new directive
    * @param  string    $content        Content of new directive
    * @param  mixed     $attributes     Directive attributes
    * @param  string    $where          Position : 'top', 'bottom', 'before', 'after'
    * @param  object    $target         Needed when $where is 'before' or 'after'
    * @return object  reference to new item or Pear_Error
    */
    function &createDirective($name, $content, $attributes = null, $where = 'bottom', $target = null)
    {
        return $this->createItem('directive', $name, $content, $attributes, $where, $target);
    } // end func &createDirective

    /**
    * Adds a section to this item.
    *
    * This is a helper method that calls createItem
    * If the section already exists, it won't create a new one. 
    * It will return reference to existing item.
    *
    * @param  string    $name           Name of new section
    * @param  array     $attributes     Section attributes
    * @param  string    $where          Position : 'top', 'bottom', 'before', 'after'
    * @param  object    $target         Needed when $where is 'before' or 'after'
    * @return object  reference to new item or Pear_Error
    */
    function &createSection($name, $attributes = null, $where = 'bottom', $target = null)
    {
        return $this->createItem('section', $name, null, $attributes, $where, $target);
    } // end func &createSection

    /**
    * Tries to find the specified item(s) and returns the objects.
    *
    * Examples:
    * $directives =& $obj->getItem('directive');
    * $directive_bar_4 =& $obj->getItem('directive', 'bar', null, 4);
    * $section_foo =& $obj->getItem('section', 'foo');
    *
    * This method can only be called on an object of type 'section'.
    * Note that root is a section.
    * This method is not recursive and tries to keep the current structure.
    * For a deeper search, use searchPath()
    *
    * @param  string    $type        Type of item: directive, section, comment, blank...
    * @param  mixed     $name        Item name
    * @param  mixed     $content     Find item with this content
    * @param  array     $attributes  Find item with attribute set to the given value
    * @param  int       $index       Index of the item in the returned object list. If it is not set, will try to return the last item with this name.
    * @return mixed  reference to item found or false when not found
    * @see &searchPath()
    */
    function &getItem($type = null, $name = null, $content = null, $attributes = null, $index = -1)
    {
        if ($this->type != 'section') {
            return PEAR::raiseError('Config_Container::getItem must be called on a section type object.', null, PEAR_ERROR_RETURN);
        }
        if (!is_null($type)) {
            $testFields[] = 'type';
        }
        if (!is_null($name)) {
            $testFields[] = 'name';
        }
        if (!is_null($content)) {
            $testFields[] = 'content';
        }
        if (!is_null($attributes) && is_array($attributes)) {
            $testFields[] = 'attributes';
        }

        $itemsArr = array();
        $fieldsToMatch = count($testFields);
        for ($i = 0, $count = count($this->children); $i < $count; $i++) {
            $match = 0;
            reset($testFields);
            foreach ($testFields as $field) {
                if ($field != 'attributes') {
                    if ($this->children[$i]->$field == ${$field}) {
                        $match++;
                    }
                } else {
                    // Look for attributes in array
                    $attrToMatch = count($attributes);
                    $attrMatch = 0;
                    foreach ($attributes as $key => $value) {
                        if (isset($this->children[$i]->attributes[$key]) &&
                            $this->children[$i]->attributes[$key] == $value) {
                            $attrMatch++;
                        }
                    }
                    if ($attrMatch == $attrToMatch) {
                        $match++;
                    }
                }
            }
            if ($match == $fieldsToMatch) {
                $itemsArr[] =& $this->children[$i];
            }
        }
        if ($index >= 0) {
            if (isset($itemsArr[$index])) {
                return $itemsArr[$index];
            } else {
                return false;
            }
        } else {
            if ($count = count($itemsArr)) {
                return $itemsArr[$count-1];
            } else {
                return false;
            }
        }
    } // end func &getItem

    /**
    * Finds a node using XPATH like format.
    * 
    * The search format is an array:
    * array(item1, item2, item3, ...)
    *
    * Each item can be defined as the following:
    * item = 'string' : will match the container named 'string'
    * item = array('string', array('name' => 'xyz'))
    * will match the container name 'string' whose attribute name is equal to "xyz"
    * For example : <string name="xyz">
    * 
    * @param    mixed   Search path and attributes
    * 
    * @return   mixed   Config_Container object, array of Config_Container objects or false on failure.
    * @access   public
    */
    function &searchPath($args)
    {
        if ($this->type != 'section') {
            return PEAR::raiseError('Config_Container::searchPath must be called on a section type object.', null, PEAR_ERROR_RETURN);
        }

        $arg = array_shift($args);

        if (is_array($arg)) {
            $name = $arg[0];
            $attributes = $arg[1];
        } else {
            $name = $arg;
            $attributes = null;
        }
        // find all the matches for first..
        $match =& $this->getItem(null, $name, null, $attributes);

        if (!$match) {
            return false;
        }
        if (!empty($args)) {
            return $match->searchPath($args);
        }
        return $match;
    } // end func &searchPath

    /**
    * Return a child directive's content.
    * 
    * This method can use two different search approach, depending on
    * the parameter it is given. If the parameter is an array, it will use
    * the {@link Config_Container::searchPath()} method. If it is a string, 
    * it will use the {@link Config_Container::getItem()} method.
    *
    * Example:
    * <code>
    * require_once 'Config.php';
    * $ini = new Config();
    * $conf =& $ini->parseConfig('/path/to/config.ini', 'inicommented');
    *
    * // Will return the value found at :
    * // [Database]
    * // host=localhost
    * echo $conf->directiveContent(array('Database', 'host')));
    *
    * // Will return the value found at :
    * // date="dec-2004"
    * echo $conf->directiveContent('date');
    *
    * </code>
    *
    * @param    mixed   Search path and attributes or a directive name
    * @param    int     Index of the item in the returned directive list.
    *                   Eventually used if args is a string.
    * 
    * @return   mixed   Content of directive or false if not found.
    * @access   public
    */
    function directiveContent($args, $index = -1)
    {
        if (is_array($args)) {
            $item =& $this->searchPath($args);
        } else {
            $item =& $this->getItem('directive', $args, null, null, $index);
        }
        if ($item) {
            return $item->getContent();
        }
        return false;
    } // end func getDirectiveContent

    /**
    * Returns how many children this container has
    *
    * @param  string    $type    type of children counted
    * @param  string    $name    name of children counted
    * @return int  number of children found
    */
    function countChildren($type = null, $name = null)
    {
        if (is_null($type) && is_null($name)) {
            return count($this->children);
        }
        $count = 0;
        if (isset($name) && isset($type)) {
            for ($i = 0, $children = count($this->children); $i < $children; $i++) {
                if ($this->children[$i]->name == $name && 
                    $this->children[$i]->type == $type) {
                    $count++;
                }
            }
            return $count;
        }
        if (isset($type)) {
            for ($i = 0, $children = count($this->children); $i < $children; $i++) {
                if ($this->children[$i]->type == $type) {
                    $count++;
                }
            }
            return $count;
        }
        if (isset($name)) {
            // Some directives can have the same name
            for ($i = 0, $children = count($this->children); $i < $children; $i++) {
                if ($this->children[$i]->name == $name) {
                    $count++;
                }
            }
            return $count;
        }
    } // end func &countChildren

    /**
    * Deletes an item (section, directive, comment...) from the current object
    * TODO: recursive remove in sub-sections
    * @return mixed  true if object was removed, false if not, or PEAR_Error if root
    */
    function removeItem()
    {
        if ($this->isRoot()) {
            return PEAR::raiseError('Cannot remove root item in Config_Container::removeItem.', null, PEAR_ERROR_RETURN);
        }
        $index = $this->getItemIndex();
        if (!is_null($index)) {
            array_splice($this->parent->children, $index, 1);
            return true;
        }
        return false;
    } // end func removeItem

    /**
    * Returns the item index in its parent children array.
    * @return int  returns int or null if root object
    */
    function getItemIndex()
    {
        if (is_object($this->parent)) {
            // This will be optimized with Zend Engine 2
            $pchildren =& $this->parent->children;
            for ($i = 0, $count = count($pchildren); $i < $count; $i++) {
                if ($pchildren[$i]->_id == $this->_id) {
                    return $i;
                }
            }
        }
        return;
    } // end func getItemIndex

    /**
    * Returns the item rank in its parent children array
    * according to other items with same type and name.
    * @return int  returns int or null if root object
    */
    function getItemPosition()
    {
        if (is_object($this->parent)) {
            $pchildren =& $this->parent->children;
            for ($i = 0, $count = count($pchildren); $i < $count; $i++) {
                if ($pchildren[$i]->name == $this->name &&
                    $pchildren[$i]->type == $this->type) {
                    $obj[] =& $pchildren[$i];
                }
            }
            for ($i = 0, $count = count($obj); $i < $count; $i++) {
                if ($obj[$i]->_id == $this->_id) {
                    return $i;
                }
            }
        }
        return;
    } // end func getItemPosition

    /**
    * Returns the item parent object.
    * @return object  returns reference to parent object or null if root object
    */
    function &getParent()
    {
        return $this->parent;
    } // end func &getParent

    /**
    * Returns the item parent object.
    * @return mixed  returns reference to child object or false if child does not exist
    */
    function &getChild($index = 0)
    {
        if (!empty($this->children[$index])) {
            return $this->children[$index];
        } else {
            return false;
        }
    } // end func &getChild

    /**
    * Set this item's name.
    * @return void
    */
    function setName($name)
    {
        $this->name = $name;
    } // end func setName

    /**
    * Get this item's name.
    * @return string    item's name
    */
    function getName()
    {
        return $this->name;
    } // end func getName

    /**
    * Set this item's content.
    * @return void
    */
    function setContent($content)
    {
        $this->content = $content;
    } // end func setContent
    
    /**
    * Get this item's content.
    * @return string    item's content
    */
    function getContent()
    {
        return $this->content;
    } // end func getContent

    /**
    * Set this item's type.
    * @return void
    */
    function setType($type)
    {
        $this->type = $type;
    } // end func setType

    /**
    * Get this item's type.
    * @return string    item's type
    */
    function getType()
    {
        return $this->type;
    } // end func getType

    /**
    * Set this item's attributes.
    * @param  array    $attributes        Array of attributes
    * @return void
    */
    function setAttributes($attributes)
    {
        $this->attributes = $attributes;
    } // end func setAttributes

    /**
    * Set this item's attributes.
    * @param  array    $attributes        Array of attributes
    * @return void
    */
    function updateAttributes($attributes)
    {
        if (is_array($attributes)) {
            foreach ($attributes as $key => $value) {
                $this->attributes[$key] = $value;
            }
        }
    } // end func updateAttributes

    /**
    * Get this item's attributes.
    * @return array    item's attributes
    */
    function getAttributes()
    {
        return $this->attributes;
    } // end func getAttributes
    
    /**
    * Get one attribute value of this item
    * @param  string   $attribute        Attribute key
    * @return mixed    item's attribute value
    */
    function getAttribute($attribute)
    {
        if (isset($this->attributes[$attribute])) {
            return $this->attributes[$attribute];
        }
        return null;
    } // end func getAttribute

    /**
    * Set a children directive content.
    * This is an helper method calling getItem and addItem or setContent for you.
    * If the directive does not exist, it will be created at the bottom.
    *
    * @param  string    $name        Name of the directive to look for
    * @param  mixed     $content     New content
    * @param  int       $index       Index of the directive to set,
    *                                in case there are more than one directive
    *                                with the same name
    * @return object    newly set directive
    */
    function &setDirective($name, $content, $index = -1)
    {
        $item =& $this->getItem('directive', $name, null, null, $index);
        if ($item === false || PEAR::isError($item)) {
            // Directive does not exist, will create one
            unset($item);
            return $this->createDirective($name, $content, null);
        } else {
            // Change existing directive value
            $item->setContent($content);
            return $item;
        }
    } // end func setDirective

    /**
    * Is this item root, in a config container object
    * @return bool    true if item is root
    */
    function isRoot()
    {
        if (is_null($this->parent)) {
            return true;
        }
        return false;
    } // end func isRoot

    /**
    * Call the toString methods in the container plugin
    * @param    string  $configType  Type of configuration used to generate the string
    * @param    array   $options     Specify special options used by the parser
    * @return   mixed   true on success or PEAR_ERROR
    */
    function toString($configType, $options = array())
    {
        $configType = strtolower($configType);
        if (!isset($GLOBALS['CONFIG_TYPES'][$configType])) {
            return PEAR::raiseError("Configuration type '$configType' is not registered in Config_Container::toString.", null, PEAR_ERROR_RETURN);
        }
        $includeFile = $GLOBALS['CONFIG_TYPES'][$configType][0];
        $className   = $GLOBALS['CONFIG_TYPES'][$configType][1];
        include_once($includeFile);
        $renderer = new $className($options);
        return $renderer->toString($this);
    } // end func toString

    /**
    * Returns a key/value pair array of the container and its children.
    *
    * Format : section[directive][index] = value
    * If the container has attributes, it will use '@' and '#'
    * index is here because multiple directives can have the same name.
    *
    * @param    bool    $useAttr        Whether to return the attributes too
    * @return array
    */
    function toArray($useAttr = true)
    {
        $array[$this->name] = array();
        switch ($this->type) {
            case 'directive':
                if ($useAttr && count($this->attributes) > 0) {
                    $array[$this->name]['#'] = $this->content;
                    $array[$this->name]['@'] = $this->attributes;
                } else {
                    $array[$this->name] = $this->content;
                }
                break;
            case 'section':
                if ($useAttr && count($this->attributes) > 0) {
                    $array[$this->name]['@'] = $this->attributes;
                }
                if ($count = count($this->children)) {
                    for ($i = 0; $i < $count; $i++) {
                        $newArr = $this->children[$i]->toArray($useAttr);
                        if (!is_null($newArr)) {
                            foreach ($newArr as $key => $value) {
                                if (isset($array[$this->name][$key])) {
                                    // duplicate name/type
                                    if (!is_array($array[$this->name][$key]) ||
                                        !isset($array[$this->name][$key][0])) {
                                        $old = $array[$this->name][$key];
                                        unset($array[$this->name][$key]);
                                        $array[$this->name][$key][0] = $old;
                                    }
                                    $array[$this->name][$key][] = $value;
                                } else {
                                    $array[$this->name][$key] = $value;
                                }
                            }
                        }
                    }
                }
                break;
            default:
                return null;
        }
        return $array;
    } // end func toArray
    
    /**
    * Writes the configuration to a file
    * 
    * @param  mixed  $datasrc        Info on datasource such as path to the configuraton file or dsn...
    * @param  string $configType     Type of configuration
    * @param  array  $options        Options for writer
    * @access public
    * @return mixed     true on success or PEAR_ERROR
    */
    function writeDatasrc($datasrc, $configType, $options = array())
    {
        $configType = strtolower($configType);
        if (!isset($GLOBALS['CONFIG_TYPES'][$configType])) {
            return PEAR::raiseError("Configuration type '$configType' is not registered in Config_Container::writeDatasrc.", null, PEAR_ERROR_RETURN);
        }
        $includeFile = $GLOBALS['CONFIG_TYPES'][$configType][0];
        $className = $GLOBALS['CONFIG_TYPES'][$configType][1];
        include_once($includeFile);

        $writeMethodName = (version_compare(phpversion(), '5', '<')) ? 'writedatasrc' : 'writeDatasrc';
        if (in_array($writeMethodName, get_class_methods($className))) {
            $writer = new $className($options);
            return $writer->writeDatasrc($datasrc, $this);
        }

        // Default behaviour
        $fp = @fopen($datasrc, 'w');
        if ($fp) {
            $string = $this->toString($configType, $options);
            $len = strlen($string);
            @flock($fp, LOCK_EX);
            @fwrite($fp, $string, $len);
            @flock($fp, LOCK_UN);
            @fclose($fp);
            return true;
        } else {
            return PEAR::raiseError('Cannot open datasource for writing.', 1, PEAR_ERROR_RETURN);
        }
    } // end func writeDatasrc
} // end class Config_Container
?>