1313use Matomo \Dependencies \OpenApiDocs \OpenApi \Generator ;
1414use Piwik \Container \StaticContainer ;
1515use Piwik \Exception \PluginNotFoundException ;
16- use Piwik \Filesystem ;
1716use Piwik \Log \LoggerInterface ;
1817use Piwik \Log \NullLogger ;
1918use Piwik \Plugin \Manager ;
19+ use Piwik \Plugins \OpenApiDocs \Artifact \ArtifactWriter ;
2020use Piwik \Plugins \OpenApiDocs \OpenApiDocs ;
2121use Piwik \SettingsPiwik ;
2222use Piwik \Validators \BaseValidator ;
@@ -29,9 +29,15 @@ class SpecGenerator
2929 */
3030 private $ specPathResolver ;
3131
32- public function __construct (?PathResolver $ specPathResolver = null )
32+ /**
33+ * @var ArtifactWriter
34+ */
35+ private $ artifactWriter ;
36+
37+ public function __construct (?PathResolver $ specPathResolver = null , ?ArtifactWriter $ artifactWriter = null )
3338 {
3439 $ this ->specPathResolver = $ specPathResolver ?? new PathResolver ();
40+ $ this ->artifactWriter = $ artifactWriter ?? new ArtifactWriter ();
3541
3642 // Set the constant for the current instance's URL
3743 if (!defined ('LOCAL_MATOMO_SERVER_URL ' )) {
@@ -126,35 +132,9 @@ public function generateSpec(array $pluginNames, string $format = 'json', string
126132 $ specContents = $ lowercaseFormat === 'yaml ' ? $ openapi ->toYaml () : $ openapi ->toJson ();
127133 if ($ writeToFile ) {
128134 $ pluginSpecPath = $ this ->specPathResolver ->getSpecFilePath ($ specFileBaseName , $ version , $ lowercaseFormat );
129- $ this ->writeSpecFile ($ pluginSpecPath , $ specContents );
135+ $ this ->artifactWriter -> writeFile ($ pluginSpecPath , $ specContents );
130136 }
131137
132138 return $ specContents ;
133139 }
134-
135- private function writeSpecFile (string $ pluginSpecPath , string $ specContents ): void
136- {
137- $ directory = dirname ($ pluginSpecPath );
138- Filesystem::mkdir ($ directory );
139-
140- if (!is_dir ($ directory ) || !is_writable ($ directory )) {
141- throw new \RuntimeException ('OpenAPI spec output directory is not writable: ' . $ directory );
142- }
143-
144- $ temporaryFile = tempnam ($ directory , 'openapi_spec_ ' );
145- if ($ temporaryFile === false ) {
146- throw new \RuntimeException ('Could not create temporary file for OpenAPI spec output in ' . $ directory );
147- }
148-
149- $ bytesWritten = @file_put_contents ($ temporaryFile , $ specContents , LOCK_EX );
150- if ($ bytesWritten === false ) {
151- @unlink ($ temporaryFile );
152- throw new \RuntimeException ('Could not write OpenAPI spec file to temporary path ' . $ temporaryFile );
153- }
154-
155- if (!@rename ($ temporaryFile , $ pluginSpecPath )) {
156- @unlink ($ temporaryFile );
157- throw new \RuntimeException ('Could not move OpenAPI spec file into place at ' . $ pluginSpecPath );
158- }
159- }
160140}
0 commit comments