Search by

adachsoft / task-contracts

Arkadiusz Adach

task-contracts

Package info

gitlab.com/a.adach/task-contracts

Issues

pkg:composer/adachsoft/task-contracts

Statistics

Installs: 163

Dependents: 5

Suggesters: 0

Stars: 0

v3.0.0 2026-11-16 05:23 UTC

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/collection 3.x
  • psr/clock 1.x
  • adachsoft/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 permissive AllowAllTaskAuthorization adapter.
  • src/UseCase/ — task, comment, checklist, attachment, and definition-query services.
  • src/Dto/, src/Collection/, src/ValueObject/, and src/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.

InterfaceOperations
TaskRepositoryInterfacefindById, findAll, findByParentId, findTree, nextIdentity, add, save, delete, addDependency, removeDependency, getDependencies, countChildrenByParentIds, search
CommentRepositoryInterfacefindByTaskId, findById, nextIdentity, add, save, delete, countByTaskIds
AttachmentRepositoryInterfacefindByTaskId, findById, nextIdentity, add, delete, countByTaskIds
AttachmentContentStorageInterfacewrite, read, delete for binary content streams
WorkflowDefinitionRepositoryInterfacefindById, findAll (read-only)
TaskTypeDefinitionRepositoryInterfacefindById, 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:

  • text is 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 includeDeleted is enabled.
  • total counts all matches before limit and offset; returned items have empty subTasks.
  • 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: id and attributes supplied by the authorization adapter, such as role.
  • subtasks: count, counts per category, and all_closed.
  • checklist: total, done, and all_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 StatusId and StatusCategoryEnum.
  • Replace AuthorId with UserId; pass the actor to mutating use-case operations. New task and comment authors are taken from that actor.
  • Replace setStatus with changeStatus and pass the target StatusId; 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 type task.
  • Update repository implementations for TaskRepositoryInterface::search(TaskQuery): TaskPage and the attachment metadata/content, workflow-definition, and task-type-definition contracts. Keep repository search category-agnostic; TaskService expands category filters before calling it.
  • Migrate each stored status to the matching StatusId in workflow default, set the task type to task, and set the author to null.

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.