-
Notifications
You must be signed in to change notification settings - Fork 16
/
XBRL-Report-Base.php
3429 lines (2935 loc) · 124 KB
/
XBRL-Report-Base.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
// @codingStandardsIgnoreStart
// @codingStandardsIgnoreEnd
/**
* Reporting base class implementation
*
* @author Bill Seddon
* @version 0.9
* @Copyright (C) 2018 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/>.
*
*/
/**
* Abstract class to support the creation of XBRL reports
*
*/
abstract class XBRL_Report_Base
{
/**
* A list of the currently loaded instance documents
* @var array $instanceDocuments
*/
private $instanceDocuments = array();
/**
* A map associated entity ids with an instance
* @var array $entityInstanceMap
*/
private $entityInstanceMap = array();
/**
* The schema file of the related taxonomy
* @var string $schemaFilename
*/
private $schemaFilename = null;
/**
* A reference to the taxonomy associated with the instance document(s)
* @var XBRL $taxonomy
*/
private $taxonomy = null;
/**
* A list of the reporting hierarches generated by the PreparePresenation function
* @var array $hierarchies
*/
private $hierarchies = null;
/**
* Flag for debugging
* @var boolean $debug
*/
private $debug = false;
/**
* An array of the years in the contexts of the instance document(s) being reported
* @var array $years
*/
protected $years = array();
/**
* A flag to control whether
* @var boolean $includeDefaults
*/
protected $includeDefaults = true;
/**
* A list of the entities in the contexts of the instance document(s) being reported
* @var array $entities
*/
protected $entities = array();
/**
* A list of the years that are valid
* @var array
*/
protected $validYears = array();
/**
* The maximum depth of the deepest used node
* @var int $maxDepth
*/
private $maxDepth = 0;
/**
* Default contructor
*/
public function __construct() {
$this->rustart = $this->startTiming();
}
/**
* Get the maximum depth of the deepest used node
* @return int
*/
public function getMaxDepth()
{
return $this->maxDepth;
}
/**
* Get the current state of the debug flag. If debugging is enabled then contexts are included in the report.
* @return boolean True is debugging output is currently enabled
*/
public function getDebugging()
{
return $this->debug;
}
/**
* Set the debug state
* @param string $state (defaults to false is not supplied)
* @return boolean The existing debug state
*/
public function setDebugging( $state = false )
{
$existingState = $this->debug;
$this->debug = $state;
return $existingState;
}
/**
* Add an instance document to the report
* @param string $instance_file The file name of the instance document to add the report
* @param string $taxonomy_file If provided the name of the .json or .zip file containing the taxonomy information
* @return void
*/
public function addInstanceDocument( $instance_file = null, $taxonomy_file = null, $useCache = false )
{
$this->log()->info( "$instance_file" );
if ( $this->hierarchies !== null )
throw new Exception( "An instance document cannot be added to a report once the report has been prepared" );
if ( $instance_file === null )
throw new Exception( "An instance document has not been supplied." );
if ( isset( $this->instanceDocuments[ $instance_file ] ) )
throw new Exception( "The instance document has already been loaded" );
// Load the document
/**
* An instance document instance
* @var XBRL_Instance $instance
*/
$instance = null;
if ( ! XBRL_Instance::FromInstanceDocument( $instance_file, $taxonomy_file, $instance, false, $useCache ) )
{
throw new Exception( $instance->getError() );
}
// If no schema file is yet set, record it. If the name of the taxonomy schema
// associated with the instance document loaded is different to the schema of
// a previously loaded instance document then report an error.
$schemaFilename = $instance->getSchemaFilename();
if ( $this->schemaFilename === null )
$this->schemaFilename = $schemaFilename;
else if ( $this->schemaFilename !== $schemaFilename )
throw new Exception( "Instance documents being compared must use the the same taxonomy schema." );
// Record it
$this->instanceDocuments[ $instance_file ] =& $instance;
$this->analyzeContexts( $instance );
// If no taxonomy is set then record it as well. Only one taxonomy is allowed per report.
if ( ! isset( $this->taxonomy ) || $this->taxonomy === null )
$this->taxonomy =& $instance->getInstanceTaxonomy();
}
/**
* Adds a valid year. If none are added, all are valid.
* @param array[int]|int $year
*/
public function addValidYear( $year )
{
if ( is_array( $year ) )
{
$this->validYears += $year;
}
elseif ( $year !== null )
{
$this->validYears[] = $year;
}
}
/**
* Removes any defined valid years. After this function is called, all years are valid.
*/
public function clearValidYears()
{
$this->validYears = array();
}
/**
* Get the array of instance documents
* @return array[XBRL_Instance]
*/
public function getInstanceDocuments()
{
return $this->instanceDocuments;
}
/**
* Call to include default nodes in the output. By default, defaults are included.
* @return void
*/
public function excludeDefaultDimensionMembers()
{
$this->includeDefaults = false;
}
/**
* Call to include default nodes in the output. This is the default position.
* @return void
*/
public function includeDefaults()
{
$this->includeDefaults = true;
}
/**
* Initialize the taxonomy based on the loaded instance documents
* The taxonomy will have been loaded but the text may not have
* been assgined to concepts and the presentation hierarchy
* @return True if initialized successfully
*/
private function initTaxonomy()
{
// Sanity check
if ( count( $this->instanceDocuments ) === 0 )
{
$this->log()->err( "There are no instance documents" );
return false;
}
if ( $this->taxonomy === null ) return false;
$xsd = pathinfo( $this->schemaFilename, PATHINFO_BASENAME );
$this->taxonomy = $this->taxonomy->getTaxonomyForXSD( $xsd );
return true;
}
/**
* Generate an alternative list of contexts by year
* Can be overridden descendant concrete implementations
* @param XBRL_Instance $instance The instance containing the contexts to analyze
*/
protected function analyzeContexts( $instance )
{
$contexts = $instance->getContexts()->getContexts();
$elements = $instance->getElements()->getElements();
foreach ( $elements as $elementKey => $element )
{
foreach ( $element as $entryKey => $entry )
{
if ( ! isset( $entry['contextRef'] ) )
continue;
if ( isset( $instance->usedContexts[ $entry['contextRef'] ] ) ) continue;
$instance->usedContexts[ $entry['contextRef'] ] = $contexts[ $entry['contextRef'] ];
$instance->usedContexts[ $entry['contextRef'] ]['year'] = substr( $contexts[ $entry['contextRef'] ]['period']['endDate'], 0, 4 );
}
}
if ( ! is_array( $this->years ) ) $this->years = array();
foreach ( $instance->usedContexts as $key => $context )
{
$year = $context['year'];
$entity = $context['entity']['identifier']['value'];
if ( ! isset( $this->years[ $year ] ) ) $this->years[ $year ] = array();
if ( ! isset( $this->years[ $year ][ $entity ] ) ) $this->years[ $year ][ $entity ] = array();
$this->years[ $year ][ $entity ][ $key ] = $context;
}
// ksort( $this->years );
// print_r( array_keys( $this->years ) );
if ( ! is_array( $this->entities ) ) $this->entities = array();
foreach ( $instance->usedContexts as $key => $context )
{
$entity = $context['entity']['identifier']['value'];
$this->entityInstanceMap[ $entity ] = $instance->getDocumentName();
if ( ! isset( $this->entities[ $entity ] ) ) $this->entities[ $entity ] = array();
$this->entities[ $entity ][ $key ] = $context;
}
}
/**
* Access the taxonomy for instances used in this report
* This is only valid when an instance document have been loaded
* @return XBRL An instance of an XBRL class or derivative
*/
public function &getTaxonomy()
{
return $this->taxonomy;
}
/**
* Get the node for a path
*
* @param array $nodes An array of nodes
* @param string $path The path representing a node. A path is a set of labels concatenated by '/'
* @return boolean|array False if the node is not found or a reference to the node represented by the $path
*/
private function &findNodeFromPath( &$nodes, $path )
{
$pathsParts = explode( '/', $path );
$node = null;
for ( $i = 0; $i < count( $pathsParts ); $i++ )
{
if ( ! isset( $nodes[ $pathsParts[ $i ] ] ) )
{
$node = false;
break;
}
$node =& $nodes[ $pathsParts[ $i ] ];
if ( isset( $node['children'] ) )
{
$nodes =& $node['children'];
continue;
}
}
return $node;
}
/**
* Compare $entry with $existingElements to determine if the associated contextRefs are equivalent.
* @param array $existingElements An array of instance entries to compare to $entry for context and value equivalence
* @param array $entry An entry node representing a record in the instance document
* @param string $entryEntity The entity for which the entry should be unique
* @return bool Returns true if $entry is unique.
*/
private function entry_is_unique( $existingElements, $entry, $entryEntity )
{
if ( isset( $entry['tuple_elements'] ) ) return true;
foreach ( $existingElements as $key => $existingElement )
{
if ( $existingElement['contextRef'] !== $entry['contextRef'] ) continue;
if ( $existingElement['value'] !== $entry['value'] ) continue;
if ( $existingElement['entity'] !== $entryEntity ) continue;
// $this->log()->info( "The $entry with contextRef {$entry['contextRef']} and value {$entry['value']} is not unique" );
return false;
}
return true;
}
/**
* Make sure the list of years (based on contexts) is the same as the specified valid year (if any have been specified)
* @return void
*/
private function alignWithValidYears()
{
// Remove any years that are not in the valid years list
if ( ! $this->validYears ) return;
$validYears = array_flip( $this->validYears );
$validYears = array_intersect_key( $validYears, $this->years );
$this->validYears = array_flip( $validYears );
$this->years = array_intersect_key( $this->years, $validYears );
}
/**
* This is a core function that processes the instance documents and their
* elements against the presentation roles of the selected taxonomy.
* The result is a series of hierarchies (one for each presentation role in
* the selected taxonomy) that can be pruned to include only those elements
* for which at least one value is assigned.
*
* It is a four stage process:
*
* 1) Process the instance document to assign instance facts to nodes in the
* presentation hierarchy and add convert hypercubes of primary item nodes
* to dimensions and their members used by instance documents including defaults;
* 2) Prune any unused presentation hierarchy nodes
* 3) Call processDimensionGroups() to expand the discovered dimensions and
* members into new nodes in the presentation hierarchy;
* 4) (optionally) call compactDimensionGroups to remove nodes that are unused
* or are only used by default members (in which case the values are
* promoted up the hierarchy to a non-default dimension member or a primary
* item.
*
* @param bool $prune True if the presentation hierarchies should be pruned to keep only items with elements assigned
* @return void
*/
public function preparePresentation( $prune = true )
{
$this->log()->info( "initTaxonomy" );
if ( ! $this->initTaxonomy() )
throw new Exception( "Failed to initialize the taxonomy" );
// $this->log()->info( "Prepare {$this->elapsedTime()}" );
$roles = &$this->taxonomy->getPresentationRoleRefs();
$taxonomies = $this->taxonomy->getImportedSchemas();
$this->maxDepth = 0;
$this->alignWithValidYears();
foreach ( $this->instanceDocuments as $instanceKey => $instance )
{
/**
* @var $instance XBRL_Instance
*/
$instance_namespaces = $instance->getInstanceNamespaces();
$instance_elements = $instance->getElements()->getElements();
$count = count( $instance_elements );
$this->log()->info( "There are $count elements to report" );
foreach ( $instance_elements as $elementKey => &$instance_element )
{
// There may be more than one entry in each instance_element
foreach ( $instance_element as $entryKey => &$entry )
{
// If valid years have been defined check to see if the
if ( false && $this->validYears )
{
$year = $instance->getYearForElement( $entry );
if ( ! $year )
{
// Probably a tuple so check any tuple elements
// If it there are none, the node is invalid
if ( ! isset( $entry['tuple_elements'] ) )
continue;
// Time to check the tuple members are valid for the valid year(s)
// If they are not, they are removed
foreach ( $entry['tuple_elements'] as $tupleKey => $tupleElements )
{
foreach ( $tupleElements as $tupleElementKey => $tupleElement )
{
$year = $instance->getYearForElement( $tupleElement );
if ( ! $year || ! in_array( $year, $this->validYears ) )
{
unset( $entry['tuple_elements'][ $tupleKey ][ $tupleElementKey ] );
}
}
if ( ! $entry['tuple_elements'][ $tupleKey ] )
{
unset( $entry['tuple_elements'][ $tupleKey ] );
}
}
if ( ! $entry['tuple_elements'] ) continue;
}
else
if ( ! in_array( $year, $this->validYears ) )
{
continue;
}
}
// $this->log()->info( "Entry: {$entry['taxonomy_element']['id']}" );
// Get the namespace for the entry's namespace prefix
// if ( $entry['taxonomy_element']['id'] === 'uk-bus_AddressLine2' ) exit;
// Get the taxonomy for the entry's namespace
if ( ! isset( $instance_namespaces[ $entry['namespace'] ] ) )
throw new Exception( "Unable to find the namespace for the prefix: {$entry['namespace']}" );
$instance_namespace = $instance_namespaces[ $entry['namespace'] ];
if ( ! isset( $taxonomies[ $instance_namespace ] ) )
throw new Exception( "Unable to find a taxonomy for the namespace '$instance_namespace'" );
/**
* @var XBRL $instance_taxonomy
*/
$instance_taxonomy = $taxonomies[ $instance_namespace ];
if ( ! $instance_taxonomy )
throw new Exception( "Unable to fund the taxonomy for the namespace '{$instance_namespaces[ $entry['namespace'] ]}'" );
// Create an href so locators can be identified. The id alone should be enough but using an href is safer.
// $xsd = $instance_taxonomy->getTaxonomyXSD();
$href = $entry['label']; // "$xsd#{$entry['taxonomy_element']['id']}";
$located_role_paths = array(); // The label can exist in more than one presentation role
// Look for the label in the locators of each presentation role.
// Use the href of the taxonomy element to find the locator and, so, the role.
foreach ( $roles as $roleKey => $role ) // <- This has to be by reference or any changes are are lost!
{
// $this->log()->info( "Role key: $roleKey" );
if ( ! isset( $role['paths'] ) )
throw new Exception( "Error occurred: paths array not available on role $roleKey" );
if ( ! isset( $role['paths'][ $entry['taxonomy_element']['id'] ] ) )
continue;
$located_role_paths[ $roleKey ] = $role['paths'][ $entry['taxonomy_element']['id'] ];
}
if ( count( $located_role_paths ) === 0 )
{
$this->log()->info( "Unable to find role for $href" );
continue;
}
// Find the element in the located_role
// $this->log()->info( "The role for {$elementKey} is {$located_role_key}" );
// $this->log()->info( "href: $href" );
// uk-gaap-pt_ApprovalDetails is an example of a concept that might
// exist in the AE document but does not exist in the presentation
// if ( $href === "uk-gaap-pt-2004-12-01.xsd#uk-gaap-pt_ApprovalDetails" )
foreach ( $located_role_paths as $roleKey => $paths )
{
foreach ( $paths as $path )
{
$currentNodes =& $roles[ $roleKey ]['hierarchy'];
if ( isset( $pathNode ) ) unset( $pathNode );
$pathNode = false;
$commonHypercubes = array();
$totalHypercubes = array();
$hypercubelessNodes = array();
$currentPath = "";
$validMembers = array();
unset( $dimInfo );
unset( $totalDimensions );
$pathsParts = explode( '/', $path );
for ( $i = 0; $i < count( $pathsParts ); $i++ )
{
if ( ! isset( $currentNodes[ $pathsParts[ $i ] ] ) )
{
$this->log()->err( "This is bad" );
$currentNodes = false;
break;
}
if ( $pathNode )
{
$currentNodes[ $pathsParts[ $i ] ]['parentNode'] =& $pathNode;
}
$pathNode =& $currentNodes[ $pathsParts[ $i ] ];
if ( ! isset( $pathNode['text'] ) )
{
// $element_xsd = parse_url( $pathNode['label'], PHP_URL_PATH );
$taxonomy = $this->getTaxonomy()->getTaxonomyForXSD( $pathNode['label'] );
$pathNode['taxonomy_element'] = $taxonomy->getElementById( $pathNode['label'] );
// $key = $pathNode['label']; // "$element_xsd#{$pathNode['taxonomy_element']['id']}";
$pathNode['text'] = $instance_taxonomy->getTaxonomyDescriptionForIdWithDefaults(
$taxonomy->getTaxonomyXSD() . "#{$pathNode['taxonomy_element']['id']}", /*$pathNode['label'], */
isset( $pathNode['preferredLabel'] ) ? $pathNode['preferredLabel'] : null,
$instance_taxonomy->getDefaultLanguage()
);
if ( ! $pathNode['text'] )
{
$pathNode['text'] = $pathNode['label'];
}
}
$currentPath = ( empty( $currentPath ) ? "" : $currentPath . "/" ) . $pathsParts[ $i ];
/*
* This code has to collect the hypercubes from the 'hypercubes' and the 'common' elements
* To new hypercubes or new common hypercubes the current path is added an element called
* 'path'. This is so the correct node can be found when adding dimensions. This way the
* dimensions are added to the appropriate node.
*/
// Collect the hypercubes
$nodeHypercubes = ( isset( $pathNode['hypercubes'] ) ? $pathNode['hypercubes'] : array() )
+ ( isset( $pathNode['common'] ) ? $pathNode['common'] : array() );
// Identify any new hypercubes (not already in the common collection)
$newHypercubes = array_diff_key( $nodeHypercubes, $commonHypercubes );
// Assign the current path to any new hypercubes
foreach ( $newHypercubes as $hcKey => $hc )
{
$newHypercubes[ $hcKey ]['path'] = $currentPath;
}
// The common list for the next go around is the existing common list plus the new hypercubes
// $commonHypercubes = array_merge_recursive( $commonHypercubes, $newHypercubes );
$commonHypercubes += $newHypercubes;
$totalHypercubes = $commonHypercubes; // Looks like $totalHypercubes = $commonHypercubes are the same thing
if ( ! isset( $pathNode['children'] ) )
{
// Better be the last!
if ( count( $pathsParts ) -1 > $i )
{
$this->log()->crit( "There are no child nodes but node '{$pathNode['label']}' is not the last part in path '$path'" );
exit;
}
continue;
}
$currentNodes =& $pathNode['children'];
} // for $pathParts
if ( ! $currentNodes )
{
$this->log()->warning( "There are no current nodes so something went wrong evaluation path '$path'" );
continue;
}
if ( ! $pathNode )
{
$this->log()->warning( "A node cannot be found for path '$path'" );
continue;
}
$entryEntity = $instance->getEntityForElement( $entry );
// If the node does not have any existing instance elements assigned add an empty element
// If instance elements have been assigned, check its not a duplicate
if ( ! isset( $pathNode['elements'] ) )
$pathNode['elements'] = array();
else if ( ! $this->entry_is_unique( $pathNode['elements'], $entry, $entryEntity ) )
continue;
// $this->log()->info( "Found entry: {$entry['taxonomy_element']['id']} ({$entry[ 'contextRef' ]})" );
$context_dimensions = array();
// contextRef will not exist if the entry element is a tuple
$preferredLabels = array_reduce( $totalHypercubes, function( $carry, $hypercube ) {
if ( ! isset( $hypercube['preferredLabel'] ) ) return $carry;
$carry[] = $hypercube['preferredLabel'];
return $carry;
}, array() );
$dimInfo = isset( $entry['contextRef'] ) ? $instance->getElementsForContext( $entry['contextRef'], $preferredLabels ) : false;
if ( $dimInfo !== false )
{
foreach ( $dimInfo as $dimInfoKey => $item )
{
if ( ! isset( $item['dimension']['element']['id'] ) ||
! isset( $item['member']['element']['id'] ) ) continue;
$dimTax = $instance_taxonomy->getTaxonomyForNamespace( $item['dimension']['namespace'] );
$dimXSD = $dimTax->getTaxonomyXSD();
$memTax = $instance_taxonomy->getTaxonomyForNamespace( $item['member']['namespace'] );
$memXSD = $memTax->getTaxonomyXSD();
$context_dimensions[ "$dimXSD#{$item['dimension']['element']['id']}" ] = array(
'member' => "$memXSD#{$item['member']['element']['id']}",
'member_text' => $item['member']['text'],
'dimension_text' => $item['dimension']['text'],
'member_taxonomy_element' => $item['member']['element'],
);
}
// Look to see if any taxonomy specific additional members exist for members of the parts path
$validMembers += $instance_taxonomy->getValidDimensionMembersForNode( $pathNode, $pathsParts );
// Check that any dimension members are valid against the context members.
// TODO: probably only need to check for members of explicit dimensions
if ( count( $validMembers ) > 0 && count( $context_dimensions ) > 0 )
{
$context_members = array_map( function( $item ) { return $item['member']; }, $context_dimensions );
$foundMembers = array_intersect_key( $validMembers, array_flip( $context_members ) );
if ( count( $context_members ) > count( $foundMembers ) )
{
// $this->log()->warning( "Not all context members are valid in this role" );
continue;
}
}
}
// Record the $entry
if ( isset( $pathEntry ) ) unset( $pathEntry );
$pathEntry = $entry;
$pathNode['elements'][] =& $pathEntry;
$pathNode['used'] = 'value';
$usedNode =& $pathNode;
$pathEntry['entity'] = $entryEntity;
while ( isset( $usedNode['parentNode'] ) )
{
// get the parent node
$usedNode =& $usedNode['parentNode'];
// If the node has already been used, we're done
if ( isset( $usedNode['used'] ) ) continue;
// Flag the path as used
$usedNode['used'] = 'path';
}
unset( $usedNode );
$pathNode['taxonomy_namespace'] = $instance_namespaces[ $entry['namespace'] ];
$label = $href;
if ( isset( $entry['tuple_elements'] ) )
{
$pathNode['tuple'] = true;
}
// Find the dimensions and member from the context or get the default for the dimension.
else if ( isset( $pathNode['nodeclass'] ) && $pathNode['nodeclass'] === "primaryitem" && ! in_array( $label, $hypercubelessNodes ) )
{
// Getting here means there are dimensions for the node.
// The dimensions could be those passed as common or associated directly with the node
// $this->log()->info( "$path/{$pathNode['label']}" );
// $this->log()->info( "Common" );
// $this->log()->info( $commonHypercubes );
if ( ! isset( $pathEntry['validCombination'] ) ) $pathEntry['validCombination'] = array();
$totalDimensions = array();
foreach ( $totalHypercubes as $hypercubeKey => $hypercube )
{
// $this->log()->info( "$hypercubeKey" );
$tax = $instance_taxonomy->getNamespace() === $hypercube['namespace']
? $instance_taxonomy
: $instance_taxonomy->getTaxonomyForNamespace( $hypercube['namespace'] );
if ( $tax === false ) continue;
$role_hypercubes = $tax->getDefinitionRoleHypercubes( $hypercube['role'] );
if ( $role_hypercubes === false || ! isset( $role_hypercubes[ $hypercubeKey ] ) )
{
$this->log()->warning( "Unable to find the hypercube '$hypercubeKey' in role '{$hypercube['role']}' of the hypercube set for taxonomy '{$hypercube['namespace']}'" );
continue;
}
if ( isset( $role_hypercubes[ $hypercubeKey ]['dimensions'] ) )
{
foreach ( $role_hypercubes[ $hypercubeKey ]['dimensions'] as $dimensionKey => $dimension )
{
if ( ! isset( $totalDimensions[ $dimensionKey ] ) )
{
// $this->log()->info( "$dimensionKey" );
$dimension['hypercube'] = array( $hypercubeKey => $hypercube['role'] );
$dimension['path'] = $hypercube['path'];
$totalDimensions[ $dimensionKey ] = $dimension;
}
else
{
$totalDimensions[ $dimensionKey ]['hypercube'][ $hypercubeKey ] = $hypercube['role'];
if ( $totalDimensions[ $dimensionKey ]['path'] !== $hypercube['path'] &&
strlen( $totalDimensions[ $dimensionKey ]['path'] ) > strlen( $hypercube['path'] ) )
{
$totalDimensions[ $dimensionKey ]['path'] = $hypercube['path'];
}
}
if ( isset( $dimension['default'] ) )
{
/**
* @var XBRL $tax
*/
$tax = $instance_taxonomy->getTaxonomyForXSD( $dimension['default']['label'] );
$dimension['default']['taxonomy_element'] = $tax->getElementById( $dimension['default']['label'] );
$pathEntry['validCombination'][ $dimensionKey ] = $tax->getTaxonomyXSD() . "#{$dimension['default']['taxonomy_element']['id']}";
// $key = parse_url( $dimensionKey, PHP_URL_FRAGMENT );
// $pathEntry['validCombination'][ $key ] = $dimension['default']['taxonomy_element']['id'];
}
}
}
}
if ( $dimInfo === false )
{
// There are dimensions (local and common) but the context does not specify members for any dimensions
// Now it the chance to find the default values
// If there are no dimension then its not necessarily a problem.
$allPossibleDimensions = array_reduce( $totalHypercubes, function( $carry, $hypercube ) {
$carry += isset( $hypercube['dimensioncount'] ) ? $hypercube['dimensioncount'] : 0; return $carry;
}, 0 );
// If there are no dimensions (eg primary item for an 'empty' hypercube) then all is good
if ( $allPossibleDimensions == 0 )
{
// $pathEntry['nodim'] = true; // Used by processDimensionGroups
continue;
}
if ( count( $totalDimensions ) > 0 )
{
// All the dimensions for all the hypercubes must have a default member
$invalidHypercubes = array_reduce( $totalHypercubes, function( $carry, $hypercube) use( $totalDimensions ) {
$allDefaultDimensions = array_reduce( $totalDimensions, function( $carry, $dimension ) use( $hypercube ) {
return $carry += isset( $dimension['hypercube'][ $hypercube['href'] ] ) && isset( $dimension['default'] ) ? 1 : 0;
}, 0 );
if ( $allDefaultDimensions != $hypercube['dimensioncount'] )
{
$carry[] = $hypercube['href'];
}
return $carry;
}, array() );
if ( count( $invalidHypercubes ) == count( $totalHypercubes ) )
{
/*
$this->log()->instance_validation(
"[Ins Err, 2]",
"All the hypercubes have no dimensions with default members. This is required because no context dimension information is supplied",
array(
STANDARD_PREFIX_XBRLDI_ERROR => 'PrimaryItemDimensionallyInvalidError',
'definition' => 21,
'id' => $entry['taxonomy_element']['id'],
'context' => $entry['contextRef'],
'hypercubes' => $invalidHypercubes,
)
);
*/
// This hypercube is not valid so only report the value
array_pop( $pathNode['elements'] );
continue;
}
// Remove hypercubes that are invalid. This does not appear to happen.
if ( $invalidHypercubes )
{
// $totalHypercubes = array_diff_key( $totalHypercubes, array_flip( $invalidHypercubes ) );
// Remove any dimensions associated soley with invalid hypercubes
foreach ( $totalDimensions as $dimKey => $dimension )
{
// if ( $dimension['hypercube'] )
}
}
}
}
else
{
// The count of total dimensions should be the same or at least one of the hypercubes should
// not be closed.
$allHypercubesAreClosed = array_reduce( $totalHypercubes, function( $carry, $hypercube ) {
return $carry || ( isset( $hypercube['closed'] ) && $hypercube['closed'] );
}, false );
if ( count( $totalDimensions ) < count( $context_dimensions ) && $allHypercubesAreClosed )
{
/*
$this->log()->instance_validation(
"[Ins Err, 2]",
"Dimensions are defined by the context that do not exist in the hypercube and the hypercube is closed.",
array(
STANDARD_PREFIX_XBRLDI_ERROR => 'PrimaryItemDimensionallyInvalidError',
'definition' => 21,
'id' => $entry['taxonomy_element']['id'],
'context' => $entry['contextRef'],
)
);
*/
// This node is not valid
array_pop( $pathNode['elements'] );
continue;
}
$pathEntry['context_dimensions'] = $context_dimensions;
}
// Look in the common dimensions
$matched_node_dimensions = array_intersect_key( $totalDimensions, $context_dimensions );
// Create a list of all the hypercubes that apply to this element
$hc = array_reduce( $matched_node_dimensions, function( $carry, $item ) { return array_merge( $carry, $item['hypercube'] ); }, array() );
// Add all the hypercubes having a dimension in $totalDimensions that have a default member
// TODO: This should be to add the hypercube if *all* its dimensions have defaults. If even one
// does not have a default then its not a valid hypercube (see https://www.xbrl.org/specification/dimensions/rec-2012-01-25/dimensions-rec-2006-09-18+corrected-errata-2012-01-25-clean.html#term-dimensionally-valid-with-respect-to-a-hypercube)
$hc = array_reduce( $totalDimensions, function( $carry, $item ) use( $context_dimensions ) {
if ( ! isset( $item['default'] ) ) return $carry;
return array_merge( $carry, $item['hypercube'] );
}, $hc );
// Filter the total dimensions list to include only those that share hypercubes used by this element
$totalDimensions = array_filter( $totalDimensions, function( $item ) use( $hc ) {
return count( array_intersect_key( $item['hypercube'], $hc ) );
});
$matched_context_dimensions = array_intersect_key( $context_dimensions, $totalDimensions );
// $matched_node_dimensions = array_intersect_key( $totalDimensions, $context_dimensions );
$count_context_dimensions = count( $context_dimensions );
$count_matched_context_dimensions = count( $matched_context_dimensions );
// All the context dimensions should be matched
if ( $count_context_dimensions > $count_matched_context_dimensions )
{
// This is just invalid so remove the element and move on.
array_pop( $pathNode['elements'] );
continue;
$diff = array_keys( array_diff_key( $context_dimensions, $matched_context_dimensions ) );
$dims = implode( ", ", $diff );
$this->log()->warning( "Not all context dimensions have been matched by dimensions for node '{$pathNode['label']}' and context '{$entry['contextRef']}' ($dims)" );
$this->log()->warning( " There are $count_context_dimensions context dimension(s) but $count_matched_context_dimensions matched context dimensions" );
$this->log()->warning( "Value: {$entry['value']}" );
// print_r( array_keys( $totalDimensions ) );
// exit;
continue;
}
$matched = array_merge_recursive( $matched_context_dimensions, $matched_node_dimensions );
foreach ( $matched as $dimensionKey => $dimension )
{
if ( isset( $dimNode ) ) unset( $dimNode );
$dimNode = array();
$dimNode = &$this->findNodeFromPath( $roles[ $roleKey ]['hierarchy'], $dimension['path'] );
if ( ! $dimNode )
{
$this->log()->warning( "Unable to find node for dimensions" );
continue;
}
if ( ! isset( $dimension['taxonomy_element'] ) )
{
/**
* @var XBRL $tax
*/
$dimTax = $instance_taxonomy->getNamespace() === $dimension['dimension_namespace']
? $instance_taxonomy
: $instance_taxonomy->getTaxonomyForNamespace( $dimension['dimension_namespace'] );
$dimension['taxonomy_element'] = $dimTax->getElementById( $dimension['label'] );
}
if ( ! isset( $dimNode['dimensions'] ) ) $dimNode['dimensions'] = array();
if ( ! isset( $dimNode['dimensions'][ $dimensionKey ] ) )
{
$dimNode['dimensions'][ $dimensionKey ] = array(
'label' => $dimensionKey,
'text' => $dimension['dimension_text'],
'targetRole' => isset( $dimension['targetRole'] ) ? $dimension['targetRole'] : "",
'hypercube' => $dimension['hypercube'],
'taxonomy_element' => $dimension['taxonomy_element'],
'order' => $dimension['order'],
);
if ( isset( $dimension['default'] ) )
{
/**
* @var XBRL $tax
*/
$tax = $instance_taxonomy->getTaxonomyForXSD( $dimension['default']['label'] );
if ( ! isset( $dimension['default']['taxonomy_element'] ) )
{
$dimension['default']['taxonomy_element'] = $tax->getElementById( $dimension['default']['label'] );
}
$member_text = $tax
? $tax->getTaxonomyDescriptionForIdWithDefaults( $dimension['default']['taxonomy_element']['id'] )
: $dimension['default']['taxonomy_element']['id'];
$default_label = $tax->getTaxonomyXSD() . "#" . $dimension['default']['taxonomy_element']['id'];
// $member = XBRL::findDimensionMember( $dimension['members'], $default_label );
$dimNode['dimensions'][ $dimensionKey ]['default'] = array(
'label' => $default_label,
'text' => $member_text,
'taxonomy_element' => $dimension['default']['taxonomy_element'],
'order' => $dimension['order'],
);
}
}
if ( ! isset( $dimNode['dimensions'][ $dimensionKey ]['members'] ) )
{
$dimNode['dimensions'][ $dimensionKey ]['members'] = array();
}
if ( ! isset( $dimNode['dimensions'][ $dimensionKey ]['members'][ $dimension['member'] ] ) )
{