TenantAtlas/app/Services/Graph/AssignmentFetcher.php
Ahmed Darrazi f314703ac6 fix: capture assignments when adding policies to backup sets
- Add includeAssignments parameter to addPoliciesToSet method
- Add 'Include Assignments' checkbox to UI (default: true)
- Fix AssignmentFetcher to use request() instead of non-existent get()
- Fix GroupResolver to use request() instead of non-existent post()
- Replace GraphLogger calls with Laravel Log facade
- Add tests for addPoliciesToSet with/without assignments
2025-12-22 17:17:52 +01:00

113 lines
3.2 KiB
PHP

<?php
namespace App\Services\Graph;
use Illuminate\Support\Facades\Log;
class AssignmentFetcher
{
public function __construct(
private readonly MicrosoftGraphClient $graphClient,
) {}
/**
* Fetch policy assignments with fallback strategy.
*
* Primary: GET /deviceManagement/configurationPolicies/{id}/assignments
* Fallback: GET /deviceManagement/configurationPolicies?$expand=assignments&$filter=id eq '{id}'
*
* @return array Returns assignment array or empty array on failure
*/
public function fetch(string $tenantId, string $policyId): array
{
try {
// Try primary endpoint
$assignments = $this->fetchPrimary($tenantId, $policyId);
if (! empty($assignments)) {
Log::debug('Fetched assignments via primary endpoint', [
'tenant_id' => $tenantId,
'policy_id' => $policyId,
'count' => count($assignments),
]);
return $assignments;
}
// Try fallback with $expand
Log::debug('Primary endpoint returned empty, trying fallback', [
'tenant_id' => $tenantId,
'policy_id' => $policyId,
]);
$assignments = $this->fetchWithExpand($tenantId, $policyId);
if (! empty($assignments)) {
Log::debug('Fetched assignments via fallback endpoint', [
'tenant_id' => $tenantId,
'policy_id' => $policyId,
'count' => count($assignments),
]);
return $assignments;
}
// Both methods returned empty
Log::debug('No assignments found for policy', [
'tenant_id' => $tenantId,
'policy_id' => $policyId,
]);
return [];
} catch (GraphException $e) {
Log::warning('Failed to fetch assignments', [
'tenant_id' => $tenantId,
'policy_id' => $policyId,
'error' => $e->getMessage(),
'context' => $e->context,
]);
return [];
}
}
/**
* Fetch assignments using primary endpoint.
*/
private function fetchPrimary(string $tenantId, string $policyId): array
{
$path = "/deviceManagement/configurationPolicies/{$policyId}/assignments";
$response = $this->graphClient->request('GET', $path, [
'tenant' => $tenantId,
]);
return $response->data['value'] ?? [];
}
/**
* Fetch assignments using $expand fallback.
*/
private function fetchWithExpand(string $tenantId, string $policyId): array
{
$path = '/deviceManagement/configurationPolicies';
$params = [
'$expand' => 'assignments',
'$filter' => "id eq '{$policyId}'",
];
$response = $this->graphClient->request('GET', $path, [
'tenant' => $tenantId,
'query' => $params,
]);
$policies = $response->data['value'] ?? [];
if (empty($policies)) {
return [];
}
return $policies[0]['assignments'] ?? [];
}
}