Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Composer
/vendor/
composer.lock

# Temporary files
*.tmp
*.temp
*~
.DS_Store
67 changes: 67 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ The SDK has the following dependencies:

## Getting started

### Version 1.7.0 - Exception Handling Support 🎉

Starting with version 1.7.0, the OneLogin PHP SDK supports exception-based error handling alongside the traditional manual error checking approach. This provides a more modern, cleaner way to handle API errors while maintaining full backward compatibility.

**New Features:**
- Optional exception throwing for API errors
- Type-safe exception classes for different error categories
- Configurable per-client or per-operation
- Fully backward compatible

You'll need a OneLogin account and a set of API credentials before you get started.

If you don't have an account you can [sign up for a free developer account here](https://www.onelogin.com/developer-signup).
Expand Down Expand Up @@ -55,10 +65,67 @@ https://onelogin.github.io/onelogin-php-sdk/index.html

### Errors and exceptions

#### Traditional Error Handling (Backward Compatible)

OneLogin's API can return 400, 401, 403 or 404 when there was any issue executing the action. When that happens, the methods of the SDK will include error and errorMessage in the OneLoginClient. Use the getError() and the getErrorDescription() to retrieve them.

In some scenarios there is an attribute not provided or invalid that causes the error on the execution of the API call, when that happens at the OneLoginClient there is available a getErrorAttribute() method that contains the name of the attribute that caused the issue. See the API documentation to verify when this data is provided by the API.

```php
$users = $client->getUsers();
if ($client->getError()) {
echo "Error: " . $client->getErrorDescription();
if ($client->getErrorAttribute()) {
echo " (Attribute: " . $client->getErrorAttribute() . ")";
}
}
```

#### Exception-Based Error Handling (Recommended)

For a more modern approach, you can enable exception throwing when creating the client or by using the `setThrowExceptions()` method. When exceptions are enabled, API errors will throw appropriate exceptions instead of requiring manual error checking.

```php
// Enable exceptions during client creation
$client = new OneLoginClient($clientId, $clientSecret, $region, 1000, true);

// Or enable on existing client
$client->setThrowExceptions(true);

try {
$users = $client->getUsers();
// Process users...
} catch (AuthenticationException $e) {
// Handle authentication errors (401, 403)
echo "Authentication failed: " . $e->getMessage();
} catch (ValidationException $e) {
// Handle validation errors (400)
echo "Validation error: " . $e->getMessage();
if ($e->getErrorAttribute()) {
echo " (Field: " . $e->getErrorAttribute() . ")";
}
} catch (RateLimitException $e) {
// Handle rate limit errors (429)
echo "Rate limit exceeded: " . $e->getMessage();
} catch (ServerException $e) {
// Handle server errors (5xx)
echo "Server error: " . $e->getMessage();
} catch (OneLoginException $e) {
// Handle any other API errors
echo "API error: " . $e->getMessage();
}
```

#### Available Exception Classes

- `OneLoginException` - Base exception for all OneLogin API errors
- `AuthenticationException` - Authentication/authorization failures (HTTP 401, 403)
- `ValidationException` - Request validation errors (HTTP 400)
- `RateLimitException` - Rate limit exceeded (HTTP 429)
- `ServerException` - Server errors (HTTP 5xx)

All exceptions include the HTTP status code via `getErrorCode()` and may include the problematic attribute via `getErrorAttribute()`.


### Authentication

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "onelogin/api",
"type": "library",
"version": "1.6.0",
"version": "1.7.0",
"minimum-stability": "dev",
"require": {
"php": ">=5.5",
Expand Down
98 changes: 98 additions & 0 deletions examples/exception_handling.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php
/**
* Example: Using OneLogin PHP SDK with Exception Handling
*
* This example demonstrates how to use the OneLogin PHP SDK with exception handling enabled.
* When exceptions are enabled, API errors will throw appropriate exceptions instead of
* requiring manual error checking.
*/

require_once '../vendor/autoload.php'; // Adjust path as needed

use OneLogin\api\OneLoginClient;
use OneLogin\api\exceptions\OneLoginException;
use OneLogin\api\exceptions\AuthenticationException;
use OneLogin\api\exceptions\ValidationException;
use OneLogin\api\exceptions\RateLimitException;
use OneLogin\api\exceptions\ServerException;

// Configuration
$clientId = 'your_client_id';
$clientSecret = 'your_client_secret';
$region = 'us'; // or 'eu'

// Example 1: Traditional approach (backward compatible)
echo "=== Traditional Approach (Backward Compatible) ===\n";
$client = new OneLoginClient($clientId, $clientSecret, $region);

// Manual error checking is still required
$users = $client->getUsers();
if ($client->getError()) {
echo "Error: " . $client->getErrorDescription() . "\n";
} else {
echo "Users retrieved successfully\n";
}

// Example 2: Exception-based approach (recommended)
echo "\n=== Exception-based Approach (Recommended) ===\n";
$clientWithExceptions = new OneLoginClient($clientId, $clientSecret, $region, 1000, true);

try {
$users = $clientWithExceptions->getUsers();
echo "Users retrieved successfully\n";
// Process users...

} catch (AuthenticationException $e) {
echo "Authentication Error: " . $e->getMessage() . "\n";
echo "HTTP Status Code: " . $e->getErrorCode() . "\n";
// Handle authentication errors (401, 403)

} catch (ValidationException $e) {
echo "Validation Error: " . $e->getMessage() . "\n";
echo "HTTP Status Code: " . $e->getErrorCode() . "\n";
if ($e->getErrorAttribute()) {
echo "Error Attribute: " . $e->getErrorAttribute() . "\n";
}
// Handle validation errors (400)

} catch (RateLimitException $e) {
echo "Rate Limit Exceeded: " . $e->getMessage() . "\n";
echo "HTTP Status Code: " . $e->getErrorCode() . "\n";
// Handle rate limiting (429) - maybe retry after delay

} catch (ServerException $e) {
echo "Server Error: " . $e->getMessage() . "\n";
echo "HTTP Status Code: " . $e->getErrorCode() . "\n";
// Handle server errors (5xx) - maybe retry later

} catch (OneLoginException $e) {
echo "OneLogin API Error: " . $e->getMessage() . "\n";
echo "HTTP Status Code: " . $e->getErrorCode() . "\n";
// Handle any other API errors
}

// Example 3: Enable exceptions on existing client
echo "\n=== Enable Exceptions on Existing Client ===\n";
$existingClient = new OneLoginClient($clientId, $clientSecret, $region);
$existingClient->setThrowExceptions(true);

try {
$user = $existingClient->getUser(12345);
echo "User retrieved successfully\n";
} catch (OneLoginException $e) {
echo "Error retrieving user: " . $e->getMessage() . "\n";
}

// Example 4: Mixed approach - temporarily disable exceptions
echo "\n=== Temporarily Disable Exceptions ===\n";
$client->setThrowExceptions(false);
$result = $client->createUser(['email' => 'test@example.com']);
if ($client->getError()) {
echo "Create user failed: " . $client->getErrorDescription() . "\n";
}

// Re-enable exceptions
$client->setThrowExceptions(true);

echo "\nExamples completed!\n";
?>
138 changes: 138 additions & 0 deletions examples/migration_guide.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?php
/**
* Migration Guide: From Manual Error Checking to Exception Handling
*
* This example shows how to migrate from manual error checking to
* exception-based error handling in the OneLogin PHP SDK.
*/

require_once '../vendor/autoload.php'; // Adjust path as needed

use OneLogin\api\OneLoginClient;
use OneLogin\api\exceptions\OneLoginException;
use OneLogin\api\exceptions\AuthenticationException;
use OneLogin\api\exceptions\ValidationException;

$clientId = 'your_client_id';
$clientSecret = 'your_client_secret';

echo "=== OneLogin SDK Migration Guide ===\n\n";

// ========================================================================
// BEFORE: Manual Error Checking (Still Supported)
// ========================================================================
echo "BEFORE - Manual Error Checking:\n";
echo str_repeat("-", 40) . "\n";

$client = new OneLoginClient($clientId, $clientSecret);

// Example: Getting users with manual error checking
$users = $client->getUsers();
if ($client->getError()) {
echo "❌ Error getting users: " . $client->getErrorDescription() . "\n";
echo " HTTP Code: " . $client->getError() . "\n";
if ($client->getErrorAttribute()) {
echo " Problem field: " . $client->getErrorAttribute() . "\n";
}
} else {
echo "✅ Users retrieved successfully\n";
}

// Example: Creating user with manual error checking
$newUser = [
'email' => 'john.doe@example.com',
'firstname' => 'John',
'lastname' => 'Doe'
];

$user = $client->createUser($newUser);
if ($client->getError()) {
echo "❌ Error creating user: " . $client->getErrorDescription() . "\n";
echo " HTTP Code: " . $client->getError() . "\n";
if ($client->getErrorAttribute()) {
echo " Problem field: " . $client->getErrorAttribute() . "\n";
}
} else {
echo "✅ User created successfully\n";
}

// ========================================================================
// AFTER: Exception-Based Error Handling (Recommended)
// ========================================================================
echo "\nAFTER - Exception-Based Error Handling:\n";
echo str_repeat("-", 40) . "\n";

// Option 1: Enable exceptions during construction
$clientWithExceptions = new OneLoginClient($clientId, $clientSecret, 'us', 1000, true);

// Option 2: Enable exceptions on existing client
// $client->setThrowExceptions(true);

try {
// Getting users - no manual error checking needed!
$users = $clientWithExceptions->getUsers();
echo "✅ Users retrieved successfully\n";

// Creating user - exceptions will be thrown automatically on error
$user = $clientWithExceptions->createUser($newUser);
echo "✅ User created successfully\n";

// Chain multiple operations safely
$userRoles = $clientWithExceptions->getUserRoles($user->getId());
$apps = $clientWithExceptions->getUserApps($user->getId());
echo "✅ User data retrieved successfully\n";

} catch (AuthenticationException $e) {
echo "❌ Authentication Error: " . $e->getMessage() . "\n";
echo " HTTP Code: " . $e->getErrorCode() . "\n";
// Handle auth errors - maybe refresh tokens or re-authenticate

} catch (ValidationException $e) {
echo "❌ Validation Error: " . $e->getMessage() . "\n";
echo " HTTP Code: " . $e->getErrorCode() . "\n";
if ($e->getErrorAttribute()) {
echo " Problem field: " . $e->getErrorAttribute() . "\n";
}
// Handle validation errors - fix the data and retry

} catch (OneLoginException $e) {
echo "❌ OneLogin API Error: " . $e->getMessage() . "\n";
echo " HTTP Code: " . $e->getErrorCode() . "\n";
// Handle any other API errors
}

// ========================================================================
// HYBRID APPROACH: Use Both as Needed
// ========================================================================
echo "\nHYBRID - Use Both Approaches as Needed:\n";
echo str_repeat("-", 40) . "\n";

$hybridClient = new OneLoginClient($clientId, $clientSecret);

// For critical operations, use exceptions
$hybridClient->setThrowExceptions(true);
try {
$criticalData = $hybridClient->getUser(12345);
echo "✅ Critical data retrieved with exceptions\n";
} catch (OneLoginException $e) {
echo "❌ Critical operation failed: " . $e->getMessage() . "\n";
}

// For optional operations, use manual checking
$hybridClient->setThrowExceptions(false);
$optionalData = $hybridClient->getUser(99999);
if ($hybridClient->getError()) {
echo "⚠️ Optional operation failed (ignored): " . $hybridClient->getErrorDescription() . "\n";
} else {
echo "✅ Optional data retrieved\n";
}

echo "\n=== Migration Complete! ===\n";
echo "Benefits of Exception-Based Approach:\n";
echo "✅ Cleaner, more readable code\n";
echo "✅ Automatic error propagation\n";
echo "✅ Type-safe error handling\n";
echo "✅ Easier to chain operations\n";
echo "✅ Better error categorization\n";
echo "✅ Still fully backward compatible!\n";
?>
Loading