作者:iamduy
项目:bowerph
/**
* Set oauth token (to increase API limit to 5000 per hour, instead of default 60)
*
* @param Client $client
*/
protected function setToken(Client $client)
{
$token = getenv('BOWERPHP_TOKEN');
if (!empty($token)) {
$client->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
}
}
作者:kunstmaa
项目:github-flow-changelo
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$changelog = array();
$client = new Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => '/tmp/github-api-cache')));
$client->authenticate($input->getArgument("token"), null, Client::AUTH_HTTP_TOKEN);
$pullRequestAPI = $client->api('pull_request');
$paginator = new ResultPager($client);
$parameters = array($input->getArgument("organisation"), $input->getArgument("repository"), array('state' => 'closed'));
$pullRequests = $paginator->fetchAll($pullRequestAPI, 'all', $parameters);
$mergedPullRequests = array_filter($pullRequests, function ($pullRequest) {
return !empty($pullRequest["merged_at"]);
});
foreach ($mergedPullRequests as $pullRequest) {
if (empty($pullRequest['milestone'])) {
$milestone = "No Milestone Selected";
} else {
$milestone = $pullRequest['milestone']['title'] . " / " . strftime("%Y-%m-%d", strtotime($pullRequest['milestone']['due_on']));
}
if (!array_key_exists($milestone, $changelog)) {
$changelog[$milestone] = array();
}
$changelog[$milestone][] = $pullRequest;
}
uksort($changelog, 'version_compare');
$changelog = array_reverse($changelog);
echo "# Changelog";
foreach ($changelog as $milestone => $pullRequests) {
echo "\n\n## {$milestone}\n\n";
foreach ($pullRequests as $pullRequest) {
echo "* " . $pullRequest['title'] . " [#" . $pullRequest['number'] . "](" . $pullRequest['html_url'] . ") ([@" . $pullRequest['user']['login'] . "](" . $pullRequest['user']['html_url'] . ")) \n";
}
}
//var_dump($changelog);
}
作者:xpyctu
项目:ShogCha
public function showPage()
{
if (isset($_POST["register-data"]) && isset($_POST["register-password"])) {
try {
$client = new Client();
$client->authenticate($_POST["register-data"], Client::AUTH_HTTP_TOKEN);
$user = $client->api('current_user')->show();
$repos = [];
foreach ($client->api('current_user')->repositories('member', 'updated', 'desc') as $repo) {
$repos[] = ["name" => $repo["full_name"], "isPrivate" => $repo["private"]];
}
if (strlen($_POST["register-password"]) >= 6) {
Users::createUser($user["login"], $client->api('current_user')->emails()->all()[0], $_POST["register-password"], $_POST["register-data"], $repos);
Channels::addChannels($repos);
echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["user" => $user])]);
} else {
echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["error" => "Passwords must be at least 6 characters long."])]);
}
} catch (\Exception $e) {
echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), ["error" => "Oh no! Your registration couldn't be completed. Do you already have an account? Is your token valid?"])]);
}
} else {
echo $this->getTemplateEngine()->render($this->getTemplateSnip("page"), ["title" => "Register", "content" => $this->getTemplateEngine()->render($this->getTemplate(), [])]);
}
//echo $this->getTemplateEngine()->render($this->getTemplate(), []);
}
作者:kinnc
项目:forke
/**
* (non-PHPdoc)
* @see \Symfony\Component\Console\Command\Command::execute()
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$dialog = $this->getHelper('dialog');
try {
$client = new Client();
$username = $input->getOption('username');
if (!$username) {
$username = $dialog->ask($output, 'Please enter your GitHub username: ');
}
$password = $input->getOption('password');
if (!$password) {
$password = $dialog->askHiddenResponse($output, 'Please enter your GitHub password: ');
}
$client->authenticate($username, $password, Client::AUTH_HTTP_PASSWORD);
$forkService = $this->getForkService($input, $client);
$forkedRepositoryList = $forkService->fork();
$message = $this->formatMessage($forkedRepositoryList);
} catch (\InvalidArgumentException $exception) {
$message = $exception->getMessage();
} catch (GithubRuntimeException $exception) {
$message = $exception->getMessage();
$message = "<error>{$message}</error>";
} finally {
$output->writeln($message);
}
}
作者:terrett
项目:gitki.ph
public function handleResponse(UserResponseInterface $response, UserService $userService)
{
$fields = $response->getResponse();
$gitHubLogin = $fields['login'];
$accessToken = $response->getAccessToken();
$user = $userService->findByGitHubLogin($gitHubLogin);
if (null === $user) {
throw new UsernameNotFoundException();
}
$oAuthUser = new OAuthUser($user);
$oAuthUser->addRole('ROLE_GITHUB_USER');
$oAuthUser->setAccessToken($accessToken);
if (array_key_exists('name', $fields)) {
$gitHubName = $fields['name'];
$oAuthUser->setRealName($gitHubName);
} else {
$oAuthUser->setRealName($gitHubLogin);
}
$client = new Client();
$client->setOption('api_version', 'v3');
$client->authenticate($response->getAccessToken(), Client::AUTH_HTTP_TOKEN);
/* @var \Github\Api\CurrentUser $currentUserApi */
$currentUserApi = $client->api('current_user');
$emails = $currentUserApi->emails();
$allEMails = $emails->all();
$oAuthUser->setEmail($this->getPrimaryEmailAddress($allEMails));
return $oAuthUser;
}
作者:nickl
项目:php-github-ap
public function testInjectApi()
{
$client = new Client();
$userApiMock = $this->getMockBuilder('Github\\Api\\ApiInterface')->getMock();
$client->setApi('user', $userApiMock);
$this->assertSame($userApiMock, $client->getUserApi());
}
作者:CipHu
项目:phansibl
/**
* {@inheritdoc}
*/
public function register(Application $app)
{
$app['github'] = $app->share(function () {
$client = new Client(new CachedHttpClient(['cache_dir' => __DIR__ . '/../../../app/cache/github-api-cache']));
return new GithubAdapter($client->getHttpClient());
});
}
作者:qasi
项目:twig-markdow
protected function getEngine()
{
$client = new Client();
if ($client->rateLimit()->getCoreLimit() < 1) {
$this->markTestSkipped('The github API rate limit is reached, so this engine cannot be tested.');
}
return new GitHubMarkdownEngine();
}
作者:matk
项目:gitspamme
/**
* Construct GitSpam instance with its dependencies
*
* @param $username
* @param $password
*
* @return GitSpam
*/
private function setup($username, $password)
{
$client = new GithubAPIClient();
$client->authenticate($username, $password);
$commitReader = new YouTrackCommitReader();
$gitSpammer = new GitSpammer($client, $commitReader);
return $gitSpammer;
}
作者:morozo
项目:diff-sniffer-pull-reques
/**
* Runs pull request validation
*
* @param Client $client GitHub client
* @param Config $config Configuration
* @param array $arguments Command line arguments
*
* @return int Exit code
* @throws \InvalidArgumentException
*/
function run(Client $client, Config $config, array $arguments)
{
$config = $config->getParams();
$client->authenticate($config['token'], null, Client::AUTH_URL_TOKEN);
$changeset = new Changeset($client, array_shift($arguments), array_shift($arguments), array_shift($arguments));
$runner = new Runner();
return $runner->run($changeset, $arguments);
}
作者:ilmal
项目:snippet
protected function getClient()
{
$httpClient = new CachedHttpClient(['cache_dir' => storage_path(config('services.github.cache_url'))]);
$client = new Client($httpClient);
//dd($client);
$client->authenticate(auth()->user()->github_token, 'http_token');
return $client;
}
作者:simplec
项目:fronten
public static function createClient(SettingsManager $settingsManager)
{
$settings = new GeneralSettings();
$settingsManager->loadSettings($settings);
$client = new Client();
$client->authenticate($settings->githubToken, null, Client::AUTH_HTTP_TOKEN);
return $client;
}
作者:mistymagic
项目:gus
/**
* {@inheritdoc}
*/
public function interact(InputInterface $input, OutputInterface $output)
{
$config = parent::interact($input, $output);
// Do authentication now so we can detect 2fa
if (self::AUTH_HTTP_PASSWORD === $config['authentication']['http-auth-type']) {
$client = new Client();
try {
$client->authenticate($config['authentication']['username'], $config['authentication']['password-or-token']);
try {
// Make a call to test authentication
$client->api('authorizations')->all();
} catch (TwoFactorAuthenticationRequiredException $e) {
// Create a random authorization to make GitHub send the code
// We expect an exception, which gets cached by the next catch-block
// Note. This authorization is not actually created
$client->api('authorizations')->create(['note' => 'Gush on ' . gethostname() . mt_rand(), 'scopes' => ['public_repo']]);
}
} catch (TwoFactorAuthenticationRequiredException $e) {
$isAuthenticated = false;
$authenticationAttempts = 0;
$authorization = [];
$scopes = ['user', 'user:email', 'public_repo', 'repo', 'repo:status', 'read:org'];
$output->writeln(sprintf('Two factor authentication of type %s is required: ', trim($e->getType())));
// We already know the password is valid, we just need a valid code
// Don't want fill in everything again when you know its valid ;)
while (!$isAuthenticated) {
// Prevent endless loop with a broken test
if ($authenticationAttempts > 500) {
$output->writeln('<error>To many attempts, aborting.</error>');
break;
}
if ($authenticationAttempts > 0) {
$output->writeln('<error>Authentication failed please try again.</error>');
}
try {
$code = $this->questionHelper->ask($input, $output, (new Question('Authentication code: '))->setValidator([$this, 'validateNoneEmpty']));
// Use a date with time to make sure its unique
// Its not possible get existing authorizations, only a new one
$time = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y-m-d\\TH:i:s');
$authorization = $client->api('authorizations')->create(['note' => sprintf('Gush on %s at %s', gethostname(), $time), 'scopes' => $scopes], $code);
$isAuthenticated = isset($authorization['token']);
} catch (TwoFactorAuthenticationRequiredException $e) {
// Noop, continue the loop, try again
} catch (\Exception $e) {
$output->writeln("<error>{$e->getMessage()}</error>");
$output->writeln('');
}
++$authenticationAttempts;
}
if ($isAuthenticated) {
$config['authentication']['http-auth-type'] = self::AUTH_HTTP_TOKEN;
$config['authentication']['password-or-token'] = $authorization['token'];
}
}
}
return $config;
}
作者:branko
项目:devboar
public function let(Client $client, HookSettings $hookSettings, GithubRepo $githubRepo, Repo $repo, Hooks $hooks)
{
$githubRepo->getOwner()->willReturn('owner');
$githubRepo->getName()->willReturn('repository');
$client->repo()->willReturn($repo);
$repo->hooks()->willReturn($hooks);
$hookSettings->getCreateHookParams()->willReturn(['params']);
$this->beConstructedWith($client, $hookSettings, $githubRepo);
}
作者:digitalkao
项目:issue
public function it_returns_the_badges(Client $client, Repo $api, Contents $content)
{
$client->repos()->willReturn($api);
$api->contents()->willReturn($content);
$content->show('foo', 'bar', '.travis.yml')->shouldBeCalled()->willReturn(['encoding' => 'base64', 'content' => base64_encode('{}')]);
$content->show('foo', 'bar', 'composer.json')->shouldBeCalled()->willReturn(['encoding' => 'base64', 'content' => base64_encode('{ "name" : "foo/bar"}')]);
$this->getBadges()->shouldBeArray();
$this->getBadges()->shouldHaveCount(3);
}
作者:matk
项目:gitspamme
/**
* Analyse Pull Request
*
* @param string $repositoryOwner
* @param string $repositoryName
* @param integer $pullRequestID
* @return array
*/
public function analysePR($repositoryOwner, $repositoryName, $pullRequestID)
{
$commits = $this->githubClient->api('pull_request')->commits($repositoryOwner, $repositoryName, $pullRequestID);
if (!$commits) {
throw new Exception('Cannot fetch Pull Request data');
}
$commitsAnalysisResults = $this->commitReader->analyseCommits($commits);
return $commitsAnalysisResults;
}
作者:manuelpichle
项目:pivotal-github-syn
/**
* Constructs a new GitHub tracker instance.
*
* @param string $username
* @param string $password
* @param string $project
* @param string $owner Optional project owner, e.g. user or organization.
*/
public function __construct($username, $password, $project, $owner = null)
{
$github = new Client();
$github->setHeaders(array('Authorization: Basic ' . base64_encode("{$username}:{$password}")));
$github->authenticate($username, $password, Client::AUTH_HTTP_PASSWORD);
$this->github = $github->getIssueApi();
$this->owner = $owner ?: $username;
$this->project = $project;
}
作者:loopline-system
项目:trello-github-issue-manage
/**
* @return Client
*/
public function getGithubClient()
{
if (!$this->client) {
$token = $this->container->getParameter('github')['api']['auth_token'];
$this->client = new \Github\Client();
$this->client->authenticate($token, null, \Github\Client::AUTH_HTTP_TOKEN);
}
return $this->client;
}
作者:ezzy133
项目:release-note
/**
* Create a github client wrapper with automated token-based authentication.
*
* @param string $token The API token to authenticate with.
* @param string $owner The owner name of the github repository.
* @param string $repo The name of the github repository.
* @param string $apiUrl The base url to the github API if different from the main github site (i.e., GitHub Enterprise).
* @return self The github client wrapper, authenticated against the API.
*/
public static function createWithToken($token, $owner, $repo, $apiUrl = null)
{
$client = new Client();
if ($apiUrl !== null) {
$client->setOption('base_url', $apiUrl);
}
$client->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
return new static($client, $owner, $repo);
}
作者:approve-cod
项目:approve-code-webap
/**
* @param string|null $accessToken
* @return Client
*/
public function createClient($accessToken = null)
{
$client = new Client();
if ($this->token instanceof OAuthToken && null === $accessToken) {
$client->authenticate($this->token->getAccessToken(), null, Client::AUTH_HTTP_TOKEN);
} elseif (null !== $accessToken) {
$client->authenticate($accessToken, null, Client::AUTH_HTTP_TOKEN);
}
return $client;
}