Skip to content

Ability to allow json files to replace @responseFile tags with files mapped #764

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/getting-started/documenting-your-api.md
Original file line number Diff line number Diff line change
@@ -337,6 +337,25 @@ public function getUser(int $id)
{
// ...
}

```

The package can also replace nested response file tags provided within the json files.

Just like doc block add `@responseFile` tag within the json content separated with by a colon and proceeded by the file to use

Main File:
```json
{"id":5,"name":"Jessica Jones","gender":"female", "profile": "@responseFile:responses/profile/profile.json"}
```
The reference file:
```json
{"id":1,"active":true,"userId":5}
```

The Final Result:
```json
{"id":5,"name":"Jessica Jones","gender":"female", "profile": {"id":1,"active":true,"userId":5}}
```

## Generating responses automatically
57 changes: 50 additions & 7 deletions src/Extracting/Strategies/Responses/UseResponseFileTag.php
Original file line number Diff line number Diff line change
@@ -20,12 +20,17 @@ class UseResponseFileTag extends Strategy
* @param array $routeRules
* @param array $context
*
* @return array|null
* @throws \Exception If the response file does not exist
*
* @return array|null
*/
public function __invoke(Route $route, \ReflectionClass $controller, \ReflectionMethod $method, array $routeRules, array $context = [])
{
public function __invoke(
Route $route,
\ReflectionClass $controller,
\ReflectionMethod $method,
array $routeRules,
array $context = []
) {
$docBlocks = RouteDocBlocker::getDocBlocksFromRoute($route);
/** @var DocBlock $methodDocBlock */
$methodDocBlock = $docBlocks['method'];
@@ -57,17 +62,55 @@ protected function getFileResponses(array $tags)
preg_match('/^(\d{3})?\s?([\S]*[\s]*?)(\{.*\})?$/', $responseFileTag->getContent(), $result);
$relativeFilePath = trim($result[2]);
$filePath = storage_path($relativeFilePath);
if (! file_exists($filePath)) {
if (!file_exists($filePath)) {
throw new \Exception('@responseFile ' . $relativeFilePath . ' does not exist');
}
$status = $result[1] ?: 200;
$content = $result[2] ? file_get_contents($filePath, true) : '{}';
$json = ! empty($result[3]) ? str_replace("'", '"', $result[3]) : '{}';
$json = !empty($result[3]) ? str_replace("'", '"', $result[3]) : '{}';
$merged = array_merge(json_decode($content, true), json_decode($json, true));

return ['content' => json_encode($merged), 'status' => (int) $status];
$content = json_encode($merged);
$contentWithReplacedTags = $this->replaceJsonFileTags($content);
return ['content' => $contentWithReplacedTags, 'status' => (int)$status];
}, $responseFileTags);

return $responses;
}

/**
* Replaces nested file tags @responseFile:path/to/file.json
*
* @param string $content
* @return string
*/
protected function replaceJsonFileTags(string $content): string
{
// finding all matching responseFile tags
preg_match_all('/@responseFile:[\S]*[\s]*\.json?/', $content, $result);

// continuing if we get any result
if (count($result) > 0) {
foreach ($result[0] as $replaceValuePath) {
$relativeFilePath = str_replace('@responseFile:', '', $replaceValuePath);
$relativeFilePath = str_replace('\\', '', $relativeFilePath);
$filePath = storage_path($relativeFilePath);

if (!file_exists($filePath)) {
throw new \Exception('@responseFile ' . $relativeFilePath . ' does not exist');
}

// fetching the file content and recursively replacing any matches within the file tagged
$fileContent = file_get_contents($filePath, true);
$normalizedFileContent = json_encode(json_decode($fileContent, true));
$nestedReplacedFileContent = $this->replaceJsonFileTags($normalizedFileContent);
$content = str_replace(
'"' . $replaceValuePath . '"',
$nestedReplacedFileContent,
$content
);
}
}

return $content;
}
}