-
Notifications
You must be signed in to change notification settings - Fork 16
/
XBRL-Formulas.php
2200 lines (1901 loc) · 78.3 KB
/
XBRL-Formulas.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 Formulas
* _ _ _ _ _
* | | _ _ __ _ _ _(_) __| (_) |_ _ _
* | | | | | |/ _` | | | | |/ _` | | __| | | |
* | |__| |_| | (_| | |_| | | (_| | | |_| |_| |
* |_____\__, |\__, |\__,_|_|\__,_|_|\__|\__, |
* |___/ |_| |___/
*
* @author Bill Seddon
* @version 0.9
* @Copyright ( C ) 2017 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/>.
*
*/
use lyquidity\xml\MS\XmlNamespaceManager;
use lyquidity\XPath2\XPath2Expression;
use XBRL\Formulas\Resources\Variables\Parameter;
use XBRL\Formulas\Resources\Variables\Signature;
use XBRL\Formulas\Resources\Variables\Implementation;
use XBRL\Formulas\Resources\Variables\FactVariable;
use XBRL\Formulas\Resources\Variables\VariableSet;
use XBRL\Formulas\Resources\Variables\Variable;
use XBRL\Formulas\Formulas;
use XBRL\Formulas\Resources\Assertions\ConsistencyAssertion;
use XBRL\Formulas\Resources\Formulas\Formula;
use XBRL\Formulas\Resources\Variables\Precondition;
use XBRL\Formulas\Resources\Assertions\AssertionSet;
use XBRL\Formulas\Resources\Formulas\GeneratedFacts;
use XBRL\Formulas\Resources\Resource;
use lyquidity\XPath2\FunctionTable;
use XBRL\Formulas\Resources\Variables\ScopeVariable;
use XBRL\Formulas\ScopeVariableBinding;
use lyquidity\XPath2\Iterator\DocumentOrderNodeIterator;
use XBRL\Formulas\Resources\Variables\Instance;
use lyquidity\xml\QName;
use XBRL\Formulas\Resources\Assertions\ValueAssertion;
use XBRL\Formulas\Resources\Assertions\ExistenceAssertion;
use lyquidity\XPath2\DOM\DOMXPathNavigator;
use XBRL\Formulas\Resources\Filters\Filter;
/**
* Main class for formula evaluation
*/
class XBRL_Formulas extends Resource
{
/**
* A namespace manager for this evaluator
* @var XmlNamespaceManager $nsMgr
*/
private $nsMgr = null;
/**
* A reference to the current logging instance
* @var XBRL_Log $log
*/
private $log = null;
/**
* A list of parameter variables indexed by qname
* @var Parameter[] $parameterQnames
*/
private $parameterQnames = null;
/**
* A list of discovered custom function signatures
* @var array $signatures
*/
private $signatures = array();
/**
* Flag indicating whether or not the formula should produce an instance
* @var bool
*/
private $produceOutputXbrlInstance = false;
/**
* A list of the variable sets that will produce an instance
* @var array
*/
private $instanceProducingVariableSets = array();
/**
* The QName to use for the output instance
* @var string|QName $instanceQName
*/
private $instanceQName = 'instances:standard-output-instance';
/**
* A list of the instances to produce
* @var array $instanceQNames
*/
private $instanceQNames = array();
/**
* A list of instances
* @var array(XBRL_Instance) $instances
*/
private $instances = array();
/**
* A list of variable sets and parameters by name (not qname)
* @var VariableSet[] $variableSets
*/
private $variableSets = array();
/**
* Flag indicating whether the variable set represents an assertion
* @var bool
*/
private $isAssertion = false;
/**
* Flag indicating whether the variable set represents a formula
* @var bool
*/
private $isFormula = false;
/**
* The name of the assertion type or null if a formula
* @var string
*/
private $assertionType = null;
/**
* A list of consistency assertions defined
* @var array $consistencyAssertions
*/
private $consistencyAssertions = array();
/**
* An instance in which a formula can accumulate facts, contexts and units
* @var GeneratedFacts $formulaFactsContainer
*/
private $formulaFactsContainer;
/**
* Flag to control when evauation can take place. For exaple, evaluation is pointless if there is no instance document.
* @var bool $canEvaluate
*/
private $canEvaluate = false;
/**
* Stores an ru structure representing the beginning of a timing session.
*/
private function startTiming()
{
if ( version_compare( PHP_VERSION, "7.0", "<" ) ) return;
$this->rustart = getrusage();
}
/**
* Generate a progress value in milliseconds
* @param string $index An index such as 'utime' or 'stime'
* @return int|number|bool
*/
private function elapsedTime( $index = 'utime')
{
if ( version_compare( PHP_VERSION, "7.0", "<" ) ) return false;
$rus = $this->rustart;
$ru = getrusage();
return ( $ru[ "ru_$index.tv_sec" ] * 1000 + intval( $ru[ "ru_$index.tv_usec" ] / 1000 ) ) - ( $rus ? $rus[ "ru_$index.tv_sec" ] * 1000 + intval( $rus[ "ru_$index.tv_usec" ] / 1000 ) : 0 );
}
/**
* Default constructor
*/
public function __construct()
{
$this->log = XBRL_Log::getInstance();
$this->nsMgr = new XmlNamespaceManager();
$this->parameterQnames = array();
}
/**
* Returns the current set of consistency assertions defined for one or more formulas
* @return array
*/
public function getConsistencyAssertions()
{
return $this->consistencyAssertions;
}
/**
* Get the namespaces for the formulas
*/
public function getNamespaceManager()
{
return $this->nsMgr;
}
/**
* Return the list of variable set. This can be useful to access generated messages on an assertion variable set
*/
public function getVariableSets()
{
return $this->variableSets;
}
/**
* Returns an array of assertion information indexed by role and concept
* @return array
*/
public function getValueAssertionFormulaSummaries()
{
$conceptsTested = array();
foreach ( $this->getVariableSets() as $roleUri => $roleFormulas )
{
$roleUri = strpos( $roleUri, '#' ) === false ? $roleUri : strstr( $roleUri, '#', true );
foreach ( $roleFormulas as $formulaIndex => $formula )
{
if ( ! $formula instanceof ValueAssertion ) continue;
/** @var ValueAssertion $valueAssertion */
$valueAssertion = $formula;
// Get all the variable references
$variableNames = array_keys( $valueAssertion->variablesByQName );
// Look for the equality operator and split the test
$testAssigmentVariables = array();
foreach ( array( '=', 'eq', 'gt', 'lt', 'ge', 'le' ) as $equality )
{
$left = array_intersect( array_map( function( $item ) { return ltrim( $item, '$' ); }, preg_split( "/[\s\(\)\-\+\/\*]/", trim( strstr( $valueAssertion->test, $equality, true ) ) ) ), $variableNames );
$right = array_intersect( array_map( function( $item ) { return ltrim( $item, '$' ); }, preg_split( "/[\s\(\)\-\+\/\*]/", trim( ltrim( strstr( $valueAssertion->test, $equality ), $equality ) ) ) ), $variableNames );
$testAssigmentVariables += count( $left ) == 1 && count( $right ) == 1
? array_merge( $left, $right )
: ( count( $left ) == 1 && count( $right ) >= 1
? $left
: (
count( $right ) == 1 && count( $left ) >= 1
? $right
: array()
) );
if ( count( $left ) || count( $right ) ) break;
}
$addTestResult = function( &$result, $success ) use( &$testAssigmentVariables, &$conceptsTested, $valueAssertion, $roleUri, &$variableNames )
{
foreach ( $testAssigmentVariables as $testAssigmentVariable )
{
/** @var DOMXPathNavigator $navigator */
$navigator = $result['vars'][ $testAssigmentVariable ];
if ( ! $navigator instanceof DOMXPathNavigator ) continue;
$variableDetails = $valueAssertion->getVariableDetails( $navigator, false );
$message = $valueAssertion->createDefaultMessage( $valueAssertion->test, $result['vars'], false );
$variableDetails['message'] = $message;
$variableDetails['satisfied'] = $success;
$variableDetails['id'] = $valueAssertion->id;
$variableDetails['label'] = $valueAssertion->label;
/** @var QName $qname */
$qName = qname( $variableDetails['concept'], array( $navigator->getPrefix() => $navigator->getNamespaceURI() ) );
$conceptsTested[ $roleUri ][ $qName->clarkNotation() ][ $variableDetails['context'] ] = $variableDetails;
}
};
foreach ( $valueAssertion->satisfied as $index => $satisfied )
{
$addTestResult( $satisfied, true );
}
foreach ( $valueAssertion->unsatisfied as $index => $unsatisfied )
{
$addTestResult( $unsatisfied, false );
}
}
}
return $conceptsTested;
}
/**
* Process any formulas in $taxonomy against the array of instances in $instances
*
* @param array|XBRL_Instance $instances A single or an array of XBRL_Instance instances
* @param array $additionalNamespaces (optional) An array of namespaces indexed by prefix
* These could be from a test cases or other document
* @param array $contextParameters A list of parameters to be added to the context
* @param string|null $roleFilterPart (optional) Retrict the evaluation of formulas to those with $roleFilterPart in the roleUri
*
* For each formula
* Determine any parameters then evaluate them and add them to the variable set
* The 'name' property identifies the parameters
* Parameters without a select property will access a value of the same name from the XPath static context
*
* Evaluate any qname expressions in filters using the parameters
* This is a pre-evaluation static replacement of parameter names for the parameter's evaluated value
*
* Determine the fact variables (these form the variable set)
* The 'name' property on the arc overrides the name property of any parameters
*
* Create a dependency hierarchy
* The default dependency hierarchy will be flat and contain all fact variables in the variable set
* Dependencies can arise because of variable references or because of references in general variables
*
* Create context for the formula and add any evaluated parameters
*
* Look for any group filters <variable:variableSetFilterArc> and an http://xbrl.org/arcrole/2008/variable-set-filter arcrole
* Create a default filter (no restrictions) and add any group filters
* for the first variable in the dependency hierarchy
* create an XPath statement
* add group filters
* add variable filters
* evaluate the statement
* for each fact
*
* add the fact to the context
*
* create a new filter
* add group filters
*
* for the next variable
* if the variable is dependent
* from the fact add aspect values that are not covered by a filter
*
*
* @return void
*/
public function processFormulasAgainstInstances( $instances, $additionalNamespaces = null, $contextParameters = null, $roleFilterPart = null )
{
$this->canEvaluate = true;
$result = true;
if ( ! is_null( $instances ) && ! is_array( $instances ) )
{
$instances = array( $instances );
}
if ( is_null( $contextParameters ) )
{
$contextParameters = array();
}
foreach ( $instances as /** @var XBRL_Instance $xbrlInstance */ $xbrlInstance )
{
// Reset for this instance
$instanceTaxonomy = $xbrlInstance->getInstanceTaxonomy();
if ( ! $instanceTaxonomy->getHasFormulas( true ) ) return true;
// BMS 2018-12-13
$schemasWithFormulas = array_filter( $instanceTaxonomy->getImportedSchemas(), function( $taxonomy ) { return $taxonomy->getHasFormulas(); } );
// // For now, take just one of the taxonomies with formulas
// $schemasWithFormulas = array( reset( $schemasWithFormulas ) );
foreach ( $schemasWithFormulas as $namespace => $taxonomy )
{
// Note that is this is not the first taxonomy then $this->variableSets
// may not be empty. Formulas that have been evaluated are retained in
// case their results need to be used in other formulas such as scope dependency
$this->parameterQnames = array();
$this->nsMgr = new XmlNamespaceManager();
// Begin loading the namespaces
$this->addNamespaces( array( XBRL_Constants::$standardPrefixes, $additionalNamespaces, $xbrlInstance->getInstanceNamespaces() ) );
// Set the instance
$this->instanceQName = qname( "instances:standard-input-instance", $this->nsMgr->getNamespaces() );
$this->instanceQNames[ "standard-input-instance" ] = $this->instanceQName ;
$this->instances[ (string)$this->instanceQName ] = $xbrlInstance;
// Look for any non-standard instances
$instanceResources = $taxonomy->getGenericResource( "variable", "instance" );
if ( $instanceResources )
foreach ( $instanceResources as $instanceKey => $instanceResource )
{
/**
* @var Instance $instance
*/
$instance = Instance::fromArray( $instanceResource['variable'] );
$this->instanceQNames[ $instance->label ] = $instance->getQName();
// TODO Add any extra instances instance
// $name = $instance['variable']['name'];
// Check there is an instance name in the list of global parameters
$clark = $instance->getQName()->clarkNotation();
// if ( ! isset( $contextParameters[ $clark ] ) )
// {
// XBRL_Log::getInstance()->formula_validation(
// "Instance",
// "A resource that references an instance QName does not exist as a global property",
// array(
// 'QName' => $clark,
// // 'error' => 'xbrlvarinste:missingInstanceProperty'
// 'error' => 'xbrlvarscopee:differentInstances'
// )
// );
// }
// $xbrlInstance = \XBRL_Instance::FromInstanceDocument( $contextParameters[ $clark ] );
// $this->instances[ $clark ] = $xbrlInstance;
}
// // DO NOT DELETE
// // This block is handy to run XPath 2.0 processor debug tests against an instance document
// $formula = new Formula();
// $formula->xbrlInstance = $xbrlInstance;
// $formula->nsMgr = $this->nsMgr;
//
// // $facts = $this->evaluateXPath( $formula, "xfi:non-nil-facts-in-instance(/xbrli:xbrl)[@contextRef]", array() );
// // $facts = $this->evaluateXPath( $formula, "/xbrli:xbrl/concept:c1/@contextRef eq /xbrli:xbrl/concept:n1/@contextRef", array() );
// // $facts = $this->evaluateXPath( $formula, "/", array() );
// // $facts = $this->evaluateXPath( $formula, "/xbrli:xbrl/context[1]/@id", array() );
// // $facts = $this->evaluateXPath( $formula, "/xbrli:xbrl", array() );
// // $facts = $this->evaluateXPath( $formula, "/xbrli:xbrl/xbrli:context[@id=/xbrli:xbrl/context[1]/@id]/entity", array() );
// // $facts = $this->evaluateXPath( $formula, "(for \$unitRef in (concat(/xbrli:xbrl/concept:C1[1]/@unitRef, '')) return \$unitRef)[1] cast as xs:string", array() );
// // $facts = $this->evaluateXPath( $formula, "1 instance of node()", array() );
// // $count = $facts->getCount();
//
// $facts = $this->evaluateXPath( $formula, $query, array() );
// $count = $facts->getCount();
// foreach ( $facts as $fact )
// {
// $x = 1;
// }
// exit();
if ( ! $this->validateCommon( $taxonomy, $contextParameters, null ) )
{
$result = false;
// return false;
}
}
}
return $result;
// return true;
}
/**
* Process any formulas in $taxonomy against the array of instances in $instances
*
* @param XBRL $taxonomy The taxonomy containing the formula linkbase information
* @param array $additionalNamespaces (optional) An array of namespaces indexed by prefix
* These could be from a test cases or other document
* @param array $contextParameters A list of parameters to be added to the context
* @param bool $validateTest True (default) if the variable set tests should be checked. This is slow.
* @return void
*/
public function processFormulasForTaxonomy( $taxonomy, $additionalNamespaces = null, $contextParameters = null, $roleFilterPart = null, $validateTest = true )
{
// BMS 2018-12-13
$schemasWithFormulas = array_filter( $taxonomy->getImportedSchemas(), function( $taxonomy ) use( $roleFilterPart )
{
/** @var \XBRL $taxonomy */
if ( $roleFilterPart && $roleFilterPart != $taxonomy->getNamespace() )
{
return false;
}
return $taxonomy->getHasFormulas();
} );
if ( is_null( $contextParameters ) )
{
$parameters = array();
}
XBRL_Instance::reset();
// $this->startTiming();
// $lastElapsed = 0;
// $lastCount = 0;
$result = true;
foreach ( $schemasWithFormulas as $namespace => $taxonomy )
{
// Begin loading the namespaces
$this->addNamespaces( array( XBRL_Constants::$standardPrefixes, $additionalNamespaces, $taxonomy->getDocumentNamespaces() ) );
// Set the instance
$this->instanceQName = qname( "instances:standard-input-instance", $this->nsMgr->getNamespaces() );
$this->instanceQNames[ $this->instanceQName->localName ] = $this->instanceQName;
$this->instances[ $this->instanceQName->clarkNotation() ] = null;
if ( ! $this->validateCommon( $taxonomy, $contextParameters, null, $validateTest ) )
{
// return false;
$result = false;
}
// $count = \XBRL::array_reduce_key( $this->variableSets, function( $carry, $assertions ) { $carry += count( $assertions ); return $carry; }, 0 );
// $diffCount = $count - $lastCount;
// $elapsed = $this->elapsedTime();
// $diffElapsed = $elapsed - $lastElapsed;
// $lastElapsed = $elapsed;
// $lastCount = $count;
// $perCount = $diffCount ? $diffElapsed / $diffCount : '-';
// error_log( "$diffElapsed $diffCount $perCount $elapsed $namespace" );
}
return $result;
}
/**
* Allows the controller class to pass the expected result node to the test class(es) created
* Returns false if there is no problem or an error string to report if there is.
* @param string $testCaseFolder
* @param array $expectedResultNode The content of the <result> node from the test case.
* The relevant test class will know how to handle its content.
* @return bool|string False if there is no error or a string that describes the failure
*/
public function compareResult( $testCaseFolder, $expectedResultNode )
{
if ( $this->consistencyAssertions )
{
foreach ( $this->consistencyAssertions as $assertionName => $consistencyAssertion )
{
$result = $consistencyAssertion->compareResult( $testCaseFolder, $expectedResultNode );
if ( $result !== false ) return $result;
}
}
// BMS 2018-03-30 Changed this so formulas are compared after any consistency assertion.
// BMS 2018-04-03 But if there have been consistency assertions then only if there is a comparison instance to use
if ( $this->formulaFactsContainer )
{
if ( ( ! $this->consistencyAssertions || $this->formulaFactsContainer->hasInstanceFile( $expectedResultNode ) ) )
{
if ( $this->formulaFactsContainer->compareResult( $testCaseFolder, $expectedResultNode, $this->instances[ $this->instanceQName instanceof \lyquidity\xml\QName ? $this->instanceQName->clarkNotation() : $this->instanceQName ] ) )
{
return false; // False means no error
}
return $this->formulaFactsContainer->comparisonError;
}
}
else
{
foreach ( $this->variableSets as $variableSetQName => $variableSetForQName )
{
foreach ( $variableSetForQName as $variableSet )
{
$result = $variableSet->compareResult( $testCaseFolder, $expectedResultNode );
if ( $result !== false ) return $result;
}
}
}
return false;
}
/**
* Get reference to the facts container
* @return GeneratedFacts
*/
public function getFactsContainer()
{
return $this->formulaFactsContainer;
}
/**
* Process the validations common to all variable sets
* @param XBRL $taxonomy
* @param array $contextParameters A list of the parameter values to be used as sources for formula parameters
* @param string|null $roleFilterPart (optional) Retrict the evaluation of formulas to those with $roleFilterPart in the roleUri
* @param bool $validateTest When true (default) the test will be compiled. If the formulas are not going to be evaluated, it can be quicker to skip this test.
* @return bool
*/
private function validateCommon( $taxonomy, $contextParameters, $roleFilterPart = null, $validateTest = true )
{
// if ( ! $this->validateParameters( $taxonomy, $contextParameters ) )
// {
// return false;
// }
if ( ! $this->validateCustomFunction( $taxonomy ) )
{
return false;
}
if ( ! $this->validateVariableSets( $taxonomy, $contextParameters, $roleFilterPart, $validateTest ) )
{
return false;
}
if ( ! $this->validateConsistencyAssertions( $taxonomy ) )
{
return false;
}
// validate default dimensions in instances and accumulate multi-instance-default dimension aspects (really, look in the contexts)
// check for variable set dependencies across output instances produced
return true;
}
/**
* Creates a namespace manager for a formula processor
* @param array $additionalNamespaces An array of namespace arrays (which is an array of namespaces indexed by prefix)
*/
private function addNamespaces( $additionalNamespaces )
{
// Load any additional namespaces
foreach ( $additionalNamespaces as $namespaces )
{
if ( is_null( $namespaces ) || ! is_array( $namespaces ) )
{
continue;
}
foreach ( $namespaces as $prefix => $namespace )
{
if ( empty( $prefix ) ) continue;
$this->nsMgr->addNamespace( $prefix, $namespace );
}
}
}
/**
* Validate and process parameters (if there are any)
* @param XBRL $taxonomy
* @param array $contextParameters A list of the parameter values to be used as sources for formula parameters
* @param VariableSet $variableSet
* @return bool
*/
private function validateParameters( $taxonomy, $contextParameters, $variableSet )
{
$parameterArcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleVariableSet, $variableSet->extendedLinkRoleUri, null, $variableSet->path, null, $variableSet->linkbase );
// Get any variable sets. These will be headed by a formula.
$parameters = array_filter( $taxonomy->getGenericResource( 'variable', 'parameter', null, null, null /*, $variableSet->linkbase */ ),
function( $resource ) use( $parameterArcs )
{
return count( array_filter( $parameterArcs, function( $arc ) use( $resource )
{
return $arc['tolinkbase'] == $resource['linkbase'];
} ) ) > 0;
}
);
// Check there are parameters to process
if ( ! $parameters ) return true;
$parameterDependencies = array();
foreach ( $parameters as $parameterReference )
{
/** @var Parameter $parameter */
$parameter = Parameter::fromArray( $parameterReference['variable'] );
if ( ! $parameter )
{
$this->log->err( "Failed to create Parameter instance from an array" );
return false;
}
if ( $parameter->path != $variableSet->path ) continue;
if ( ! $parameter->validate( null, $this->nsMgr ) )
{
return false;
}
$parameterDependencies[ $parameter->getQName()->clarkNotation() ] = $parameter->getVariableRefs();
$this->parameterQnames[ $parameter->getQName()->clarkNotation() ] = $parameter;
$variableSet->parameters[ $parameter->getQName()->clarkNotation() ] = $parameter;
}
/**
* Examines parameter dependcies
* @var Closure $hasCircularReference
*/
$parameterQnames = $this->parameterQnames;
$hasCircularReference = function( $dependencies, $history = array() ) use( &$hasCircularReference, $parameterDependencies, $parameterQnames )
{
foreach ( $dependencies as /** @var QName $dependency */ $dependency )
{
// Check if this is a cyclic reference
if ( in_array( $dependency, $history ) )
{
$this->log->formula_validation( 'Variable parameter', 'Cyclic dependencies in parameter names to names dependencies', array(
'parameter' => end( $history ),
'dependency' => $dependency->clarkNotation(),
'error' => 'xbrlve:parameterCyclicDependencies'
) );
return true;
}
// The dependency MUST appear in $parameterQnames or it is undefined
if ( ! isset( $parameterQnames[ $dependency->clarkNotation() ] ) )
{
$this->log->formula_validation( 'Variable parameter', 'Undefined dependencies in parameter to names dependencies', array(
'parameter' => end( $history ),
'dependency' => $dependency->clarkNotation(),
'error' => 'xbrlve:unresolvedDependency'
) );
return true;
}
// Look for the dependency in $parameterDependencies
if ( ! isset( $parameterDependencies[ $dependency->clarkNotation() ] ) )
{
continue;
}
// Check the next dependencies
$history[] = $dependency->clarkNotation();
if ( $hasCircularReference( $parameterDependencies[ $dependency->clarkNotation() ], $history ) )
{
return true;
}
}
return false;
};
// Perform the dependency check
foreach ( $parameterDependencies as $qname => $dependencies )
{
if ( $hasCircularReference( $dependencies, array( $qname ) ) )
{
return false;
}
}
// Check there is a context parameter for each formula parameter that is marked as required
foreach ( $this->parameterQnames as $clark => /** @var Parameter $parameter */ $parameter )
{
// If the parameter references a qname from the the instance then there is nothing to do here
if ( $taxonomy->getElementByName( $parameter->getQName()->localName ) ) continue;
try
{
// Check to see if the parameter is one of the context (passed in) parameters
if ( isset( $contextParameters[ $clark ] ) )
{
// Test the compatibility of the context parameter type and value
$parameter->select = $contextParameters[ $clark ]['value'];
$expression = XPath2Expression::Compile( "{$contextParameters[ $clark ]['datatype']}({$contextParameters[ $clark ]['value']}) cast as {$contextParameters[ $clark ]['datatype']}", $this->nsMgr );
$value = $expression->EvaluateWithVars( null, array() );
$parameter->expression = $expression;
// Now check the $value type is compatible with the parameter type.
// The evaluation step will throw an exception if not
if ( $parameter->as )
{
$expression = XPath2Expression::Compile( "\$value cast as {$parameter->as}", $this->nsMgr );
$result = $expression->EvaluateWithVars( null, array( 'value' => $value ) );
// Replace with casted expression if valid
// $parameter->expression = $expression;
}
}
else if ( $parameter->required )
{
$this->log->formula_validation( 'Variable parameter', 'Parameter is required but not input', array(
'parameter' => $clark,
'error' => 'xbrlve:missingParameterValue'
) );
return false;
}
else if ( ! isset( $parameter->select ) || ! strlen( $parameter->select ) )
{
$this->log->formula_validation( 'Variable parameter', 'Parameter does not have a select attribute', array(
'parameter' => $clark,
'error' => 'xbrlve:missingParameterValue'
) );
return false;
}
}
catch ( Exception $ex )
{
$this->log->formula_validation( 'Variable parameter', 'The input parameter type is not valid', array(
'parameter' => $clark,
'cause' => $ex->getMessage(),
'error' => 'xbrlve:parameterTypeMismatch'
) );
return false;
}
}
// TODO This needs to be checked
// There should be no dependencies so this routine should resolve all parameter expressions to result values.
$parameters = $this->parameterQnames;
while ( $parameters )
{
// Get the first parameter
$parameter = reset( $parameters );
unset( $parameters[ key( $parameters ) ] );
// Get a list of dependencies for this parameter
$dependencies = $parameter->getVariableRefs();
$vars = array();
// Make sure that each dependency has been evaluated
foreach ( $dependencies as $qname => $dependentQName )
{
if ( ! isset( $this->parameterQnames[ $dependentQName->clarkNotation() ] ) )
{
continue;
}
$dependentParameter = $this->parameterQnames[ $dependentQName->clarkNotation() ];
if ( ! $dependentParameter->result ) continue;
$vars[ $dependentParameter->name ] = $dependentParameter->result;
}
try
{
$result = $parameter->expression->EvaluateWithVars( null, $vars );
$parameter->result = $result;
}
catch ( Exception $ex )
{
$this->log->formula_validation( 'Variable parameter', 'Parameter type is not valid', array(
'parameter' => $parameter->getQName()->clarkNotation(),
'select' => $parameter->getSelectAsExpression(),
'as' => $parameter->as,
'cause' => $ex->getMessage(),
'error' => 'xbrlve:parameterTypeMismatch'
) );
}
}
return true;
}
/**
* Process and validate any instances defined. The default instances is
* passed in automatically and is associated with the parameter with QNme
* '{http://xbrl.org/2010/variable/instance"}standard-input-instance'
* so ignore it.
* @param XBRL $taxonomy
* @param array $contextParameters A list of the parameter values to be used as sources for formula parameters
* @return bool
*/
/**
* Process and validate the variables in the current taxonomy
* @param XBRL $taxonomy
* @param array $contextParameters
* @param string|null $roleFilterPart (optional) Retrict the evaluation of formulas to those with $roleFilterPart in the roleUri
* @return bool
*/
private function validateVariableSets( $taxonomy, $contextParameters, $roleFilterPart = null, $validateTest = true )
{
// Variable sets are headed by a formula or assertion
$variableSets = $taxonomy->getGenericResource( 'variableset', null );
if ( $variableSets )
foreach ( $variableSets as $variableSet )
{
if ( $roleFilterPart )
{
if ( strpos( $variableSet['roleUri'], $roleFilterPart ) === false ) continue;
}
$variableSetResource = $variableSet['variableset'];
// Workout the class for this variable set resource
$element = $variableSetResource[ "{$variableSetResource['type']}Type" ];
$variableSetClassName = '\\XBRL\\Formulas\\Resources\\' .
Formulas::$formulaElements[ $element ]['part'] .
( isset( Formulas::$formulaElements[ $element ]['className'] )
? Formulas::$formulaElements[ $element ]['className']
: ucfirst( $element )
);
if ( is_null( $variableSetClassName ) )
{
$this->log->err( "Variable set sub-type '{$variableSetResource['type']}Type' is not valid" );
return false;
}
// Create the instance and store it
/** @var VariableSet $variableSetInstance */
unset( $variableSetInstance );
$variableSetInstance = $variableSetClassName::fromArray( $variableSetResource );
$variableSetInstance->instanceName = $this->instanceQName; // Set a default. It may be overridden by an instance arc
$variableSetInstance->xbrlTaxonomy = $taxonomy;
$variableSetInstance->extendedLinkRoleUri = $variableSet['roleUri'];
$variableSetInstance->linkbase = $variableSet['linkbase'];
$this->variableSets[ "{$variableSet['roleUri']}#{$variableSet['resourceName']}" ][] =& $variableSetInstance;
$linkbaseInfo = $taxonomy->getLinkbase( $variableSet['linkbase'] );
if ( $linkbaseInfo )
{
$this->addNamespaces( array( $linkbaseInfo['namespaces'] ) );
}
$this->validateLabels( $taxonomy, $variableSetInstance, $taxonomy->getDefaultLanguage() );
$this->validateParameters( $taxonomy, $contextParameters, $variableSetInstance );
// Find all variables related to this variable set
$instanceArcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleFormulaInstance, $variableSet['roleUri'], $variableSet['resourceName'], $variableSetInstance->path, $variableSetInstance->linkbase );
foreach ( $instanceArcs as $instanceArc )
{
if ( $instanceArc['from'] != $variableSetInstance->label ) continue;
// Look for the instance resource
if ( ! isset( $this->instanceQNames[ $instanceArc['label'] ] ) ) continue;
$variableSetInstance->instanceName = $this->instanceQNames[ $instanceArc['label'] ];
}
// Find all variables related to this variable set
$variableSetArcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleVariableSet, $variableSet['roleUri'], $variableSet['resourceName'], $variableSetInstance->path /* , $variableSetInstance->linkbase */ );
$variableResources = array();
foreach ( $variableSetArcs as $arcIndex => $variableSetArc )
{
if ( $variableSetArc['fromlinkbase'] != $variableSetInstance->linkbase ) continue;
if ( $variableSetInstance->path != $variableSetArc['frompath'] ) continue;
$result = $taxonomy->getGenericResource( 'variable', null, function( $roleUri, $linkbase, $variableSetName, $index, $resource ) use( &$variableResources, $variableSetArc )
{
// This test is probably redundant because I believe $variableSetName is the same as $variableSetArc['label']
if ( /* $linkbase == $variableSetArc['tolinkbase'] && */ $resource['path'] == $variableSetArc['topath'] && $variableSetName == $variableSetArc['label'] )
{
$resource['name'] = $variableSetArc['name'];
$resource['linkbase'] = $linkbase;
$variableResources[ $variableSetName ][] = $resource;
}
return true;
}, $variableSetArc['toRoleUri'], $variableSetArc['to'], $variableSetArc['tolinkbase'] );
}
// Process each located variable resource
foreach ( $variableResources as $variableLabel => $variableResourceSet )
{
foreach ( $variableResourceSet as $variableResource )
{
// if ( $variableSetInstance->path != $variableResource['path'] )
// continue;
if ( $variableResource['variableType'] == 'parameter' )
{
// Find the parameter with label $variableResource['label']. This becomes
// the parameter with qname $variableResource['name']
$resourceQName = new QName( $variableResource['name']['originalPrefix'], $variableResource['name']['namespace'], $variableResource['name']['name'] );
foreach ( $this->parameterQnames as $qname => $parameter )
{
if ( $parameter->label == $variableResource['label'] )
{
// BMS 2018-03-23 One test too many
// if ( $qname == $resourceQName->clarkNotation() )
{
$variableSetInstance->parameters[ $resourceQName->clarkNotation() ] = $this->parameterQnames[ $qname ];
}
break;
}
}
continue;
}
$variableClassName = '\\XBRL\\Formulas\\Resources\\' .
Formulas::$formulaElements[ $variableResource['variableType'] ]['part'] .
( isset( Formulas::$formulaElements[ $variableResource['variableType'] ]['className'] )
? Formulas::$formulaElements[ $variableResource['variableType'] ]['className']
: ucfirst( $variableResource['variableType'] )
);
if ( is_null( $variableClassName ) )
{
$this->log->formula_validation( "Variables", "Invalid variable type",
array(
'variable type' => $variableResource['variableType'],
)
);
return false;
}
/** @var Variable $variable */
$variable = $variableClassName::fromArray( $variableResource );
$variable->extendedLinkRoleUri = $variableResource['linkRoleUri'];