*/ private Collection $objectives; /** * The content of the Description tab. Each item has a type set up by the admin in * Settings > Configuration > Program. * * @var Collection */ private Collection $descriptionItems; /** * The cost lines of the Allocations tab. Each item has a type set up by the admin in * Settings > Configuration > Program. * * @var Collection */ private Collection $allocationItems; /** * The audiences of the Audiences tab: links to the audiences of the global directory * (Programs > Audiences), each with the audience's priority in this plan and possibly a * program-specific message. See ProgramAudience. * * @var Collection */ private Collection $audiences; /** * The links to the stakeholders of the global directory (Programs > Stakeholders), each with the * stakeholder's role in this plan. See ProgramStakeholder. * * @var Collection */ private Collection $stakeholders; /** * Tasks are managed on their own pages (TaskController). * Read-only from the program: deleting an program * deletes its tasks through the database (ON DELETE CASCADE). * * @var Collection */ private Collection $tasks; private ?string $name = null; private ProgramStatus $status = ProgramStatus::Draft; /** * Required in the form. The column is nullable only so that deleting the user doesn't delete the plan (SET NULL). */ private ?User $owner = null; private ?\DateTime $startDate = null; private ?\DateTime $endDate = null; private ?\DateTime $completedAt = null; /** * DECIMAL(12,2), in the general currency (CurrencyProvider). Doctrine returns decimals as strings to * keep precision. */ private ?string $budgetPlanned = null; private ?Category $category = null; public function __construct() { $this->objectives = new ArrayCollection(); $this->descriptionItems = new ArrayCollection(); $this->allocationItems = new ArrayCollection(); $this->audiences = new ArrayCollection(); $this->stakeholders = new ArrayCollection(); $this->tasks = new ArrayCollection(); } public function __clone() { $this->id = null; $this->completedAt = null; $this->tasks = new ArrayCollection(); // A clone gets its own copies of the objectives, description items and allocation items. $objectives = $this->objectives; $this->objectives = new ArrayCollection(); foreach ($objectives as $objective) { $this->addObjective(clone $objective); } $descriptionItems = $this->descriptionItems; $this->descriptionItems = new ArrayCollection(); foreach ($descriptionItems as $descriptionItem) { $this->addDescriptionItem(clone $descriptionItem); } $allocationItems = $this->allocationItems; $this->allocationItems = new ArrayCollection(); foreach ($allocationItems as $allocationItem) { $this->addAllocationItem(clone $allocationItem); } // A clone keeps the same audiences (directory entries), with fresh links. $audiences = $this->audiences; $this->audiences = new ArrayCollection(); foreach ($audiences as $audience) { $this->addAudience(clone $audience); } // A clone keeps the same stakeholders (directory entries), with fresh links. $stakeholders = $this->stakeholders; $this->stakeholders = new ArrayCollection(); foreach ($stakeholders as $stakeholder) { $this->addStakeholder(clone $stakeholder); } parent::__clone(); } public static function loadMetadata(OrmClassMetadata $metadata): void { $builder = new ClassMetadataBuilder($metadata); $builder->setTable(self::TABLE_NAME) ->setCustomRepositoryClass(ProgramRepository::class) ->addIndex(['status'], 'program_status'); // id and name; no description column (replaced by description items). The false is // core's own way to skip the column (addIdColumns checks it for truthiness); core's // @param string docblock just doesn't mention it. $builder->addIdColumns('name', false); // @phpstan-ignore argument.type (false is core's own way to skip the column; its @param string docblock doesn't mention it) // Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191). $metadata->mapField([ 'fieldName' => 'status', 'type' => Types::STRING, 'length' => 20, 'enumType' => ProgramStatus::class, ]); $builder->createManyToOne('owner', User::class) ->addJoinColumn('owner_id', 'id', true, false, 'SET NULL') ->build(); $builder->addNamedField('startDate', Types::DATETIME_MUTABLE, 'start_date', true); $builder->addNamedField('endDate', Types::DATETIME_MUTABLE, 'end_date', true); $builder->addNamedField('completedAt', Types::DATETIME_MUTABLE, 'completed_at', true); $builder->createField('budgetPlanned', Types::DECIMAL) ->columnName('budget_planned') ->precision(12) ->scale(2) ->nullable() ->build(); // ManyToOne Category, nullable, onDelete SET NULL. $builder->addCategory(); $builder->createField('version', Types::SMALLINT) ->option('unsigned', true) ->option('default', self::VERSION_MIN) ->build(); $builder->createOneToMany('objectives', ProgramObjective::class) ->mappedBy('program') ->cascadePersist() ->cascadeRemove() ->orphanRemoval() ->setOrderBy(['position' => 'ASC']) ->fetchExtraLazy() ->build(); $builder->createOneToMany('descriptionItems', ProgramDescriptionItem::class) ->mappedBy('program') ->cascadePersist() ->cascadeRemove() ->orphanRemoval() ->setOrderBy(['position' => 'ASC']) ->fetchExtraLazy() ->build(); $builder->createOneToMany('allocationItems', ProgramAllocationItem::class) ->mappedBy('program') ->cascadePersist() ->cascadeRemove() ->orphanRemoval() ->setOrderBy(['position' => 'ASC']) ->fetchExtraLazy() ->build(); $builder->createOneToMany('audiences', ProgramAudience::class) ->mappedBy('program') ->cascadePersist() ->cascadeRemove() ->orphanRemoval() ->setOrderBy(['position' => 'ASC']) ->fetchExtraLazy() ->build(); $builder->createOneToMany('stakeholders', ProgramStakeholder::class) ->mappedBy('program') ->cascadePersist() ->cascadeRemove() ->orphanRemoval() ->setOrderBy(['position' => 'ASC']) ->fetchExtraLazy() ->build(); $builder->createOneToMany('tasks', Task::class) ->mappedBy('program') ->setOrderBy(['name' => 'ASC']) ->fetchExtraLazy() ->build(); } public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('version', new NotNull(message: 'mt3s.marketing_program.version.range')); $metadata->addPropertyConstraint('version', new Range( notInRangeMessage: 'mt3s.marketing_program.version.range', min: self::VERSION_MIN, max: self::VERSION_MAX, )); $metadata->addPropertyConstraint('objectives', new Valid()); $metadata->addPropertyConstraint('descriptionItems', new Valid()); $metadata->addPropertyConstraint('allocationItems', new Valid()); $metadata->addPropertyConstraint('audiences', new Valid()); $metadata->addPropertyConstraint('stakeholders', new Valid()); $metadata->addPropertyConstraint('name', new NotBlank(message: 'mautic.core.name.required')); $metadata->addPropertyConstraint('owner', new NotBlank(message: 'mt3s.marketing_program.owner.required')); $metadata->addConstraint(new EndDateAfterStartDate()); } public function getId(): ?int { return $this->id; } public function getVersion(): ?int { return $this->version; } /** * Accepts null so that an empty form field reaches validation (NotNull) instead of failing here. */ public function setVersion(?int $version): static { $this->isChanged('version', $version); $this->version = $version; return $this; } /** * The objectives sorted by priority (1 first), then by position for ties, as a new collection * (Doctrine itself reads the property). * * Sorted here, not only by the mapping's orderBy: after a reorder, positions change in memory while the * loaded collection keeps its old order, and the page shown right after saving uses that collection. * * @return Collection */ public function getObjectives(): Collection { $objectives = self::sortedByPosition($this->objectives)->toArray(); usort($objectives, function (ProgramObjective $a, ProgramObjective $b): int { // An objective without a priority yet sorts last; ties keep the position order. $pa = $a->getPriority() ?? PHP_INT_MAX; $pb = $b->getPriority() ?? PHP_INT_MAX; return $pa === $pb ? 0 : ($pa < $pb ? -1 : 1); }); return new ArrayCollection($objectives); } /** * @return Collection */ public function getTasks(): Collection { return $this->tasks; } /** * The audience links sorted by position, as a new collection; see getObjectives(). * * @return Collection */ public function getAudiences(): Collection { return self::sortedByPosition($this->audiences); } public function addAudience(ProgramAudience $audience): static { if (!$this->audiences->contains($audience)) { $audience->setProgram($this); $this->audiences->add($audience); } return $this; } /** * Removing an audience link from the plan deletes it (orphanRemoval). The audience itself stays * in the global directory. */ public function removeAudience(ProgramAudience $audience): static { $this->audiences->removeElement($audience); return $this; } /** * The stakeholder links sorted by position, as a new collection; see getObjectives(). * * @return Collection */ public function getStakeholders(): Collection { return self::sortedByPosition($this->stakeholders); } public function addStakeholder(ProgramStakeholder $stakeholder): static { if (!$this->stakeholders->contains($stakeholder)) { $stakeholder->setProgram($this); $this->stakeholders->add($stakeholder); } return $this; } /** * Removing a stakeholder link from the plan deletes it (orphanRemoval). The stakeholder itself * stays in the global directory. */ public function removeStakeholder(ProgramStakeholder $stakeholder): static { $this->stakeholders->removeElement($stakeholder); return $this; } public function addObjective(ProgramObjective $objective): static { if (!$this->objectives->contains($objective)) { $objective->setProgram($this); $this->objectives->add($objective); } return $this; } /** * Removing an objective from the plan deletes it (orphanRemoval). */ public function removeObjective(ProgramObjective $objective): static { $this->objectives->removeElement($objective); return $this; } /** * The description items sorted by position, as a new collection; see getObjectives(). * * @return Collection */ public function getDescriptionItems(): Collection { return self::sortedByPosition($this->descriptionItems); } /** * The allocation items sorted by position, as a new collection; see getObjectives(). * * @return Collection */ public function getAllocationItems(): Collection { return self::sortedByPosition($this->allocationItems); } public function addAllocationItem(ProgramAllocationItem $allocationItem): static { if (!$this->allocationItems->contains($allocationItem)) { $allocationItem->setProgram($this); $this->allocationItems->add($allocationItem); } return $this; } /** * Removing an allocation item from the plan deletes it (orphanRemoval). */ public function removeAllocationItem(ProgramAllocationItem $allocationItem): static { $this->allocationItems->removeElement($allocationItem); return $this; } /** * Total planned and real costs of the allocation items, in the general currency. Each total is a * string with 2 decimals, or null when no item has that cost. * * @return array{planned: ?string, real: ?string} */ public function getAllocationTotals(): array { // Summed in cents, as integers, to avoid floating-point drift. $cents = ['planned' => null, 'real' => null]; foreach ($this->allocationItems as $item) { foreach (['planned' => $item->getPlannedCost(), 'real' => $item->getRealCost()] as $kind => $cost) { if (null === $cost || '' === $cost) { continue; } $cents[$kind] = ($cents[$kind] ?? 0) + (int) round(((float) $cost) * 100); } } return [ 'planned' => null === $cents['planned'] ? null : number_format($cents['planned'] / 100, 2, '.', ''), 'real' => null === $cents['real'] ? null : number_format($cents['real'] / 100, 2, '.', ''), ]; } /** * @template T of ProgramObjective|ProgramDescriptionItem|ProgramAllocationItem|ProgramAudience|ProgramStakeholder * * @param Collection $collection * * @return Collection */ private static function sortedByPosition(Collection $collection): Collection { $rows = $collection->toArray(); usort($rows, fn ($a, $b): int => $a->getPosition() <=> $b->getPosition()); return new ArrayCollection($rows); } public function addDescriptionItem(ProgramDescriptionItem $descriptionItem): static { if (!$this->descriptionItems->contains($descriptionItem)) { $descriptionItem->setProgram($this); $this->descriptionItems->add($descriptionItem); } return $this; } /** * Removing a description item from the plan deletes it (orphanRemoval). */ public function removeDescriptionItem(ProgramDescriptionItem $descriptionItem): static { $this->descriptionItems->removeElement($descriptionItem); return $this; } /** * Renumbers objective, description item, allocation item and audience positions 0..n-1 following their * current positions, so that the order stays contiguous after rows are added, removed or moved. */ public function normalizePositions(): void { foreach ([$this->objectives, $this->descriptionItems, $this->allocationItems, $this->audiences, $this->stakeholders] as $collection) { $rows = $collection->toArray(); usort($rows, fn ($a, $b): int => $a->getPosition() <=> $b->getPosition()); foreach ($rows as $index => $row) { $row->setPosition($index); } } } public function getName(): ?string { return $this->name; } public function setName(?string $name): static { $this->isChanged('name', $name); $this->name = $name; return $this; } public function getStatus(): ProgramStatus { return $this->status; } /** * Sets completedAt when the plan moves to "completed" from another status, * and clears it when the plan leaves "completed". */ public function setStatus(ProgramStatus $status): static { if ($status === $this->status) { return $this; } // isChanged() can't log enums (they aren't stringable), so log the backing values. $this->addChange('status', [$this->status->value, $status->value]); if (ProgramStatus::Completed === $status) { $this->setCompletedAt(new \DateTime()); } elseif (ProgramStatus::Completed === $this->status) { $this->setCompletedAt(null); } $this->status = $status; return $this; } public function getOwner(): ?User { return $this->owner; } public function setOwner(?User $owner): static { $this->isChanged('owner', $owner); $this->owner = $owner; return $this; } public function getStartDate(): ?\DateTime { return $this->startDate; } public function setStartDate(?\DateTime $startDate): static { $this->isChanged('startDate', $startDate); $this->startDate = $startDate; return $this; } public function getEndDate(): ?\DateTime { return $this->endDate; } public function setEndDate(?\DateTime $endDate): static { $this->isChanged('endDate', $endDate); $this->endDate = $endDate; return $this; } public function getCompletedAt(): ?\DateTime { return $this->completedAt; } public function setCompletedAt(?\DateTime $completedAt): static { $this->isChanged('completedAt', $completedAt); $this->completedAt = $completedAt; return $this; } public function getBudgetPlanned(): ?string { return $this->budgetPlanned; } public function setBudgetPlanned(?string $budgetPlanned): static { $this->isChanged('budgetPlanned', $budgetPlanned); $this->budgetPlanned = $budgetPlanned; return $this; } public function getCategory(): ?Category { return $this->category; } public function setCategory(?Category $category): static { $this->isChanged('category', $category); $this->category = $category; return $this; } }