Files
breadcrumb-the-shire/pages/admin/departments/create().php
fs d6be536fbf refactor(departments-create): migrate to actionCreateContext (step 9)
First production use of actionCreateContext — the second aggregator
introduced in step 1 and unit-tested at the building-block level, but
not yet exercised against a real caller. Helper file stays 0-diff for
the sixth consecutive migration.

The migration uncovers one real API gap and resolves it at the policy
layer rather than at the helper:

* actionCreateContext always calls actionEnforceCanViewPage. The
  Departments create-decision was the only Departments authorize
  branch that did not emit can_view_page (View and EditContext both
  did). Adding 'can_view_page' => true to the create-capabilities
  map is tautological — every actor that survives the deny() guards
  at lines 69-70 and 75-76 can by definition see the page. No new
  forbidden path is created. View, Create, and EditContext now share
  the same capability shape.

Three drift decisions reproduced where applicable:
* notFoundFlashScopeKey is N/A (no model lookup in create flow).
* t() consistency: all three Flash::success('Department created', …)
  calls now flow through t().
* Defensive scope consumption: $canManageAllTenants reads
  $tenantScope['scope'] === 'all', mirroring the edit-action pattern.
  The GET tenant filter rewrites from is_array($allowedTenantIds) to
  the three-way scope-tuple form.

AuthzAdminMasterDataContractTest gets a single-line assertion update
(AuthorizationService::class → actionCreateContext() pattern). The
aggregator wraps the same authorize call internally, so this is a
pattern-rename, not a semantic shift.

ActionContextCsrfPairingContractTest now covers six callers (five
edits + departments-create) and stays green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 14:44:09 +02:00

110 lines
4.1 KiB
PHP

<?php
use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('admin/departments');
$createTarget = requestPathWithReturnTarget('admin/departments/create', $returnTarget);
$tenantService = app(\MintyPHP\Service\Tenant\TenantService::class);
$directoryScopeGateway = app(\MintyPHP\Service\Tenant\TenantScopeService::class);
$departmentService = app(\MintyPHP\Service\Org\DepartmentService::class);
$currentUserId = (int) ($session['user']['id'] ?? 0);
$context = actionCreateContext([
'abilityKey' => DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_CREATE,
'context' => ['actor_user_id' => $currentUserId],
'viewAuthFlags' => [],
'forbiddenStrategy' => 'deny',
]);
$capabilities = $context['capabilities'];
$tenantScope = $context['tenantScope'];
$viewAuth = $context['viewAuth'];
$canManageAllTenants = $tenantScope['scope'] === 'all';
$allowedTenantIds = toIntIds($capabilities['allowed_tenant_ids'] ?? []);
$isStrictScope = (bool) ($capabilities['is_strict_scope'] ?? false);
$errorBag = formErrors();
$errors = [];
$warnings = [];
$form = [
'description' => '',
'tenant_id' => 0,
'code' => '',
'cost_center' => '',
'active' => '1',
];
$tenants = $tenantService->list();
if ($canManageAllTenants) {
// No filtering — actor may pick any tenant.
} elseif ($allowedTenantIds) {
$tenants = array_values(array_filter($tenants, static function (array $tenant) use ($allowedTenantIds): bool {
$tenantId = (int) ($tenant['id'] ?? 0);
return $tenantId > 0 && in_array($tenantId, $allowedTenantIds, true);
}));
} elseif ($isStrictScope) {
$tenants = [];
}
if ($request->isMethod('POST') && !actionRequireCsrf($createTarget, $createTarget, 'csrf_expired')) {
return;
}
if ($request->isMethod('POST')) {
$selectedTenantId = $request->bodyInt('tenant_id');
$selectedTenantIds = $directoryScopeGateway->filterTenantIdsForUser([$selectedTenantId], $currentUserId);
$selectedTenantId = (int) ($selectedTenantIds[0] ?? 0);
$input = $request->bodyAll();
$input['tenant_id'] = $selectedTenantId;
$result = $departmentService->createFromAdmin($input, $currentUserId);
$form = $result['form'] ?? $form;
$errorBag->merge($result['errors'] ?? []);
$warnings = $result['warnings'] ?? [];
$form['tenant_id'] = $selectedTenantId;
if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
$action = (string) $request->body('action', 'create');
if ($action === 'create_close') {
if ($warnings) {
Flash::info(implode(' ', $warnings), $closeTarget, 'department_warning');
}
Flash::success(t('Department created'), $closeTarget, 'department_created');
Router::redirect($closeTarget);
} else {
$uuid = (string) ($result['uuid'] ?? '');
if ($uuid !== '') {
$target = requestPathWithReturnTarget("admin/departments/edit/{$uuid}", $returnTarget);
if ($warnings) {
Flash::info(implode(' ', $warnings), $target, 'department_warning');
}
Flash::success(t('Department created'), $target, 'department_created');
Router::redirect($target);
} else {
if ($warnings) {
Flash::info(implode(' ', $warnings), $closeTarget, 'department_warning');
}
Flash::success(t('Department created'), $closeTarget, 'department_created');
Router::redirect($closeTarget);
}
}
}
}
$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
Buffer::set('title', t('Create department'));
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('Departments'), 'path' => 'admin/departments'],
['label' => t('Create department')],
];