adachsoft / task-contracts
task-contracts
Requires
- php: ^8.3
- adachsoft/collection: ^3.0
- adachsoft/rule-evaluator-contract: ^0.1
- psr/clock: ^1.0
Requires (Dev)
- adachsoft/php-code-style: ^0.7
- adachsoft/rule-evaluator-expression-language: ^0.1
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.2
- phpunit/phpunit: ^13.1
- rector/rector: ^2.4
- symplify/phpstan-rules: ^14.17
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-16 04:27:03 UTC
README
adachsoft/task-contracts provides PHP contracts, immutable DTOs, value objects, exceptions, and application use cases for task management. It defines storage-independent APIs for tasks, comments, workflows, search, checklists, and attachments.
Requirements
- PHP 8.3 or newer
adachsoft/collection3.xpsr/clock1.xadachsoft/rule-evaluator-contract^0.1
Installation
composer require adachsoft/task-contracts
Optional adapters used by the integration example are adachsoft/task-memory and adachsoft/rule-evaluator-expression-language. Applications may provide their own repository implementations and RuleEvaluatorInterface adapter.
Package structure
src/Interface/— task, comment, attachment, definition, authorization, and status-resolver contracts.src/Query/— task search filters, parent filters, and paginated results.src/Workflow/— transition guards, condition context, and available-transition resolution.src/Definition/— built-in definitions and workflow resolution.src/Authorization/— the permissiveAllowAllTaskAuthorizationadapter.src/UseCase/— task, comment, checklist, attachment, and definition-query services.src/Dto/,src/Collection/,src/ValueObject/, andsrc/Enum/— immutable API data types.packages/task-memory/— optional in-memory repositories and attachment content storage.
Repository contracts
Implement these interfaces to connect the package to an application's storage. Reads do not prescribe a storage engine; task and comment writes use optimistic locking.
| Interface | Operations |
|---|---|
TaskRepositoryInterface | findById, findAll, findByParentId, findTree, nextIdentity, add, save, delete, addDependency, removeDependency, getDependencies, countChildrenByParentIds, search |
CommentRepositoryInterface | findByTaskId, findById, nextIdentity, add, save, delete, countByTaskIds |
AttachmentRepositoryInterface | findByTaskId, findById, nextIdentity, add, delete, countByTaskIds |
AttachmentContentStorageInterface | write, read, delete for binary content streams |
WorkflowDefinitionRepositoryInterface | findById, findAll (read-only) |
TaskTypeDefinitionRepositoryInterface | findById, findAll, getDefault (read-only) |
TaskStatusResolverInterface resolves a parent's status from its subtasks' categories and can synchronize the parent after a subtask change.
TaskRepositoryInterface::search(TaskQuery): TaskPage returns matching tasks, the total before pagination, and the requested page. Repositories do not resolve workflow categories: TaskService::search() expands category filters into status IDs, intersects them with explicit status IDs when both filters are present, and sends the repository a query with no categories. A repository must reject a query that still contains categories with InvalidTaskQueryException. Status IDs must have the same category in every workflow.
Search semantics:
textis a case-insensitive substring of the title or description.- Values within one list filter are ORed; separate filters are ANDed.
- Every requested attribute key must match with strict value and type equality.
- Deleted tasks are excluded unless
includeDeletedis enabled. totalcounts all matches beforelimitandoffset; returned items have emptysubTasks.- Sorting follows the query; ties are broken by natural task ID order ascending.
Workflows and statuses
A workflow is a read-only, user-defined task lifecycle: named statuses, each assigned a fixed category, and allowed transitions with optional expressions evaluated through RuleEvaluatorInterface. StatusCategoryEnum contains TODO, IN_PROGRESS, BLOCKED, DONE, and CANCELLED; category-based filters and parent synchronization do not depend on status names.
Example workflow definition:
{
"id": "bug",
"name": "Bug",
"initial": "reported",
"statuses": [
{"id": "reported", "name": "Reported", "category": "TODO"},
{"id": "confirmed", "name": "Confirmed", "category": "TODO"},
{"id": "fixing", "name": "In progress", "category": "IN_PROGRESS"},
{"id": "review", "name": "In review", "category": "IN_PROGRESS"},
{"id": "closed", "name": "Closed", "category": "DONE"},
{"id": "rejected", "name": "Rejected", "category": "CANCELLED"}
],
"transitions": [
{"from": "reported", "to": "confirmed"},
{"from": "reported", "to": "rejected"},
{"from": "confirmed", "to": "fixing"},
{"from": "fixing", "to": "review", "condition": "checklist.all_done"},
{"from": "review", "to": "fixing"},
{"from": "review", "to": "closed", "condition": "'supervisor' in actor.roles"}
]
}
from: null allows a transition from any status. Conditions use dot notation against these context keys:
task:id,type,status,category,attributes,author.actor:idand attributes supplied by the authorization adapter, such asrole.subtasks:count, counts per category, andall_closed.checklist:total,done, andall_done.
The built-in default workflow has statuses TODO, IN_PROGRESS, BLOCKED, DONE, and CANCELLED; each category has the same status ID, every status can transition to any other status, and there are no conditions. The built-in task type task uses this workflow.
Task types
A task type names a kind of task and selects its workflow, for example bug or feature. CreateTaskDto has no status input: a new task always starts at its type's workflow initial status. If no type is supplied, the type defaults to task. Changing a task to a type backed by another workflow selects the first status in the new workflow with the current category; if none exists, the change is rejected.
Actors and authorization
UserId identifies a human or agent account. The host supplies the acting user explicitly to use-case operations; an AI model or request payload must not choose the actor. Task and comment authorship is derived from that actor.
TaskAuthorizationInterface provides isGranted(UserId, TaskPermissionEnum, ?TaskDto): bool for permission checks and actorContext(UserId): array for workflow conditions. AllowAllTaskAuthorization grants every permission and is intended for simple local or test setups; production applications should inject an authorization adapter connected to their own identity and access-control system.
Permissions are TASK_CREATE, TASK_EDIT, TASK_DELETE, TASK_CHANGE_STATUS, COMMENT_ADD, COMMENT_EDIT, COMMENT_DELETE, ATTACHMENT_ADD, and ATTACHMENT_DELETE. Denied operations throw TaskAccessDeniedException.
Use cases
TaskServiceFactory creates the services and their shared workflow dependencies.
TaskService:create,update,changeStatus,delete,read,findTree,findByParentId,findAll,search,addDependency,removeDependency,listDependencies.CommentService:add,edit,delete,find,listByTaskId.ChecklistService:addItem,editItem,setDone,removeItem,reorder.AttachmentService:attach,list,read,delete.DefinitionQueryService:listTaskTypes,getTaskType,listWorkflows,getWorkflow,workflowForType.
The factory exposes createTaskService, createCommentService, createChecklistService, createAttachmentService, and createDefinitionQueryService. Its default authorization policy allows all operations; pass an application-specific TaskAuthorizationInterface for production use.
Example integration
This example uses the in-memory repositories and the optional Symfony ExpressionLanguage adapter. The in-memory definition repositories default to the default workflow and task type.
use AdachSoft\RuleEvaluatorExpressionLanguage\ExpressionLanguageRuleEvaluatorFactory;
use AdachSoft\TaskContracts\Query\TaskQuery;
use AdachSoft\TaskContracts\UseCase\Dto\CreateTaskDto;
use AdachSoft\TaskContracts\UseCase\TaskServiceFactory;
use AdachSoft\TaskContracts\ValueObject\StatusId;
use AdachSoft\TaskContracts\ValueObject\UserId;
use AdachSoft\TaskMemory\Repository\InMemoryAttachmentRepository;
use AdachSoft\TaskMemory\Repository\InMemoryCommentRepository;
use AdachSoft\TaskMemory\Repository\InMemoryTaskRepository;
use AdachSoft\TaskMemory\Repository\InMemoryTaskTypeDefinitionRepository;
use AdachSoft\TaskMemory\Repository\InMemoryWorkflowDefinitionRepository;
$taskService = TaskServiceFactory::createTaskService(
taskRepository: new InMemoryTaskRepository(),
commentRepository: new InMemoryCommentRepository(),
attachmentRepository: new InMemoryAttachmentRepository(),
taskTypeDefinitionRepository: new InMemoryTaskTypeDefinitionRepository(),
workflowDefinitionRepository: new InMemoryWorkflowDefinitionRepository(),
ruleEvaluator: (new ExpressionLanguageRuleEvaluatorFactory())->createDefault(),
);
$actor = new UserId('agent-17');
$task = $taskService->create(
new CreateTaskDto(title: 'Review release', description: 'Review the 3.0 release.'),
$actor,
);
$task = $taskService->changeStatus($task->id, new StatusId('IN_PROGRESS'), $actor);
$page = $taskService->search(new TaskQuery(text: 'release', limit: 20));
Exceptions
- Attachments:
AttachmentAlreadyExistsException,AttachmentNotFoundException,AttachmentRejectedException. - Checklists:
ChecklistItemNotFoundException. - Comments:
CommentAlreadyExistsException,CommentNotFoundException. - Concurrency and dependencies:
ConcurrentModificationException,DependencyAlreadyExistsException,DependencyNotFoundException. - Definitions and queries:
InvalidDefinitionException,InvalidTaskQueryException,TaskTypeNotFoundException,WorkflowDefinitionNotFoundException. - Task data and access:
InvalidTaskDataException,TaskAccessDeniedException,TaskAlreadyExistsException,TaskHierarchyCycleException,TaskNotFoundException. - Workflow transitions:
StatusTransitionNotAllowedException,TransitionConditionNotMetException.
Concurrency model
Task and comment inserts start at version 1. Successful save() calls use the supplied version and increment it; task dependency changes also increment the task version. A stale update throws ConcurrentModificationException rather than overwriting newer data. Generated task, comment, and attachment identities may be retried after an atomic insert collision; concurrent updates are never retried automatically.
See docs/adr/0001-task-storage-concurrency.md for the storage and concurrency decision.
Upgrading from 2.x
- Replace the fixed status enum with workflow-defined statuses represented by
StatusIdandStatusCategoryEnum. - Replace
AuthorIdwithUserId; pass the actor to mutating use-case operations. New task and comment authors are taken from that actor. - Replace
setStatuswithchangeStatusand pass the targetStatusId; transitions are checked against the task's workflow. - Remove the status field from
CreateTaskDto; creation now uses the workflow's initial status and defaults to task typetask. - Update repository implementations for
TaskRepositoryInterface::search(TaskQuery): TaskPageand the attachment metadata/content, workflow-definition, and task-type-definition contracts. Keep repository search category-agnostic;TaskServiceexpands category filters before calling it. - Migrate each stored status to the matching
StatusIdin workflowdefault, set the task type totask, and set the author tonull.
Development
Install development dependencies and run the checks:
composer install
vendor/bin/phpunit
vendor/bin/phpstan analyse src
vendor/bin/phpstan analyse tests
vendor/bin/rector process src
vendor/bin/rector process tests
vendor/bin/php-cs-fixer fix src
vendor/bin/php-cs-fixer fix tests
License
This library is released under the MIT License. See the LICENSE file for details.