Class yii\authclient\clients\GitHub
| Inheritance | yii\ |
|---|---|
| Implements | yii\ |
| Available since version | 2.0 |
| Source Code | https://github.com/yiisoft/yii2-authclient/blob/master/clients/GitHub.php |
GitHub allows authentication via GitHub OAuth.
In order to use GitHub OAuth you must register your application at https://github.com/settings/developers.
Example application configuration:
'components' => [
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'github' => [
'class' => 'yii\authclient\clients\GitHub',
'clientId' => 'github_client_id',
'clientSecret' => 'github_client_secret',
],
],
]
// ...
]
See also:
Public Properties
Public Methods
Protected Methods
Constants
| Constant | Value | Description | Defined By |
|---|---|---|---|
| ACCESS_TOKEN_LOCATION_BODY | 'body' | Apply the access token to the request body | yii\ |
| ACCESS_TOKEN_LOCATION_HEADER | 'header' | Apply the access token to the request header | yii\ |
Property Details
The location of the access token when it is applied to the request.
NOTE: According to the OAuth2 specification this should be header by default,
however, for backwards compatibility the default value used here is body.
API base URL.
This field will be used as \yii\httpclient\Client::baseUrl value of $httpClient. Note: changing this property will take no effect after $httpClient is instantiated.
Authorize URL.
Method Details
Defined in:
yii\
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
| public __call( string $name, array $params ): mixed | ||
| $name | string |
The method name |
| $params | array |
Method parameters |
| return | mixed |
The method return value |
|---|---|---|
| throws | yii\ |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in:
yii\
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
| public __clone( ): mixed |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in:
yii\
Constructor.
The default implementation does two things:
- Initializes the object with the given configuration
$config. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$confighere. - call the parent implementation at the end of the constructor.
| public __construct( array<string, mixed> $config = [] ): mixed | ||
| $config | array<string, mixed> |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in:
yii\
Returns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;.
See also __set().
| public __get( string $name ): mixed | ||
| $name | string |
The property name |
| return | mixed |
The property value or the value of a behavior's property |
|---|---|---|
| throws | yii\ |
if the property is not defined |
| throws | yii\ |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in:
yii\
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
falsefor non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property).
| public __isset( string $name ): boolean | ||
| $name | string |
The property name or the event name |
| return | boolean |
Whether the named property is set |
|---|---|---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in:
yii\
Sets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;.
See also __get().
| public __set( string $name, mixed $value ): mixed | ||
| $name | string |
The property name or the event name |
| $value | mixed |
The property value |
| throws | yii\ |
if the property is not defined |
|---|---|---|
| throws | yii\ |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
if ($value instanceof Behavior) {
$this->attachBehavior($name, $value);
} elseif ($value instanceof \Closure) {
$this->attachBehavior($name, call_user_func($value));
} elseif (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (!isset($value['__class']) && isset($value['class']) && is_subclass_of($value['class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (is_string($value) && is_subclass_of($value, Behavior::class, true)) {
$this->attachBehavior($name, Yii::createObject($value));
} else {
throw new InvalidConfigException('Class is not of type ' . Behavior::class . ' or its subclasses');
}
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in:
yii\
Sets a component property to be null.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property).
| public __unset( string $name ): mixed | ||
| $name | string |
The property name |
| throws | yii\ |
if the property is read only. |
|---|---|---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in:
yii\
Performs request to the OAuth API returning response data.
You may use createApiRequest() method instead, gaining more control over request execution.
See also createApiRequest().
| public api( string|array $apiSubUrl, string $method = 'GET', array|string $data = [], array $headers = [] ): array | ||
| $apiSubUrl | string|array |
API sub URL, which will be append to $apiBaseUrl, or absolute API URL. |
| $method | string |
Request method. |
| $data | array|string |
Request data or content. |
| $headers | array |
Additional request headers. |
| return | array |
API response data. |
|---|---|---|
public function api($apiSubUrl, $method = 'GET', $data = [], $headers = [])
{
$request = $this->createApiRequest()
->setMethod($method)
->setUrl($apiSubUrl)
->addHeaders($headers);
if (!empty($data)) {
if (is_array($data)) {
$request->setData($data);
} else {
$request->setContent($data);
}
}
return $this->sendRequest($request);
}
Applies access token to the HTTP request instance.
| public applyAccessTokenToRequest( mixed $request, mixed $accessToken ): mixed | ||
| $request | mixed |
HTTP request instance. |
| $accessToken | mixed |
Access token instance. |
| throws | yii\ |
|
|---|---|---|
public function applyAccessTokenToRequest($request, $accessToken)
{
$request->getHeaders()->add('Authorization', 'token ' . $accessToken->getToken());
}
Defined in:
yii\
Applies client credentials (e.g. $clientId and $clientSecret) to the HTTP request instance.
This method should be invoked before sending any HTTP request, which requires client credentials.
| protected applyClientCredentialsToRequest( \yii\httpclient\Request $request ): mixed | ||
| $request | \yii\httpclient\Request |
HTTP request instance. |
protected function applyClientCredentialsToRequest($request)
{
$request->addData([
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
]);
}
Defined in:
yii\
Attaches a behavior to this component.
This method will create the behavior object based on the given
configuration. After that, the behavior object will be attached to
this component by calling the yii\
See also detachBehavior().
| public attachBehavior( string $name, string|array|yii\ | ||
| $name | string |
The name of the behavior. |
| $behavior | string|array|yii\ |
The behavior configuration. This can be one of the following:
|
| return | yii\ |
The behavior object |
|---|---|---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in:
yii\
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\
See also attachBehavior().
| public attachBehaviors( array $behaviors ): mixed | ||
| $behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in:
yii\
Authenticate OAuth client directly at the provider without third party (user) involved, using 'client_credentials' grant type.
| public authenticateClient( array $params = [] ): yii\ | ||
| $params | array |
Additional request params. |
| return | yii\ |
Access token. |
|---|---|---|
public function authenticateClient($params = [])
{
$defaultParams = [
'grant_type' => 'client_credentials',
];
if (!empty($this->scope)) {
$defaultParams['scope'] = $this->scope;
}
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData(array_merge($defaultParams, $params));
$this->applyClientCredentialsToRequest($request);
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
Defined in:
yii\
Authenticates user directly by 'username/password' pair, using 'password' grant type.
| public authenticateUser( string $username, string $password, array $params = [] ): yii\ | ||
| $username | string |
User name. |
| $password | string |
User password. |
| $params | array |
Additional request params. |
| return | yii\ |
Access token. |
|---|---|---|
public function authenticateUser($username, $password, $params = [])
{
$defaultParams = [
'grant_type' => 'password',
'username' => $username,
'password' => $password,
];
if (!empty($this->scope)) {
$defaultParams['scope'] = $this->scope;
}
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData(array_merge($defaultParams, $params));
$this->applyClientCredentialsToRequest($request);
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
Defined in:
yii\
Authenticates user directly using JSON Web Token (JWT).
See also https://tools.ietf.org/html/rfc7515.
| public authenticateUserJwt( string $username, yii\ | ||
| $username | string | |
| $signature | yii\ |
Signature method or its array configuration. If empty - $signatureMethod will be used. |
| $options | array |
Additional options. Valid options are:
|
| $params | array |
Additional request params. |
| return | yii\ |
Access token. |
|---|---|---|
public function authenticateUserJwt($username, $signature = null, $options = [], $params = [])
{
if (empty($signature)) {
$signatureMethod = $this->getSignatureMethod();
} elseif (is_object($signature)) {
$signatureMethod = $signature;
} else {
$signatureMethod = $this->createSignatureMethod($signature);
}
$header = isset($options['header']) ? $options['header'] : [];
$payload = isset($options['payload']) ? $options['payload'] : [];
$header = array_merge([
'typ' => 'JWT'
], $header);
if (!isset($header['alg'])) {
$signatureName = $signatureMethod->getName();
if (preg_match('/^([a-z])[a-z]*\-([a-z])[a-z]*([0-9]+)$/is', $signatureName, $matches)) {
// convert 'RSA-SHA256' to 'RS256' :
$signatureName = $matches[1] . $matches[2] . $matches[3];
}
$header['alg'] = $signatureName;
}
$payload = array_merge([
'iss' => $username,
'scope' => $this->scope,
'aud' => $this->tokenUrl,
'iat' => time(),
], $payload);
if (!isset($payload['exp'])) {
$payload['exp'] = $payload['iat'] + 3600;
}
$signatureBaseString = base64_encode(Json::encode($header)) . '.' . base64_encode(Json::encode($payload));
$signatureKey = isset($options['signatureKey']) ? $options['signatureKey'] : $this->clientSecret;
$signature = $signatureMethod->generateSignature($signatureBaseString, $signatureKey);
$assertion = $signatureBaseString . '.' . $signature;
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData(array_merge([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $assertion,
], $params));
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
Defined in:
yii\
Handles Request::EVENT_BEFORE_SEND event.
Applies $accessToken to the request.
| public beforeApiRequestSend( \yii\httpclient\RequestEvent $event ): mixed | ||
| $event | \yii\httpclient\RequestEvent |
Event instance. |
| throws | yii\ |
on invalid access token. |
|---|---|---|
public function beforeApiRequestSend($event)
{
$accessToken = $this->getAccessToken();
if (!is_object($accessToken) || (!$accessToken->getIsValid() && !$this->autoRefreshAccessToken)) {
throw new Exception('Invalid access token.');
} elseif ($accessToken->getIsExpired() && $this->autoRefreshAccessToken) {
$accessToken = $this->refreshAccessToken($accessToken);
}
$this->applyAccessTokenToRequest($event->request, $accessToken);
}
Defined in:
yii\
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\
Behaviors declared in this method will be attached to the component automatically (on demand).
| public behaviors( ): array<array-key, class-string|array{class: class-string}|yii\ | ||
| return | array<array-key, class-string|array{class: class-string}|yii\ |
The behavior configurations. |
|---|---|---|
public function behaviors()
{
return [];
}
Defined in:
yii\
Composes user authorization URL.
| public buildAuthUrl( array $params = [] ): string | ||
| $params | array |
Additional auth GET params. |
| return | string |
Authorization URL. |
|---|---|---|
public function buildAuthUrl(array $params = [])
{
$defaultParams = [
'client_id' => $this->clientId,
'response_type' => 'code',
'redirect_uri' => $this->getReturnUrl(),
];
if (!empty($this->scope)) {
$defaultParams['scope'] = $this->scope;
}
if ($this->validateAuthState) {
$authState = $this->generateAuthState();
$this->setState('authState', $authState);
$defaultParams['state'] = $authState;
}
if ($this->enablePkce) {
$codeVerifier = bin2hex(Yii::$app->security->generateRandomKey(64));
$this->setState('authCodeVerifier', $codeVerifier);
$defaultParams['code_challenge'] = trim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
$defaultParams['code_challenge_method'] = 'S256';
}
return $this->composeUrl($this->authUrl, array_merge($defaultParams, $params));
}
Defined in:
yii\
Returns a value indicating whether a property can be read.
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true); - an attached behavior has a readable property of the given name (when
$checkBehaviorsis true).
See also canSetProperty().
| public canGetProperty( string $name, boolean $checkVars = true, boolean $checkBehaviors = true ): boolean | ||
| $name | string |
The property name |
| $checkVars | boolean |
Whether to treat member variables as properties |
| $checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
| return | boolean |
Whether the property can be read |
|---|---|---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in:
yii\
Returns a value indicating whether a property can be set.
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true); - an attached behavior has a writable property of the given name (when
$checkBehaviorsis true).
See also canGetProperty().
| public canSetProperty( string $name, boolean $checkVars = true, boolean $checkBehaviors = true ): boolean | ||
| $name | string |
The property name |
| $checkVars | boolean |
Whether to treat member variables as properties |
| $checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
| return | boolean |
Whether the property can be written |
|---|---|---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class instead.
Defined in:
yii\
Returns the fully qualified name of this class.
| public static className( ): string | ||
| return | string |
The fully qualified name of this class. |
|---|---|---|
public static function className()
{
return get_called_class();
}
Defined in:
yii\
Composes URL from base URL and GET params.
| protected composeUrl( string $url, array $params = [] ): string | ||
| $url | string |
Base URL. |
| $params | array |
GET params. |
| return | string |
Composed URL. |
|---|---|---|
protected function composeUrl($url, array $params = [])
{
if (!empty($params)) {
if (strpos($url, '?') === false) {
$url .= '?';
} else {
$url .= '&';
}
$url .= http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
return $url;
}
Defined in:
yii\
Creates an HTTP request for the API call.
The created request will be automatically processed adding access token parameters and signature before sending. You may use createRequest() to gain full control over request composition and execution.
See also createRequest().
| public createApiRequest( ): \yii\httpclient\Request | ||
| return | \yii\httpclient\Request |
HTTP request instance. |
|---|---|---|
public function createApiRequest()
{
$request = $this->createRequest();
$request->on(Request::EVENT_BEFORE_SEND, [$this, 'beforeApiRequestSend']);
return $request;
}
Defined in:
yii\
Creates HTTP client instance from reference or configuration.
| protected createHttpClient( mixed $reference ): \yii\httpclient\Client | ||
| $reference | mixed |
Component name or array configuration. |
| return | \yii\httpclient\Client |
HTTP client instance. |
|---|---|---|
protected function createHttpClient($reference)
{
$httpClient = parent::createHttpClient($reference);
$httpClient->baseUrl = $this->apiBaseUrl;
return $httpClient;
}
Defined in:
yii\
Creates HTTP request instance.
| public createRequest( ): \yii\httpclient\Request | ||
| return | \yii\httpclient\Request |
HTTP request instance. |
|---|---|---|
public function createRequest()
{
return $this->getHttpClient()
->createRequest()
->addOptions($this->defaultRequestOptions())
->addOptions($this->getRequestOptions());
}
Defined in:
yii\
Creates signature method instance from its configuration.
| protected createSignatureMethod( array $signatureMethodConfig ): yii\ | ||
| $signatureMethodConfig | array |
Signature method configuration. |
| return | yii\ |
Signature method instance. |
|---|---|---|
protected function createSignatureMethod(array $signatureMethodConfig)
{
if (!array_key_exists('class', $signatureMethodConfig)) {
$signatureMethodConfig['class'] = signature\HmacSha1::class;
}
return Yii::createObject($signatureMethodConfig);
}
Defined in:
yii\
Creates token from its configuration.
| protected createToken( array $tokenConfig = [] ): yii\ | ||
| $tokenConfig | array |
Token configuration. |
| return | yii\ |
Token instance. |
|---|---|---|
protected function createToken(array $tokenConfig = [])
{
$defaultTokenConfig = ['tokenParamKey' => 'access_token'];
$tokenConfig = array_merge($defaultTokenConfig, $tokenConfig);
return parent::createToken($tokenConfig);
}
Generates service name.
| protected defaultName( ): string | ||
| return | string |
Service name. |
|---|---|---|
protected function defaultName()
{
return 'github';
}
Defined in:
yii\
Returns the default $normalizeUserAttributeMap value.
Particular client may override this method in order to provide specific default map.
| protected defaultNormalizeUserAttributeMap( ): array | ||
| return | array |
Normalize attribute map. |
|---|---|---|
protected function defaultNormalizeUserAttributeMap()
{
return [];
}
Defined in:
yii\
Composes default $origin value, deriving it from $returnUrl.
| protected defaultOrigin( ): string | ||
| return | string |
Origin value. |
|---|---|---|
| throws | yii\ |
if the origin can not be derived from $returnUrl. |
protected function defaultOrigin()
{
$components = parse_url($this->getReturnUrl());
if (!isset($components['scheme'], $components['host'])) {
throw new InvalidConfigException('Unable to derive the origin from "returnUrl". Set the "origin" property explicitly.');
}
$origin = $components['scheme'] . '://' . $components['host'];
if (isset($components['port'])) {
$origin .= ':' . $components['port'];
}
return $origin;
}
Defined in:
yii\
Returns default HTTP request options.
| protected defaultRequestOptions( ): array | ||
| return | array |
HTTP request options. |
|---|---|---|
protected function defaultRequestOptions()
{
return [
'userAgent' => Inflector::slug(Yii::$app->name) . ' OAuth ' . $this->version . ' Client',
'timeout' => 30,
];
}
Defined in:
yii\
Composes default $returnUrl value.
| protected defaultReturnUrl( ): string | ||
| return | string |
Return URL. |
|---|---|---|
protected function defaultReturnUrl()
{
$params = Yii::$app->getRequest()->getQueryParams();
$params = array_intersect_key($params, array_flip($this->parametersToKeepInReturnUrl));
$params[0] = Yii::$app->controller->getRoute();
return Yii::$app->getUrlManager()->createAbsoluteUrl($params);
}
Generates service title.
| protected defaultTitle( ): string | ||
| return | string |
Service title. |
|---|---|---|
protected function defaultTitle()
{
return 'GitHub';
}
Defined in:
yii\
Returns the default $viewOptions value.
Particular client may override this method in order to provide specific default view options.
| protected defaultViewOptions( ): array | ||
| return | array |
List of default $viewOptions |
|---|---|---|
protected function defaultViewOptions()
{
return [];
}
Defined in:
yii\
Detaches a behavior from the component.
The behavior's yii\
| public detachBehavior( string $name ): yii\ | ||
| $name | string |
The behavior's name. |
| return | yii\ |
The detached behavior. Null if the behavior does not exist. |
|---|---|---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in:
yii\
Detaches all behaviors from the component.
| public detachBehaviors( ): mixed |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in:
yii\
Makes sure that the behaviors declared in behaviors() are attached to this component.
| public ensureBehaviors( ): mixed |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Defined in:
yii\
Fetches access token from authorization code.
| public fetchAccessToken( string $authCode, array $params = [] ): yii\ | ||
| $authCode | string |
Authorization code, usually comes at GET parameter 'code'. |
| $params | array |
Additional request params. |
| return | yii\ |
Access token. |
|---|---|---|
| throws | yii\ |
on invalid auth state in case enableStateValidation is enabled. |
public function fetchAccessToken($authCode, array $params = [])
{
if ($this->validateAuthState) {
$authState = $this->getState('authState');
$incomingRequest = Yii::$app->getRequest();
$incomingState = $incomingRequest->get('state', $incomingRequest->post('state'));
if (
!isset($incomingState)
|| empty($authState)
|| !Yii::$app->getSecurity()->compareString($incomingState, $authState)
) {
throw new HttpException(400, 'Invalid auth state parameter.');
}
$this->removeState('authState');
}
$defaultParams = [
'code' => $authCode,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->getReturnUrl(),
];
if ($this->enablePkce) {
$authCodeVerifier = $this->getState('authCodeVerifier');
if (empty($authCodeVerifier)) {
// Prevent PKCE Downgrade Attack
// https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#name-pkce-downgrade-attack
throw new HttpException(409, 'Invalid auth code verifier.');
}
$defaultParams['code_verifier'] = $authCodeVerifier;
$this->removeState('authCodeVerifier');
}
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData(array_merge($defaultParams, $params));
// Azure AD will complain if there is no `Origin` header.
if ($this->enablePkce) {
$request->addHeaders(['Origin' => $this->getOrigin()]);
}
$this->applyClientCredentialsToRequest($request);
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
Defined in:
yii\
Generates the auth state value.
| protected generateAuthState( ): string | ||
| return | string |
Auth state value. |
|---|---|---|
protected function generateAuthState()
{
$baseString = get_class($this) . '-' . time();
if (Yii::$app->has('session')) {
$baseString .= '-' . Yii::$app->session->getId();
}
return hash('sha256', uniqid($baseString, true));
}
Defined in:
yii\
| public getAccessToken( ): yii\ | ||
| return | yii\ |
Auth token instance. |
|---|---|---|
public function getAccessToken()
{
if (!is_object($this->_accessToken)) {
$this->_accessToken = $this->restoreAccessToken();
}
return $this->_accessToken;
}
Defined in:
yii\
Reads the current or stored access token without refreshing it or changing the in-memory token.
| protected getAccessTokenWithoutRefresh( ): mixed | ||
| return | mixed |
Stored token, normally an OAuthToken instance or null. |
|---|---|---|
protected function getAccessTokenWithoutRefresh()
{
return $this->_accessToken ?? $this->getState('token');
}
Defined in:
yii\
Returns the named behavior object.
| public getBehavior( string $name ): yii\ | ||
| $name | string |
The behavior name |
| return | yii\ |
The behavior object, or null if the behavior does not exist |
|---|---|---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in:
yii\
Returns all behaviors attached to this component.
| public getBehaviors( ): array<yii\ | ||
| return | array<yii\ |
List of behaviors attached to this component |
|---|---|---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
Defined in:
yii\
Returns HTTP client.
| public getHttpClient( ): \yii\httpclient\Client | ||
| return | \yii\httpclient\Client |
Internal HTTP client. |
|---|---|---|
public function getHttpClient()
{
if (!is_object($this->_httpClient)) {
$this->_httpClient = $this->createHttpClient($this->_httpClient);
}
return $this->_httpClient;
}
Defined in:
yii\
| public getId( ): string | ||
| return | string |
Service id |
|---|---|---|
public function getId()
{
if (empty($this->_id)) {
$this->_id = $this->getName();
}
return $this->_id;
}
Defined in:
yii\
| public getName( ): string | ||
| return | string |
Service name. |
|---|---|---|
public function getName()
{
if ($this->_name === null) {
$this->_name = $this->defaultName();
}
return $this->_name;
}
| public getNormalizeUserAttributeMap( ): array | ||
| return | array |
Normalize user attribute map. |
|---|---|---|
public function getNormalizeUserAttributeMap()
{
if ($this->_normalizeUserAttributeMap === null) {
$this->_normalizeUserAttributeMap = $this->defaultNormalizeUserAttributeMap();
}
return $this->_normalizeUserAttributeMap;
}
Defined in:
yii\
| public getOrigin( ): string | ||
| return | string |
Origin value. |
|---|---|---|
public function getOrigin()
{
if ($this->_origin === null) {
$this->_origin = $this->defaultOrigin();
}
return $this->_origin;
}
Defined in:
yii\
| public getRequestOptions( ): array | ||
| return | array |
HTTP request options. |
|---|---|---|
public function getRequestOptions()
{
return $this->_requestOptions;
}
Defined in:
yii\
| public getReturnUrl( ): string | ||
| return | string |
Return URL. |
|---|---|---|
public function getReturnUrl()
{
if ($this->_returnUrl === null) {
$this->_returnUrl = $this->defaultReturnUrl();
}
return $this->_returnUrl;
}
Defined in:
yii\
| public getSignatureMethod( ): yii\ | ||
| return | yii\ |
Signature method instance. |
|---|---|---|
public function getSignatureMethod()
{
if (!is_object($this->_signatureMethod)) {
$this->_signatureMethod = $this->createSignatureMethod($this->_signatureMethod);
}
return $this->_signatureMethod;
}
Defined in:
yii\
Returns persistent state value.
| protected getState( string $key ): mixed | ||
| $key | string |
State key. |
| return | mixed |
State value. |
|---|---|---|
protected function getState($key)
{
return $this->getStateStorage()->get($this->getStateKeyPrefix() . $key);
}
Defined in:
yii\
Returns session key prefix, which is used to store internal states.
| protected getStateKeyPrefix( ): string | ||
| return | string |
Session key prefix. |
|---|---|---|
protected function getStateKeyPrefix()
{
return get_class($this) . '_' . $this->getId() . '_';
}
Defined in:
yii\
| public getStateStorage( ): yii\ | ||
| return | yii\ |
Stage storage. |
|---|---|---|
public function getStateStorage()
{
if (!is_object($this->_stateStorage)) {
$this->_stateStorage = Yii::createObject($this->_stateStorage);
}
return $this->_stateStorage;
}
Defined in:
yii\
| public getTitle( ): string | ||
| return | string |
Service title. |
|---|---|---|
public function getTitle()
{
if ($this->_title === null) {
$this->_title = $this->defaultTitle();
}
return $this->_title;
}
Defined in:
yii\
| public getUserAttributes( ): array | ||
| return | array |
List of user attributes |
|---|---|---|
public function getUserAttributes()
{
if ($this->_userAttributes === null) {
$this->_userAttributes = $this->normalizeUserAttributes($this->initUserAttributes());
}
return $this->_userAttributes;
}
Defined in:
yii\
| public getViewOptions( ): array | ||
| return | array |
View options in format: optionName => optionValue |
|---|---|---|
public function getViewOptions()
{
if ($this->_viewOptions === null) {
$this->_viewOptions = $this->defaultViewOptions();
}
return $this->_viewOptions;
}
Defined in:
yii\
Returns a value indicating whether there is any handler attached to the named event.
| public hasEventHandlers( string $name ): boolean | ||
| $name | string |
The event name |
| return | boolean |
Whether there is any handler attached to the event. |
|---|---|---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in:
yii\
Returns a value indicating whether a method is defined.
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviorsis true).
| public hasMethod( string $name, boolean $checkBehaviors = true ): boolean | ||
| $name | string |
The property name |
| $checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
| return | boolean |
Whether the method is defined |
|---|---|---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in:
yii\
Returns a value indicating whether a property is defined for this component.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true); - an attached behavior has a property of the given name (when
$checkBehaviorsis true).
See also:
| public hasProperty( string $name, boolean $checkVars = true, boolean $checkBehaviors = true ): boolean | ||
| $name | string |
The property name |
| $checkVars | boolean |
Whether to treat member variables as properties |
| $checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
| return | boolean |
Whether the property is defined |
|---|---|---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
| public init( ): mixed |
public function init()
{
parent::init();
if ($this->scope === null) {
$this->scope = 'user';
}
}
Initializes authenticated user attributes.
| protected initUserAttributes( ): array | ||
| return | array |
Auth user attributes. |
|---|---|---|
protected function initUserAttributes()
{
$attributes = $this->api('user', 'GET');
if (empty($attributes['email'])) {
// in case user set 'Keep my email address private' in GitHub profile, email should be retrieved via extra API request
$scopes = explode(' ', $this->scope);
if (in_array('user:email', $scopes, true) || in_array('user', $scopes, true)) {
$emails = $this->api('user/emails', 'GET');
if (!empty($emails)) {
foreach ($emails as $email) {
if ($email['primary'] == 1 && $email['verified'] == 1) {
$attributes['email'] = $email['email'];
break;
}
}
}
}
}
return $attributes;
}
Defined in:
yii\
Normalize given user attributes according to $normalizeUserAttributeMap.
| protected normalizeUserAttributes( array $attributes ): array | ||
| $attributes | array |
Raw attributes. |
| return | array |
Normalized attributes. |
|---|---|---|
| throws | yii\ |
on incorrect normalize attribute map. |
protected function normalizeUserAttributes($attributes)
{
foreach ($this->getNormalizeUserAttributeMap() as $normalizedName => $actualName) {
if (is_scalar($actualName)) {
if (array_key_exists($actualName, $attributes)) {
$attributes[$normalizedName] = $attributes[$actualName];
}
} else {
if (is_callable($actualName)) {
$attributes[$normalizedName] = call_user_func($actualName, $attributes);
} elseif (is_array($actualName)) {
$haystack = $attributes;
$searchKeys = $actualName;
$isFound = true;
while (($key = array_shift($searchKeys)) !== null) {
if (is_array($haystack) && array_key_exists($key, $haystack)) {
$haystack = $haystack[$key];
} else {
$isFound = false;
break;
}
}
if ($isFound) {
$attributes[$normalizedName] = $haystack;
}
} else {
throw new InvalidConfigException('Invalid actual name "' . gettype($actualName) . '" specified at "' . get_class($this) . '::normalizeUserAttributeMap"');
}
}
}
return $attributes;
}
Defined in:
yii\
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
| public off( string $name, callable|null $handler = null ): boolean | ||
| $name | string |
Event name |
| $handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
| return | boolean |
If a handler is found and detached |
|---|---|---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in:
yii\
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event is an yii\
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
| public on( string $name, callable $handler, mixed $data = null, boolean $append = true ): mixed | ||
| $name | string |
The event name |
| $handler | callable |
The event handler |
| $data | mixed |
The data to be passed to the event handler when the event is triggered.
When the event handler is invoked, this data can be accessed via yii\ |
| $append | boolean |
Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
Defined in:
yii\
Gets new auth token to replace expired one.
| public refreshAccessToken( yii\ | ||
| $token | yii\ |
Expired auth token. |
| return | yii\ |
New auth token. |
|---|---|---|
public function refreshAccessToken(OAuthToken $token)
{
$params = [
'grant_type' => 'refresh_token'
];
$params = array_merge($token->getParams(), $params);
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData($params);
$this->applyClientCredentialsToRequest($request);
$response = $this->sendRequest($request);
if (!is_array($response)) {
throw new \UnexpectedValueException('OAuth2 token refresh response must be an array.');
}
$token = $this->createToken(['params' => array_merge($token->getParams(), $response)]);
$this->setAccessToken($token);
return $token;
}
Defined in:
yii\
Removes persistent state value.
| protected removeState( string $key ): boolean | ||
| $key | string |
State key. |
| return | boolean |
Success. |
|---|---|---|
protected function removeState($key)
{
return $this->getStateStorage()->remove($this->getStateKeyPrefix() . $key);
}
Defined in:
yii\
Restores access token.
| protected restoreAccessToken( ): yii\ | ||
| return | yii\ |
Auth token. |
|---|---|---|
protected function restoreAccessToken()
{
$token = $this->getState('token');
if (is_object($token)) {
/** @var OAuthToken $token */
if ($token->getIsExpired() && $this->autoRefreshAccessToken && $token->hasRefreshToken()) {
$token = $this->refreshAccessToken($token);
}
}
return $token;
}
Defined in:
yii\
Saves token as persistent state.
| protected saveAccessToken( yii\ | ||
| $token | yii\ |
Auth token to be saved. |
| return | $this |
The object itself. |
|---|---|---|
protected function saveAccessToken($token)
{
return $this->setState('token', $token);
}
Defined in:
yii\
Sends the given HTTP request, returning response data.
| protected sendRequest( \yii\httpclient\Request $request ): array|string|null | ||
| $request | \yii\httpclient\Request |
HTTP request to be sent. |
| return | array|string|null |
Response data. |
|---|---|---|
| throws | yii\ |
on client error response codes. |
| throws | yii\ |
on non-successful (other than client error) response codes. |
| throws | \yii\httpclient\Exception | |
protected function sendRequest($request)
{
$response = $request->send();
if (!$response->getIsOk()) {
$statusCode = (int)$response->getStatusCode();
if ($statusCode >= 400 && $statusCode < 500) {
$exceptionClass = 'yii\\authclient\\ClientErrorResponseException';
} else {
$exceptionClass = 'yii\\authclient\\InvalidResponseException';
}
throw new $exceptionClass(
$response,
'Request failed with code: ' . $statusCode . ', message: ' . $response->getContent(),
$statusCode
);
}
if (stripos($response->headers->get('content-type', ''), 'application/jwt') !== false) {
return $response->getContent();
} else {
return $response->getData();
}
}
Defined in:
yii\
Sets access token to be used.
| public setAccessToken( array|yii\ | ||
| $token | array|yii\ |
Access token or its configuration. Set to null to restore token from token store. |
public function setAccessToken($token)
{
if (!is_object($token) && $token !== null) {
$token = $this->createToken($token);
}
$this->_accessToken = $token;
$this->saveAccessToken($token);
}
Defined in:
yii\
Sets HTTP client to be used.
| public setHttpClient( mixed $httpClient ): mixed | ||
| $httpClient | mixed |
Internal HTTP client. |
public function setHttpClient($httpClient)
{
if (is_object($httpClient)) {
$httpClient = clone $httpClient;
$httpClient->baseUrl = $this->apiBaseUrl;
}
parent::setHttpClient($httpClient);
}
Defined in:
yii\
| public setId( string $id ): mixed | ||
| $id | string |
Service id. |
public function setId($id)
{
$this->_id = $id;
}
Defined in:
yii\
| public setName( string $name ): mixed | ||
| $name | string |
Service name. |
public function setName($name)
{
$this->_name = $name;
}
| public setNormalizeUserAttributeMap( array $normalizeUserAttributeMap ): mixed | ||
| $normalizeUserAttributeMap | array |
Normalize user attribute map. |
public function setNormalizeUserAttributeMap($normalizeUserAttributeMap)
{
$this->_normalizeUserAttributeMap = $normalizeUserAttributeMap;
}
Defined in:
yii\
| public setOrigin( string $origin ): void | ||
| $origin | string |
Origin value. |
public function setOrigin($origin)
{
$this->_origin = $origin;
}
Defined in:
yii\
| public setRequestOptions( array $options ): mixed | ||
| $options | array |
HTTP request options. |
public function setRequestOptions(array $options)
{
$this->_requestOptions = $options;
}
Defined in:
yii\
| public setReturnUrl( string $returnUrl ): mixed | ||
| $returnUrl | string |
Return URL |
public function setReturnUrl($returnUrl)
{
$this->_returnUrl = $returnUrl;
}
Defined in:
yii\
Set signature method to be used.
| public setSignatureMethod( array|yii\ | ||
| $signatureMethod | array|yii\ |
Signature method instance or its array configuration. |
| throws | yii\ |
on wrong argument. |
|---|---|---|
public function setSignatureMethod($signatureMethod)
{
if (!is_object($signatureMethod) && !is_array($signatureMethod)) {
throw new InvalidArgumentException('"' . get_class($this) . '::signatureMethod" should be instance of "\yii\autclient\signature\BaseMethod" or its array configuration. "' . gettype($signatureMethod) . '" has been given.');
}
$this->_signatureMethod = $signatureMethod;
}
Defined in:
yii\
Sets persistent state.
| protected setState( string $key, mixed $value ): $this | ||
| $key | string |
State key. |
| $value | mixed |
State value |
| return | $this |
The object itself |
|---|---|---|
protected function setState($key, $value)
{
$this->getStateStorage()->set($this->getStateKeyPrefix() . $key, $value);
return $this;
}
Defined in:
yii\
| public setStateStorage( yii\ | ||
| $stateStorage | yii\ |
Stage storage to be used. |
public function setStateStorage($stateStorage)
{
$this->_stateStorage = $stateStorage;
}
Defined in:
yii\
| public setTitle( string $title ): mixed | ||
| $title | string |
Service title. |
public function setTitle($title)
{
$this->_title = $title;
}
Defined in:
yii\
| public setUserAttributes( array $userAttributes ): mixed | ||
| $userAttributes | array |
List of user attributes |
public function setUserAttributes($userAttributes)
{
$this->_userAttributes = $this->normalizeUserAttributes($userAttributes);
}
Defined in:
yii\
| public setViewOptions( array $viewOptions ): mixed | ||
| $viewOptions | array |
View options in format: optionName => optionValue |
public function setViewOptions($viewOptions)
{
$this->_viewOptions = $viewOptions;
}
Defined in:
yii\
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
| public trigger( string $name, yii\ | ||
| $name | string |
The event name |
| $event | yii\ |
The event instance. If not set, a default yii\ |
public function trigger($name, ?Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}