-
Notifications
You must be signed in to change notification settings - Fork 16
/
XBRL-Inline.php
2133 lines (1862 loc) · 72.3 KB
/
XBRL-Inline.php
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* XBRL Inline document loading and validation
*
* @author Bill Seddon
* @version 0.9
* @Copyright (C) 2021 Lyquidity Solutions Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace lyquidity\ixbrl;
use DOMDocument;
use lyquidity\ixt\IXBRL_Transforms;
use lyquidity\XPath2\DOM\DOMXPathNavigator;
use lyquidity\XPath2\TreeComparer;
use XBRL\Formulas\ContextComparer;
require __DIR__. '/IXBRL-Transforms.php';
require __DIR__. '/IXBRL-CreateInstance.php';
#region iXBRL Elements
define( "IXBRL_ELEMENT_CONTEXT", "context" );
define( "IXBRL_ELEMENT_CONTINUATION", "continuation" );
define( "IXBRL_ELEMENT_DENOMINATOR", "denominator" );
define( "IXBRL_ELEMENT_EXCLUDE", "exclude" );
define( "IXBRL_ELEMENT_FOOTNOTE", "footnote" );
define( "IXBRL_ELEMENT_FRACTION", "fraction" );
define( "IXBRL_ELEMENT_HEADER", 'header' );
define( "IXBRL_ELEMENT_HIDDEN", "hidden" );
define( "IXBRL_ELEMENT_NONFRACTION", "nonFraction" );
define( "IXBRL_ELEMENT_NONNUMERIC", "nonNumeric" );
define( "IXBRL_ELEMENT_NUMERATOR", "numerator" );
define( "IXBRL_ELEMENT_REFERENCES", "references" );
define( "IXBRL_ELEMENT_RELATIONSHIP", "relationship" );
define( "IXBRL_ELEMENT_RESOURCES", "resources" );
define( "IXBRL_ELEMENT_TUPLE", "tuple" );
define( "IXBRL_ELEMENT_HTML", "html" );
define( "IXBRL_ELEMENT_XHTML", "xhtml" );
#endregion
#region iXBRL Attributes
define( "IXBRL_ATTR_ARCROLE", "arcrole" );
define( "IXBRL_ATTR_BASE", "base" );
define( "IXBRL_ATTR_CONTEXTREF", "contextRef" );
define( "IXBRL_ATTR_CONTINUATIONFROM", "continuationFrom" );
define( "IXBRL_ATTR_CONTINUEDAT", "continuedAt" );
define( "IXBRL_ATTR_DECIMALS", "decimals" );
define( "IXBRL_ATTR_ESCAPE", "escape" );
define( "IXBRL_ATTR_FOOTNOTEROLE", "footnoteRole" );
define( "IXBRL_ATTR_FORMAT", "format" );
define( "IXBRL_ATTR_FROMREFS", "fromRefs" );
define( "IXBRL_ATTR_ID", "id" );
define( "IXBRL_ATTR_LINKROLE", "linkRole" );
define( "IXBRL_ATTR_NAME", "name" );
define( "IXBRL_ATTR_NIL", "xsi:nil" );
define( "IXBRL_ATTR_PRECISION", "precision" );
define( "IXBRL_ATTR_ORDER", "order" );
define( "IXBRL_ATTR_SCALE", "scale" );
define( "IXBRL_ATTR_SIGN", "sign" );
define( "IXBRL_ATTR_TARGET", "target" );
define( "IXBRL_ATTR_TITLE", "title" );
define( "IXBRL_ATTR_TOREFS", "toRefs" );
define( "IXBRL_ATTR_TUPLEID", "tupleID" );
define( "IXBRL_ATTR_TUPLEREF", "tupleRef" );
define( "IXBRL_ATTR_UNITREF", "unitRef" );
define( "IXBRL_ATTR_LANG", "lang" );
#endregion
/**
* A class to validate and load an inline XBRL document
*
*/
class XBRL_Inline
{
/**
* @var \XBRL_Global
*/
private static $context = null;
/**
* A holder for the documents being created
* @var array
*/
private static $outputs = null;
/**
* The set of source documents
* @var XBRL_Inline[]
*/
public static $documents = [];
/**
* @var \DOMDocument
*/
public $document = null;
/**
* Url to the source iXBRL document
*
* @var [type]
*/
public $url = null;
/**
* The document root element
*
* @var \DOMElement
*/
private $root = null;
/**
* An xpath instance for the document
*
* @var \DOMXPath
*/
public $xpath = null;
/**
* True if the document is IXBRL
*
* @var boolean
*/
public $isIXBRL = false;
/**
* The prefix of the namespace being used
*
* @var string
*/
public $ixPrefix = 'ix11';
/**
* Any document can be IXBRL. This flag is true if the document is HTML or
*
* @var boolean
*/
public $isXHTML = false;
/**
* Capture the format status
* @var boolean
*/
private static $formatOutput = true;
/**
* The base url to be used. Will be empty unless there is @base in <head>
* @var string
*/
private $base = '';
/**
* Inline XBRL class constructor instantiating DOMDocument
* @throws \Exception When the document is not an IXBRL document
*/
public function __construct( $docUrl )
{
if ( ! $docUrl ) return;
$this->document = new \DOMDocument();
// A bug in libxml2 used in PHP means that whitespace collapse is only respected
// on an attribute if the whitespace comes after the attribute value. So need to
// explicitly remove whitespace from instances of @format.
$xml = file_get_contents( $docUrl );
$xml = preg_replace( '/(\s+format\s*=\s*["\'])\s*(\S+)\s*(["\'])/', "$1$2$3", $xml );
$xml = preg_replace( '/(measure>)\s*(\S+)\s*(<\/)/', "$1$2$3", $xml );
// if ( ! $this->document->load( $docUrl ) )
if ( ! $this->document->loadXML( $xml ) )
{
throw new IXBRLException('Failed to load the document');
}
// The baseURI has been lost so add this variable to hold the docUrl
$this->document->docUrl = $docUrl;
$this->url = $docUrl;
$this->root = $this->document->documentElement;
$ns = $this->root->namespaceURI;
$ln = $this->root->localName;
$this->xpath = $xpath = new \DOMXPath( $this->document );
$xpath->registerNamespace( 'ix10', \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_IXBRL10] );
$xpath->registerNamespace( 'ix11', \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_IXBRL11] );
$xpath->registerNamespace( STANDARD_PREFIX_XBRLI, \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XBRLI] );
$xpath->registerNamespace( STANDARD_PREFIX_SCHEMA_XHTML, \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_SCHEMA_XHTML] );
if ( count( $xpath->query( '//ix11:*', $this->root ) ) && count( $xpath->query( '//ix10:*', $this->root ) ) )
{
throw new IXBRLDocumentValidationException('ix:multipleIxNamespaces', 'The document uses more than one iXBRL namespace');
}
$iXBRLNamespaces = array_intersect( \XBRL_Constants::$ixbrlNamespaces, $this->getElementNamespaces() );
$this->ixPrefix = array_flip( \XBRL_Constants::$ixbrlNamespaces )[ reset( $iXBRLNamespaces ) ];
// These are two test functions
// $x = $this->getTRR('ixt');
// $result = $this->format( 'ixt:numdash', '-' );
// Any document can be IXBRL
$this->isIXBRL = count( $iXBRLNamespaces ) > 0;
if ( ! $this->isIXBRL )
throw new IXBRLException('This is not an Inline XBRL document');
$this->isXHTML = $ns == \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_SCHEMA_XHTML ] && ( $ln == IXBRL_ELEMENT_HTML || $ln == IXBRL_ELEMENT_XHTML );
$base = $xpath->query('//xhtml:html/xhtml:head/xhtml:base[@href]');
if ( $base->length )
{
$this->base = $base[0]->getAttribute('href');
}
}
private $elementNamespaces = array();
/**
* Returns an array of namespaces in the document if it is valid
*
* @param [DOMElement] $element If provided the query operates on this element otherwise the root.
* @return string[]
*/
public function getElementNamespaces( $element = null)
{
$path = $element ? $element->getNodePath() : '';
if ( ! isset( $this->elementNamespaces[ $path ] ) )
$this->elementNamespaces[ $path ] = $this->getNodeValues('namespace::*', $element );
return $this->elementNamespaces[ $path ];
}
/**
* Returns an array of all namespaces in the document, including those of nested elements, if the document is valid
*
* @param [DOMElement] $element If provided the query operates on this element otherwise the root.
* @return string[]
*/
public function getAllNamespaces( $element = null )
{
$path = $element ? $element->getNodePath() : '';
if ( ! isset( $this->elementNamespaces[ $path ] ) )
$this->elementNamespaces[ $path ] = $this->getNodeValues('//namespace::*', $element );
return $this->elementNamespaces[ $path ];
}
/**
* Get the base URI in scope for an element by working up the node hierarchy until an absolute uri is found or one is not found
* @param \DOMElement $node
* @return string
*/
public function getBaseURI( $node )
{
$baseURI = '';
while( $node && $node->nodeType == XML_ELEMENT_NODE )
{
if( $node->hasAttributeNS( \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XML ], IXBRL_ATTR_BASE ) )
{
$base = $node->getAttributeNodeNS( \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XML ], IXBRL_ATTR_BASE )->value;
$baseURI = \XBRL::resolve_path( $base, $baseURI );
}
$node = $node->parentNode;
}
if ( $this->base )
{
\XBRL::resolve_path( $baseURI, $this->base );
}
// $node is now the ownerDocument
else if ( substr( ( $node->nodeType == XML_DOCUMENT_NODE ? $node : $node->ownerDocument )->docUrl, -1 ) =='/' )
{
$baseURI = \XBRL::resolve_path( $baseURI, $node->ownerDocument->docUrl );
}
return $baseURI;
}
/**
* Core function to return the node values of a query as an array
*
* @param string $query The xpath query to execute
* @param [DOMElement] $element If provided the query operates on this element otherwise the root.
* @return string[]
*/
private function getNodeValues( $query, $element = null )
{
$result = array();
if ( $this->root )
{
$xpath = new \DOMXPath( $this->document );
foreach( $xpath->query( $query, $element ? $element : $this->root ) as $node )
{
$result[] = $node->nodeValue;
}
$result = array_unique( $result );
}
return $result;
}
/**
* Returns a list of all the targets defined in the document
* The list is indexed by target name and the elements are nodes that declare that target
* @param \DOMElement[][] $targets
* @return \DOMElement[][]
*/
private function getTargets( $targets = array() )
{
/** @var \DOMElement[][] */
$targets[null] = $targets[null] ?? array();
// Get all ix nodes that DO NOT have a 'target' attribute (these are for the default document)
$nodes = $this->xpath->query( sprintf("//{$this->ixPrefix}:*[not(@%s)]", IXBRL_ATTR_TARGET ), $this->root );
/** @var \DOMElement[][] */
$targets[null] = array_merge( $targets[null], iterator_to_array( $nodes ) );
// Get all ix nodes that have a 'target' attribute
$nodes = $this->xpath->query( sprintf("//{$this->ixPrefix}:*[@%s]", IXBRL_ATTR_TARGET ), $this->root );
/** @var \DOMElement[][] */
$targets = array_reduce( iterator_to_array( $nodes ), function( $carry, $node )
{
/** @var \DOMElement $node */
$target = $node->getAttribute( IXBRL_ATTR_TARGET );
$carry[ $target ][] = $node;
return $carry;
}, $targets );
/** @var \DOMElement[][] $targets */
return $targets;
}
/**
* Returns a list of all the targets defined in the document
* The list is indexed by target name and the elements are nodes that declare that target
* @param \DOMElement[]? $idNodes
* @return \DOMElement[]
*/
private function getIDs( $idNodes = array() )
{
// Get all ix nodes that have an IXBRL_ATTR_ID attribute
$nodes = iterator_to_array( $this->xpath->query( sprintf("//{$this->ixPrefix}:*[@%s]", IXBRL_ATTR_ID ), $this->root ) );
$idNodes = array_merge( $idNodes, $nodes );
// Get all xbrli nodes that have a IXBRL_ATTR_ID attribute
$nodes = iterator_to_array( $this->xpath->query( sprintf("//xbrli:*[@%s]", IXBRL_ATTR_ID ), $this->root ) );
$idNodes = array_merge( $idNodes, $nodes );
return $idNodes;
}
/**
* Get the TRR for a prefix
* @param string $namespace
* @return IXBRL_Transforms
*/
private function getTRR( $namespace )
{
if ( ! $namespace )
throw new IXBRLInvalidNamespaceException("A namespace has not been provided");
if ( array_search( $namespace, \XBRL_Constants::$ixtNamespaces ) === false )
throw new IXBRLInvalidNamespaceException("'$namespace' is not a TRR namespace");
/**
* @var IXBRL_Transforms
*/
$transformInstance = IXBRL_Transforms::getInstance();
$transformInstance->setTransformVersion( $namespace );
return $transformInstance;
}
/**
* Format a value using the requested format
* @param string $formatQname The qname of the format to use
* @param string $value Thev alue to be formatted
* @param \DOMElement $node
* @param boolean [$validate] (default: false)
* @return string
*/
private function format( $formatQname, $value, $node, $validate = false )
{
list( $prefix, $localName ) = explode( ':', $formatQname );
try
{
$namespace = $node->lookupNamespaceURI( $prefix );
$instance = $this->getTRR( $namespace, $node );
$result = $instance->transform( $localName, $value );
return $result;
}
catch( \Exception $ex )
{
if ( $validate ) throw $ex;
}
return $value;
}
/**
* Validate the current document if there is one
* @throws \Exception If there is no valid document
* @throws IXBRLSchemaValidationException If there are schema violations in the structure of the document
*/
public function validateDocument()
{
if ( ! $this->document )
{
throw new IXBRLException('There is no valid iXBRL document');
}
// Can only validate xhtml against the schema
if ( ! $this->isXHTML ) return;
$validator = new ValidateInlineDocument();
$validator->validateDOMDocument( $this->document, $this->ixPrefix );
// Getting here means the document validates against the iXBRL schema
}
/**
* Create an instance document from in input iXBRL document set
* @param string $name
* @param string[] $documentSet
* @param string $cacheLocation
* @param boolean? $validate
* @param callable? $fn This is a dummy parameter to get around the intelliphense type checking which insists that the arg to libxml_set_external_entity_loader cannot be null.
* @return \DOMDocument[] An array of the generated documents
*/
public static function createInstanceDocument( $name, $documentSet, $cacheLocation, $validate = true )
{
if ( ! self::$context )
{
// Only do this once
// $cacheLocation = \lyquidity\xbrl_validate\get_taxonomy_cache_location();
\XBRL_Global::reset();
self::$context = $context = \XBRL_Global::getInstance();
$context->useCache = true;
$context->cacheLocation = $cacheLocation;
$context->initializeCache();
}
/**
* @var \DOMElement[][]
*/
$targets = array();
$idNodes = array();
self::$outputs = array();
self::$tupleIDs = null;
try
{
foreach( $documentSet as $documentUrl )
{
// Use the entity loader to make sure libxml uses files from the local.
// This is an order of magnitude faster.
$context->setEntityLoader( dirname( $documentUrl ) );
$document = new XBRL_Inline( $documentUrl );
self::$documents[ $documentUrl ] = $document;
if ( $document->document->documentElement->localName != IXBRL_ELEMENT_HTML || $document->document->documentElement->namespaceURI != \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_SCHEMA_XHTML ])
{
throw new IXBRLDocumentValidationException( 'UnsupportedDocumentType', "The url does not reference a valid iXBRL document: $documentUrl" );
}
$document->validateDocument(); // Schema validation
// Special case: test case FAIL-empty-class-attribute.html does not fail as expected
if ( ( $document->xpath->query('//*[@class=""]') )->length )
{
throw new IXBRLDocumentValidationException( 'xbrl.core.xml.SchemaValidationError.cvc-minLength-valid', 'Failed using schemaValidate' );
}
/** @var \DOMElement[][] */
$targets = $document->getTargets( $targets );
$idNodes = $document->getIDs( $idNodes );
$context->resetEntityLoader();
}
unset( $document );
unset( $documentUrl );
// There will be an output document for every target found
$outputNodes = array_filter(
$targets,
function( $nodes )
{
return array_filter(
$nodes,
function( $node ) { /** @var \DOMElement $node */ return array_search( $node->localName, array( IXBRL_ELEMENT_HEADER, IXBRL_ELEMENT_RESOURCES ) ) === false; }
);
}
);
self::$outputs = array_fill_keys( array_keys( $outputNodes ), array() );
// Create list of the idNodes indexed by the id string. The element value is the index into
$ids = \XBRL::array_reduce_key( $idNodes, function( $carry, $node, $index )
{
/** @var \DOMElement $node */
$id = $node->getAttribute(IXBRL_ATTR_ID);
$carry[ $id ][] = $index;
return $carry;
}, [] );
$duplicateIds = array_filter( $ids, function( $indexes ) { return count( $indexes ) > 1; } );
if ( $duplicateIds )
{
// Create a string of node qnames to report the error
$error = [];
foreach( $duplicateIds as $id => $indexes )
{
/** @var int[] $indexes */
$error[] = "$id (" . join(', ', array_map( function( $index ) use( &$idNodes )
{
return $idNodes[ $index ]->tagName;
}, $indexes ) ) . ")";
}
throw new IXBRLDocumentValidationException('DuplicateId', join( ' and ', $error ) );
}
// Now there will be a one-to-one correspondence between an id and index so recreate idNodes
$idNodes = \XBRL::array_reduce_key( $ids, function( $carry, $indexes, $id ) use ( &$idNodes )
{
$carry[ $id ] = $node = $idNodes[ $indexes[0] ];
return $carry;
}, array() );
unset( $ids );
unset( $duplicateIds );
// Re-index ix elements to index by localname
/** @var \DOMElement[][] */
$nodesByLocalNames = array_reduce( $targets, function( $carry, $nodes )
{
/** @var \DOMElement[] $nodes */
foreach( $nodes as $node )
{
if ( $node->namespaceURI == \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XBRLI ] ) continue;
$carry[ $node->localName ][] = $node;
}
return $carry;
}, array() );
if ( ! isset( $nodesByLocalNames[ IXBRL_ELEMENT_HEADER ] ) )
{
throw new IXBRLDocumentValidationException( 'HeaderAbsent', 'Section 8.1.1 A <header> element cannot be found' );
}
if ( ! isset( $nodesByLocalNames[ IXBRL_ELEMENT_REFERENCES ] ) )
{
throw new IXBRLDocumentValidationException( 'ReferencesAbsent', 'Section 12.1.1 A <references> element cannot be found' );
}
if ( ! isset( $nodesByLocalNames[ IXBRL_ELEMENT_RESOURCES ] ) )
{
throw new IXBRLDocumentValidationException( 'ResourcesAbsent', 'Section 14.1.1 A <resources> element cannot be found' );
}
// Get and validate the ix:header and other elements
if ( $validate )
{
foreach( $nodesByLocalNames as $localName => $nodes )
{
foreach( $nodes as $node )
{
/** @var \DOMElement $node */
self::validateConstraints( $node, $localName, $nodesByLocalNames, $idNodes );
}
}
self::checkTupleOrders( $node, "15.1.1", $nodesByLocalNames );
}
// Check cross-element continuation validation rules
self::checkCrossElementContinuations( $nodesByLocalNames );
// Check cross-references validation rules (12.1.2)
self::checkCrossReferencesRules( $nodesByLocalNames, $targets );
$documents = IXBRL_CreateInstance::createInstanceDocuments( array_keys( self::$outputs ), $name, $nodesByLocalNames, $idNodes, $targets );
return $documents;
}
catch( \Exception $ex )
{
throw $ex;
}
finally
{
$context->resetEntityLoader();
$context->reset();
self::$context = null;
self::$documents = [];
}
}
/**
* Get the inner HTML for a node
* @param \DOMNode $node
* @param bool $hasElements Will be true if any of the content are elements such as <i> <b> etc.
* @param bool $first Will be true to signal the node should be processed as a top level node
* @return void
*/
private static function innerHTML( $node, &$hasElements, $first = true)
{
if ( ! ( $node instanceof \DOMNode ) ) return '';
$document = self::$documents[ $node->ownerDocument->docUrl ];
$updateChildren = function( \DOMNodeList $nodes, bool &$hasElements, bool $first = true ) use( &$updateChildren, $document )
{
$result = '';
foreach( $nodes as $child )
{
/** @var \DOMNode $child */
if ( $child instanceof \DOMElement )
{
if ( array_search( $child->namespaceURI, \XBRL_Constants::$ixbrlNamespaces ) )
{
$result .= $updateChildren( $child->childNodes, $hasElements, $first );
continue;
}
$result .= "<{$child->tagName}";
if ( $document->base )
{
$base = \XBRL::endswith( $document->base, '/' ) || pathinfo( $document->base, PATHINFO_EXTENSION ) ? $document->base : $document->base . '/../';
foreach( array( 'href', 'src', 'archive', 'classid', 'data', 'codebase' ) as $name )
{
if ( ! $value = $child->getAttribute( $name ) ) continue;
switch( $name )
{
case 'href':
case 'src':
$urls = array( $value );
break;
case 'data':
if ( $child->hasAttribute('codebase') ) continue 2;
// break;
default:
$urls = explode( ' ', $value );
break;
}
$url = join( ' ', array_map( function( $url ) use( $base )
{
@list( $url, $fragment ) = explode( '#', $url );
return ( $url ? ( /* absolute? */preg_match( "!^https?://!", $url ) ? $url : \XBRL::resolve_path( $base, $url ) ) : $base ) . ( $fragment ? "#$fragment" : '' );
}, $urls ) );
$child->setAttribute( $name, $url );
}
}
// Add xmlns:xhtml to any new child nodes that are not an xbrli node
if ( array_search( $child->namespaceURI, \XBRL_Constants::$ixbrlNamespaces ) === false && ! $child->hasAttributeNS( 'http://www.w3.org/2000/xmlns/', "xmlns" ) )
{
$hasElements = true;
if ( $first )
$result .= " xmlns=\"" . \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_SCHEMA_XHTML] . "\"";
}
foreach( $child->attributes as $attr )
{
/** @var \DOMAttr $attr */
$result .= " " . $attr->nodeName . '="' . $attr->nodeValue . '"';
}
if ( $child->nodeValue || $child->hasChildNodes() )
{
$result .= ">";
if ( $child->hasChildNodes() )
{
$result .= $updateChildren( $child->childNodes, $hasElements, false );
}
$result .= "</{$child->tagName}>";
}
else
{
$result .= "/>";
}
}
else
{
$result .= htmlentities( $child->nodeValue, ENT_NOQUOTES );
// $result .= preg_replace( '/\s+/', ' ', htmlentities( $child->nodeValue, ENT_NOQUOTES ) );
}
}
return $result;
};
$result = $node->hasChildNodes()
? $updateChildren( $node->childNodes, $hasElements, $first )
: $node->textContent;
return $result;
}
/**
* Outputs the XML for the generated document
* @param \DOMNode $node
* @param mixed $options
* @param \DOMDocument $document
* @return string
*/
public static function saveXML( $document, $formatOutput, $options = null )
{
$document->formatOutput = $formatOutput;
if ( ! $formatOutput ) return $document->saveXML( null, $options );
// Expand all xmlns declarations so they appear on separate lines
$xml = $document->saveXML( null, $options );
// $xml = str_replace( array('xmlns', 'xsi:schemaLocation'), array("\n\txmlns", "\n\txsi:schemaLocation"), $xml );
// Expand the schema location entries so that appear on separate lines
$xml = preg_replace_callback( '/(xsi:schemaLocation=")(.*)(")/', function( $matches )
{
return $matches[1] . "\n\t\t" . str_replace( '.xsd', ".xsd\n\t\t", $matches[2] ) . $matches[3];
}, $xml );
// Find elements with attributes and put the second and subsequent attributes on separate lines
// $xml = preg_replace_callback( '|\s*<[a-z]+:.*? .*?" .*|', function( $matches )
// {
// return str_replace('" ', "\"\n\t\t", $matches[0] );
// }, $xml );
return $xml;
}
/**
* Check cross-element continuation validation rules
* @param [type] $nodesByLocalNames
* @return void
*/
private static function checkCrossElementContinuations( &$nodesByLocalNames )
{
// Make sure continuedAt attributes don't reference the same id
$correspondents = array( IXBRL_ELEMENT_FOOTNOTE, IXBRL_ELEMENT_NONNUMERIC, IXBRL_ELEMENT_CONTINUATION );
$atIds = array();
// Get the nodes for continuation, footnote and nonNumeric elements
foreach( $correspondents as $localName )
{
foreach( $nodesByLocalNames[ $localName ] ?? array() as $node )
{
if ( ! $node->hasAttribute( IXBRL_ATTR_CONTINUEDAT ) ) continue;
$continuedAt = $node->getAttribute( IXBRL_ATTR_CONTINUEDAT );
if ( array_search( $continuedAt, $atIds ) !== false )
{
throw new IXBRLDocumentValidationException( 'ContinuationReuse', 'Section 4.1.1 A \'continuationAt\' attribute with value \'$continuedAt\' has been used more than once' );
}
$parentNode = self::checkParentNodes( $node, function( $parentNode ) { return $parentNode->localName== IXBRL_ELEMENT_CONTINUATION; } );
if ( $parentNode && $parentNode->getAttribute( IXBRL_ATTR_ID ) == $continuedAt )
{
throw new IXBRLDocumentValidationException( 'ContinuationInvalidNesting', 'Section 4.1.1 A \'continuationAt\' attribute with value \'$continuedAt\' has @id in it parenmt' );
}
$atIds[] = $continuedAt;
}
}
}
/**
* Check cross-references validation rules (12.1.2)
* @param \DOMElement[][] $nodesByLocalNames
* @param \DOMElement[][] $targets
* @return void
*/
private static function checkCrossReferencesRules( &$nodesByLocalNames, &$targets )
{
if ( ( ! $nodesByLocalNames[ IXBRL_ELEMENT_REFERENCES ] ?? false ) ) return;
// Each attribute value should be unique across all <references> for attribute not in the IX namespace
$attributes = array();
$ixNamespaces = array( \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_IXBRL10], \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_IXBRL11] );
foreach( $nodesByLocalNames[ IXBRL_ELEMENT_REFERENCES ] ?? array() as $node )
{
$target = $node->hasAttribute( IXBRL_ATTR_TARGET )
? $node->getAttribute( IXBRL_ATTR_TARGET )
: '';
foreach( $node->attributes as $name => $attr )
{
if ( $name == IXBRL_ATTR_TARGET ) continue;
if ( $name == IXBRL_ATTR_BASE ) continue;
/** @var \DOMAttr $attr */
if ( array_search( $attr->namespaceURI, $ixNamespaces ) !== false ) continue;
if ( isset( $attributes[ $target ][ $name ] ) && $attr->nodeValue )
{
throw new IXBRLDocumentValidationException( $name == 'id' ? 'RepeatedIdAttribute' : 'RepeatedOtherAttributes', "Section 12.1.2 A <references> attribute/value pair has been used more than once ($name/{$attr->nodeValue}" );
}
$attributes[ $target ][ $name ] = $attr->nodeValue;
}
}
// Each target must have a <references>
// Test PASS-ix-references-rule-multiple-matched-target.html shows that a target can be valid without references if its the default
// Filter nodes to remove ix elements that do not have a target attribute
foreach( array_intersect_key( $targets, self::$outputs ) as $target => $nodes )
{
// Only one can have an id attribute
$idFound = array();
$referencesFound = false;
$defaultNamespace = null;
foreach( $nodes as $targetNode )
{
/** @var \DOMElement $targetNode */
if ( $targetNode->localName != IXBRL_ELEMENT_REFERENCES ) continue;
$referencesFound = true;
if ( $targetNode->hasAttribute( IXBRL_ATTR_ID ) )
{
if ( $idFound )
throw new IXBRLDocumentValidationException( 'MoreThanOneID', "Section 12.1.2 Only one <references> element for a target can include an id attribute. Found '" . join( "','", $idFound ) . "'" );
$idFound[] = $targetNode->getAttribute( IXBRL_ATTR_ID );
}
// Go to the document and then to the root element so the base uri is not affected by local xml:base definitions
$document = self::$documents[ $targetNode->ownerDocument->docUrl ];
$namespaces = array_diff( $document->getElementNamespaces( $targetNode ), $document->getElementNamespaces() );
if ( $namespaces )
{
$namespace = reset( $namespaces );
if ( $defaultNamespace && $defaultNamespace != $namespace )
{
throw new IXBRLDocumentValidationException( 'ReferencesNamespaceClash', "Section 12.1.2 Only one default namespace can be used across all <references>. Two or more detected: '$defaultNamespace' and '{$namespace}'" );
}
else
{
$defaultNamespace = $namespace;
}
}
else if ( $defaultNamespace && $defaultNamespace != 'default' )
{
throw new IXBRLDocumentValidationException( 'ReferencesNamespaceClash', "Section 12.1.2 Only one default namespace can be used across all <references>. Two or more detected: '$defaultNamespace' and 'default'" );
}
else
{
$defaultNamespace = 'default';
}
}
if( ! $referencesFound )
throw new IXBRLDocumentValidationException( 'ReferencesAbsent', "Section 12.1.2 A <references> must exist for all targets. Missing element for target '$target'" );
}
}
/**
* Check that a node does not use ix attributes
* @param \DOMElement $node
* @param string $section
* @param string $localName
* @return void
*/
private static function checkIXbrlAttribute( $node, $section, $localName )
{
$xbrliNS = \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XBRLI ];
foreach( $node->attributes as $attr )
{
/** @var \DOMAttr $attr */
if ( $attr->namespaceURI == $xbrliNS )
{
throw new IXBRLDocumentValidationException( 'InvalidAttributeContent', "Section $section <$localName> elements must not include attributes in the xbrli namespace" );
}
}
}
/**
* Check parent nodes for some criteria
* @param \DOMElement $node
* @param string $section
* @return \DOMElement
*/
public static function checkParentNodes( \DOMElement $node, \Closure $test )
{
$parentNode = $node->parentNode;
while( $parentNode && $parentNode instanceof \DOMElement )
{
if ( $test( $parentNode ) ) return $parentNode;
// Up another level
$parentNode = $parentNode->parentNode;
}
return null;
}
/**
* Use to check the equivalence of a <nonFraction> attribute with that of any parent
* @param \DOMElement $node
* @param string $attrName
* @param string $attrValue
* @param string $section
* @param string $localName
* @param string $errorCode
* @return \DOMElement
*/
private static function checkAttributeConsistency( \DOMElement $node, string $attrName, string $attrValue, string $section, string $localName, $errorCode = null )
{
if ( strpos( $attrValue, ':') !== false )
{
list( $prefix, $name ) = explode( ':', $attrValue );
$attrValue = '{' . $node->lookupNamespaceURI( $prefix ) . '}' . ":$name";
}
if ( is_null( $errorCode ) ) $errorCode = 'NonFractionNestedAttributeMismatch';
return self::checkParentNodes( $node, function( \DOMElement $parentNode ) use( $attrName, $attrValue, $errorCode, $localName, $section )
{
if ( $parentNode->localName != $localName ) return false;
$parentAttr = $parentNode->getAttributeNode( $attrName );
$parentAttrValue = $parentAttr ? trim( $parentAttr->nodeValue ) : '';
if ( strpos( $parentAttrValue, ':') !== false )
{
list( $prefix, $name ) = explode( ':', $parentAttrValue );
$parentAttrValue = '{' . $parentNode->lookupNamespaceURI( $prefix ) . '}' . ":$name";
}
if ( $parentAttrValue == $attrValue ) return false;
throw new IXBRLDocumentValidationException( $errorCode, "Section $section Attribute @'$attrName' should be consistent in nested <$localName>" );
// return true; // End here. Any other parents will be checked when the parent is validated.
} );
}
/**
* Check the attributes of two nodes (usually children of a <tuple> instance) are thesame
*
* @param \DOMElement $nodeA
* @param \DOMElement $nodeB
* @return boolean
*/
private static function checkSameAttributes( $nodeA, $nodeB )
{
}
/**
* Check the contextRef is valid
* @param \DOMElement $node
* @param [type] $idNodes
* @param string $section
* @param string $localName
* @return void
*/
private static function checkContextRef( $node, &$idNodes, $section, $localName )
{
$contextRef = $node->getAttribute('contextRef');
$contextNode = $idNodes[ $contextRef ] ?? null;
if ( ! $contextNode )
{
throw new IXBRLDocumentValidationException( 'UnknownContext', "Section $section The c@ontextRef in <$localName> with id '$contextRef' does not exist" );
}
}
/**
* Check the unitRef is valid
* @param \DOMElement $node
* @param [type] $idNodes
* @param string $section
* @param string $localName
* @return void
*/
private static function checkUnitRef( $node, &$idNodes, $section, $localName, $errorCode = null )
{
$unitRef = trim( $node->getAttribute( IXBRL_ATTR_UNITREF ) );
$unit = $idNodes[ $unitRef ] ?? null;
if ( ! $unit )
{
throw new IXBRLDocumentValidationException( 'UnknownUnit', "Section $section The unit with id '$unitRef' does not exist" );
}
self::checkAttributeConsistency( $node, IXBRL_ATTR_UNITREF, $unitRef, $section, $localName, $errorCode );
}
/**
* Check the sign is valid
* @param \DOMElement $node
* @param string $section
* @param string $localName
* @return void
*/
private static function checkSign( $node, $section, $localName )
{
$sign = $node->getAttribute( IXBRL_ATTR_SIGN );