-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnnotationGenerator.php
More file actions
2022 lines (1792 loc) · 85.2 KB
/
AnnotationGenerator.php
File metadata and controls
2022 lines (1792 loc) · 85.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
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
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
declare(strict_types=1);
namespace Piwik\Plugins\OpenApiDocs\Annotations;
use Matomo\Dependencies\OpenApiDocs\phpDocumentor\Reflection\DocBlock\Description;
use Matomo\Dependencies\OpenApiDocs\phpDocumentor\Reflection\DocBlock\Tags\Param;
use Matomo\Dependencies\OpenApiDocs\phpDocumentor\Reflection\DocBlock\Tags\TagWithType;
use Matomo\Dependencies\OpenApiDocs\phpDocumentor\Reflection\DocBlockFactory;
use Piwik\Exception\PluginNotFoundException;
use Piwik\API\DocumentationGenerator;
use Piwik\API\NoDefaultValue;
use Piwik\API\Proxy;
use Piwik\API\Request;
use Piwik\Http;
use Piwik\Piwik;
use Piwik\Plugin\Manager;
use Piwik\Plugins\OpenApiDocs\Artifact\ArtifactWriter;
use Piwik\Plugins\OpenApiDocs\OpenApiDocs;
use Piwik\Plugins\OpenApiDocs\Specs\PathResolver;
use Piwik\SettingsPiwik;
use Piwik\Url;
use Piwik\UrlHelper;
use Piwik\Validators\BaseValidator;
use Piwik\Validators\NotEmpty;
class AnnotationGenerator
{
public const EXAMPLE_CHAR_LIMIT = 3000;
public const GLOBAL_PARAMETER_NAMES = [
'idSite',
'period',
'date',
'segment',
'expanded',
'idSubtable',
'flat',
'filter_pattern',
'filter_column',
'filter_pattern_recursive',
'filter_column_recursive',
'filter_excludelowpop',
'filter_excludelowpop_value',
'filter_sort_column',
'filter_sort_order',
'filter_truncate',
'filter_limit',
'filter_offset',
'keep_summary_row',
'disable_generic_filters',
'disable_queued_filters',
'hideColumns',
'showColumns',
'label',
'idGoal',
];
/**
* @var string
*/
protected $currentPluginDir;
/**
* @var DocumentationGenerator
*/
protected $generator;
/**
* @var PathResolver
*/
protected $pathResolver;
/**
* @var ArtifactWriter
*/
protected $artifactWriter;
/**
* @var array[]
*/
protected $reportMetadata;
/**
* @var array[]
*/
protected $missingImportantDataWarnings;
/**
* @var bool
*/
protected $allowLocalRequests;
public function __construct(
DocumentationGenerator $generator,
?PathResolver $pathResolver = null,
?ArtifactWriter $artifactWriter = null,
bool $allowLocalRequests = false
) {
$this->generator = $generator;
$this->pathResolver = $pathResolver ?? new PathResolver();
$this->artifactWriter = $artifactWriter ?? new ArtifactWriter();
$this->missingImportantDataWarnings = [];
$this->allowLocalRequests = $allowLocalRequests;
$this->currentPluginDir = Manager::getInstance()::getPluginDirectory('OpenApiDocs');
}
/**
* Generate all the annotations for a plugin's public API endpoints and return them as an array of strings. A string
* for each line to be output or written to file.
*
* @param string $pluginName The name of the plugin. E.g. TagManager
* @param bool $writeToFile Indicate whether the results should be written to file. Default is false so that a dry
* run won't affect the file-system.
*
* @return string[]|array[] The collection of all the lines which make up the generated annotations for the public API
* endpoints defined by the plugin.
* @throws PluginNotFoundException If the plugin is not present in the filesystem.
* @throws \Throwable
*/
public function generatePluginApiAnnotations(string $pluginName, bool $writeToFile = false): array
{
BaseValidator::check('plugin', $pluginName, [new NotEmpty()]);
if (in_array($pluginName, OpenApiDocs::PLUGIN_BLOCKLIST, true)) {
throw new \RuntimeException('OpenAPI doc generation is blocked for ' . $pluginName . '.');
}
if (!Manager::getInstance()->isPluginInFilesystem($pluginName)) {
throw new PluginNotFoundException($pluginName);
}
$rules = require $this->currentPluginDir . '/Annotations/config.php';
$pluginAnnotationPath = $this->pathResolver->getAnnotationFilePath($pluginName);
$className = Request::getClassNameAPI($pluginName);
try {
$reflectionClass = new \ReflectionClass($className);
} catch (\ReflectionException $e) {
return [];
}
Proxy::getInstance()->registerClass($className);
$pluginMetadata = Proxy::getInstance()->getMetadata()[$className] ?? [];
$annotations = [[sprintf('@OA\Tag(name="%s")', $pluginName)]];
if (!empty($pluginMetadata['__documentation'])) {
$tagLines = $this->buildLinesForAnnotationObject('@OA\Tag', [
sprintf('name="%s"', $pluginName),
sprintf('description="%s"', $this->normaliseDescriptionText($pluginMetadata['__documentation'])),
]);
$this->removeTrailingCommaFromLastLine($tagLines);
$annotations[] = $tagLines;
}
foreach (array_keys($pluginMetadata) as $metadataMethod) {
if (!$reflectionClass->hasMethod($metadataMethod)) {
continue;
}
$methodAnnotations = $this->buildAnnotationForMethod($rules, $pluginName, $reflectionClass->getMethod($metadataMethod));
if (empty($methodAnnotations)) {
continue;
}
$annotations[] = $methodAnnotations;
}
if ($writeToFile) {
$this->writeAnnotationsToFile($annotations, $pluginAnnotationPath, $pluginName);
}
if (count($this->missingImportantDataWarnings) === 0) {
return $annotations;
}
$lines = [];
foreach ($this->missingImportantDataWarnings as $methodName => $warnings) {
if (empty($warnings)) {
continue;
}
$lines[] = $methodName . ' has the following warnings:';
foreach ($warnings as $paramName => $warningLines) {
if (empty($warningLines)) {
continue;
}
$lines[] = '- ' . $paramName . ':';
$lines[] = " - " . implode("\n - ", $warningLines);
}
}
return $lines;
}
/**
* Write the collection of annotation lines to file, overwriting the file if it already exists.
*
* @param array[] $annotations Collection of generated annotations. It's an array of arrays containing the lines
* which make up all the annotations which need to be written to file.
* @param string $pluginName Name of the plugin. E.g. TagManager
*
* @return string The full string content of the generated annotations file.
*/
public function getContentForGeneratedAnnotationsFile(array $annotations, string $pluginName): string
{
$lines = [
'<?php',
'',
'namespace Piwik\\Plugins\\OpenApiDocs\\tmp\\annotations;',
'',
'/**',
];
foreach ($annotations as $annotation) {
foreach ($annotation as $line) {
$lines[] = ' * ' . $line;
}
}
$lines = array_merge($lines, [
' */',
"class {$pluginName}GeneratedAnnotations",
'{',
'',
'}',
]);
// Return the fully assembled content for the generated annotations file
return implode(PHP_EOL, $lines);
}
/**
* Write the collection of annotation lines to file, overwriting the file if it already exists.
*
* @param array[] $annotations Collection of generated annotations. It's an array of arrays containing the lines
* which make up all the annotations which need to be written to file.
* @param string $filePath Full path of the file to be overwritten with the annotations.
* @param string $pluginName Name of the plugin. E.g. TagManager
*
* @return false|int Indicating how much was written to file.
* @see file_put_contents To explain the return value.
*/
protected function writeAnnotationsToFile(array $annotations, string $filePath, string $pluginName)
{
return $this->writeFile($filePath, $this->getContentForGeneratedAnnotationsFile($annotations, $pluginName));
}
/**
* Build the full array of lines for an OA operation, like OA\Get or OA\Post. This pulls data from various sources,
* including making API calls to get example responses.
*
* @param array $rules An array of configs determining which responses to include by default.
* @param string $pluginName Name of the plugin. E.g. TagManager.
* @param \ReflectionMethod $reflectionMethod The reflective representation of the method to provide metadata.
*
* @return array
* @throws \Throwable
*/
protected function buildAnnotationForMethod(array $rules, string $pluginName, \ReflectionMethod $reflectionMethod): array
{
// Skip methods which have been marked as internal or auto annotations disabled
if (self::shouldApiMethodBeIgnored($reflectionMethod)) {
return [];
}
$methodName = $reflectionMethod->getName();
$opId = Proxy::getInstance()->buildApiActionName($pluginName, $methodName);
$path = $this->buildVirtualPath(
$rules['virtualPathTemplate'] ?? '/' . $opId,
$pluginName,
$methodName
);
$params = $this->determineParameters($rules, $pluginName, $methodName, $reflectionMethod);
$responses = $this->determineResponses($rules, $pluginName, $methodName, $reflectionMethod, $params);
$description = $this->determineDescription($pluginName, $methodName, $reflectionMethod);
$isPost = !empty($rules['plugins'][$pluginName]['methodsRequiringPost'])
&& in_array($methodName, $rules['plugins'][$pluginName]['methodsRequiringPost']);
return $this->compileOperationLines($path, $opId, $pluginName, $params, $responses, $description, $isPost);
}
/**
* Check whether the method should be included in public documentation, or it's been marked as internal or similar.
*
* @param \ReflectionMethod $reflectionMethod Reflection method used to check the comment block for annotations.
*
* @return bool Whether the API method should be ignored while generating documentation, like being marked as
* internal, hide, deprecated, etc.
*/
public static function shouldApiMethodBeIgnored(\ReflectionMethod $reflectionMethod): bool
{
$existing = $reflectionMethod->getDocComment();
// Skip methods which have been marked as internal or hide
if (
$existing !== false
&& (
stripos($existing, '@internal') !== false
|| stripos($existing, '@hide') !== false
|| stripos($existing, '@deprecated') !== false
|| stripos($existing, '@ignore') !== false
)
) {
return true;
}
return false;
}
/**
* Try to extract the list of parameters and key information about them from the method's doc block string.
*
* @param string $docBlock The comment block from a method, which hopefully contains the param annotations.
*
* @return array Of each param provided in the comment block and key information about them like the type and
* description, if available. The array can be empty if there are no param annotations present. E.g.
* ['idSite' => ['type' => 'integer', 'description' => 'Site ID'], 'date' => ['type' => 'string', 'description' => '']]
*/
public function getParamInfoFromDocBlock(string $docBlock): array
{
$factory = DocBlockFactory::createInstance();
$docBlockObject = $factory->create($docBlock);
$params = [];
foreach ($docBlockObject->getTagsByName('param') as $param) {
if (!($param instanceof Param)) {
continue;
}
$name = ltrim($param->getVariableName(), '$');
$params[$name] = [
'type' => (string) $param->getType(),
// Normalise the description. E.g. remove linebreaks and indentation
'description' => trim(preg_replace(['/^\h+/m', '/\R+/u',], ['', ' '], (string) $param->getDescription())),
'byRef' => $param->isReference(),
'variadic' => $param->isVariadic(),
];
}
return $params;
}
/**
* Try to extract the response-type of a method from the doc block string.
*
* @param string $docBlock The comment block from a method, which hopefully contains the return annotation.
*
* @return array The collection of key information about the method's return type if any is found.
* E.g. ['type' => 'integer', 'description' => 'The ID of the newly created report.'] or ['type' => null] if no
* return annotation is present.
*/
public function getResponseInfoFromDocBlock(string $docBlock): array
{
$factory = DocBlockFactory::createInstance();
$docBlockObject = $factory->create($docBlock);
$responseInfo = ['type' => null];
$returnTags = $docBlockObject->getTagsByName('return');
if (empty($returnTags) || !($returnTags[0] instanceof TagWithType)) {
return $responseInfo;
}
$returnTag = $returnTags[0];
$tagValue = strval($returnTag->getType());
$responseInfo['type'] = $this->getOpenApiTypeFromPhpType($tagValue);
if ($responseInfo['type'] === 'string' && !empty($tagValue) && strtolower($tagValue) !== 'string') {
$responseInfo['type'] = '';
$responseInfo['description'] = 'Response of unknown type';
}
if (!empty($returnTag->getDescription())) {
$responseInfo['description'] = $this->getDescriptionText($returnTag->getDescription());
}
return $responseInfo;
}
/**
* Extract the description/summary from a given docblock
*
* @param string $docBlock The comment block from a method, which hopefully contains a description.
*
* @return string Description/summary extracted from the docblock
*/
public function getDescriptionFromDocBlock(string $docBlock): string
{
$factory = DocBlockFactory::createInstance();
$docBlockObject = $factory->create($docBlock);
return $docBlockObject->getSummary();
}
/**
* This is a helper method for building the path used for an operation annotation. It takes a path template, like
* the one from the config array and populates it with the plugin name and API method name.
*
* @param string $virtualPathTemplate The template of what the path should be.
* E.g. /index.php?module=API&method={plugin}.{method}
* @param string $plugin The name of the plugin. E.g. TagManager
* @param string $method The name of the API method. E.g. getCustomReport
*
* @return string The finalised path to be used in an operation annotation.
* E.g. /index.php?module=API&method=CustomReports.getConfiguredReport
*/
public function buildVirtualPath(string $virtualPathTemplate, string $plugin, string $method): string
{
return str_replace(['{plugin}', '{method}'], [$plugin, $method], $virtualPathTemplate);
}
/**
* Build the key data for the specified parameter. This should be all the data necessary to create an OA\Parameter
* annotation object.
*
* @param string $methodName The name of the method. E.g. getAlert
* @param string $paramName The name of the parameter. E.g. idSite or period
* @param array $paramMetadata The collection of metadata from the old DocumentationGenerator class. Things like
* whether the parameter is typed, is required, or has a default value.
* @param array $paramDocInfo The collection of parameter information built from the method doc block. This is
* especially useful when the metadata wasn't able to determine the type. We can check the param annotation for the
* type and description.
*
* @return array The array of key information about the parameter like the type (types if more than one is hinted),
* the name, whether it's required, default value, and example. Since there may be more than one type from the doc
* block, the type is specified as a 'types' array even if there's only one type. E.g.
* [
* 'name' => 'idSite',
* 'types' => ['integer' => null, 'string' => null],
* 'description' => 'The ID of the site.',
* 'required' => 'true', // It's a string here, but gets converted to boolean in the annotation.
* 'default' => '\Piwik\API\NoDefaultValue', // This class name indicates no default value since falsy values might be valid.
* 'example' => 1,
* ]
*/
public function buildParameterAnnotationData(string $methodName, string $paramName, array $paramMetadata, array $paramDocInfo): array
{
$docType = strtolower(trim($paramDocInfo['type'] ?? ''));
if (empty($docType)) {
$this->addMissingImportantDataWarning($methodName, $paramName, 'Type is not specified in comment block.');
}
$metaType = strtolower(trim($paramMetadata['type'] ?? $docType));
$type = in_array($metaType, ['string', 'bool']) && !empty($docType) && $docType !== $metaType ? $docType : $metaType;
// Sometimes, doc-block can wrap type hinting with parenthesis. Remove them.
$type = trim($type, '()');
// If the signature type is array, but the type hinting provides more, use that instead
if ($type === 'array' && strpos($docType, '[]') !== false && strpos($docType, '|') === false) {
$type = $docType;
}
$typesMap = [];
// Check for pipes and try to list possible types
$typeHints = array_map(function ($typeHint) {
return trim($typeHint);
}, explode('|', $type));
// If there's more than 1 type hinted and one is bool, remove bool. This is because many params default to false regardless of expected type
if (count($typeHints) > 1 && in_array('bool', $typeHints)) {
$typeHints = array_diff($typeHints, ['bool']);
}
$allTypeHintsAreStringLiterals = $this->areAllTypeHintsStringLiterals($typeHints);
$enumValues = [];
if ($allTypeHintsAreStringLiterals) {
$typesMap['string'] = null;
foreach ($typeHints as $typeHint) {
$enumValues[] = trim(trim($typeHint), '\'"');
}
} else {
foreach ($typeHints as $typePart) {
$typePart = trim($typePart, ' ()');
$normalisedType = $this->getOpenApiTypeFromPhpType($typePart);
// If the type is array, check if there's a subType
$subType = null;
if ($normalisedType === 'array' && $typePart !== 'array' && strpos($typePart, '[]') !== false) {
$subType = substr($typePart, 0, strpos($typePart, '[]'));
}
$typesMap[$normalisedType] = $subType !== null ? $this->getOpenApiTypeFromPhpType($subType) : $subType;
}
}
$isRequired = !key_exists('default', $paramMetadata) || $paramMetadata['default'] instanceof NoDefaultValue;
$description = $paramDocInfo['description'] ?? '';
if (empty($description)) {
$this->addMissingImportantDataWarning($methodName, $paramName, 'Description is not specified in comment block.');
}
$example = '';
// Check the description for the example value
if (preg_match('/\[@example\s*=\s*([^\n]+)\]/', $description, $m)) {
if ($m[1] !== '') {
$example = $m[1];
}
// Remove the example from the description and trim any excess whitespace
$description = trim(str_replace($m[0], '', $description));
// Trim any excess whitespace and surrounding quotes from the example
$example = trim($example);
$example = trim($example, '"');
}
// Clean up the descriptions a little more like removing linebreaks and escaping double-quotes
$description = $this->normaliseDescriptionText($description);
$default = $paramMetadata['default'] ?? null;
if (!is_string($default)) {
$default = json_encode($default);
}
$paramData = [
'name' => $paramName,
'types' => $typesMap,
'description' => $description,
'required' => $isRequired ? 'true' : 'false',
'default' => !$isRequired ? $default : NoDefaultValue::class,
'example' => $example,
];
if (!empty($enumValues)) {
$paramData['enum'] = $enumValues;
}
return $paramData;
}
/**
* Determine whether all type hints are quoted string literals.
*
* @param array $typeHints
*
* @return bool
*/
protected function areAllTypeHintsStringLiterals(array $typeHints): bool
{
if (empty($typeHints)) {
return false;
}
foreach ($typeHints as $typeHint) {
$typeHint = trim(strval($typeHint));
$firstChar = $typeHint[0] ?? '';
$lastChar = $typeHint[strlen($typeHint) - 1] ?? '';
if (!(($firstChar === "'" && $lastChar === "'") || ($firstChar === '"' && $lastChar === '"'))) {
return false;
}
}
return true;
}
/**
* Take description text and normalise it. This includes trimming surrounding whitespace, removing newlines and
* escaping double-quote characters.
*
* @param string $description
*
* @return string
*/
protected function normaliseDescriptionText(string $description): string
{
$description = str_replace("\n", ' ', trim($description));
return str_replace('"', '""', $description);
}
/**
* Normalise phpDocumentor description values into plain strings.
*
* @param mixed $description
*
* @return string
*/
protected function getDescriptionText($description): string
{
if ($description instanceof Description) {
return $description->getBodyTemplate();
}
return is_string($description) ? $description : '';
}
/**
* Add an entry to the map of warnings about missing important information, like type and description of parameters
* and returns.
*
* @param string $methodName Name of the method to more easily identify where in the code needs adjustment.
* @param string $paramName Name of the parameter or "return" for the response. E.g. idSite, period, return, ...
* @param string $message Message indicating what is missing. E.g. "Type is not specified in comment block."
*
* @return void
*/
protected function addMissingImportantDataWarning(string $methodName, string $paramName, string $message): void
{
// Make sure that the inner arrays have been initialised and then add the message to the warning map
$this->missingImportantDataWarnings[$methodName] = $this->missingImportantDataWarnings[$methodName] ?? [];
$this->missingImportantDataWarnings[$methodName][$paramName] = $this->missingImportantDataWarnings[$methodName][$paramName] ?? [];
$this->missingImportantDataWarnings[$methodName][$paramName][] = $message;
}
/**
* Remove a warning from the collection. This is useful when it's determined after the fact that a parameter has
* a global component which can be used, like idSite or period.
*
* @param string $methodName Name of the method.
* @param string $paramName Name of the parameter or "return" for the response. E.g. idSite, period, return, ...
*
* @return void
*/
protected function removeMissingImportantDataWarning(string $methodName, string $paramName): void
{
if (empty($this->missingImportantDataWarnings[$methodName][$paramName])) {
return;
}
// If it's the only param in the collection for the method, remove the method
if (count($this->missingImportantDataWarnings[$methodName]) === 1) {
unset($this->missingImportantDataWarnings[$methodName]);
return;
}
unset($this->missingImportantDataWarnings[$methodName][$paramName]);
}
/**
* Build the collection of parameters and key information about them for the specified method.
*
* @param array $rules An array of configs determining which responses to include by default.
* @param string $plugin Name of the plugin. E.g. TagManager.
* @param string $method The name of the method being annotated.
* @param \ReflectionMethod $reflectionMethod The reflective representation of the method to provide metadata.
*
* @return array List of each method parameter and key data points like the data type, whether it's required,
* default value, and example value.
* @see self::buildParameterAnnotationData() where the parameter data is built.
*/
protected function determineParameters(array $rules, string $plugin, string $method, \ReflectionMethod $reflectionMethod): array
{
$refs = [];
if (!empty($rules['defaultParamRefs'])) {
$refs = array_merge($refs, $rules['defaultParamRefs']);
}
if (isset($rules['plugins'][$plugin]['paramRefsByMethod'][$method])) {
$refs = array_merge($refs, $rules['plugins'][$plugin]['paramRefsByMethod'][$method]);
}
$paramsMetadata = Proxy::getInstance()->getParametersListWithTypes(Request::getClassNameAPI($plugin), $method);
$paramsInfo = [];
$docBlock = $reflectionMethod->getDocComment();
if (!empty($docBlock)) {
$paramsInfo = $this->getParamInfoFromDocBlock($docBlock);
}
$customParams = [];
foreach ($paramsMetadata as $name => $paramMetadata) {
$paramInfo = $paramsInfo[$name] ?? [];
// Skip references and variadic for now
// TODO - determine whether these can be handled automatically or if they have to be manual
if (!empty($paramInfo['byRef']) || !empty($paramInfo['variadic'])) {
continue;
}
// If the parameter doesn't have a description and matches a global, use a reference to the global instead.
$customParamData = $this->buildParameterAnnotationData($method, $name, $paramMetadata, $paramInfo);
if (empty($customParamData['description']) && in_array($name, self::GLOBAL_PARAMETER_NAMES)) {
$globalParamSuffix = $customParamData['required'] === 'true' ? 'Required' : 'Optional';
$paramRef = '#/components/parameters/' . $name . $globalParamSuffix;
$customParams[] = $paramRef;
$this->removeMissingImportantDataWarning($method, $name);
// Remove any duplicates from the global references array.
if (count($refs) > 0 && in_array($paramRef, $refs)) {
$refs = array_diff($refs, [$paramRef]);
}
continue;
}
$customParams[] = $customParamData;
}
return [
'refs' => array_values(array_unique($refs)),
'custom' => $customParams,
];
}
/**
* Get the description/summary of a given method
*
* @param string $plugin Name of the plugin. E.g. TagManager.
* @param string $method The name of the method being annotated.
* @param \ReflectionMethod $reflectionMethod The reflective representation of the method to provide metadata.
*
* @return string Description of the method
*/
protected function determineDescription(string $plugin, string $method, \ReflectionMethod $reflectionMethod): string
{
$description = '';
$docBlock = $reflectionMethod->getDocComment();
if (!empty($docBlock)) {
$description = $this->getDescriptionFromDocBlock($docBlock);
}
return $description;
}
/**
* Map the PHP type to the OpenAPI type. The currently available types for v3.1.1 are the following: “null”,
* “boolean”, “object”, “array”, “number”, “string”, or “integer”.
*
* @link https://spec.openapis.org/oas/v3.1.1.html#data-types
*
* @param string $type The PHP type from the method signature or doc-block
*
* @return string The normalised Data Type to be used in the swagger-php annotation
*/
public function getOpenApiTypeFromPhpType(string $type): string
{
// TODO - Is there a good way to handle object type or should that always be ref?
// TODO - Eventually handle the Data Type Formats: https://spec.openapis.org/oas/v3.1.1.html#data-type-format
switch (strtolower($type)) {
case 'array':
case '[]':
case 'int[]':
case 'string[]':
case 'bool[]':
case 'float[]':
case 'double[]':
$type = 'array';
break;
case 'int':
case 'integer':
$type = 'integer';
break;
case 'bool':
case 'boolean':
$type = 'boolean';
break;
case 'float':
case 'double':
$type = 'number';
break;
case 'void':
$type = 'null';
break;
default:
$type = 'string';
}
return $type;
}
/**
* Try to build example URLs for a specific API method. This uses the old DocumentationGenerator to build the same
* example URLs which have been available on the API documentation page for a long time. E.g. XML, JSON, and TSV.
* Unlike the old documentation, this only includes URLs if a valid response was received from the demo server or
* local Matomo instance. For example, some endpoints respond that the data structure is not TSV compatible and the
* old documentation would still include the link. This shows 'TSV (N/A)' in those instances.
*
* @param string $pluginName The name of the plugin. E.g. TagManager.
* @param string $methodName The name of the plugin specific API method. E.g. getCustomReport.
* @param array[] $paramsData The collection of parameter data compiled using reflection and metadata. This includes
* types, default values, and examples. It can be used to build URLs using required parameters which aren't globals,
* like idSite and period which have established example values.
*
* @return array The example URLs with only the required query parameters and only if a valid example responses were
* received when the URL was queried. Empty string if no URL could be determined or no valid response was received.
* E.g. ['xml => 'https://demo...&format=xml', 'json' => 'https://demo...&format=JSON', 'tsv' => 'https://demo...&format=Tsv']
* @throws \Throwable
*/
protected function getApplicableDemoExampleUrls(string $pluginName, string $methodName, array $paramsData): array
{
// Get the example URLs for the success responses
$parametersToSet = [
'idSite' => 1,
'period' => 'day',
'date' => 'today',
];
// Don't build example URLs for anything that isn't the R in CRUD. E.g. No create, update, or delete.
$notAllowedExampleUrlOperations = ['create', 'add', 'save', 'set', 'update', 'delete', 'remove', 'copy', 'duplicate'];
foreach ($notAllowedExampleUrlOperations as $operation) {
if (stripos($methodName, $operation) === 0) {
return [];
}
}
$parametersToReplace = [];
if (!empty($paramsData['custom'])) {
foreach ($paramsData['custom'] as $customParam) {
// Skip any which might be references.
if (!is_array($customParam)) {
continue;
}
$paramName = strval($customParam['name']);
if (isset($customParam['example']) && $customParam['example'] !== '') {
$example = $customParam['example'];
$decodedExample = [];
// If the type is array, try decoding it
if (in_array('array', array_keys($customParam['types']))) {
$decodedExample = json_decode($example, true);
}
// Check if the example is an array and needs special handling.
$queryString = !empty($decodedExample) ? Http::buildQuery([$paramName => $decodedExample]) : '';
if (stripos($queryString, urlencode($customParam['name'] . '[')) === 0) {
// Mark the param to be replaced and change the value to a placeholder
$parametersToReplace[$paramName] = $queryString;
$example = 'PlaceholderValue';
}
// Add the URL encoded param and value to the collection
$parametersToSet[$paramName] = urlencode($example);
}
}
}
$className = Request::getClassNameAPI($pluginName);
$exampleUrl = $this->generator->getExampleUrl($className, $methodName, $parametersToSet);
// Replace the placeholders with the actual array params now that we have an example URL
if (!empty($exampleUrl) && !empty($parametersToReplace)) {
foreach ($parametersToReplace as $name => $encodedValue) {
$exampleUrl = str_replace('&' . $name . '=PlaceholderValue', '&' . $encodedValue, $exampleUrl);
}
}
if (empty($exampleUrl)) {
// If we couldn't get an example URL from the generator, try getting one from metadata
$exampleUrl = $this->getReportExampleUrlFromMetadata($pluginName, $methodName);
if (empty($exampleUrl)) {
return [];
}
}
$exampleUrl = $this->prependInstanceUrl($exampleUrl);
return [
'xml' => $exampleUrl . '&format=xml&token_auth=anonymous',
'json' => $exampleUrl . '&format=JSON&token_auth=anonymous',
'tsv' => $exampleUrl . '&format=Tsv&token_auth=anonymous',
];
}
/**
* Query for report metadata which can later be used to help determine good example URLs for
* specific API endpoints. This method is only used when the example URL can't be determined using the default
* method. This only works for endpoints associated with reports and have metadata provided by the containing
* plugin. The response is cached as a property so the request is only made once regardless of how many times this
* method is called. The exception is if a valid response wasn't received. In that case, it will keep making the
* request until a non-empty response is received.
*
* @return array|array[] The decoded JSON array of all the report metadata from the demo server.
* @throws \Exception
*/
protected function getDemoReportMetadata(): array
{
if (is_array($this->reportMetadata) && count($this->reportMetadata)) {
return $this->reportMetadata;
}
$url = $this->getReportMetadataUrl();
try {
$response = Http::sendHttpRequestBy(
Http::getTransportMethod(),
$url,
$timeout = 30, // We can use a somewhat longer timeout for this request since it's cached afterward.
$userAgent = null,
$destinationPath = null,
$file = null,
$followDepth = 0,
$acceptLanguage = false,
$acceptInvalidSslCertificate = true,
$byteRange = false,
$getExtendedInfo = true,
$httpMethod = 'GET'
);
} catch (\Exception $e) {
// Add a little bit more context for troubleshooting the failed request
throw new \Exception('Error getting report metadata from URL: ' . $url . PHP_EOL . $e, 0, $e);
}
if (empty($response['data']) || ($response['status'] ?? 1) !== 200 || strpos($response['data'], 'Error: ') === 0) {
return [];
}
$this->reportMetadata = json_decode($response['data'], true) ?? [];
return $this->reportMetadata;
}
/**
* Take the example URL and query the endpoint for an example response, hiding subtables. If a response isn't
* received, it can try using a temporary token to make the request against the current
* instance of Matomo.
*
* @param string $url The full example URL.
* @param bool $useLocalToken A boolean indicating whether to get a temporary token and try the request against the
* currently running Matomo instance.
* @param bool $ignoreCached A boolean indicating whether the cached response file should be ignored. Default is
* false. This is simply in case we want to replace the existing responses with new ones.
*
* @return string The response received from the API endpoint if no error was received or the response wasn't empty.
* An empty string is returned by default.
* @throws \Throwable
*/
protected function getExampleIfAvailable(string $url, bool $useLocalToken = false, bool $ignoreCached = false): string
{
$queryString = Url::getQueryStringFromUrl($url);
$queryParams = UrlHelper::getArrayFromQueryString($queryString);
if (empty($queryParams['method']) || empty($queryParams['format'])) {
throw new \Exception('Missing method or format in URL: ' . $url);
}
$method = $queryParams['method'];
$format = strtolower($queryParams['format']);
[$pluginName, $methodName] = explode('.', $method);
$exampleFilePath = $this->pathResolver->getExampleResponseFilePath($pluginName, $methodName, $format);
// If there's already a file, use that instead of making a new server call. Ignore the file when the flag is set.
if (!$ignoreCached) {
// If an example file is found, return its contents instead of making the server call.
$exampleContents = $this->getCachedExampleResponseFile($pluginName, $methodName, $format);
if (!empty($exampleContents)) {
return $exampleContents;
}
}
// Include a specific parameter for the TSV requests.
if ($format === 'tsv') {
$url .= '&convertToUnicode=0';
}
// If the flag to use a temp token is set, get a token and update the request URL
$tempUrl = $url . '&hideIdSubDatable=1';
if ($useLocalToken) {
$token = Piwik::requestTemporarySystemAuthToken('OpenApiDocs', 24);
$tempUrl = str_replace('&token_auth=anonymous', '&token_auth=' . $token, $tempUrl);
}
try {
$response = Http::sendHttpRequestBy(
Http::getTransportMethod(),
$tempUrl,
$timeout = 10,
$userAgent = null,
$destinationPath = null,
$file = null,
$followDepth = 0,
$acceptLanguage = false,
$acceptInvalidSslCertificate = true,
$byteRange = false,
$getExtendedInfo = true,
$httpMethod = 'GET'
);
} catch (\Throwable $e) {
// Add a little bit more context for troubleshooting the failed request
throw new \Exception('Error getting example from URL: ' . $url . PHP_EOL . $e, 0, $e);
}
// If the example didn't load or resulted in an error, simply return an empty string
if (
empty($response['data']) || ($response['status'] ?? 1) !== 200
|| strpos($response['data'], 'Error: ') === 0
|| stripos(str_replace(["\n", "\t"], '', $response['data']), '<result><error message=') !== false
|| stripos($response['data'], '"result":"error"') !== false
|| stripos($response['data'], '<result />') !== false
|| trim($response['data']) === '[]'
|| (stripos($url, 'format=tsv') !== false && trim($response['data']) === 'No data available')
|| !preg_match("/(json|xml|vnd.ms-excel)/", $response['headers']['content-type'] ?? $response['headers']['Content-Type'] ?? '') // Some ask for xml/json/tsv but return image/png, shouldn't be treated as xml
) {
return '';
}
$body = $response['data'];
// Write the example response to file as a cache and reference.
$this->writeFile($exampleFilePath, $body);
// Convert the XML responses into a JSON object and then encode it into a string. This is helpful for building schemas.
if ($format === 'xml') {
// Some plugins have invalid XML (e.g <North America>)
try {
$body = json_encode($this->convertExampleXmlToObject($body));
} catch (\Exception $e) {
return '';
}
}
return $body;
}