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: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105:
<?php
/**
* This file is part of the league/oauth2-client library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Alex Bilbie <hello@alexbilbie.com>
* @license http://opensource.org/licenses/MIT MIT
* @link http://thephpleague.com/oauth2-client/ Documentation
* @link https://packagist.org/packages/league/oauth2-client Packagist
* @link https://github.com/thephpleague/oauth2-client GitHub
*/
namespace League\OAuth2\Client\Grant;
use League\OAuth2\Client\Grant\Exception\InvalidGrantException;
/**
* Represents a factory used when retrieving an authorization grant type.
*/
class GrantFactory
{
/**
* @var array
*/
protected $registry = [];
/**
* Defines a grant singleton in the registry.
*
* @param string $name
* @param AbstractGrant $grant
* @return self
*/
public function setGrant($name, AbstractGrant $grant)
{
$this->registry[$name] = $grant;
return $this;
}
/**
* Returns a grant singleton by name.
*
* If the grant has not be registered, a default grant will be loaded.
*
* @param string $name
* @return AbstractGrant
*/
public function getGrant($name)
{
if (empty($this->registry[$name])) {
$this->registerDefaultGrant($name);
}
return $this->registry[$name];
}
/**
* Registers a default grant singleton by name.
*
* @param string $name
* @return self
*/
protected function registerDefaultGrant($name)
{
// PascalCase the grant. E.g: 'authorization_code' becomes 'AuthorizationCode'
$class = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $name)));
$class = 'League\\OAuth2\\Client\\Grant\\' . $class;
$this->checkGrant($class);
return $this->setGrant($name, new $class);
}
/**
* Determines if a variable is a valid grant.
*
* @param mixed $class
* @return boolean
*/
public function isGrant($class)
{
return is_subclass_of($class, AbstractGrant::class);
}
/**
* Checks if a variable is a valid grant.
*
* @throws InvalidGrantException
* @param mixed $class
* @return void
*/
public function checkGrant($class)
{
if (!$this->isGrant($class)) {
throw new InvalidGrantException(sprintf(
'Grant "%s" must extend AbstractGrant',
is_object($class) ? get_class($class) : $class
));
}
}
}