Snippets

Michael Schramm Codeship Status

Created by Michael Schramm
<?php

// check blog post: http://blog.ms07.at/?p=374
define('BITBUCKET_USER', 'XXX');
define('BITBUCKET_API_KEY', 'XXX');

error_reporting(E_ALL);

function result($data) {
    header('content-type: text/json');
    echo json_encode($data);
    die();
}

/** @var array $json */
$json = @json_decode(file_get_contents('php://input'), true);
$build = $json['build'];

// SUCCESSFUL || FAILED || INPROGRESS

switch ($build['status']) {
    case 'testing':
        $state = 'INPROGRESS';
        break;

    case 'success':
        $state = 'SUCCESSFUL';
        break;

    case 'error':
    case 'stopped':
    case 'infrastructure_failure':
        $state = 'FAILED';
        break;

    case 'waiting':
    case 'ignored':
    case 'blocked':
    default:
        result([
            'error' => $build['status'] ?: 'Failed to get Build Data'
        ]);
}

if (!empty($_GET['message'])) {
    $message = $_GET['message'];
} else {
    $message = 'status update';
}

$data = [
    'key' => 'codeship',
    'state' => $state,
    'name' => 'Codeship Tests',
    'url' => $build['build_url'],
    'description' => $message
];

$url = sprintf(
    'https://api.bitbucket.org/2.0/repositories/%s/commit/%s/statuses/build',
    $build['project_name'],
    $build['commit_id']
);
$opts = [
    'http' => [
        'method' => 'POST',
        'header' => [
            'Content-type: application/json',
            'Authorization: Basic '.base64_encode(BITBUCKET_USER.':'.BITBUCKET_API_KEY)
        ],
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);

$data = @json_decode($result, true);

if (!$data) {
    result([
        'error' => $build['status']
    ]);
}

result($data);

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.