Files
breadcrumb-the-shire/pages/admin/roles/create().php

119 lines
4.4 KiB
PHP
Raw Normal View History

2026-02-04 23:31:53 +01:00
<?php
use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
2026-02-04 23:31:53 +01:00
use MintyPHP\Router;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
2026-02-23 12:58:19 +01:00
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
2026-02-04 23:31:53 +01:00
$session = app(SessionStoreInterface::class)->all();
2026-02-04 23:31:53 +01:00
Guard::requireLogin();
2026-03-04 15:56:58 +01:00
$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('admin/roles');
$createTarget = requestPathWithReturnTarget('admin/roles/create', $returnTarget);
$currentUserId = (int) ($session['user']['id'] ?? 0);
refactor(creates-batch): migrate roles/permissions/tenants-create (step 10) Cluster-7 batch-replay of the departments-create pilot (step 9). All three remaining create actions follow the same shape with minor domain-specific variations. Each migration touches one action and one policy: * roles-create + RoleAuthorizationPolicy::authorizeAdminRolesCreate — policy previously returned bare allow() with no capabilities; now emits ['can_view_page' => true]. Action passes viewAuthFlags: []. * permissions-create + PermissionAuthorizationPolicy::authorizeAdminPermissionsCreate — same pattern as roles-create. * tenants-create + TenantAuthorizationPolicy::authorizeAdminTenantsCreate — policy already emitted can_manage_sso + can_manage_custom_fields; can_view_page is added as the first capability. Action passes viewAuthFlags: ['can_manage_sso', 'can_manage_custom_fields'] and materializes both booleans from the aggregator capabilities. All three policy updates are tautological — every actor that survives the deny() branches in each policy can by definition see the page. View, Create, and EditContext now share a consistent capability shape across all four core master-data domains (departments, roles, permissions, tenants). Three drift decisions reproduced: * notFoundFlashScopeKey is N/A (no model lookup in create flows). * t() consistency: Flash::success('Role created' / 'Permission created' / 'Tenant created') now flow through t(). * Defensive scope consumption: $canManageAllTenants reads $tenantScope['scope'] === 'all' as a resilient hook even where the policy emits no manage-all flag (roles/permissions are global, tenants-create has no filter logic). Inline comments document the intentional non-consumption of $tenantScope['ids']. Two contract-test pattern updates (AuthzAdminMasterDataContractTest + AuthzAdminTenantsContractTest) shift the assertion targets from AuthorizationService::class to actionCreateContext( — semantically equivalent because the aggregator wraps the same authorize call internally. ActionContextCsrfPairingContractTest now covers nine callers (five edits + four creates) and stays green. Helper file core/Support/helpers/action_context.php is 0-diff for the seventh consecutive migration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:00:05 +02:00
$context = actionCreateContext([
'abilityKey' => RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_CREATE,
'context' => ['actor_user_id' => $currentUserId],
'viewAuthFlags' => [],
'forbiddenStrategy' => 'deny',
]);
refactor(creates-batch): migrate roles/permissions/tenants-create (step 10) Cluster-7 batch-replay of the departments-create pilot (step 9). All three remaining create actions follow the same shape with minor domain-specific variations. Each migration touches one action and one policy: * roles-create + RoleAuthorizationPolicy::authorizeAdminRolesCreate — policy previously returned bare allow() with no capabilities; now emits ['can_view_page' => true]. Action passes viewAuthFlags: []. * permissions-create + PermissionAuthorizationPolicy::authorizeAdminPermissionsCreate — same pattern as roles-create. * tenants-create + TenantAuthorizationPolicy::authorizeAdminTenantsCreate — policy already emitted can_manage_sso + can_manage_custom_fields; can_view_page is added as the first capability. Action passes viewAuthFlags: ['can_manage_sso', 'can_manage_custom_fields'] and materializes both booleans from the aggregator capabilities. All three policy updates are tautological — every actor that survives the deny() branches in each policy can by definition see the page. View, Create, and EditContext now share a consistent capability shape across all four core master-data domains (departments, roles, permissions, tenants). Three drift decisions reproduced: * notFoundFlashScopeKey is N/A (no model lookup in create flows). * t() consistency: Flash::success('Role created' / 'Permission created' / 'Tenant created') now flow through t(). * Defensive scope consumption: $canManageAllTenants reads $tenantScope['scope'] === 'all' as a resilient hook even where the policy emits no manage-all flag (roles/permissions are global, tenants-create has no filter logic). Inline comments document the intentional non-consumption of $tenantScope['ids']. Two contract-test pattern updates (AuthzAdminMasterDataContractTest + AuthzAdminTenantsContractTest) shift the assertion targets from AuthorizationService::class to actionCreateContext( — semantically equivalent because the aggregator wraps the same authorize call internally. ActionContextCsrfPairingContractTest now covers nine callers (five edits + four creates) and stays green. Helper file core/Support/helpers/action_context.php is 0-diff for the seventh consecutive migration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:00:05 +02:00
$capabilities = $context['capabilities'];
$tenantScope = $context['tenantScope'];
$viewAuth = $context['viewAuth'];
// Roles are global; $tenantScope['ids'] is intentionally not consumed here.
// $canManageAllTenants stays as a resilient hook for future policy extensions.
$canManageAllTenants = $tenantScope['scope'] === 'all';
2026-02-04 23:31:53 +01:00
2026-03-04 15:56:58 +01:00
$errorBag = formErrors();
2026-02-04 23:31:53 +01:00
$errors = [];
$warnings = [];
2026-02-04 23:31:53 +01:00
$form = [
'description' => '',
2026-02-11 19:28:12 +01:00
'code' => '',
'active' => 1,
2026-02-04 23:31:53 +01:00
];
2026-03-04 15:56:58 +01:00
$permissionRepository = app(\MintyPHP\Repository\Access\PermissionRepository::class);
$rolePermissionRepository = app(\MintyPHP\Repository\Access\RolePermissionRepository::class);
2026-02-23 12:58:19 +01:00
$permissions = $permissionRepository->listActive();
2026-02-04 23:31:53 +01:00
$selectedPermissionIds = [];
if ($request->isMethod('POST') && !actionRequireCsrf($createTarget, $createTarget, 'csrf_expired')) {
return;
}
if ($request->isMethod('POST')) {
$dbSession = app(\MintyPHP\Repository\Support\DatabaseSessionRepository::class);
$transactionStarted = false;
try {
$dbSession->beginTransaction();
$transactionStarted = true;
2026-02-04 23:31:53 +01:00
$result = app(\MintyPHP\Service\Access\RoleService::class)->createFromAdmin($request->bodyAll(), $currentUserId);
$form = $result['form'] ?? $form;
$warnings = $result['warnings'] ?? [];
$errorBag->merge($result['errors'] ?? []);
$selectedPermissionIds = toIntIds($request->body('permission_ids', $selectedPermissionIds));
if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
$permissionIds = toIntIds($request->body('permission_ids', []));
$createdId = (int) ($result['id'] ?? 0);
if ($createdId <= 0) {
throw new \RuntimeException('role_create_missing_id');
}
$rolePermissionRepository->replaceForRole($createdId, $permissionIds);
$dbSession->commitTransaction();
$transactionStarted = false;
$action = (string) $request->body('action', 'create');
if ($action === 'create_close') {
if ($warnings) {
Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
}
refactor(creates-batch): migrate roles/permissions/tenants-create (step 10) Cluster-7 batch-replay of the departments-create pilot (step 9). All three remaining create actions follow the same shape with minor domain-specific variations. Each migration touches one action and one policy: * roles-create + RoleAuthorizationPolicy::authorizeAdminRolesCreate — policy previously returned bare allow() with no capabilities; now emits ['can_view_page' => true]. Action passes viewAuthFlags: []. * permissions-create + PermissionAuthorizationPolicy::authorizeAdminPermissionsCreate — same pattern as roles-create. * tenants-create + TenantAuthorizationPolicy::authorizeAdminTenantsCreate — policy already emitted can_manage_sso + can_manage_custom_fields; can_view_page is added as the first capability. Action passes viewAuthFlags: ['can_manage_sso', 'can_manage_custom_fields'] and materializes both booleans from the aggregator capabilities. All three policy updates are tautological — every actor that survives the deny() branches in each policy can by definition see the page. View, Create, and EditContext now share a consistent capability shape across all four core master-data domains (departments, roles, permissions, tenants). Three drift decisions reproduced: * notFoundFlashScopeKey is N/A (no model lookup in create flows). * t() consistency: Flash::success('Role created' / 'Permission created' / 'Tenant created') now flow through t(). * Defensive scope consumption: $canManageAllTenants reads $tenantScope['scope'] === 'all' as a resilient hook even where the policy emits no manage-all flag (roles/permissions are global, tenants-create has no filter logic). Inline comments document the intentional non-consumption of $tenantScope['ids']. Two contract-test pattern updates (AuthzAdminMasterDataContractTest + AuthzAdminTenantsContractTest) shift the assertion targets from AuthorizationService::class to actionCreateContext( — semantically equivalent because the aggregator wraps the same authorize call internally. ActionContextCsrfPairingContractTest now covers nine callers (five edits + four creates) and stays green. Helper file core/Support/helpers/action_context.php is 0-diff for the seventh consecutive migration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:00:05 +02:00
Flash::success(t('Role created'), $closeTarget, 'role_created');
Router::redirect($closeTarget);
} else {
$uuid = (string) ($result['uuid'] ?? '');
if ($uuid !== '') {
$target = requestPathWithReturnTarget("admin/roles/edit/{$uuid}", $returnTarget);
if ($warnings) {
Flash::info(implode(' ', $warnings), $target, 'role_warning');
}
refactor(creates-batch): migrate roles/permissions/tenants-create (step 10) Cluster-7 batch-replay of the departments-create pilot (step 9). All three remaining create actions follow the same shape with minor domain-specific variations. Each migration touches one action and one policy: * roles-create + RoleAuthorizationPolicy::authorizeAdminRolesCreate — policy previously returned bare allow() with no capabilities; now emits ['can_view_page' => true]. Action passes viewAuthFlags: []. * permissions-create + PermissionAuthorizationPolicy::authorizeAdminPermissionsCreate — same pattern as roles-create. * tenants-create + TenantAuthorizationPolicy::authorizeAdminTenantsCreate — policy already emitted can_manage_sso + can_manage_custom_fields; can_view_page is added as the first capability. Action passes viewAuthFlags: ['can_manage_sso', 'can_manage_custom_fields'] and materializes both booleans from the aggregator capabilities. All three policy updates are tautological — every actor that survives the deny() branches in each policy can by definition see the page. View, Create, and EditContext now share a consistent capability shape across all four core master-data domains (departments, roles, permissions, tenants). Three drift decisions reproduced: * notFoundFlashScopeKey is N/A (no model lookup in create flows). * t() consistency: Flash::success('Role created' / 'Permission created' / 'Tenant created') now flow through t(). * Defensive scope consumption: $canManageAllTenants reads $tenantScope['scope'] === 'all' as a resilient hook even where the policy emits no manage-all flag (roles/permissions are global, tenants-create has no filter logic). Inline comments document the intentional non-consumption of $tenantScope['ids']. Two contract-test pattern updates (AuthzAdminMasterDataContractTest + AuthzAdminTenantsContractTest) shift the assertion targets from AuthorizationService::class to actionCreateContext( — semantically equivalent because the aggregator wraps the same authorize call internally. ActionContextCsrfPairingContractTest now covers nine callers (five edits + four creates) and stays green. Helper file core/Support/helpers/action_context.php is 0-diff for the seventh consecutive migration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:00:05 +02:00
Flash::success(t('Role created'), $target, 'role_created');
Router::redirect($target);
} else {
if ($warnings) {
Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
}
refactor(creates-batch): migrate roles/permissions/tenants-create (step 10) Cluster-7 batch-replay of the departments-create pilot (step 9). All three remaining create actions follow the same shape with minor domain-specific variations. Each migration touches one action and one policy: * roles-create + RoleAuthorizationPolicy::authorizeAdminRolesCreate — policy previously returned bare allow() with no capabilities; now emits ['can_view_page' => true]. Action passes viewAuthFlags: []. * permissions-create + PermissionAuthorizationPolicy::authorizeAdminPermissionsCreate — same pattern as roles-create. * tenants-create + TenantAuthorizationPolicy::authorizeAdminTenantsCreate — policy already emitted can_manage_sso + can_manage_custom_fields; can_view_page is added as the first capability. Action passes viewAuthFlags: ['can_manage_sso', 'can_manage_custom_fields'] and materializes both booleans from the aggregator capabilities. All three policy updates are tautological — every actor that survives the deny() branches in each policy can by definition see the page. View, Create, and EditContext now share a consistent capability shape across all four core master-data domains (departments, roles, permissions, tenants). Three drift decisions reproduced: * notFoundFlashScopeKey is N/A (no model lookup in create flows). * t() consistency: Flash::success('Role created' / 'Permission created' / 'Tenant created') now flow through t(). * Defensive scope consumption: $canManageAllTenants reads $tenantScope['scope'] === 'all' as a resilient hook even where the policy emits no manage-all flag (roles/permissions are global, tenants-create has no filter logic). Inline comments document the intentional non-consumption of $tenantScope['ids']. Two contract-test pattern updates (AuthzAdminMasterDataContractTest + AuthzAdminTenantsContractTest) shift the assertion targets from AuthorizationService::class to actionCreateContext( — semantically equivalent because the aggregator wraps the same authorize call internally. ActionContextCsrfPairingContractTest now covers nine callers (five edits + four creates) and stays green. Helper file core/Support/helpers/action_context.php is 0-diff for the seventh consecutive migration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:00:05 +02:00
Flash::success(t('Role created'), $closeTarget, 'role_created');
Router::redirect($closeTarget);
}
}
}
} catch (\Throwable) {
if ($transactionStarted) {
try {
$dbSession->rollbackTransaction();
} catch (\Throwable) {
2026-02-04 23:31:53 +01:00
}
}
if (!$errorBag->hasAny()) {
$errorBag->merge([t('Failed to update role permissions')]);
}
2026-02-04 23:31:53 +01:00
}
}
2026-03-04 15:56:58 +01:00
$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
2026-02-04 23:31:53 +01:00
Buffer::set('title', t('Create role'));
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('Roles'), 'path' => 'admin/roles'],
['label' => t('Create role')],
];