openvk/Web/Models/Entities/Traits/TAttachmentHost.php
Alexander Minkin 6ec54a379d
feat: add linting of code (#1220)
* feat(lint): add php-cs-fixer for linting

Removing previous CODE_STYLE as it was not enforced anyway and using PER-CS 2.0.

This is not the reformatting commit.

* style: format code according to PER-CS 2.0 with php-cs-fixer

* ci(actions): add lint action

Resolves #1132.
2025-01-31 18:20:13 +03:00

104 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
namespace openvk\Web\Models\Entities\Traits;
use openvk\Web\Models\Entities\{Attachable, Photo, Video};
use openvk\Web\Util\Makima\Makima;
use Chandler\Database\DatabaseConnection;
trait TAttachmentHost
{
private function composeAttachmentRequestData(Attachable $attachment): array
{
return [
"target_type" => get_class($this),
"target_id" => $this->getId(),
"attachable_type" => get_class($attachment),
"attachable_id" => $attachment->getId(),
];
}
public function getChildren(): \Traversable
{
$sel = DatabaseConnection::i()->getContext()
->table("attachments")
->where("target_id", $this->getId())
->where("attachments.target_type", get_class($this));
foreach ($sel as $rel) {
$repoName = $rel->attachable_type . "s";
$repoName = str_replace("Entities", "Repositories", $repoName);
$repo = new $repoName();
yield $repo->get($rel->attachable_id);
}
}
public function getChildrenWithLayout(int $w, int $h = -1): object
{
if ($h < 0) {
$h = $w;
}
$children = iterator_to_array($this->getChildren());
$skipped = $photos = $result = [];
foreach ($children as $child) {
if ($child instanceof Photo || $child instanceof Video && $child->getDimensions()) {
$photos[] = $child;
continue;
}
$skipped[] = $child;
}
$height = "unset";
$width = $w;
if (sizeof($photos) < 2) {
if (isset($photos[0])) {
$result[] = ["100%", "unset", $photos[0], "unset"];
}
} else {
$mak = new Makima($photos);
$layout = $mak->computeMasonryLayout($w, $h);
$height = $layout->height;
$width = $layout->width;
for ($i = 0; $i < sizeof($photos); $i++) {
$tile = $layout->tiles[$i];
$result[] = [$tile->width . "px", $tile->height . "px", $photos[$i], "left"];
}
}
return (object) [
"width" => $width . "px",
"height" => $height . "px",
"tiles" => $result,
"extras" => $skipped,
];
}
public function attach(Attachable $attachment): void
{
DatabaseConnection::i()->getContext()
->table("attachments")
->insert($this->composeAttachmentRequestData($attachment));
}
public function detach(Attachable $attachment): bool
{
$res = DatabaseConnection::i()->getContext()
->table("attachments")
->where($this->composeAttachmentRequestData($attachment))
->delete();
return $res > 0;
}
public function unwire(): void
{
$this->getRecord()
->related("attachments.target_id")
->where("attachments.target_type", get_class($this))
->delete();
}
}