蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在 PHP 8.4 CLI 离线实测原生 RESTful 路由分发、内容协商与 HTTP 状态码

PHPWindows x64、PHP 8.4 本地 CLI 环境。explore-restful.php
explore-restful.php248 行
<?php
declare(strict_types=1);

class SiteRepository
{
    /** @var array<int, string> */
    private array $sites = [
        1 => 'AlphaDocs',
        2 => 'CloudHub',
        3 => 'BlueSky',
        4 => 'DataGrid',
        5 => 'StreamAPI',
        6 => 'OpenTools',
    ];

    /** @return array<int, string> */
    public function getAllSites(): array
    {
        return $this->sites;
    }

    /** @return array<int, string> */
    public function getSite(int $id): array
    {
        if (!isset($this->sites[$id])) {
            return [];
        }
        return [$id => $this->sites[$id]];
    }
}

class SimpleRest
{
    private string $httpVersion = 'HTTP/1.1';

    public function buildHeaders(string $contentType, int $statusCode): array
    {
        $statusMessage = $this->getHttpStatusMessage($statusCode);
        return [
            'status_line' => $this->httpVersion . ' ' . $statusCode . ' ' . $statusMessage,
            'status_code' => $statusCode,
            'content_type' => $contentType,
        ];
    }

    public function getHttpStatusMessage(int $statusCode): string
    {
        $httpStatus = [
            200 => 'OK',
            201 => 'Created',
            204 => 'No Content',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            500 => 'Internal Server Error',
        ];
        return $httpStatus[$statusCode] ?? $httpStatus[500];
    }
}

class SiteRestHandler extends SimpleRest
{
    private SiteRepository $repo;

    public function __construct(?SiteRepository $repo = null)
    {
        $this->repo = $repo ?? new SiteRepository();
    }

    public function handle(string $view, ?int $id, string $accept): array
    {
        if ($view === 'all') {
            $rawData = $this->repo->getAllSites();
        } elseif ($view === 'single' && $id !== null) {
            $rawData = $this->repo->getSite($id);
        } else {
            $rawData = [];
        }

        if ($rawData === []) {
            $statusCode = 404;
            $rawData = ['error' => 'No sites found!'];
        } else {
            $statusCode = 200;
        }

        if (str_contains($accept, 'application/json')) {
            $contentType = 'application/json';
            $body = $this->encodeJson($rawData);
        } elseif (str_contains($accept, 'text/html')) {
            $contentType = 'text/html';
            $body = $this->encodeHtml($rawData);
        } elseif (str_contains($accept, 'application/xml')) {
            $contentType = 'application/xml';
            $body = $this->encodeXml($rawData);
        } else {
            $statusCode = 406;
            $contentType = 'application/json';
            $body = $this->encodeJson(['error' => 'Not Acceptable']);
        }

        return [
            'headers' => $this->buildHeaders($contentType, $statusCode),
            'body' => $body,
        ];
    }

    public function encodeHtml(array $data): string
    {
        $html = "<table border='1'>";
        foreach ($data as $k => $v) {
            $html .= '<tr><td>' . htmlspecialchars((string)$k, ENT_QUOTES, 'UTF-8')
                . '</td><td>' . htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8') . '</td></tr>';
        }
        return $html . '</table>';
    }

    public function encodeJson(array $data): string
    {
        return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    public function encodeXml(array $data): string
    {
        $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><sites></sites>');
        foreach ($data as $k => $v) {
            $node = $xml->addChild('site', htmlspecialchars((string)$v, ENT_XML1, 'UTF-8'));
            $node->addAttribute('id', (string)$k);
        }
        return trim($xml->asXML());
    }
}

function matchRewriteRoute(string $uriPath): array
{
    $trimmed = trim($uriPath, '/');
    if (preg_match('#^site/list$#i', $trimmed)) {
        return ['view' => 'all', 'id' => null];
    }
    if (preg_match('#^site/list/([0-9]+)$#i', $trimmed, $m)) {
        return ['view' => 'single', 'id' => (int)$m[1]];
    }
    return ['view' => '', 'id' => null];
}

$handler = new SiteRestHandler();
$cases = [];

// Case 1: GET /site/list/ with Accept: application/json -> 200 OK
$r1 = matchRewriteRoute('/site/list/');
$res1 = $handler->handle($r1['view'], $r1['id'], 'application/json');
$decoded1 = json_decode($res1['body'], true);
$c1Actual = [
    'status_line' => $res1['headers']['status_line'],
    'content_type' => $res1['headers']['content_type'],
    'count' => count($decoded1),
    'site_3' => $decoded1['3'],
];
$c1Expected = [
    'status_line' => 'HTTP/1.1 200 OK',
    'content_type' => 'application/json',
    'count' => 6,
    'site_3' => 'BlueSky',
];
$cases[] = [
    'name' => 'rest_list_json_200',
    'passed' => $c1Actual === $c1Expected,
    'expected' => $c1Expected,
    'actual' => $c1Actual,
];

// Case 2: GET /site/list/3/ content negotiation (text/html & application/xml)
$r2 = matchRewriteRoute('/site/list/3/');
$resHtml = $handler->handle($r2['view'], $r2['id'], 'text/html');
$resXml = $handler->handle($r2['view'], $r2['id'], 'application/xml');
$parsedXml = simplexml_load_string($resXml['body']);
$c2Actual = [
    'html_status' => $resHtml['headers']['status_code'],
    'html_type' => $resHtml['headers']['content_type'],
    'html_body' => $resHtml['body'],
    'xml_status' => $resXml['headers']['status_code'],
    'xml_type' => $resXml['headers']['content_type'],
    'xml_site_id' => (string)$parsedXml->site[0]['id'],
    'xml_site_name' => (string)$parsedXml->site[0],
];
$c2Expected = [
    'html_status' => 200,
    'html_type' => 'text/html',
    'html_body' => "<table border='1'><tr><td>3</td><td>BlueSky</td></tr></table>",
    'xml_status' => 200,
    'xml_type' => 'application/xml',
    'xml_site_id' => '3',
    'xml_site_name' => 'BlueSky',
];
$cases[] = [
    'name' => 'rest_single_html_and_xml_200',
    'passed' => $c2Actual === $c2Expected,
    'expected' => $c2Expected,
    'actual' => $c2Actual,
];

// Case 3: GET /site/list/999/ -> 404 Not Found
$r3 = matchRewriteRoute('/site/list/999/');
$res3 = $handler->handle($r3['view'], $r3['id'], 'application/json');
$c3Actual = [
    'status_line' => $res3['headers']['status_line'],
    'content_type' => $res3['headers']['content_type'],
    'body' => json_decode($res3['body'], true),
];
$c3Expected = [
    'status_line' => 'HTTP/1.1 404 Not Found',
    'content_type' => 'application/json',
    'body' => ['error' => 'No sites found!'],
];
$cases[] = [
    'name' => 'rest_not_found_404',
    'passed' => $c3Actual === $c3Expected,
    'expected' => $c3Expected,
    'actual' => $c3Actual,
];

// Case 4: Rewrite URI routing & 406 Not Acceptable
$rUnknown = matchRewriteRoute('/site/unknown/');
$res406 = $handler->handle('all', null, 'image/png');
$c4Actual = [
    'route_all' => $r1,
    'route_single' => $r2,
    'route_unknown' => $rUnknown,
    'not_acceptable_status' => $res406['headers']['status_line'],
];
$c4Expected = [
    'route_all' => ['view' => 'all', 'id' => null],
    'route_single' => ['view' => 'single', 'id' => 3],
    'route_unknown' => ['view' => '', 'id' => null],
    'not_acceptable_status' => 'HTTP/1.1 406 Not Acceptable',
];
$cases[] = [
    'name' => 'rest_uri_rewrite_router',
    'passed' => $c4Actual === $c4Expected,
    'expected' => $c4Expected,
    'actual' => $c4Actual,
];

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、PHP 8.4 本地 CLI 环境。

入口文件:projects/php-restful-lab/explore-restful.php

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-restful.php,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1304.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习