-
Notifications
You must be signed in to change notification settings - Fork 0
Initial implementation of API endpoint info export #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| <?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 Piwik\API\Proxy; | ||
| use Piwik\API\Request; | ||
| use Piwik\Plugin\Manager; | ||
| use Piwik\Plugins\OpenApiDocs\OpenApiDocs; | ||
| use Piwik\Validators\BaseValidator; | ||
| use Piwik\Validators\NotEmpty; | ||
|
|
||
| class ApiMethodInfoExtractor | ||
| { | ||
| /** | ||
| * Look up the Matomo Reporting API methods for the specified plugin(s) and output the basic information for each. | ||
| * This includes the comment block, parameter information, and things like that. This can then be fed to a secure | ||
| * AI model which can come up with suggestions on how to improve the descriptions, type hinting, etc. | ||
| * | ||
| * @param string $pluginName Name or comma-separated list of names of the plugins to extract API endpoint info for. | ||
| * @param bool $writeToFile Whether to output the result to console or write it to tmp file. | ||
| * | ||
| * @return string String result of the extracted info. | ||
| * @throws \Exception | ||
| */ | ||
| public function extractMethodInfo(string $pluginName, bool $writeToFile = false): string | ||
| { | ||
| BaseValidator::check('plugin', $pluginName, [new NotEmpty()]); | ||
| $pluginNames = explode(',', $pluginName); | ||
|
|
||
| BaseValidator::check('pluginNames', $pluginNames, [new NotEmpty()]); | ||
| $currentPluginDir = Manager::getInstance()::getPluginDirectory('OpenApiDocs'); | ||
|
|
||
| $methodInfoArray = []; | ||
| foreach ($pluginNames as $plugin) { | ||
| BaseValidator::check('pluginName', $plugin, [new NotEmpty()]); | ||
| Manager::getInstance()->checkIsPluginActivated($plugin); | ||
|
|
||
| $className = Request::getClassNameAPI($plugin); | ||
|
|
||
| $result = $this->buildEndpointInfoArrayForApiClass($className); | ||
| if (!empty($result)) { | ||
| $methodInfoArray = array_merge($methodInfoArray, $result); | ||
| } | ||
| } | ||
| $methodInfoString = json_encode($methodInfoArray); | ||
|
|
||
| $fileBaseName = 'matomo'; | ||
| // If there's only one plugin, name the spec after the plugin | ||
| if (count($pluginNames) === 1) { | ||
| $fileBaseName = $pluginNames[0]; | ||
| } | ||
|
|
||
| if ($writeToFile) { | ||
| $pluginSpecPath = $currentPluginDir . OpenApiDocs::GENERATED_ANNOTATIONS_PATH . $fileBaseName . '_api_method_info.json'; | ||
| file_put_contents($pluginSpecPath, $methodInfoString); | ||
| } | ||
|
|
||
| return $methodInfoString; | ||
| } | ||
|
|
||
| /** | ||
| * Build the array of info about all the public API endpoints for a specific API class. It uses reflection and the | ||
| * metadata from the Proxy class used to build documentation. | ||
| * | ||
| * @param string $apiClassName Full name of the class which can be used to instantiate a ReflectionClass. | ||
| * | ||
| * @return array[] Collection of key details about each public API endpoint in the specified class. | ||
| */ | ||
| public function buildEndpointInfoArrayForApiClass(string $apiClassName): array | ||
| { | ||
| try { | ||
| $reflectionClass = new \ReflectionClass($apiClassName); | ||
| } catch (\ReflectionException $e) { | ||
| throw new \RuntimeException('Unable to get reflection class for API class: ' . $apiClassName, 0, $e); | ||
| } | ||
|
|
||
| Proxy::getInstance()->registerClass($apiClassName); | ||
| $pluginMetadata = Proxy::getInstance()->getMetadata()[$apiClassName] ?? []; | ||
|
|
||
| // The proxy has already determined which methods should be ignored, so we just use the list it came up with. | ||
| $methodInfoArray = []; | ||
| foreach ($pluginMetadata as $methodName => $metadataMethod) { | ||
| if ($methodName === '__documentation') { | ||
| continue; | ||
| } | ||
| $result = $this->buildJsonInfoForApiMethod($reflectionClass, $methodName, $metadataMethod); | ||
| if (!empty($result)) { | ||
| $methodInfoArray[] = $result; | ||
| } | ||
| } | ||
|
|
||
| return $methodInfoArray; | ||
| } | ||
|
|
||
| /** | ||
| * Build the array of info about a specific API endpoint. | ||
| * | ||
| * @param \ReflectionClass $reflectionClass Reflection class used to get the method data defined in the signature. | ||
| * @param string $methodName Name of the method being processed. | ||
| * @param array $methodMetadata Metadata from the Proxy class which can be used to enhance the reflection data. | ||
| * | ||
| * @return array Collection of key details about the API endpoint. | ||
| * @throws \ReflectionException If the method cannot be found on the class. | ||
| */ | ||
| public function buildJsonInfoForApiMethod(\ReflectionClass $reflectionClass, string $methodName, array $methodMetadata): array | ||
| { | ||
| $reflectionMethod = $reflectionClass->getMethod($methodName); | ||
| if (AnnotationGenerator::shouldApiMethodBeIgnored($reflectionMethod)) { | ||
| return []; | ||
| } | ||
|
|
||
| $doc = $reflectionMethod->getDocComment() ?: ''; | ||
|
|
||
| $signatureString = 'public function ' . $methodName . '('; | ||
| $paramsString = ''; | ||
| $signature = $this->buildMethodSignatureUsingReflection($reflectionMethod); | ||
| foreach ($signature['params'] as $param) { | ||
| $paramsString .= !empty($param['php_type']) ? $param['php_type'] . ' ' : ''; | ||
| $paramsString .= $param['name']; | ||
| $paramsString .= $param['default'] !== null ? ' = ' . (!is_string($param['default']) ? json_encode($param['default']) : $param['default']) : ''; | ||
| $paramsString .= ', '; | ||
| } | ||
| $paramsString = rtrim($paramsString, ', '); | ||
| $signatureString .= $paramsString . ')'; | ||
| if (!empty($signature['return']) && !empty($signature['return']['php_type'])) { | ||
| $signatureString .= ': ' . ($signature['return']['nullable'] ? '?' : '') . $signature['return']['php_type']; | ||
| } | ||
|
|
||
| $fileName = $reflectionMethod->getFileName(); | ||
| $fileName = str_replace(PIWIK_DOCUMENT_ROOT . '/', '', $fileName); | ||
|
|
||
| return [ | ||
| 'fqcn' => $reflectionClass->getName(), | ||
| 'method' => $methodName, | ||
| 'source' => ['file' => $fileName, 'start' => $reflectionMethod->getStartLine(), 'end' => $reflectionMethod->getEndLine()], | ||
| 'header' => $signatureString, | ||
| 'signature' => $signature, | ||
| 'docblock_raw' => $doc, | ||
| ]; | ||
| } | ||
|
|
||
| /** | ||
| * Use reflection to build up information about the method signature, such as parameter and return type details. | ||
| * | ||
| * @param \ReflectionMethod $reflectionMethod The reflection method which can provide all the necessary info. | ||
| * | ||
| * @return array[] Collection of parameter and return type details, such as php type and whether they're nullable. | ||
| */ | ||
| public function buildMethodSignatureUsingReflection(\ReflectionMethod $reflectionMethod) | ||
| { | ||
| $params = []; | ||
| foreach ($reflectionMethod->getParameters() as $reflectionParameter) { | ||
| $defaultValue = null; | ||
| if ($reflectionParameter->isOptional() && $reflectionParameter->isDefaultValueAvailable()) { | ||
| $defaultValue = $reflectionParameter->getDefaultValue(); | ||
| $defaultValue = $defaultValue !== null ? $defaultValue : json_encode($reflectionParameter->getDefaultValue()); | ||
| } | ||
| $param = [ | ||
| 'name' => '$' . $reflectionParameter->getName(), | ||
| 'php_type' => $reflectionParameter->hasType() ? strval($reflectionParameter->getType()) : null, | ||
| 'required' => !$reflectionParameter->isOptional(), | ||
| 'nullable' => $reflectionParameter->hasType() && $reflectionParameter->getType() !== null && $reflectionParameter->getType()->allowsNull(), | ||
| 'default' => $defaultValue, | ||
| 'byRef' => $reflectionParameter->isPassedByReference(), | ||
| 'variadic' => $reflectionParameter->isVariadic(), | ||
| ]; | ||
|
|
||
| $params[] = $param; | ||
| } | ||
|
|
||
| $returnType = $reflectionMethod->getReturnType(); | ||
| $returnTypeInfo = [ | ||
| 'php_type' => $returnType ? strval($returnType) : null, | ||
| 'nullable' => $returnType !== null && $returnType->allowsNull(), | ||
| ]; | ||
|
|
||
| return ['params' => $params, 'return' => $returnTypeInfo]; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| <?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\Commands; | ||
|
|
||
| use Piwik\Plugin\ConsoleCommand; | ||
| use Piwik\Plugins\OpenApiDocs\Annotations\ApiMethodInfoExtractor; | ||
|
|
||
| /** | ||
| * This class lets you define a new command. To read more about commands have a look at our Matomo Console guide on | ||
| * https://developer.matomo.org/guides/piwik-on-the-command-line | ||
| * | ||
| * As Matomo Console is based on the Symfony Console you might also want to have a look at | ||
| * https://symfony.com/doc/current/components/console/index.html | ||
| */ | ||
| class ExtractReportingApiMethodInfo extends ConsoleCommand | ||
| { | ||
| /** | ||
| * This method allows you to configure your command. Here you can define the name and description of your command | ||
| * as well as all options and arguments you expect when executing it. | ||
| */ | ||
| protected function configure() | ||
| { | ||
| $this->setName('openapidocs:extract-api-method-info'); | ||
| $this->setDescription('Extract the comment block and basic information about methods for the Matomo Reporting API.'); | ||
| $this->addRequiredValueOption('plugin', 'p', 'Name of the plugin to inspect'); | ||
| $this->addNoValueOption('not-dry-run', null, 'Flag to allow writing to file instead of outputting a dry run.'); | ||
| } | ||
|
|
||
| /** | ||
| * Interact with the user. | ||
| * | ||
| * This method is executed before the InputDefinition is validated. | ||
| * This means that this is the only place where the command can | ||
| * interactively ask for values of missing required arguments. | ||
| */ | ||
| protected function doInteract(): void | ||
| { | ||
| } | ||
|
|
||
| /** | ||
| * Initializes the command after the input has been bound and before the input | ||
| * is validated. | ||
| * | ||
| * This is mainly useful when a lot of commands extends one main command | ||
| * where some things need to be initialized based on the input arguments and options. | ||
| */ | ||
| protected function doInitialize(): void | ||
| { | ||
| } | ||
|
|
||
| /** | ||
| * The actual task is defined in this method. Here you can access any option or argument that was defined on the | ||
| * command line via $this->getInput() and write anything to the console via $this->getOutput(). | ||
| * In case anything went wrong during the execution you should throw an exception to make sure the user will get a | ||
| * useful error message and to make sure the command does not exit with the status code 0. | ||
| * | ||
| * Ideally, the actual command is quite short as it acts like a controller. It should only receive the input values, | ||
| * execute the task by calling a method of another class and output any useful information. | ||
| * | ||
| * Execute the command like: ./console openapidocs:extract-api-method-info --plugin=TagManager --not-dry-run | ||
| */ | ||
| protected function doExecute(): int | ||
| { | ||
| $input = $this->getInput(); | ||
| $output = $this->getOutput(); | ||
|
|
||
| $plugin = $input->getOption('plugin'); | ||
| if (empty($plugin)) { | ||
| throw new \RuntimeException('Please specify a plugin name.'); | ||
| } | ||
| $notDryRun = $input->getOption('not-dry-run') ?: false; | ||
|
|
||
| $message = sprintf('<info>Extracting API method info for: %s</info>', $plugin); | ||
|
|
||
| $output->writeln($message); | ||
|
|
||
| $result = (new ApiMethodInfoExtractor())->extractMethodInfo($plugin, $notDryRun); | ||
|
|
||
| if ($notDryRun) { | ||
| $output->writeln('<info>Results written to plugins/OpenApiDocs/tmp/annotations directory.</info>'); | ||
|
|
||
| return $result ? self::SUCCESS : self::FAILURE; | ||
| } | ||
|
|
||
| $output->writeln($result); | ||
|
|
||
| return $result ? self::SUCCESS : self::FAILURE; | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Makes it more readable for file
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@AltamashShaikh I might hold off on that change for now as it would make the file larger and I'm already worried about the file size when we try exporting all endpoints for the entire Matomo application/plugins.