プロジェクト

全般

プロフィール

XML_Util-1.2.3_to_1.3.0.diff

Shinichi Urabe, 2017-01-17 19:10

ダウンロード (21.9 KB)

差分を表示:

XML/Util.php
1 1
<?php
2

  
3
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4

  
5 2
/**
6 3
 * XML_Util
7 4
 *
......
48 45
 */
49 46

  
50 47
/**
51
 * error code for invalid chars in XML name
48
 * Error code for invalid chars in XML name
52 49
 */
53 50
define('XML_UTIL_ERROR_INVALID_CHARS', 51);
54 51

  
55 52
/**
56
 * error code for invalid chars in XML name
53
 * Error code for invalid chars in XML name
57 54
 */
58 55
define('XML_UTIL_ERROR_INVALID_START', 52);
59 56

  
60 57
/**
61
 * error code for non-scalar tag content
58
 * Error code for non-scalar tag content
62 59
 */
63 60
define('XML_UTIL_ERROR_NON_SCALAR_CONTENT', 60);
64 61

  
65 62
/**
66
 * error code for missing tag name
63
 * Error code for missing tag name
67 64
 */
68 65
define('XML_UTIL_ERROR_NO_TAG_NAME', 61);
69 66

  
70 67
/**
71
 * replace XML entities
68
 * Replace XML entities
72 69
 */
73 70
define('XML_UTIL_REPLACE_ENTITIES', 1);
74 71

  
75 72
/**
76
 * embedd content in a CData Section
73
 * Embedd content in a CData Section
77 74
 */
78 75
define('XML_UTIL_CDATA_SECTION', 5);
79 76

  
80 77
/**
81
 * do not replace entitites
78
 * Do not replace entitites
82 79
 */
83 80
define('XML_UTIL_ENTITIES_NONE', 0);
84 81

  
85 82
/**
86
 * replace all XML entitites
83
 * Replace all XML entitites
87 84
 * This setting will replace <, >, ", ' and &
88 85
 */
89 86
define('XML_UTIL_ENTITIES_XML', 1);
90 87

  
91 88
/**
92
 * replace only required XML entitites
89
 * Replace only required XML entitites
93 90
 * This setting will replace <, " and &
94 91
 */
95 92
define('XML_UTIL_ENTITIES_XML_REQUIRED', 2);
96 93

  
97 94
/**
98
 * replace HTML entitites
95
 * Replace HTML entitites
99 96
 * @link http://www.php.net/htmlentities
100 97
 */
101 98
define('XML_UTIL_ENTITIES_HTML', 3);
......
111 108
define('XML_UTIL_COLLAPSE_XHTML_ONLY', 2);
112 109

  
113 110
/**
114
 * utility class for working with XML documents
111
 * Utility class for working with XML documents
115 112
 *
116

  
117 113
 * @category  XML
118 114
 * @package   XML_Util
119 115
 * @author    Stephan Schmidt <schst@php.net>
120 116
 * @copyright 2003-2008 Stephan Schmidt <schst@php.net>
121 117
 * @license   http://opensource.org/licenses/bsd-license New BSD License
122
 * @version   Release: 1.2.3
118
 * @version   Release: 1.3.0
123 119
 * @link      http://pear.php.net/package/XML_Util
124 120
 */
125 121
class XML_Util
126 122
{
127 123
    /**
128
     * return API version
124
     * Return API version
129 125
     *
130 126
     * @return string $version API version
131
     * @access public
132
     * @static
133 127
     */
134
    function apiVersion()
128
    public static function apiVersion()
135 129
    {
136 130
        return '1.1';
137 131
    }
138 132

  
139 133
    /**
140
     * replace XML entities
134
     * Replace XML entities
141 135
     *
142 136
     * With the optional second parameter, you may select, which
143 137
     * entities should be replaced.
......
172 166
     *                                by the htmlentities() function
173 167
     *
174 168
     * @return string string with replaced chars
175
     * @access public
176
     * @static
177
     * @see reverseEntities()
169
     * @see    reverseEntities()
178 170
     */
179
    function replaceEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML,
180
        $encoding = 'ISO-8859-1')
181
    {
171
    public static function replaceEntities(
172
        $string, $replaceEntities = XML_UTIL_ENTITIES_XML, $encoding = 'ISO-8859-1'
173
    ) {
182 174
        switch ($replaceEntities) {
183 175
        case XML_UTIL_ENTITIES_XML:
184
            return strtr($string, array(
185
                '&'  => '&amp;',
186
                '>'  => '&gt;',
187
                '<'  => '&lt;',
188
                '"'  => '&quot;',
189
                '\'' => '&apos;' ));
176
            return strtr(
177
                $string,
178
                array(
179
                    '&'  => '&amp;',
180
                    '>'  => '&gt;',
181
                    '<'  => '&lt;',
182
                    '"'  => '&quot;',
183
                    '\'' => '&apos;'
184
                )
185
            );
190 186
            break;
191 187
        case XML_UTIL_ENTITIES_XML_REQUIRED:
192
            return strtr($string, array(
193
                '&' => '&amp;',
194
                '<' => '&lt;',
195
                '"' => '&quot;' ));
188
            return strtr(
189
                $string,
190
                array(
191
                    '&' => '&amp;',
192
                    '<' => '&lt;',
193
                    '"' => '&quot;'
194
                )
195
            );
196 196
            break;
197 197
        case XML_UTIL_ENTITIES_HTML:
198 198
            return htmlentities($string, ENT_COMPAT, $encoding);
......
202 202
    }
203 203

  
204 204
    /**
205
     * reverse XML entities
205
     * Reverse XML entities
206 206
     *
207 207
     * With the optional second parameter, you may select, which
208 208
     * entities should be reversed.
......
238 238
     *                                by the html_entity_decode() function
239 239
     *
240 240
     * @return string string with replaced chars
241
     * @access public
242
     * @static
243
     * @see replaceEntities()
241
     * @see    replaceEntities()
244 242
     */
245
    function reverseEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML,
246
        $encoding = 'ISO-8859-1')
247
    {
243
    public static function reverseEntities(
244
        $string, $replaceEntities = XML_UTIL_ENTITIES_XML, $encoding = 'ISO-8859-1'
245
    ) {
248 246
        switch ($replaceEntities) {
249 247
        case XML_UTIL_ENTITIES_XML:
250
            return strtr($string, array(
251
                '&amp;'  => '&',
252
                '&gt;'   => '>',
253
                '&lt;'   => '<',
254
                '&quot;' => '"',
255
                '&apos;' => '\'' ));
248
            return strtr(
249
                $string,
250
                array(
251
                    '&amp;'  => '&',
252
                    '&gt;'   => '>',
253
                    '&lt;'   => '<',
254
                    '&quot;' => '"',
255
                    '&apos;' => '\''
256
                )
257
            );
256 258
            break;
257 259
        case XML_UTIL_ENTITIES_XML_REQUIRED:
258
            return strtr($string, array(
259
                '&amp;'  => '&',
260
                '&lt;'   => '<',
261
                '&quot;' => '"' ));
260
            return strtr(
261
                $string,
262
                array(
263
                    '&amp;'  => '&',
264
                    '&lt;'   => '<',
265
                    '&quot;' => '"'
266
                )
267
            );
262 268
            break;
263 269
        case XML_UTIL_ENTITIES_HTML:
264 270
            return html_entity_decode($string, ENT_COMPAT, $encoding);
......
268 274
    }
269 275

  
270 276
    /**
271
     * build an xml declaration
277
     * Build an xml declaration
272 278
     *
273 279
     * <code>
274 280
     * require_once 'XML/Util.php';
......
282 288
     * @param bool   $standalone document is standalone (or not)
283 289
     *
284 290
     * @return string xml declaration
285
     * @access public
286
     * @static
287
     * @uses attributesToString() to serialize the attributes of the XML declaration
291
     * @uses   attributesToString() to serialize the attributes of the
292
     *         XML declaration
288 293
     */
289
    function getXMLDeclaration($version = '1.0', $encoding = null,
290
        $standalone = null)
291
    {
294
    public static function getXMLDeclaration(
295
        $version = '1.0', $encoding = null, $standalone = null
296
    ) {
292 297
        $attributes = array(
293 298
            'version' => $version,
294 299
        );
......
301 306
            $attributes['standalone'] = $standalone ? 'yes' : 'no';
302 307
        }
303 308

  
304
        return sprintf('<?xml%s?>',
305
            XML_Util::attributesToString($attributes, false));
309
        return sprintf(
310
            '<?xml%s?>',
311
            XML_Util::attributesToString($attributes, false)
312
        );
306 313
    }
307 314

  
308 315
    /**
309
     * build a document type declaration
316
     * Build a document type declaration
310 317
     *
311 318
     * <code>
312 319
     * require_once 'XML/Util.php';
......
321 328
     * @param string $internalDtd internal dtd entries
322 329
     *
323 330
     * @return string doctype declaration
324
     * @access public
325
     * @static
326
     * @since 0.2
331
     * @since  0.2
327 332
     */
328
    function getDocTypeDeclaration($root, $uri = null, $internalDtd = null)
329
    {
333
    public static function getDocTypeDeclaration(
334
        $root, $uri = null, $internalDtd = null
335
    ) {
330 336
        if (is_array($uri)) {
331 337
            $ref = sprintf(' PUBLIC "%s" "%s"', $uri['id'], $uri['uri']);
332 338
        } elseif (!empty($uri)) {
......
343 349
    }
344 350

  
345 351
    /**
346
     * create string representation of an attribute list
352
     * Create string representation of an attribute list
347 353
     *
348 354
     * <code>
349 355
     * require_once 'XML/Util.php';
......
375 381
     *                               XML_UTIL_ENTITIES_HTML)
376 382
     *
377 383
     * @return string string representation of the attributes
378
     * @access public
379
     * @static
380
     * @uses replaceEntities() to replace XML entities in attribute values
381
     * @todo allow sort also to be an options array
384
     * @uses   replaceEntities() to replace XML entities in attribute values
385
     * @todo   allow sort also to be an options array
382 386
     */
383
    function attributesToString($attributes, $sort = true, $multiline = false,
384
        $indent = '    ', $linebreak = "\n", $entities = XML_UTIL_ENTITIES_XML)
385
    {
387
    public static function attributesToString(
388
        $attributes, $sort = true, $multiline = false,
389
        $indent = '    ', $linebreak = "\n", $entities = XML_UTIL_ENTITIES_XML
390
    ) {
386 391
        /*
387 392
         * second parameter may be an array
388 393
         */
......
410 415
            if ($sort) {
411 416
                ksort($attributes);
412 417
            }
413
            if ( !$multiline || count($attributes) == 1) {
418
            if (!$multiline || count($attributes) == 1) {
414 419
                foreach ($attributes as $key => $value) {
415 420
                    if ($entities != XML_UTIL_ENTITIES_NONE) {
416 421
                        if ($entities === XML_UTIL_CDATA_SECTION) {
......
446 451
     *                      or only XHTML (XML_UTIL_COLLAPSE_XHTML_ONLY) ones.
447 452
     *
448 453
     * @return string XML
449
     * @access public
450
     * @static
451
     * @todo PEAR CS - unable to avoid "space after open parens" error
452
     *       in the IF branch
453 454
     */
454
    function collapseEmptyTags($xml, $mode = XML_UTIL_COLLAPSE_ALL)
455
    public static function collapseEmptyTags($xml, $mode = XML_UTIL_COLLAPSE_ALL)
455 456
    {
456 457
        if ($mode == XML_UTIL_COLLAPSE_XHTML_ONLY) {
457 458
            return preg_replace(
458 459
                '/<(area|base(?:font)?|br|col|frame|hr|img|input|isindex|link|meta|'
459 460
                . 'param)([^>]*)><\/\\1>/s',
460 461
                '<\\1\\2 />',
461
                $xml);
462
                $xml
463
            );
462 464
        } else {
463 465
            return preg_replace('/<(\w+)([^>]*)><\/\\1>/s', '<\\1\\2 />', $xml);
464 466
        }
465 467
    }
466 468

  
467 469
    /**
468
     * create a tag
470
     * Create a tag
469 471
     *
470 472
     * This method will call XML_Util::createTagFromArray(), which
471 473
     * is more flexible.
......
496 498
     * @param bool   $sortAttributes  Whether to sort the attributes or not
497 499
     *
498 500
     * @return string XML tag
499
     * @access public
500
     * @static
501
     * @see createTagFromArray()
502
     * @uses createTagFromArray() to create the tag
501
     * @see    createTagFromArray()
502
     * @uses   createTagFromArray() to create the tag
503 503
     */
504
    function createTag($qname, $attributes = array(), $content = null,
504
    public static function createTag(
505
        $qname, $attributes = array(), $content = null,
505 506
        $namespaceUri = null, $replaceEntities = XML_UTIL_REPLACE_ENTITIES,
506 507
        $multiline = false, $indent = '_auto', $linebreak = "\n",
507
        $sortAttributes = true)
508
    {
508
        $sortAttributes = true
509
    ) {
509 510
        $tag = array(
510 511
            'qname'      => $qname,
511 512
            'attributes' => $attributes
......
521 522
            $tag['namespaceUri'] = $namespaceUri;
522 523
        }
523 524

  
524
        return XML_Util::createTagFromArray($tag, $replaceEntities, $multiline,
525
            $indent, $linebreak, $sortAttributes);
525
        return XML_Util::createTagFromArray(
526
            $tag, $replaceEntities, $multiline,
527
            $indent, $linebreak, $sortAttributes
528
        );
526 529
    }
527 530

  
528 531
    /**
529
     * create a tag from an array
530
     * this method awaits an array in the following format
532
     * Create a tag from an array.
533
     * This method awaits an array in the following format
531 534
     * <pre>
532 535
     * array(
533 536
     *     // qualified name of the tag
......
576 579
     * @param bool   $sortAttributes  Whether to sort the attributes or not
577 580
     *
578 581
     * @return string XML tag
579
     * @access public
580
     * @static
581
     * @see createTag()
582
     *
583
     * @see  createTag()
582 584
     * @uses attributesToString() to serialize the attributes of the tag
583 585
     * @uses splitQualifiedName() to get local part and namespace of a qualified name
584 586
     * @uses createCDataSection()
585 587
     * @uses raiseError()
586 588
     */
587
    function createTagFromArray($tag, $replaceEntities = XML_UTIL_REPLACE_ENTITIES,
589
    public static function createTagFromArray(
590
        $tag, $replaceEntities = XML_UTIL_REPLACE_ENTITIES,
588 591
        $multiline = false, $indent = '_auto', $linebreak = "\n",
589
        $sortAttributes = true)
590
    {
592
        $sortAttributes = true
593
    ) {
591 594
        if (isset($tag['content']) && !is_scalar($tag['content'])) {
592
            return XML_Util::raiseError('Supplied non-scalar value as tag content',
593
            XML_UTIL_ERROR_NON_SCALAR_CONTENT);
595
            return XML_Util::raiseError(
596
                'Supplied non-scalar value as tag content',
597
                XML_UTIL_ERROR_NON_SCALAR_CONTENT
598
            );
594 599
        }
595 600

  
596 601
        if (!isset($tag['qname']) && !isset($tag['localPart'])) {
597
            return XML_Util::raiseError('You must either supply a qualified name '
602
            return XML_Util::raiseError(
603
                'You must either supply a qualified name '
598 604
                . '(qname) or local tag name (localPart).',
599
                XML_UTIL_ERROR_NO_TAG_NAME);
605
                XML_UTIL_ERROR_NO_TAG_NAME
606
            );
600 607
        }
601 608

  
602 609
        // if no attributes hav been set, use empty attributes
......
633 640
        if (isset($tag['namespaceUri']) && !empty($tag['namespaceUri'])) {
634 641
            // is a namespace given
635 642
            if (isset($tag['namespace']) && !empty($tag['namespace'])) {
636
                $tag['attributes']['xmlns:' . $tag['namespace']] =
637
                    $tag['namespaceUri'];
643
                $tag['attributes']['xmlns:' . $tag['namespace']]
644
                    = $tag['namespaceUri'];
638 645
            } else {
639 646
                // define this Uri as the default namespace
640 647
                $tag['attributes']['xmlns'] = $tag['namespaceUri'];
......
649 656
        }
650 657

  
651 658
        // create attribute list
652
        $attList = XML_Util::attributesToString($tag['attributes'],
653
            $sortAttributes, $multiline, $indent, $linebreak);
659
        $attList = XML_Util::attributesToString(
660
            $tag['attributes'],
661
            $sortAttributes, $multiline, $indent, $linebreak
662
        );
654 663
        if (!isset($tag['content']) || (string)$tag['content'] == '') {
655 664
            $tag = sprintf('<%s%s />', $tag['qname'], $attList);
656 665
        } else {
......
661 670
                $tag['content'] = XML_Util::createCDataSection($tag['content']);
662 671
                break;
663 672
            default:
664
                $tag['content'] = XML_Util::replaceEntities($tag['content'],
665
                    $replaceEntities);
673
                $tag['content'] = XML_Util::replaceEntities(
674
                    $tag['content'], $replaceEntities
675
                );
666 676
                break;
667 677
            }
668
            $tag = sprintf('<%s%s>%s</%s>', $tag['qname'], $attList, $tag['content'],
669
                $tag['qname']);
678
            $tag = sprintf(
679
                '<%s%s>%s</%s>', $tag['qname'], $attList, $tag['content'],
680
                $tag['qname']
681
            );
670 682
        }
671 683
        return $tag;
672 684
    }
673 685

  
674 686
    /**
675
     * create a start element
687
     * Create a start element
676 688
     *
677 689
     * <code>
678 690
     * require_once 'XML/Util.php';
......
693 705
     * @param bool   $sortAttributes Whether to sort the attributes or not
694 706
     *
695 707
     * @return string XML start element
696
     * @access public
697
     * @static
698
     * @see createEndElement(), createTag()
708
     * @see    createEndElement(), createTag()
699 709
     */
700
    function createStartElement($qname, $attributes = array(), $namespaceUri = null,
710
    public static function createStartElement(
711
        $qname, $attributes = array(), $namespaceUri = null,
701 712
        $multiline = false, $indent = '_auto', $linebreak = "\n",
702
        $sortAttributes = true)
703
    {
713
        $sortAttributes = true
714
    ) {
704 715
        // if no attributes hav been set, use empty attributes
705 716
        if (!isset($attributes) || !is_array($attributes)) {
706 717
            $attributes = array();
......
728 739
        }
729 740

  
730 741
        // create attribute list
731
        $attList = XML_Util::attributesToString($attributes, $sortAttributes,
732
            $multiline, $indent, $linebreak);
742
        $attList = XML_Util::attributesToString(
743
            $attributes, $sortAttributes,
744
            $multiline, $indent, $linebreak
745
        );
733 746
        $element = sprintf('<%s%s>', $qname, $attList);
734 747
        return  $element;
735 748
    }
736 749

  
737 750
    /**
738
     * create an end element
751
     * Create an end element
739 752
     *
740 753
     * <code>
741 754
     * require_once 'XML/Util.php';
......
747 760
     * @param string $qname qualified tagname (including namespace)
748 761
     *
749 762
     * @return string XML end element
750
     * @access public
751
     * @static
752
     * @see createStartElement(), createTag()
763
     * @see    createStartElement(), createTag()
753 764
     */
754
    function createEndElement($qname)
765
    public static function createEndElement($qname)
755 766
    {
756 767
        $element = sprintf('</%s>', $qname);
757 768
        return $element;
758 769
    }
759 770

  
760 771
    /**
761
     * create an XML comment
772
     * Create an XML comment
762 773
     *
763 774
     * <code>
764 775
     * require_once 'XML/Util.php';
......
770 781
     * @param string $content content of the comment
771 782
     *
772 783
     * @return string XML comment
773
     * @access public
774
     * @static
775 784
     */
776
    function createComment($content)
785
    public static function createComment($content)
777 786
    {
778 787
        $comment = sprintf('<!-- %s -->', $content);
779 788
        return $comment;
780 789
    }
781 790

  
782 791
    /**
783
     * create a CData section
792
     * Create a CData section
784 793
     *
785 794
     * <code>
786 795
     * require_once 'XML/Util.php';
......
792 801
     * @param string $data data of the CData section
793 802
     *
794 803
     * @return string CData section with content
795
     * @access public
796
     * @static
797 804
     */
798
    function createCDataSection($data)
805
    public static function createCDataSection($data)
799 806
    {
800
        return sprintf('<![CDATA[%s]]>',
801
            preg_replace('/\]\]>/', ']]]]><![CDATA[>', strval($data)));
802

  
807
        return sprintf(
808
            '<![CDATA[%s]]>',
809
            preg_replace('/\]\]>/', ']]]]><![CDATA[>', strval($data))
810
        );
803 811
    }
804 812

  
805 813
    /**
806
     * split qualified name and return namespace and local part
814
     * Split qualified name and return namespace and local part
807 815
     *
808 816
     * <code>
809 817
     * require_once 'XML/Util.php';
......
823 831
     * @param string $defaultNs default namespace (optional)
824 832
     *
825 833
     * @return array array containing namespace and local part
826
     * @access public
827
     * @static
828 834
     */
829
    function splitQualifiedName($qname, $defaultNs = null)
835
    public static function splitQualifiedName($qname, $defaultNs = null)
830 836
    {
831 837
        if (strstr($qname, ':')) {
832 838
            $tmp = explode(':', $qname);
......
842 848
    }
843 849

  
844 850
    /**
845
     * check, whether string is valid XML name
851
     * Check, whether string is valid XML name
846 852
     *
847 853
     * <p>XML names are used for tagname, attribute names and various
848 854
     * other, lesser known entities.</p>
......
863 869
     * @param string $string string that should be checked
864 870
     *
865 871
     * @return mixed true, if string is a valid XML name, PEAR error otherwise
866
     * @access public
867
     * @static
872
     *
868 873
     * @todo support for other charsets
869 874
     * @todo PEAR CS - unable to avoid 85-char limit on second preg_match
870 875
     */
871
    function isValidName($string)
876
    public static function isValidName($string)
872 877
    {
873 878
        // check for invalid chars
874 879
        if (!preg_match('/^[[:alpha:]_]\\z/', $string{0})) {
875
            return XML_Util::raiseError('XML names may only start with letter '
876
                . 'or underscore', XML_UTIL_ERROR_INVALID_START);
880
            return XML_Util::raiseError(
881
                'XML names may only start with letter or underscore',
882
                XML_UTIL_ERROR_INVALID_START
883
            );
877 884
        }
878 885

  
879 886
        // check for invalid chars
880
        if (!preg_match('/^([[:alpha:]_]([[:alnum:]\-\.]*)?:)?[[:alpha:]_]([[:alnum:]\_\-\.]+)?\\z/',
881
            $string)
882
        ) {
883
            return XML_Util::raiseError('XML names may only contain alphanumeric '
887
        $match = preg_match(
888
            '/^([[:alpha:]_]([[:alnum:]\-\.]*)?:)?'
889
            . '[[:alpha:]_]([[:alnum:]\_\-\.]+)?\\z/',
890
            $string
891
        );
892
        if (!$match) {
893
            return XML_Util::raiseError(
894
                'XML names may only contain alphanumeric '
884 895
                . 'chars, period, hyphen, colon and underscores',
885
                XML_UTIL_ERROR_INVALID_CHARS);
896
                XML_UTIL_ERROR_INVALID_CHARS
897
            );
886 898
        }
887 899
        // XML name is valid
888 900
        return true;
889 901
    }
890 902

  
891 903
    /**
892
     * replacement for XML_Util::raiseError
904
     * Replacement for XML_Util::raiseError
893 905
     *
894 906
     * Avoids the necessity to always require
895 907
     * PEAR.php
......
898 910
     * @param int    $code error code
899 911
     *
900 912
     * @return PEAR_Error
901
     * @access public
902
     * @static
903
     * @todo PEAR CS - should this use include_once instead?
913
     * @todo   PEAR CS - should this use include_once instead?
904 914
     */
905
    function raiseError($msg, $code)
915
    public static function raiseError($msg, $code)
906 916
    {
907
        require_once 'PEAR.php';
917
        include_once 'PEAR.php';
908 918
        return PEAR::raiseError($msg, $code);
909 919
    }
910 920
}