Giter Club home page Giter Club logo

php-github-api's Introduction

PHP GitHub API

Build Status StyleCI Latest Stable Version Total Downloads Monthly Downloads Daily Downloads

A simple Object Oriented wrapper for GitHub API, written with PHP.

Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is very similar to the RESTful API.

Features

  • Light and fast thanks to lazy loading of API classes
  • Extensively tested and documented

Requirements

Quick install

Via Composer.

This command will get you up and running quickly with a Guzzle HTTP client.

composer require knplabs/github-api:^3.0 guzzlehttp/guzzle:^7.0.1 http-interop/http-factory-guzzle:^1.0

Advanced install

We are decoupled from any HTTP messaging client with help by HTTPlug.

Using a different http client

composer require knplabs/github-api:^3.0 symfony/http-client nyholm/psr7

To set up the Github client with this HTTP client

use Github\Client;
use Symfony\Component\HttpClient\HttplugClient;

$client = Client::createWithHttpClient(new HttplugClient());

Read more about using different clients in our docs.

Framework integrations

Laravel

To integrate this library in laravel Graham Campbell created graham-campbell/github. See the installation instructions to get started in laravel.

Basic usage of php-github-api client

<?php

// This file is generated by Composer
require_once __DIR__ . '/vendor/autoload.php';

$client = new \Github\Client();
$repositories = $client->api('user')->repositories('ornicar');

From $client object, you have access to all available GitHub api endpoints.

Cache usage

This example uses the PSR6 cache pool redis-adapter. See http://www.php-cache.com/ for alternatives.

<?php

// This file is generated by Composer
require_once __DIR__ . '/vendor/autoload.php';

use Cache\Adapter\Redis\RedisCachePool;

$client = new \Redis();
$client->connect('127.0.0.1', 6379);
// Create a PSR6 cache pool
$pool = new RedisCachePool($client);

$client = new \Github\Client();
$client->addCache($pool);

// Do some request

// Stop using cache
$client->removeCache();

Using cache, the client will get cached responses if resources haven't changed since last time, without reaching the X-Rate-Limit imposed by github.

Documentation

See the doc directory for more detailed documentation.

License

php-github-api is licensed under the MIT License - see the LICENSE file for details

Maintainers

Please read this post first.

This library is maintained by the following people (alphabetically sorted) :

Contributors

Thanks to GitHub for the high quality API and documentation.

php-github-api's People

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  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

php-github-api's Issues

Delete a folder or multiple files

Would it be possible to add a way to delete the contents of a folder?
Alternatively, a way to delete multiple files in one commit?

Comment creation not working

I'm getting a 404 Not Found, but it's working fine with curl (debug pasted below).

Here's what I'm using: $client->api('issue')->comments()->create('mattwkelly', 'test', 1, array('body' => 'My new comment'));

Here's the PHP debug:

Github\HttpClient\Message\Request::__set_state(array(
   'method' => 'POST',
   'resource' => '/repos/mattwkelly/test/issues/1/comments',
   'host' => 'https://api.github.com',
   'protocolVersion' => 1,
   'headers' =>
  array (
    0 => 'Accept: application/vnd.github.beta+json',
    1 => 'User-Agent: php-github-api (http://github.com/KnpLabs/php-github-api)',
    2 => 'If-Modified-Since: Wed, 31 Dec 1969 16:00:00 -0800',
  ),
   'content' => '{"body":"My new comment"}',
))
Github\HttpClient\Message\Response::__set_state(array(
   'remainingCalls' => NULL,
   'protocolVersion' => NULL,
   'statusCode' => NULL,
   'reasonPhrase' => NULL,
   'headers' =>
  array (
  ),
   'content' => NULL,
))
array (
)
NULL
Github\HttpClient\Message\Request::__set_state(array(
   'method' => 'POST',
   'resource' => '/repos/mattwkelly/test/issues/1/comments',
   'host' => 'https://api.github.com',
   'protocolVersion' => 1,
   'headers' =>
  array (
    0 => 'Accept: application/vnd.github.beta+json',
    1 => 'User-Agent: php-github-api (http://github.com/KnpLabs/php-github-api)',
    2 => 'If-Modified-Since: Wed, 31 Dec 1969 16:00:00 -0800',
  ),
   'content' => '{"body":"My new comment"}',
))
Github\HttpClient\Message\Response::__set_state(array(
   'remainingCalls' => NULL,
   'protocolVersion' => NULL,
   'statusCode' => NULL,
   'reasonPhrase' => NULL,
   'headers' =>
  array (
    0 => 'HTTP/1.1 404 Not Found',
    1 => 'Server: GitHub.com',
    2 => 'Date: Wed, 26 Jun 2013 07:08:47 GMT',
    3 => 'Content-Type: application/json; charset=utf-8',
    4 => 'Connection: keep-alive',
    5 => 'Status: 404 Not Found',
    6 => 'X-RateLimit-Limit: 60',
    7 => 'X-RateLimit-Remaining: 30',
    8 => 'X-GitHub-Media-Type: github.beta; format=json',
    9 => 'X-Content-Type-Options: nosniff',
    10 => 'Content-Length: 23',

curl:

curl -iu mattwkelly -X POST "https://api.github.com/repos/mattwkelly/test/issues/1/comments" -d '{"body":"Support test comment."}'
HTTP/1.1 201 Created
Server: GitHub.com
Date: Wed, 26 Jun 2013 07:11:16 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Status: 201 Created
X-RateLimit-Limit: 5000
X-RateLimit-Remaining: 4981
Location: https://api.github.com/repos/mattwkelly/test/issues/comments/20030516
X-GitHub-Media-Type: github.beta
X-Content-Type-Options: nosniff
Content-Length: 1499
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: ETag, Link, X-RateLimit-Limit, X-RateLimit-Remaining, X-OAuth-Scopes, X-Accepted-OAuth-Scopes
Access-Control-Allow-Origin: *
ETag: "47c61f7a32cc3517abd42466a7539825"
Cache-Control: max-age=0, private, must-revalidate

{
  "url": "https://api.github.com/repos/mattwkelly/test/issues/comments/20030516",
  "html_url": "https://github.com/mattwkelly/test/issues/1#issuecomment-20030516",
  "issue_url": "https://api.github.com/repos/mattwkelly/test/issues/1",
  "id": 20030516,
  "user": {
    "login": "mattwkelly",
    "id": 174449,
    "avatar_url": "https://secure.gravatar.com/avatar/b8671ed333a50c613f7a9dd7bf5d469f?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgrava                                                                                                                          tars%2Fgravatar-user-420.png",
    "gravatar_id": "b8671ed333a50c613f7a9dd7bf5d469f",
    "url": "https://api.github.com/users/mattwkelly",
    "html_url": "https://github.com/mattwkelly",
    "followers_url": "https://api.github.com/users/mattwkelly/followers",
    "following_url": "https://api.github.com/users/mattwkelly/following{/other_user}",
    "gists_url": "https://api.github.com/users/mattwkelly/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/mattwkelly/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/mattwkelly/subscriptions",
    "organizations_url": "https://api.github.com/users/mattwkelly/orgs",
    "repos_url": "https://api.github.com/users/mattwkelly/repos",
    "events_url": "https://api.github.com/users/mattwkelly/events{/privacy}",
    "received_events_url": "https://api.github.com/users/mattwkelly/received_events",
    "type": "User"
  },
  "created_at": "2013-06-26T07:11:16Z",
  "updated_at": "2013-06-26T07:11:16Z",
  "body": "Support test comment."
}

getHttpClient()->get() returning "remainingCalls": null

So, I'm following the docs outlined here about requesting any route.

I'm trying to request some of the newer github endpoints, for events and stuff. repos/:owner/:repo/issues/events - http://developer.github.com/v3/issues/events/#list-events-for-a-repository

No matter what url I try for (even getting a user or a repo) I always get "remainingCalls": null returned from the getHttpClient()->get() call. What am I doing wrong? I'm able to fetch other data, so it can't be that I've hit the rate limit...

Pagination

It seems like pagination is often not supported, or requires the developer to extend/override and reimplement lots of code.

E.g. I was looking at various things for organization management and most of the methods don't seem to support setting a page or return the necessary info currently.

I looked into iterators in guzzle, but it seems like that requires a web service client and what not.

Do you guys have any thoughts on this?

Best way to use authentication and security

What is the best way to implement and use authentication functions. Cannot get it working. Please see how I am implementing it here

What should be the expected response after calling:
$auth= $client->authenticate('myclientid','mysecret',AUTH_URL_CLIENT_ID);

Thanks

Repo API's hooks()->create() doesn't like my name field.

Hi. I'm trying to add a service hook programmatically using the following code:

  $hook_conf = array(
    'name' => $name,                                                                               
    'config' => array(
      'url' => 'http://requestb.in/wmmxenwm',
      'content_type' => 'json',
      'secret' => 'some secret text', 
    ),  
    'events' => array('issues', 'issue_comment', 'status'),
  );  
  $new = $gh->api('repo')->hooks()->create($user, $repo, $hook_conf);

This gives me:

Fatal error: Uncaught exception 'Github\Exception\ValidationFailedException' with message 'Validation Failed: Field "name" is invalid, for resource "Hook"' in /mnt/var/vcap.local/dea/apps/scholar-issue-sync-0-34332dbf2f71986cf4772c71d8fda7b8/app/vendor/knplabs/github-api/lib/Github/HttpClient/Listener/ErrorListener.php:81
Stack trace:
#0 /mnt/var/vcap.local/dea/apps/scholar-issue-sync-0-34332dbf2f71986cf4772c71d8fda7b8/app/vendor/knplabs/github-api/lib/Github/HttpClient/HttpClient.php(196): Github\HttpClient\Listener\ErrorListener->postSend(Object(Github\HttpClient\Message\Request), Object(Github\HttpClient\Message\Response))
#1 /mnt/var/vcap.local/dea/apps/scholar-issue-sync-0-34332dbf2f71986cf4772c71d8fda7b8/app/vendor/knplabs/github-api/lib/Github/HttpClient/HttpClient.php(134): Github\HttpClient\HttpClient->request('repos/sagotsky/...', Array, 'POST', Array)
#2 /mnt/var/vcap.local/dea/apps/scholar-issue-sync-0-34332dbf2f71986cf4772c71d8fda7b8/app/vendor/knplabs/github-api/lib/Github/Api/AbstractApi.php(48): Github\Htt in /mnt/var/vcap.local/dea/apps/scholar-issue-sync-0-34332dbf2f71986cf4772c71d8fda7b8/app/vendor/knplabs/github-api/lib/Github/HttpClient/Listener/ErrorListener.php on line 81

When I remove the name parameter I get an error that it's missing, as expected.

Not sure how to make this work since the name field causes errors no matter what I do with it.

Support for older php?

I am having difficulty introducing this library into my framework. I have yet to move to namespaces and on including and calling the library I get a list of errors from my autoloader not knowing what to do with namespaces.

My autoloader is as follows... I use it for loading models only. Libs are included manually. I'm not using composer either.

function __autoload($class_name) {
  $files = array();
  $files[] = DIR_ROOT . SITE_BACKEND_PATH . '/models/' . $class_name . '.php';

  foreach ($files as $file) {
    if (file_exists($file)) {
      require_once $file;
      return;
    }
  }

  die("Class does not exist: $class_name. Autoloader failed to find this class");
}
spl_autoload_register('__autoload');

I'm initialising the API here...

    $gitclient = new Github\Client();
    $repositories = $gitclient->api('user')->repositories('lukeoliff');
    var_dump($repositories);

And my include is as follows;

/**
 * Include the github API library
 * https://github.com/KnpLabs/php-github-api
 */
require_once 'libs/Github/Client.php';

The error I get is (the die straight out of my autoloader);

Class does not exist: Github\Api\User. Autoloader failed to find this class

and when I comment out the die I get the following;

Fatal error: Class 'Github\Api\User' not found in /Users/oliffl/Sites/core/admin/libs/Github/Client.php on line 134

Simple Repo Listing?

I've can't find any documentation for just listing the contents of a given directory of a repo. Does this even exist? I know I can do the request any route, but that object isn't exactly clean. ;)

GitData => Tree issue

the github api is expecting an array of objects when creating a tree. Your script checks for array with a single level and you get an "internal server error". I removed the checks and and sent something like this:

"tree":  [
     {
      "type": "blob",
      "path": "something.txt",
      "mode": "100644"
      "sha": "929246f65aab4d636cb229c790f966afc332c124"
    }
  ],

and github was much happier.

How to use pagination with Gists?

Hi!

Sorry if my question is stupid but I don't understand how to use pagination with a specific user Gists list.

Could you please provide me a full working example?

Thank you so much!

Cannot utilize cache

My apologies for asking what seems like such a trivial question, but I cannot use the cache functionality. "Class 'CachedHttpClient' not found", I don't believe the autoloader is loading everything? Any suggestions?

$github = new Github\Client(new CachedHttpClient(FilesystemCache('/tmp/github-api-cache')));

Can't authenticate with AUTH_URL_CLIENT_ID

Hi there, I'm just getting started with php-github-api but can't figure out how to make it auth. I created a file, required the autoload.php, verified that it works and then added the following two lines:

$client = new Github\Client();
$client->authenticate('my_client_id', 'my_client_secret', Github\Client::AUTH_URL_CLIENT_ID);

I expected that I when I ran the page I would get redirected to the GitHub login page, but nothing happens. No request is made to GitHub, the page is not redirected, and if I make a call to something that requires authentication I get an error (not authenticated). What am I missing?

Confusion over authenticate()

Should this not work?

$token = '...'; // already authenticated and saved
$client->authenticate($token, null, \Github\Client::AUTH_URL_TOKEN);

Whenever I try a request such as

$client->api('me')->show();

I get a Bad Credentials error. I have tested the token in a simple browser GET request and it returns as expected.... What am I missing?

Edit: After a about an hour on this I noticed a typo in the token. What a joke.

pagination

i queried repositories from github organisation and hit the pagination limit (when more than 30 results would be found, you just get a first page). the only mention about pagination i find in the code is in Github/HttpClient/Message/Response.php and its never called as far as i can see.

any ideas how i could handle this? i am happy to do a pull request to improve the situation, but would love to hear if you have ideas how it should be done.

Errors + warnings when client used with cache

If I replace the client with a cached http client, I get a php notice and an exception is thrown.

Old:

$client = new Github\Client();

New:

$cache  = new Github\HttpClient\CachedHttpClient(array(
    'cache_dir' => 'data/github-api-cache'
));

$client = new Github\Client($cache);

I get a notice:

Notice: Undefined index: base_url in /path/to/vendor/knplabs/github-api/lib/Github/HttpClient/HttpClient.php on line 46

And the exception:

Github\Exception\RuntimeException

File:
/path/to/vendor/knplabs/github-api/lib/Github/HttpClient/HttpClient.php:142

Message:
[curl] 3:  malformed [url] /repos/MyOrganisation/MyRepository/commits```

With the "normal" client all works fine, swapping the cached http client does trigger both. I am using php 5.3.14.

tag it please, not just alias branched

can i ask a big favor? on knplabs/github-api?
i am having a big of a nightmare related to a similar problem to this sonata-project/SonataDoctrineORMAdminBundle#196
basically requiring the 1.3.x-dev in any way gives problems
1.3.*@dev, 1.3.x-dev, ~1.3@dev, everything gives problems
even dev-master@dev
if there was a tag like 1.3.0 or 1.2.9
would make life easier
i need the bugfixess in :)
https://github.com/cordoval/gush/blob/master/composer.json#L22

@dev works but unfortunately

 - Installing knplabs/github-api (1.2.0)
    Loading from cache

installs 1.2 which is not good

Miscellaneous Endpoints

I just added the Meta endpoint to my local version of php-github-api and was wondering if you folks had any interest in integrating a full section for the miscellaneous endpoints. If so I can cook that up shortly and send a pull request.

Bad credentials

Hi,
Thanks for your hard work. It's really a blessing to have this project.
I'm having the error in title when trying to access user data after having authenticated the client. Lets post the code to explain better:

This is the line where authentication occurs. $assc_service->getServiceUid() returns the client ID (a number, not login that I retrieved from Github using HWIOAuthBundle) which so far is what I understand is needed. I have checked it and it is returning OK. GithubClient is an alias for Github\Client.

$this->client->authenticate($assc_service->getServiceUid(), null, GithubClient::AUTH_HTTP_TOKEN);

Now this is the line where I try to get the user info:

return $this->client->api('user')->show('aUser');

There is no much logic associated, and regarding Github API that's all. Can someone tell me what can be going wrong here? At least what do I need to check to discover the problem?
Thanks in advance.

Update repo throw exception

Hi,

When trying to update a repo via the method :

$repo = $client->api('repo')->update('username', 'my-new-repo', array('description' => 'some new description'));

We got an exception :

Uncaught exception 'Github\Exception\ValidationFailedException' with message 'Validation Failed: name is too short (minimum is 1 characters)' in ../vendor/knplabs/github-api/lib/Github/HttpClient/Listener/ErrorListener.php:79

We are of course authenticated and the exception is thrown whatever the repo type is (public/private).

Server error on creating tree

I m creating a tree .
$treeData = array('base_tree'=>$basetree['tree'][1]['sha'],'tree'=>
array( 'path'=>'welcome.txt'
,'mode'=>'100644'
,'type'=>'blob'
,'sha'=>$newBlob['sha']
)
);
this ling give me server error

criteria for tagging and insight assessment

i wonder what is the criteria for tagging this repo and if we can do it or
my question would be (currently insightsensiolabs is giving a warning because i do not specify a version but rather *) what is a work around to not request a version here.

If we use semver i think some bugs would be tagged as 1.0.1 or such, but i don't see many releases. So could you please try to implement a tagging policy for these? That way one can actually include serious critical bug fixes by doing ~1.0 and we will get all fixes with an update and yet don't be bothered by insightsensiolabs.

Thanks for your time reading this.

Unable to retrieve pull request diff

The following code snippet is supposed to produce the pull reques diff. It used to work a while ago but now it doesnt.

$client = new Github\Client();
$client->authenticate(
    'put-your-token-here',
    null,
    Github\Client::AUTH_URL_TOKEN
);

/** @var Github\Api\PullRequest $api */
$api = $client->api('pull_request');
$client->setHeaders(array(
    sprintf(
        'Accept: application/vnd.github.%s.diff',
        $client->getOption('api_version')
    )
));

$diff = $api->show('KnpLabs', 'php-github-api', '92');

echo gettype($diff);
// expected: string
// actual: array

The point is that here default Accept header is appepended with custom but not overridden, thus both of them are sent.

Default User-Agent and Accept headers should be sent only if other values are not specified.

Unable to list private repos for my organization

The following code:

$client = new Github\Client();
$client->authenticate('MY_TOKEN', Github\Client::AUTH_HTTP_TOKEN);

$client->api('organization')->repositories('MY_ORGANIZATION');

only returns the public repos of my organization.

When the following code:

$client = new Github\Client();

$client->getHttpClient()->get('orgs/MY_ORGANIZATION/repos', array(), array('Authorization: token MY_TOKEN'))->getContent();

returns all the repositories for my organization.

So I guess there is a problem with the authentication listener.

Model usage

Do you have any plans to add a model/OO interface to this? For example:

<?php

$org = new Github\Model\Org('screenpages');
$repo = $org->createRepo('github-api');
$issue = $repo->createIssue('This is a problem', array(
    'body' => 'Oh dear, now what?!'
));

$issue->addLabel('critical');

print_r($issue->labels());

I have been making these sort of classes (using the original Api\* objects underneath) since starting this new project, and decided to factor it in to my fork. So if you are planning something like this, let me know.

archive() returns an error when using cache.

Hello.

I'm using your package with Laravel and when using cache I get an error trying to call the archive() function of the Contents API.

Code:

public $github;

public function __construct()
{
    $this->github = new \Github\Client(
        new \Github\HttpClient\CachedHttpClient(array('cache_dir' => storage_path() . '/cache/github/'))
    );
}
$project['archive'] = $this->github->api('repo')->contents()->archive('zanmoskotevc', $repo, 'zipball');

Error:
Guzzle\Http\Message\Response::serialize() must return a string or NULL

image

Am I doing something wrong or is this a bug?
Other functions seem to work.

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.