Markdown.php 2.9 KB
<?php

namespace Lackoxygen\ShowDocGeneration\Writer;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Lackoxygen\ShowDocGeneration\Annotations\Method;
use Lackoxygen\ShowDocGeneration\Parser\Doc;

class Markdown
{
    protected string $template = <<<t
##### 简要描述

- {{title}}

##### 请求URL
- ` {{url}} `

##### 请求方式
- {{method}}

##### 参数
|参数名|必选|类型|说明|
|:----|:---|:----- |-----|
{{params}}

##### 中间件
{{middles}}

##### 请求头
|参数名|说明|
|:----    |:---|
{{headers}}

##### 返回示例

```
{{resp}}
```

##### 返回参数说明

|参数名|类型|说明|
|:-----|:-----|:-----------------------------|
{{respRemark}}

##### 备注

- 最后更新时间:{{updateTime}}
t;

    protected string $output = '';

    public function __construct(Doc $doc, string $resourcePath)
    {
        $editTemplate = $this->template;

        $replaces = [
            'title' => Arr::get($doc->title, 'value'),
            'url' => Arr::get($doc->url, 'path'),
            'method' => Arr::get($doc->method, 'method', Method::METHOD_GET),
            'headers' => join("\n", $this->tableTbody($doc->headerLine)),
            'params' => join("\n", $this->tableTbody($doc->paramLine)),
            'resp' => '{}',
            'respRemark' => join("\n", $this->tableTbody($doc->respLine)),
            'middles' => join("\n", $this->unorderedList($doc->middles)),
            'updateTime' => now()->toString()
        ];

        $respResource = Arr::get($doc->respResource, 'resource');

        if ($respResource) {
            $resourceInfo = pathinfo($respResource);

            if (!isset($resourceInfo['extension'])) {
                $respResource .= '.json';
            }

            $resourceFile = rtrim($resourcePath, '/\\') . DIRECTORY_SEPARATOR . $respResource;

            $fs = new Filesystem();

            if ($fs->exists($resourceFile) && $respData = $fs->sharedGet($resourceFile)) {
                Arr::set($replaces, 'resp', $respData);
            }
        }

        $this->output = \str_replace(
            \array_map(function (string $key) {
                return '{{' . $key . '}}';
            }, \array_keys($replaces)),
            \array_values($replaces),
            $editTemplate
        );
    }

    protected function unorderedList(array $list): array
    {
        return \array_map(function ($v) {
            return '- ' . $v;
        }, $list);
    }

    protected function tableTbody(array $tbody): array
    {
        return \array_map(function (array $line) {
            $line = \array_map(function ($v) {
                if (\is_bool($v)) {
                    $v = $v ? '是' : '否';
                }
                return $v;
            }, $line);
            return '|' . \join('|', \array_values($line)) . '|';
        }, $tbody);
    }

    public function toString(): string
    {
        return $this->output;
    }
}