NoraBear Package API Documentation

はじめに

NoraBear Packageへようこそ!このライブラリは、BEAR.Sundayアプリケーションで使いやすいカスタマイズコンポーネントを提供します。

クイックスタート

インストール

composer require nora-bear/package

Module設定

use Ray\Di\AbstractModule;
use NoraBear\Package\Module\JsonRestModule;

class AppModule extends AbstractModule
{
    protected function configure()
    {
        $this->install(new JsonRestModule);
    }
}

最初のJsonRestResource

use BEAR\Resource\ResourceObject;
use NoraBear\Package\Annotation\JsonRest;

class Users extends ResourceObject
{
    #[JsonRest]
    public function onPost(array $userData): static
    {
        $userId = $this->createUser($userData);

        $this->code = 201;
        $this->body = ['id' => $userId];

        return $this;
    }
}

レスポンス例

成功時(HTTP 201):

{
  "info": {"status": "ok"},
  "payload": {"id": 123}
}

エラー時(HTTP 422):

{
  "info": {
    "status": "error",
    "message": "Validation failed"
  },
  "payload": {
    "description": ["Invalid email format"],
    "errors": [
      {
        "input": "email",
        "label": "email",
        "message": "Invalid email format"
      }
    ]
  }
}

EndpointModuleの使用

EndpointModuleを使用すると、 page://app://Resource\Endpoint 名前空間にマッピングできます。

Module設定

use Ray\Di\AbstractModule;
use NoraBear\Package\Module\EndpointModule;

class AppModule extends AbstractModule
{
    protected function configure(): void
    {
        $this->install(new EndpointModule);
    }
}

ディレクトリ構造

EndpointModuleを使用する場合、以下のようなディレクトリ構造になります:

src/
└── Resource/
    └── Endpoint/
        ├── Index.php          (page://self/)
        ├── User.php           (page://self/user)
        ├── UserProfile.php    (page://self/user-profile)
        └── Api/
            └── Users.php      (page://self/api/users)

従来の Resource\PageResource\App の代わりに、すべてのリソースを Resource\Endpoint 配下に配置します。

既存プロジェクトからの移行

  1. src/Resource/Page/src/Resource/App/ のファイルを src/Resource/Endpoint/ に移動
  2. 各ファイルの名前空間を変更:

    // Before
    namespace MyApp\Resource\Page;
    
    // After
    namespace MyApp\Resource\Endpoint;
  3. AppModuleEndpointModule をインストール

NoraLib Validationとの統合

use Ray\Validation\Annotation\Valid;
use Ray\Validation\Annotation\OnValidate;
use NoraLib\Validation\Validator;

class Users extends ResourceObject
{
    /**
     * @Valid
     */
    #[JsonRest]
    public function onPost(array $userData): static
    {
        // バリデーション済みデータで処理
        $userId = $this->createUser($userData);

        $this->code = 201;
        $this->body = ['id' => $userId];

        return $this;
    }

    /**
     * @OnValidate
     */
    public function onValidatePost(mixed $userData): \Ray\Validation\Validation
    {
        if (!is_array($userData)) {
            throw new \NoraLib\Validation\Exception\ValidationalError(
                input_key: 'userData',
                message: 'Request body must be an array'
            );
        }

        $validator = new Validator();
        $userValidator = $validator->array([
            'email' => $validator->validEmail(),
            'password' => $validator
                ->notEmpty()
                ->length(min: 12)
                ->passwordComplexity(4),
        ]);

        $userValidator->assert($userData);

        return new \Ray\Validation\Validation();
    }
}

Webアプリケーションへの組み込み

GitLabプライベートリポジトリからのインストール

BEAR.Sundayアプリケーションの composer.json に以下を追加:

{
    "require": {
        "nora-bear/package": "^1.0",
        "nora-lib/auth": "^1.0",
        "nora-lib/utils": "^1.0"
    },
    "repositories": [
        {
            "type": "vcs",
            "url": "git@gitlab.avaper.day:nora/php-lib/norabear/package.git"
        },
        {
            "type": "vcs",
            "url": "git@gitlab.avaper.day:nora/php-lib/auth.git"
        },
        {
            "type": "vcs",
            "url": "git@gitlab.avaper.day:nora/php-lib/utils.git"
        }
    ]
}

インストール:

composer install

ディレクトリ構造

your-bear-app/
├── src/
│   ├── Module/
│   │   └── AppModule.php          # モジュール設定
│   ├── Resource/
│   │   └── Endpoint/              # EndpointModuleを使う場合
│   │       ├── Index.php
│   │       └── Users.php
│   └── AuthContext.php            # ユーザー定義の認証コンテキスト
├── var/
│   └── conf/
│       ├── openapi.yaml          # OpenAPIスキーマ
│       └── jwt_secret.key        # JWT秘密鍵
└── composer.json

AppModule完全設定

すべての機能を有効にした src/Module/AppModule.php の例:

<?php
namespace YourApp\Module;

use BEAR\Package\AbstractAppModule;
use NoraLib\Auth\Validator\{JWTValidator, AuraSessionValidator};
use NoraBear\Package\Module\{JsonRestModule, EndpointModule, OpenAPIModule};
use NoraBear\Package\Auth\Module\AuthModule;
use YourApp\AuthContext;

class AppModule extends AbstractAppModule
{
    protected function configure(): void
    {
        // JsonRest機能
        $this->install(new JsonRestModule);

        // Endpoint機能(page://とapp://を統合)
        $this->install(new EndpointModule);

        // OpenAPI統合
        $this->install(new OpenAPIModule(
            schemaFile: $this->appMeta->appDir . '/var/conf/openapi.yaml'
        ));

        // 認証・認可機能
        $validators = [
            new JWTValidator(
                secretKey: $this->appMeta->appDir . '/var/conf/jwt_secret.key',
                algorithm: 'HS256'
            ),
            new AuraSessionValidator(
                sessionSegment: 'auth'
            ),
        ];

        $this->install(new AuthModule(
            authContextClass: AuthContext::class,
            validators: $validators
        ));

        parent::configure();
    }
}

AuthContext定義

src/AuthContext.php を作成:

<?php
namespace YourApp;

readonly class AuthContext
{
    public function __construct(
        public string $userId,
        public string $scheme,
        public array $roles = [],
        public array $permissions = []
    ) {}

    public function getRoles(): array
    {
        return $this->roles;
    }

    public function getPermissions(): array
    {
        return $this->permissions;
    }
}

OpenAPIスキーマ配置

var/conf/openapi.yaml を作成:

openapi: 3.0.0
info:
  title: Your API
  version: 1.0.0

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    sessionAuth:
      type: apiKey
      in: cookie
      name: PHPSESSID

paths:
  /users:
    get:
      summary: Get users list
      security:
        - bearerAuth: []
        - sessionAuth: []
      responses:
        '200':
          description: Success
    post:
      summary: Create user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - email
                - password
              properties:
                email:
                  type: string
                  format: email
                password:
                  type: string
                  minLength: 12
      responses:
        '201':
          description: Created

JWT秘密鍵の生成

# JWT秘密鍵を生成
openssl rand -base64 64 > var/conf/jwt_secret.key
chmod 600 var/conf/jwt_secret.key

# .gitignoreに追加
echo "var/conf/jwt_secret.key" >> .gitignore

認証付きリソースの実装

src/Resource/Endpoint/Users.php の例:

<?php
namespace YourApp\Resource\Endpoint;

use BEAR\Resource\ResourceObject;
use NoraLib\Auth\Annotation\{Authenticated, Authorize};
use NoraBear\Package\Annotation\JsonRest;
use NoraBear\Package\OpenAPI\Annotation\OpenAPIValidated;

class Users extends ResourceObject
{
    // 認証が必要なGETエンドポイント
    #[JsonRest]
    #[Authenticated]
    public function onGet(): static
    {
        $this->body = [
            'users' => [
                ['id' => 1, 'name' => 'Alice'],
                ['id' => 2, 'name' => 'Bob'],
            ]
        ];

        return $this;
    }

    // OpenAPIバリデーション + 認証 + 認可
    #[JsonRest]
    #[OpenAPIValidated]
    #[Authenticated]
    #[Authorize(roles: ['admin'])]
    public function onPost(string $email, string $password): static
    {
        // バリデーション済み、認証済み、管理者権限チェック済み
        $userId = $this->createUser($email, $password);

        $this->code = 201;
        $this->body = ['id' => $userId];

        return $this;
    }

    private function createUser(string $email, string $password): int
    {
        // ユーザー作成ロジック
        return 123;
    }
}

開発サーバーで起動

# アプリケーションをコンパイル
composer compile

# 開発サーバーで起動
php -S 127.0.0.1:8080 -t public

APIテスト

# 認証なしでアクセス(401エラー)
curl http://127.0.0.1:8080/users

# JWT付きでアクセス(成功)
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
     http://127.0.0.1:8080/users

# ユーザー作成(管理者権限必要)
curl -X POST \
     -H "Authorization: Bearer YOUR_JWT_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"email":"test@example.com","password":"secure_pass_123"}' \
     http://127.0.0.1:8080/users

本番環境チェックリスト

  • [ ] バージョンタグを作成(v1.0.0など)
  • [ ] composer.jsonに依存関係を追加
  • [ ] AppModuleに各モジュールをインストール
  • [ ] OpenAPIスキーマを作成・配置
  • [ ] AuthContextクラスを定義
  • [ ] JWT秘密鍵を生成(.gitignoreに追加)
  • [ ] リソースに適切なアノテーションを適用
  • [ ] WebサーバーでBEAR.Sundayアプリケーションを設定
  • [ ] ログ設定を確認
  • [ ] エラーハンドリングをテスト

次のステップ

Search results