jolicode/slack-php-api

repository·main·Indexed 42 days ago

https://github.com/jolicode/slack-php-api

An automatically generated PHP SDK for the Slack Web API built with JanePHP. It provides a full object-oriented interface for Slack endpoints, featuring PSR-7 and PSR-18 compliance, typed response models, and built-in support for cursor-based pagination via iterate* methods.

Tokens
3.6K
Snippets
14
Records
19
Agent score
54%

What's inside slack-php-api

  1. Understanding the SDK architecture

    main

    The SDK is primarily composed of code generated from the official Slack OpenAPI specification. It consists of four main types of classes:

    • Endpoints: Represent the requests made to API methods.
    • Models: Represent the data exchanged with the API.
    • Normalizers: Transform JSON from the API into PHP models.
    • Runtime: Internal classes required for the Jane library to function.

    End-users should use ClientFactory to manage these components automatically.

  2. Iterate over paginated results using iterate* methods

    main

    Many Slack API endpoints use cursor-based pagination. Instead of manually managing cursors, the client provides virtual methods prefixed with iterate. These methods allow you to use a standard foreach loop to traverse all pages of results automatically, hiding the complexity of cursor management.

    $userNames = [];
    
    /** @var JoliCode\Slack\Api\Model\ObjsUser $user */
    foreach ($client->iterateUsersList() as $user) {
        $userNames[] = $user->getName();
    }
  3. Manual pagination handling

    main

    If you need manual control over pagination, you can use the standard API methods by passing a cursor in the options array. You can retrieve the next cursor from the response metadata using getResponseMetadata()->getNextCursor().

    $userNames = [];
    $cursor = '';
    
    do {
        $response = $client->usersList([
            'limit' => 200,
            'cursor' => $cursor,
        ]);
    
        /** @var JoliCode\Slack\Api\Model\ObjsUser $user */
        foreach ($response->getUsers() as $user) {
            $userNames[] = $user->getName();
        }
    
        $cursor = $response->getResponseMetadata() ? $response->getResponseMetadata()->getNextCursor() : '';
    } while (!empty($cursor));
  4. Regenerate the SDK from the specification

    main

    If you have updated the specification and need to rebuild the SDK, follow these steps:

    1. Clear existing code: Remove all content from the generated directory to ensure a clean state:

      rm -Rf generated/*
    2. Run Jane: Use the Jane OpenAPI generator with the project's configuration file to regenerate the models and endpoints:

      vendor/bin/jane-openapi generate --config-file=.jane-openapi.php
    rm -Rf generated/*
    vendor/bin/jane-openapi generate --config-file=.jane-openapi.php
  5. Quick start with the Slack client

    main

    To interact with the Slack Web API, use the JoliCode\Slack\ClientFactory::create() method with your Slack Bot Token. The resulting client provides a full object-oriented interface for all Slack endpoints. Methods return response objects that allow you to access data via typed getter methods (e.g., getUser()).

    // $client contains all the methods to interact with the API
    $client = JoliCode\Slack\ClientFactory::create($yourSlackToken);
    
    $user = $client->usersInfo(['user' => 'U123AZER'])->getUser();
  6. Generate a new specification patch

    main

    If you find a bug in the Slack specification that isn't covered by existing patches, you can propose a new patch by following this workflow:

    1. Modify the spec: Manually edit resources/slack-openapi-patched.json to fix the issue.
    2. Verify the SDK: Regenerate the SDK (using the steps in 'Regenerate the SDK') and test the resulting code to ensure the fix works as expected.
    3. Create the patch file: Run the spec:generate-patch command to create a new cumulative patch file in the resources directory:
      ./bin/slack-api-client-generator spec:generate-patch
    4. Validate the patch: Before committing, verify that the patch can be correctly re-applied by running the update command:
      ./bin/slack-api-client-generator spec:update
    # 1. Edit resources/slack-openapi-patched.json
    # 2. Regenerate and test SDK
    # 3. Generate new patch
    ./bin/slack-api-client-generator spec:generate-patch
    # 4. Verify
    ./bin/slack-api-client-generator spec:update
  7. Initialize the Slack Client

    main

    To start using the SDK, use the ClientFactory::create() method and pass your Slack token. This returns a Client instance which provides access to all Slack API methods. The SDK is object-oriented: every endpoint, response, and model is represented by a specific PHP class with full typehinting and PHPDoc support.

    <?php
    
    use JoliCode//Slack//Api//Client;
    use JoliCode//Slack//ClientFactory;
    
    /** @var Client $client */
    $client = ClientFactory::create($yourSlackToken);
  8. Install the Slack PHP API

    main

    The Slack PHP API is built on PSR-7 and PSR-18 interfaces. Before installing the SDK, ensure your project has a PSR-7 message factory and a PSR-18 HTTP client implementation.

    If you do not have these installed, you can install default implementations using Symfony and Nyholm:

    composer require symfony/http-client nyholm/psr7

    Once the dependencies are ready, install the Slack client via Composer:

    composer require jolicode/slack-php-api
  9. Fetch the latest Slack API specification and apply patches

    main

    Because the official Slack OpenAPI specification may be incomplete or incorrect, this SDK uses a patched version. To download the latest official specification, sort the keys, and apply the project's custom patches to create resources/slack-openapi-patched.json, run the spec:update command using the client generator.

    This command performs these steps:

    1. Downloads the official Slack OpenAPI spec to resources/slack-openapi.json.
    2. Sorts JSON keys and saves to resources/slack-openapi-sorted.json.
    3. Applies patches and saves the final version to resources/slack-openapi-patched.json.
    ./bin/slack-api-client-generator spec:update
  10. Iterate through paginated Slack resources

    main

    The Client provides magic methods to automatically handle pagination for several Slack API resources. By prefixing a standard API method name with iterate, the client will automatically follow the next_cursor provided by Slack and yield items one by one using a PHP generator.

    Supported iteration methods include:

    • iterateConversationsHistory(): Yields ObjsMessage objects.
    • iterateConversationsList(): Yields ObjsConversation objects.
    • iterateConversationsMembers(): Yields strings (member IDs).
    • iterateConversationsReplies(): Yields mixed content.
    • iterateFilesInfo(): Yields mixed content.
    • iterateUsergroupsList(): Yields ObjsSubteam objects.
    • iterateReactionsList(): Yields mixed content.
    • iterateStarsList(): Yields mixed content.
    • iterateUsersList(): Yields ObjsUser objects.

    When calling these methods, you can pass an array of arguments as the first parameter. The client defaults the limit to 1000 if not specified.

    // Example: Iterating through all messages in a conversation history
    foreach ($client->iterateConversationsHistory(['channel' => 'C12345']) as $message) {
        echo $message->getText();
    }