php-jira-rest-client

repository·main·Indexed 19 days ago

https://github.com/lesstif/php-jira-rest-client

A PHP client for interacting with the Jira REST API, specifically designed for On-Premise Jira installations. It provides high-level services for managing projects, issues, custom fields, users, and more. Requires PHP >= 8.0 and supports authentication via personal access tokens, basic auth, and session cookies.

Tokens
20.9K
Snippets
63
Records
67
Agent score
67%

What's inside php-jira-rest-client

  1. Configure using Dotenv (.env)

    main

    To use environment variables for configuration, install vlucas/phpdotenv:

    composer require vlucas/phpdotenv

    Create a .env file in your project root. Note that if TOKEN_BASED_AUTH is set to true, the JIRA_USER and JIRA_PASS settings are ignored in favor of PERSONAL_ACCESS_TOKEN.

    Note on Authentication: Basic auth with passwords is deprecated by Atlassian. It is recommended to use an API token instead of a password.

  2. Install the PHP JIRA Rest Client

    main

    Install the client using Composer. This project requires PHP >= 8.0, netresearch/jsonmapper, and vlucas/phpdotenv.

    1. Install Composer if you haven't already:
      curl -sS https://getcomposer.org/installer | php
    2. Require the package:
      php composer.phar require lesstif/php-jira-rest-client
      Alternatively, add "lesstif/php-jira-rest-client": "^5.0" to your composer.json.
    3. Run the install command:
      php composer.phar install
    4. Include the autoloader in your PHP project:
      require 'vendor/autoload.php';

    Laravel Integration: If automatic package discovery is disabled, register JiraRestApi\JiraRestApiServiceProvider in your config/app.php.

    php composer.phar require lesstif/php-jira-rest-client
  3. Use JqlFunction to construct JQL expressions

    main

    The JqlFunction class is a helper used with JqlQuery to set JQL (Jira Query Language) function calls as values in expressions. Instead of writing raw JQL strings, you can use the static methods provided by JqlFunction to generate valid JQL function syntax. These functions are typically passed into JqlQuery methods like setAssignee() or addExpression() to build complex queries.

    $jql = new JqlQuery();
    $jql->setAssignee(JqlFunction::currentUser())
        ->addExpression('issue', 'in', JqlFunction::issueHistory());
  4. Build JQL queries with JqlQuery

    main

    The JqlQuery class provides a fluent interface for constructing Jira Query Language (JQL) strings used to search for issues. You can build complex queries by chaining method calls that add specific field conditions, using logical operators like AND or OR to join them.

    To use a built query, call getQuery() to retrieve the generated JQL string, which can then be passed to an issue service's search method.

    $query = new JqlQuery();
    $query->setProject('Project-Key')
        ->setAssignee('someUser');
    
    $issues = $issueService->search($query->getQuery());
  5. Initialize the JiraClient

    main

    To use the library, instantiate the JiraClient class. You can provide a custom ConfigurationInterface implementation or a LoggerInterface. If no configuration is provided, the client defaults to using DotEnvConfiguration, which looks for a .env file in the provided $path (defaults to ./).

    If the .env file is not found in the specified path, it attempts to look in the parent directory (../).

    use JiraRestApi\JiraClient;
    use JiraRestApi\Configuration\ConfigurationInterface;
    use Psr\Log\LoggerInterface;
    
    // Option 1: Default configuration via .env file
    $client = new JiraClient(null, null, './');
    
    // Option 2: Custom configuration and logger
    $client = new JiraClient($myCustomConfig, $myLogger, './');
  6. Get epic issues using EpicService

    main

    You can retrieve all issues associated with a specific epic using the EpicService class. The getEpicIssues method accepts the epic ID (or key) and an optional array of parameters to filter or paginate the results, such as maxResults and jql (Jira Query Language).

    Note that when using jql in the parameters array, you should urlencode the query string. The method may throw a JiraRestApi\JiraException if the request fails.

    <?php
    require 'vendor/autoload.php';
    
    try {
      $epic_service = new JiraRestApi\Epic\EpicService();
      $epic_id = 1;
      $issues = $epic_service->getEpicIssues($epic_id, [
        'maxResults' => 500,
        'jql' => urlencode('status != Closed'),
      ]);
    
    foreach ($issues as $issue) {
        var_dump($issue);
      }
    } catch (JiraRestApi\JiraException $e) {
        print('Error Occured! ' . $e->getMessage());
    }
  7. Manage Priorities with PriorityService

    main

    Use JiraRestApi\Priority\PriorityService to retrieve priority settings from Jira. You can fetch all available priorities or retrieve a specific priority by its ID.

    <?php
    require 'vendor/autoload.php';
    
    use JiraRestApi\Priority\PriorityService;
    use JiraRestApi\JiraException;
    
    try {
        $ps = new PriorityService();
    
        // Get all priorities
        $p = $ps->getAll();
        var_dump($p);
    
        // Get a specific priority by ID
        $p_single = $ps->get(1);
        var_dump($p_single);
    
    } catch (JiraRestApi\JiraException $e) {
        print('Error Occured! ' . $e->getMessage());
    }
  8. Create a sub-task

    main

    To create a sub-task, configure an IssueField with the issue type set to 'Sub-task' and provide the parent issue's key or ID using setParentKeyOrId($issueKeyOrId).

    $issueField->setIssueTypeAsString('Sub-task')
               ->setParentKeyOrId('TEST-143');
    
    $issueService = new IssueService();
    $ret = $issueService->create($issueField);
  9. Update an existing issue

    main

    To update an issue, instantiate IssueField with true as the first argument (e.g., new IssueField(true)) to indicate an update operation. Use this object to define the fields you wish to change, then call IssueService::update($issueKey, $issueField, $editParams).

    $editParams is an optional array for additional query parameters, such as ['notifyUsers' => false] to suppress notifications.

    <?php
    require 'vendor/autoload.php';
    
    use JiraRestApi\Issue\IssueService;
    use JiraRestApi\Issue\IssueField;
    
    $issueKey = 'TEST-879';
    
    try {
        // Passing true to constructor for update mode
        $issueField = new IssueField(true);
    
        $issueField->setAssigneeNameAsString('admin')
                    ->setPriorityNameAsString('Blocker')
                    ->addLabel('test-label-first');
    
        $editParams = ['notifyUsers' => false];
    
        $issueService = new IssueService();
        $ret = $issueService->update($issueKey, $issueField, $editParams);
    
        var_dump($ret);
    } catch (JiraRestApi\JiraException $e) {
        print('Update Failed: ' . $e->getMessage());
    }
  10. Manage Issue Watchers

    main

    Use IssueService to control who is watching an issue. You can add a user as a watcher or remove an existing watcher using their user ID/username.

    <?php
    use JiraRestApi\Issue\IssueService;
    
    $issueKey = 'TEST-961';
    $watcher = 'lesstif';
    $issueService = new IssueService();
    
    // Add watcher
    $issueService->addWatcher($issueKey, $watcher);
    
    // Remove watcher
    $issueService->removeWatcher($issueKey, $watcher);
  11. Delete an issue

    main

    Use IssueService::deleteIssue($issueKey) to remove an issue. If you need to delete an issue along with all its sub-tasks, pass an options array: deleteIssue($issueKey, ['deleteSubtasks' => 'true']).

    <?php
    require 'vendor/autoload.php';
    
    use JiraRestApi\Issue\IssueService;
    
    try {
        $issueService = new IssueService();
        // To delete issues with sub-tasks:
        // $ret = $issueService->deleteIssue($issueKey, ['deleteSubtasks' => 'true']);
        
        $ret = $issueService->deleteIssue('TEST-879');
        var_dump($ret);
    } catch (JiraRestApi\JiraException $e) {
        print('Remove Issue Failed: ' . $e->getMessage());
    }
  12. Manage Worklogs in an Issue

    main

    Use IssueService and the Worklog class to manage time tracking entries for a specific issue. You can add new worklogs, edit existing ones using a worklog ID, or retrieve worklogs (either all worklogs for an issue or a specific one by ID).

    <?php
    require 'vendor/autoload.php';
    
    use JiraRestApi//Issue/IssueService;
    use JiraRestApi//Issue/Worklog;
    use JiraRestApi//JiraException;
    
    $issueKey = 'TEST-961';
    
    try {
        // Add worklog
        $workLog = new Worklog();
        $workLog->setComment('I did some work here.')
                ->setStarted('2016-05-28 12:35:54')
                ->setTimeSpent('1d 2h 3m');
    
        $issueService = new IssueService();
        $ret = $issueService->addWorklog($issueKey, $workLog);
        $workLogid = $ret->{'id'};
    
        // Edit worklog
        $workLogEdit = new Worklog();
        $workLogEdit->setComment('I did edit previous worklog here.')
                     ->setStarted('2016-05-29 13:15:34')
                     ->setTimeSpent('3d 4h 5m');
        $retEdit = $issueService->editWorklog($issueKey, $workLogEdit, '12345');
    
        // Get worklogs
        $worklogs = $issueService->getWorklog($issueKey)->getWorklogs();
        $singleWl = $issueService->getWorklogById($issueKey, 12345);
    
    } catch (JiraRestApi\JiraException $e) {
        echo $e->getMessage();
    }