GithubHandler.php 1.52 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
<?php

namespace AppBundle\Utils\WebhookAdapters;

use AppBundle\Model\WebhookEvent;
use Symfony\Component\HttpFoundation\Request;

class GithubHandler implements WebhookHandler {

  /**
   * @inheritdoc
   */
  public function handle(Request $request): WebhookEvent {
    $event = new WebhookEvent();
    $event->setType($request->headers->get('X-GitHub-Event'));
    $event->setSource($event::SOURCE_GITHUB);
    $this->getDetailsFromPush($event, $request->getContent());

    return $event;
  }

  /**
   * @inheritdoc
   */
  public function canHandle(Request $request): bool {
    return $request->headers->has('X-Github-Event');
  }

  /**
   * Use a "push" event to figure out what branch and repo we are talking
   * about, and the also work out what emails we should send.
   *
   * @param WebhookEvent $event
   * @param string $payload
   *
   * @return WebhookEvent
   *
   * @throws \Exception
   */
  protected function getDetailsFromPush(WebhookEvent $event, $payload) {
    $payload = json_decode($payload);

    if (empty($payload)) {
      throw new \Exception('Could not decode webhook body');
    }

    $branch = basename($payload->ref);;

    if (empty($branch)) {
      throw new \Exception("Unable to determine branch from payload data");
    }

    $repo = $payload->repository->html_url;
    if (empty($repo)) {
      throw new \Exception("Unable to determine repository from payload data");
    }

    $event->setRepo($repo);
    $event->setBranch($branch);
    $event->setCommits($payload->commits);

    return $event;
  }
}