GithubHelp home page GithubHelp logo

github-php-client's Introduction

GitHub API PHP Client

See full API reference

Authenticating

<?php
require_once(__DIR__ . '/client/GitHubClient.php');

$client = new GitHubClient();
$client->setCredentials($username, $password);

Listing commits

<?php
require_once(__DIR__ . '/client/GitHubClient.php');

$owner = 'tan-tan-kanarek';
$repo = 'github-php-client';

$client = new GitHubClient();
$client->setPage();
$client->setPageSize(2);
$commits = $client->repos->commits->listCommitsOnRepository($owner, $repo);

echo "Count: " . count($commits) . "\n";
foreach($commits as $commit)
{
    /* @var $commit GitHubCommit */
    echo get_class($commit) . " - Sha: " . $commit->getSha() . "\n";
}

$commits = $client->getNextPage();

echo "Count: " . count($commits) . "\n";
foreach($commits as $commit)
{
    /* @var $commit GitHubCommit */
    echo get_class($commit) . " - Sha: " . $commit->getSha() . "\n";
}

Listing issues

<?php
require_once(__DIR__ . '/client/GitHubClient.php');

$owner = 'tan-tan-kanarek';
$repo = 'github-php-client';

$client = new GitHubClient();

$client->setPage();
$client->setPageSize(2);
$issues = $client->issues->listIssues($owner, $repo);

foreach ($issues as $issue)
{
    /* @var $issue GitHubIssue */
    echo get_class($issue) . "[" . $issue->getNumber() . "]: " . $issue->getTitle() . "\n";
}

Creating issues

<?php
require_once(__DIR__ . '/client/GitHubClient.php');

$owner = 'tan-tan-kanarek';
$repo = 'github-php-client';
$title = 'Something is broken.'
$body = 'Please fix it.'.

$client = new GitHubClient();
$client->setCredentials($username, $password);
$client->issues->createAnIssue($owner, $repo, $title, $body);

Creating a release

<?php
require_once(__DIR__ . '/client/GitHubClient.php');

$owner = 'tan-tan-kanarek';
$repo = 'github-php-client';
$username = 'tan-tan-kanarek';
$password = 'myPassword';

$tag_name = 'myTag';
$target_commitish = 'master';
$name = 'myReleaseName';
$body = 'My release description';
$draft = false;
$prerelease = true;

$client = new GitHubClient();
$client->setDebug(true);
$client->setCredentials($username, $password);

$release = $client->repos->releases->create($owner, $repo, $tag_name, $target_commitish, $name, $body, $draft, $prerelease);
/* @var $release GitHubReposRelease */
$releaseId = $release->getId();

$filePath = 'C:\myPath\bin\myFile.jar';
$contentType = 'application/java-archive';
$name = 'MyFile-1.0.0.jar';

$client->repos->releases->assets->upload($owner, $repo, $releaseId, $name, $contentType, $filePath);

Pagination

<?php
require_once(__DIR__ . '/client/GitHubClient.php');

$owner = 'tan-tan-kanarek';
$repos = array(
	'github-php-client',
);

$client = new GitHubClient();

foreach($repos as $repo)
{
	$pageSize = 4;
	$client->setPage();
	$client->setPageSize($pageSize);
	
	$commits = $client->repos->commits->listCommitsOnRepository($owner, $repo);
	while(true)
	{
		$page = $client->getPage();
		echo "================ Page $page - " . count($commits) . " items ================\n";
		foreach($commits as $commit)
		{
			/* @var $commit GitHubCommit */
			$sha = $commit->getSha();
			$message = $commit->getCommit()->getMessage();
			
			echo "\t$sha - $message\n";
		}
		

		if(!$client->hasNextPage())
			break;
			
		$commits = $client->getNextPage();
		if($client->getPage() == $page)
			break;
	}
}

*[8/06/2015] Fixed pull request comment function

Bitdeli Badge

github-php-client's People

Contributors

acuthbert avatar alehlipka avatar arkitecht avatar bitdeli-chef avatar davidstutz avatar djplaner avatar dunkoh avatar egogo-nl avatar existenznl avatar ff1601com avatar gastonprieto avatar gonenradai avatar guillaumev avatar ivanfemia avatar iwillscoop avatar jdarwood007 avatar martey avatar mikeroetgers avatar polevaultweb avatar rimas-kudelis avatar ryandesign avatar scottarver avatar shreyans264 avatar shreyansjain26 avatar stephenharris avatar tan-tan-kanarek avatar torunar avatar willeeklund avatar xabier1989 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

github-php-client's Issues

Get comment of commit

Hello!

Just wondering if there is anyway to get the comment left when someone commits? Something like:
$commit->getComment();

Thanks

Help with github-php-client

Hello. Sorry about my english. I'd find your github-php-client . I think that it i realy need for my https://github.com/averony/datebott . Please correct me if I'm wrong. Your code allows you to log your experiments at github, and make changes in files of your repository by means of curl? Now I have the task to automate the process of adding new rows in the file https://github.com/averony/datebott/blob/master/woman.js . woman.js - is a database in text form. When you try to use your code I get the following error:
https://github.com/averony/datebott/blob/master/supertest.js

Can't create issues

Hi,

i'm using your library and i'm trying to create issue.

There is my code:

   $client = new GitHubClient();
   $client->setCredentials('username', 'password');
   $issue = new GithubIssues($client);
   $issue->createAnIssue('name', 'repo', 'title', 'content');

I'm getting a 500 error:

    Expected status [201], actual status [400], URL [/repos/nicolasheraly/API-Culture/issues]

Here is the stack trace:

at GitHubClientBase->parseResponse('/repos/nicolasheraly/API-Culture/issues', 'HTTP/1.1 100 ContinueHTTP/1.1 400 Bad RequestServer: GitHub.comDate: Wed, 07 May 2014 15:51:26 GMTContent-Type: application/json; charset=utf-8Status: 400 Bad RequestX-RateLimit-Limit: 5000X-RateLimit-Remaining: 4991X-RateLimit-Reset: 1399480094X-GitHub-Media-Type: github.v3X-XSS-Protection: 1; mode=blockX-Frame-Options: denyContent-Security-Policy: default-src 'none'Content-Length: 89Access-Control-Allow-Credentials: trueAccess-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-IntervalAccess-Control-Allow-Origin: *X-GitHub-Request-Id: BCA56D52:6B89:A1B1689:536A567EStrict-Transport-Security: max-age=31536000X-Content-Type-Options: nosniff{"message":"Problems parsing JSON","documentation_url":"https://developer.github.com/v3"}', 'GitHubIssue', 201, )
in SF_ROOT_DIR/lib/model/github-php-client/client/GitHubClientBase.php line 271 ...

I hope you can help me,

Nicolas Héraly

Pagination example fails when there are fewer objects than page size

The example pagination code from your readme fails when there are fewer objects than the page size. That is: your example gets commit messages 4 at a time. If pointed at a repo with fewer than 4 commits, such as https://github.com/ryandesign/test-fairly-empty which has 2 commits, it fails:

$ php test-pagination.php
================ Page 1 - 2 items ================
    a6a3406f266c8ad5e8d6ea910c22bb54a70bd5db - Update README.md
    d0b8d67f5ff769d9f39e975193e51beededde406 - Initial commit
PHP Fatal error:  Uncaught GitHubClientException: Page not defined in /path/to/github-php-client/client/GitHubClientBase.php:166
Stack trace:
#0 /path/to/test-pagination.php(31): GitHubClientBase->getNextPage()
#1 {main}
  thrown in /path/to/github-php-client/client/GitHubClientBase.php on line 166

Fatal error: Uncaught GitHubClientException: Page not defined in /path/to/github-php-client/client/GitHubClientBase.php:166
Stack trace:
#0 /path/to/test-pagination.php(31): GitHubClientBase->getNextPage()
#1 {main}
  thrown in /path/to/github-php-client/client/GitHubClientBase.php on line 166

As long as page size is set less than or equal to the number of items, the example works, but of course that defeats the purpose since I don't know in advance how many items there are and I want to set the page size to its maximum value of 100 to minimize the number of requests I send.

Value/interest in an approach to Oauth via web application flow?

G'day,

Problem

My aim in using this client has been to use it in a web application. The problem is that I don't believe that the client supports GitHub Oauth via web application flow

Possible solution

I've developed a possible solution by combining this client with this PHP OAuth wrapper. The code below is for a simple web application that has the combination working.

To get this working has required some changes to GitHubClient base.

Relevant questions are

  • Have I completely missed the client's existing capability to support this type of thing?
  • If not, is there sufficient interest in this capability for me to generate a pull request?
<?php

// Combine PHP-OAuth2 and GitHubClient to get details of authenticated user via Oauth web application flow

require('PHP-OAuth2/Client.php');
require('PHP-OAuth2/GrantType/IGrantType.php');
require('PHP-OAuth2/GrantType/AuthorizationCode.php');

require_once( __DIR__ . '/client/client/GitHubClient.php' );

// GitHub client details - need to register here https://github.com/settings/applications/new
// to get values for your script
const CLIENT_ID     = '?? replace with your value ??';
const CLIENT_SECRET = '?? replace with your value??';

// redirect URI for app - replace with URI for where you put this script
const REDIRECT_URI           = 'http://localhost:8080/oauth_combine.php';

// GitHub Oauth URLs
const AUTHORIZATION_ENDPOINT = 'https://github.com/login/oauth/authorize';
const TOKEN_ENDPOINT         = 'https://github.com/login/oauth/access_token';

// Generate a unique state variable 
$address=1530;
$STATE= hash('sha256', microtime(TRUE).rand().$address);

// the oauth client
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);

if (!isset($_GET['code'])) {
    // if haven't got a code 
    // Send user to github oauth login

    // PHP-OAuth2 doesn't know about the extras for github
    $EXTRAS = Array( 'state' => $STATE, 'scope' => "user" );
    $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT,
                                                REDIRECT_URI, $EXTRAS);
    header('Location: ' . $auth_url);
    die('Redirect');
} else {
    // Got the temp code, need to exchange it for a token so we can get cracking

    $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
    $EXTRAS = Array( 'state' => $_GET['state'] );
    $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code',
                                        $params, $EXTRAS);

    if ( $response['code'] != 200 ) {
        // oh dear, that failed
        print "<h3> Response was " . $response['code'] . "</h3>";
        die;
    }

    // got a 200 response = success?, parse the response and try to get token
    parse_str($response['result'], $info);

    if ( array_key_exists( 'access_token', $info ) ) {
        print "<h1>Got access token " . $info['access_token'] . "</h1>";

        // hand the token over to GitHubClient to start doing the query
        $oauth_token = $info['access_token'];
        $client = new GitHubClient();
        // The following two methods are new additions
        $client->setAuthType( 'Oauth' );
        $client->setOauthToken( $oauth_token );

        $response = $client->users->getTheAuthenticatedUser();

        // just dump the output
        var_dump( $response );

        // the following only works if a change is made to 
        // services/GitHubUsers.php
        print "<h3>Show user details</h3>";
        print "<ul> <li> Name: " . $response->getName() . "</li>" .
                 "<li> Email: " . $response->getEmail() . "</li></ul> ";
    } else {
         print "<h1> FAILURE - no token </h1>";
         print_r( $info );
    }
}

private repo auth

Does $client->setCredentials('user', 'pass'); work for private repos?

What pre-req's are there to gain api access to private repo's from your client?

Repos public?

Hey,
i'm trying show my repos list but i get an object private. i cant read for exemple the id or name or full_name. how can i read it?

Incomplete GitHubCommitCommitAuthor?

G'day

First, thanks for the client. Found it very useful for a project.

It appears that GitHubCommitCommitAuthor is incomplete. It doesn't actually declare the class variables/methods required to actually use it.

No great show stopper. I've been able to make the changes myself.

Wondering if I've missed some important point?

David.

how to create repository?

function delete repository work very well.
but create is not work

i think
case PATCH:

not implementate

Showing Files commited

hey, i'm want show the files included on commit. but i dont find the function to do it.

Showing Files commited

hey, i'm want show the files included on commit. but i dont find the function to do it.

Composer

Can you make the library compatible with Composer so that I can use it in my Laravel application?

How to list milestones

I'm confused about how to get a list of milestones in a repository.

In GitHubIssuesLabels.php you have listAllLabelsForThisRepository() which lists the labels, and getSingleLabel() which gets a single label. This makes sense.

But in GitHubIssuesMilestones.php you have listMilestonesForRepository() which does not list milestones but rather gets a single milestone.

Can't create issues with labels

How can I create an issue with label

I tried this code but it didn't work

$client->issues->createAnIssue('KareemMAX', 'Minecraft-Skiner', $_POST["title"], $_POST["body"],null,null,null,array("Bug tracker"));

OAuth example

Do you have an example of using OAuth integration? I'm writing a GitHub application which the user authorises and needs to fetch their repositories etc.

GitHubOauth Problems

Hi there
I keep getting 401 response when using

$client = new GitHubClient();
$client->oauth->createNewAuthorization($clientId);

Same with webApplicationFlow:

I tried Oauth manually and it works fine.
Am I missing somethings or is there a problem?

Needs a stable release

Hi - the library is great - thanks!

But could you create an official version tag and publish that to packagist? I'm trying to use the library in a project but don't want to set the minimum stability to dev if I can avoid it!

Thanks!

Create label

not working.

It's correct ?
$client->Issues->issuesLabels->createLabel($owner, $repo, $title, $color);

image

List issues

The documentation is a bit uncomplete. How can I get the issues of a repo?

Fatal error: 'GitHubRepoContentCommit' not found

This class is specified as return for some GitHubRepoContents methods. e.g.:

return $this->client->request("/repos/$owner/$repo/contents/$path", 'PUT', $data, 201, 'GitHubRepoContentCommit');

But I can't find any trace of that class anywhere except for this issue: #96

Here's the stack trace:

Stack trace:

.../vendor/tan-tan-kanarek/github-php-client/client/GitHubClientBase.php(355): GitHubClientBase->parseResponse('...', Object(stdClass), 'GitHubRepoConte...', 201, false)
.../vendor/tan-tan-kanarek/github-php-client/client/services/GitHubReposContents.php(59): GitHubClientBase->request('...', 'PUT', Array, 201, 'GitHubRepoConte...')
...index.php(15): GitHubReposContents->createFile('username', 'repo', 'file.txt', 'message', '...encoded content...')
{main}
thrown in ...vendor/tan-tan-kanarek/github-php-client/client/GitHubClientBase.php on line 437

Does this class need to be defined, or is the return type wrong?

Should getTheAuthenticatedUser be changed?

In #75 I included some code that made use of the method getTheAuthenticatedUser and in doing so I identified what I thought was a problem.

As implemented the core of the method is this

return $this->client->request("/user", 'GET', $data, 200, 'GitHubPrivateUser');

The problem is GitHubPrivateUser is only interested/able to use a very narrow subset of the data that GitHub passes back.

GitHubPrivateUser is only interested in

array(
            'total_private_repos' => 'int',
            'owned_private_repos' => 'int',
            'private_gists' => 'int',
            'disk_usage' => 'int',
            'collaborators' => 'int',

Whereas the GitHub API actually passes back a great deal extra information.

When used as I've done with Oauth in #75 it is much more useful to be able to access all of the information passed back. As an interim step I've modified getTheAuthenticatedUser so that it is now doing the following

        return $this->client->request("/user", 'GET', $data, 200, 'GitHubFullUser');

Is this an improvement? Or is it just plain wrong?

Documentation for objects and methods?

Would be great to have documentation for the available methods and objects used by this system.

The problem is, I have no clue what methods map to Github's various endpoints and what given arguments are required or accepted by said methods for the Client library to function...

Committer info not retrieved?

Hi,

I am trying to retrieve the date of a commit;

foreach($commits as $commit)
{
$c = $commit->getCommit();
$message = $c->getMessage();
$committer = $c->getCommitter(); // EMPTY :(
$author = $c->getAuthor(); // EMPTY :(
...

The $message variable is set perfectly, but unfortunately both $committer and $author are blank when I var_dump them. Is this part not yet implemented perhaps? Or do I do something wrong?

Would hope you can help me out,

Regards,
Gert-Jan

Commit changes with your code

Sorry, it's me again. Thank you again for the help last time. I finally made it. But the thing is that that is not what I need. Maybe you have a solution for my problem. I need to make changes(Commit changes) to the file base https://github.com/averony/datebott/edit/master/woman.js . Let's say I have a server receives payment, your code works and through curl automatically changes the content in this file. You can implement something similar with your help? Or can you tell me any other solution?
Thanks in advance, you help me a lot.

Manipulating team members results in GitHubClientException with HTTP Code 422

How do I...

Hello there! I am really really new at this, how do I "install" this? please help ^^

repos->listYourRepositories return all repos, not just mine

Do you have an idea what might be wrong, I have checked the CURL and the username and password is being passed on ...

class Github {

private $username = NULL;
private $password = NULL;

private $client = NULL;

public function __construct($username=NULL, $password=NULL) {
    $this->username = $username;
    $this->password = $password;

    $this->client = new GitHubClient();
    $this->client->setCredentials($username, $password);
}

public function listRepos() {
    return $this->client->repos->listYourRepositories();
}

OAuth Authenication

Hello There! Thank you for creating this awesome API.

Unfortunately, I have some issues with it. I am currently attempting to connect with OAuth however I keep receiving 404 responses. Do you perhaps have some code examples or guides on how to set this up?

Thank you,
Bart

What License is this under?

This is a great project, makes it very easy to get going with GitHub. However, I don't see a LICENSE so I'm wondering, what is this license under? Is it GPL compatible?

Thanks,

Sean

How to iterate over all pages

It's unclear how to iterate over all pages of results. I can get the first page, the next page, or the last page, but I don't see how to construct a loop that iterates over every page from the first to the last. Your existing sample code assumes there are exactly two pages of results. Your full API reference does not include the pagination functions.

Composer package is out of date

Hi. I try install this package with composer. Installed version of library is very old, as i understand. Please update composer package if you can. Thanks.

webApplicationFlow - missing?

The API docs list "webApplicationFlow" as a method for GitHubOauth. Can't find it in the code and attempts to use it (not suprisingly) get

Fatal error: Call to undefined method GitHubOauth::webApplicationFlow()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.