PHPackages                             tourze/gitee-api-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. tourze/gitee-api-bundle

ActiveSymfony-bundle[API Development](/categories/api)

tourze/gitee-api-bundle
=======================

Gitee API integration bundle for Symfony

0.0.1(11mo ago)00MITPHPPHP ^8.1CI passing

Since May 24Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/tourze/gitee-api-bundle)[ Packagist](https://packagist.org/packages/tourze/gitee-api-bundle)[ RSS](/packages/tourze-gitee-api-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (21)Versions (2)Used By (0)

GiteeApiBundle
==============

[](#giteeapibundle)

[English](README.md) | [中文](README.zh-CN.md)

\[[![Latest Version](https://camo.githubusercontent.com/5bedf43c88d3d2fe1ffa7b0d26106cb7d4793f8b7609b44384952e63d309386b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f67697465652d6170692d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/5bedf43c88d3d2fe1ffa7b0d26106cb7d4793f8b7609b44384952e63d309386b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f67697465652d6170692d62756e646c652e7376673f7374796c653d666c61742d737175617265)\] () \[[![PHP Version](https://camo.githubusercontent.com/34764cfb8e54c79e0fd349f1dc3d214ede3884a21aa8da1a5f61a79c8ca33a18/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f67697465652d6170692d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/34764cfb8e54c79e0fd349f1dc3d214ede3884a21aa8da1a5f61a79c8ca33a18/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f67697465652d6170692d62756e646c652e7376673f7374796c653d666c61742d737175617265)\] () \[[![License](https://camo.githubusercontent.com/4a79fb1a2dc36365c521d2997d17bfba4b316277c10366f33b69ed8abdaaebd6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f67697465652d6170692d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/4a79fb1a2dc36365c521d2997d17bfba4b316277c10366f33b69ed8abdaaebd6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f67697465652d6170692d62756e646c652e7376673f7374796c653d666c61742d737175617265)\] () [![Build Status](https://camo.githubusercontent.com/71c899315a8f155d504bb23baebabdd724ea15a42a5f7e72e49e6b4e9ebc30d3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f75727a652f7068702d6d6f6e6f7265706f2f746573742e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/tourze/php-monorepo/actions)\[[![Code Coverage](https://camo.githubusercontent.com/6ce0146325478eb7cebae4cc6139b2af2c161735dd0e3c6ff6802f2c5a708179/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f3f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/6ce0146325478eb7cebae4cc6139b2af2c161735dd0e3c6ff6802f2c5a708179/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f7068702d6d6f6e6f7265706f3f7374796c653d666c61742d737175617265)\] ()

A comprehensive Gitee API integration bundle for Symfony applications, providing OAuth authentication, API client, repository synchronization, and data management features.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Requirements](#requirements)
- [Configuration](#configuration)
- [Usage](#usage)
    - [OAuth Authentication](#oauth-authentication)
    - [Multiple Tokens](#multiple-tokens)
    - [API Calls](#api-calls)
    - [Console Commands](#console-commands)
    - [Customizing the OAuth Flow](#customizing-the-oauth-flow)
- [Advanced Usage](#advanced-usage)
- [Data Model](#data-model)
- [Service Architecture](#service-architecture)
- [Security](#security)
- [Error Handling](#error-handling)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

- 🔐 **OAuth 2.0 Authentication** - Full OAuth flow with multiple token support per user
- 🔌 **Comprehensive API Client** - Access user info, repositories, branches, issues, and pull requests
- 🔄 **Repository Synchronization** - Sync and cache repository data locally
- 🎛️ **Flexible Scope Management** - Configure OAuth scopes per application
- 🏗️ **Doctrine Integration** - Entities for applications, tokens, and repositories
- 🛠️ **Console Commands** - CLI tools for data management
- 🎨 **Customizable Controllers** - Extend or replace default OAuth controllers
- 📦 **Auto-configuration** - Symfony Flex recipe for quick setup

Installation
------------

[](#installation)

1. Add the bundle to your project:

```
composer require tourze/gitee-api-bundle
```

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Symfony 6.4 or higher
- Doctrine ORM 3.0 or higher

Configuration
-------------

[](#configuration)

1. Create and configure your Gitee OAuth application in the database:

```
use GiteeApiBundle\Enum\GiteeScope;

$application = new GiteeApplication();
$application->setName('My Gitee App')
    ->setClientId('your_client_id')
    ->setClientSecret('your_client_secret')
    ->setHomepage('https://your-domain.com')
    ->setDescription('My Gitee application description')
    ->setScopes([
        GiteeScope::USER,
        GiteeScope::PROJECTS,
        GiteeScope::PULL_REQUESTS,
        GiteeScope::ISSUES,
    ]);

$entityManager->persist($application);
$entityManager->flush();
```

By default, applications are configured with the following scopes:

- `user_info`: Access user information
- `projects`: Access repositories
- `pull_requests`: Access pull requests
- `issues`: Access issues
- `notes`: Access comments

Additional available scopes:

- `enterprises`: Access enterprise information
- `gists`: Access gists
- `groups`: Access groups
- `hook`: Access webhooks

2. Configure the callback URL in your Gitee application settings:

```
https://your-domain.com/gitee/oauth/callback/{applicationId}

```

Usage
-----

[](#usage)

### OAuth Authentication

[](#oauth-authentication)

The bundle provides built-in controllers for handling the OAuth flow. To start the authentication process, redirect users to:

```
/gitee/oauth/connect/{applicationId}?callbackUrl={successUrl}

```

The `callbackUrl` parameter supports the following template variables:

- `{accessToken}`: The OAuth access token
- `{userId}`: The user ID (Gitee username if no user is authenticated)
- `{giteeUsername}`: The Gitee username
- `{applicationId}`: The application ID

Example usage in your templates:

```
{# Basic usage #}

    Connect with Gitee

{# With custom callback URL #}

    Connect with Gitee

```

The bundle will:

1. Redirect users to Gitee's authorization page with configured scopes
2. Handle the OAuth callback
3. Store the access token
4. Redirect to the specified callback URL with template variables replaced, or to the homepage route if no callback URL is provided

### Multiple Tokens

[](#multiple-tokens)

The bundle now supports multiple tokens per user per application. Each time a user authorizes the application, a new token is created instead of updating the existing one. When using the API, the most recently created valid token will be used.

### API Calls

[](#api-calls)

```
// Get user information (requires user_info scope)
$user = $giteeApiClient->getUser($userId, $application);

// Get user repositories (requires projects scope)
$repos = $giteeApiClient->getRepositories($userId, $application);

// Get repository details (requires projects scope)
$repo = $giteeApiClient->getRepository('owner', 'repo', $userId, $application);

// Get repository branches (requires projects scope)
$branches = $giteeApiClient->getBranches('owner', 'repo', $userId, $application);

// Get repository issues (requires issues scope)
$issues = $giteeApiClient->getIssues('owner', 'repo', ['state' => 'open'], $userId, $application);

// Get repository pull requests (requires pull_requests scope)
$prs = $giteeApiClient->getPullRequests('owner', 'repo', ['state' => 'open'], $userId, $application);
```

### Console Commands

[](#console-commands)

The bundle provides console commands to manage Gitee data:

#### gitee:sync:repositories

[](#giteesyncrepositories)

Synchronizes a user's Gitee repositories with the local database.

```
# Sync repositories for a specific user and application
php bin/console gitee:sync:repositories {userId} {applicationId}

# Force update all repositories (even if they haven't changed)
php bin/console gitee:sync:repositories {userId} {applicationId} --force
```

**Arguments:**

- `userId`: The user ID to sync repositories for
- `applicationId`: The ID of the Gitee application to use

**Options:**

- `--force` (`-f`): Force update all repository information even if no changes detected

The command will:

1. Fetch all repositories for the specified user using the application's OAuth token
2. Compare with existing local repository data
3. Create new repository records or update existing ones if changes are detected
4. Skip repositories that haven't been updated since the last sync (unless `--force` is used)
5. Display progress and summary statistics

Customizing the OAuth Flow
--------------------------

[](#customizing-the-oauth-flow)

The default controllers provide a basic OAuth flow. You can customize the flow by:

1. Creating your own controller that extends the default one:

```
use GiteeApiBundle\Controller\OAuthController;

class CustomOAuthController extends OAuthController
{
    public function callback(Request $request, GiteeApplication $application): Response
    {
        $token = parent::callback($request, $application);

        // Add your custom logic here

        return $this->redirectToRoute('your_custom_route');
    }
}
```

2. Or implementing the flow entirely in your own controller using the services:

```
use GiteeApiBundle\Service\GiteeOAuthService;

class YourController
{
    public function __construct(
        private readonly GiteeOAuthService $oauthService,
        private readonly UrlGeneratorInterface $urlGenerator,
    ) {
    }

    public function connect(Request $request, GiteeApplication $application): Response
    {
        $callbackUrl = 'https://your-domain.com/success?token={accessToken}';

        $authUrl = $this->oauthService->getAuthorizationUrl(
            $application,
            $this->urlGenerator->generate('your_callback_route', [
                'applicationId' => $application->getId(),
            ], UrlGeneratorInterface::ABSOLUTE_URL),
            $callbackUrl
        );

        return new RedirectResponse($authUrl);
    }

    public function callback(Request $request, GiteeApplication $application): Response
    {
        $token = $this->oauthService->handleCallback(
            $request->query->get('code'),
            $this->getUser()?->getId(),
            $application,
            $this->urlGenerator->generate('your_callback_route', [
                'applicationId' => $application->getId(),
            ], UrlGeneratorInterface::ABSOLUTE_URL)
        );

        // Handle the callback URL from state if needed
        $state = $request->query->get('state');
        $callbackUrl = $state ? $this->oauthService->verifyState($state) : null;

        if ($callbackUrl) {
            $callbackUrl = strtr($callbackUrl, [
                '{accessToken}' => $token->getAccessToken(),
                '{userId}' => $token->getUserId(),
                '{giteeUsername}' => $token->getGiteeUsername() ?? '',
            ]);

            return new RedirectResponse($callbackUrl);
        }

        return $this->redirectToRoute('your_success_route');
    }
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Token Management

[](#token-management)

For applications requiring multiple authentication workflows or token management:

```
// Get all tokens for a user-application pair
$tokens = $tokenRepository->findByUserAndApplication($userId, $applicationId);

// Get the most recent valid token
$latestToken = $tokenRepository->findLatestValidToken($userId, $applicationId);

// Manually refresh a token
$refreshedToken = $oauthService->refreshToken($token);
```

### Custom API Endpoints

[](#custom-api-endpoints)

Extend the API client for custom endpoints:

```
class CustomGiteeApiClient extends GiteeApiClient
{
    public function getCustomData(string $userId, GiteeApplication $application): array
    {
        return $this->request('GET', '/v5/custom-endpoint', [], $userId, $application);
    }
}
```

### Repository Filtering

[](#repository-filtering)

Filter synchronized repositories based on criteria:

```
// Only sync public repositories
$publicRepos = array_filter($repositories, fn($repo) => !$repo['private']);

// Only sync repositories with specific languages
$phpRepos = array_filter($repositories, fn($repo) => $repo['language'] === 'PHP');
```

Data Model
----------

[](#data-model)

The bundle provides three main entities:

### GiteeApplication

[](#giteeapplication)

Stores Gitee OAuth application configuration:

- Client ID and secret
- OAuth scopes
- Application metadata

### GiteeAccessToken

[](#giteeaccesstoken)

Manages user OAuth tokens:

- Access and refresh tokens
- Token expiration
- User-application associations
- Support for multiple tokens per user

### GiteeRepository

[](#giteerepository)

Caches repository information:

- Repository metadata
- Owner and permissions
- Clone URLs
- Last push timestamps

Service Architecture
--------------------

[](#service-architecture)

The bundle provides several services:

- **GiteeApiClient** - HTTP client for Gitee API requests
- **GiteeOAuthService** - OAuth flow management
- **GiteeRepositoryService** - Repository data management
- **Repository classes** - Doctrine repositories for data access

Security
--------

[](#security)

### Token Security

[](#token-security)

- Store tokens securely in the database with proper encryption if needed
- Never expose access tokens in logs or error messages
- Implement token rotation for long-lived applications
- Use HTTPS for all OAuth redirects and API calls

### Input Validation

[](#input-validation)

- All entity properties include validation constraints
- API responses are validated before processing
- OAuth state parameters include CSRF protection

### Scope Management

[](#scope-management)

- Request only the minimum required scopes
- Validate scope requirements before API calls
- Allow users to review and revoke permissions

### Rate Limiting

[](#rate-limiting)

- Respect Gitee's API rate limits
- Implement exponential backoff for failed requests
- Monitor API usage patterns

Error Handling
--------------

[](#error-handling)

The bundle throws `GiteeApiException` for API-related errors. Always wrap API calls in try-catch blocks:

```
use GiteeApiBundle\Exception\GiteeApiException;

try {
    $user = $giteeApiClient->getUser($userId, $application);
} catch (GiteeApiException $e) {
    // Handle API errors
    $logger->error('Gitee API error: ' . $e->getMessage());
}
```

Testing
-------

[](#testing)

Run the test suite:

```
# Run all tests
vendor/bin/phpunit packages/gitee-api-bundle/tests

# Run with coverage
vendor/bin/phpunit packages/gitee-api-bundle/tests --coverage-html coverage
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests and ensure they pass
5. Submit a pull request

Please follow PSR-12 coding standards and write tests for new features.

License
-------

[](#license)

This bundle is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance63

Regular maintenance activity

Popularity0

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

359d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-gitee-api-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-gitee-api-bundle/health.svg)](https://phpackages.com/packages/tourze-gitee-api-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
