summaryrefslogtreecommitdiff
path: root/src/Model/Artwork.php
blob: 6380f62bc315de726102b8892684190096cd5169 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php

namespace Elements\Model;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Table;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\PersistentCollection;
use Elements\DB;
use Symfony\Component\HttpFoundation\File\UploadedFile;

#[Entity]
#[Table(name: 'artworks')]
/**
 * @Entity
 * @Table(name="artworks")
 */
class Artwork
{
  #[Id]
  #[Column(type: 'integer')]
  #[GeneratedValue]
  /**
   * @Id
   * @Column(type="integer")
   * @GeneratedValue
   */
  public int $id;

  #[Column(type: 'string')]
  /**
   * @Column(type="string")
   */
  public string $path;

  #[ManyToOne(targetEntity: Card::class, inversedBy: 'artworks')]
  /**
   * @ManyToOne(targetEntity="Card", inversedBy="artworks", cascade={"persist"})
   */
  public Card $card;

  #[OneToMany(targetEntity: VoteArtwork::class, mappedBy: 'artwork')]
  /**
   * @OneToMany(targetEntity="VoteArtwork", mappedBy="artwork")
   */
  public Collection|ArrayCollection|PersistentCollection $votes;

  /**
   * Artwork constructor.
   */
  public function __construct(string $path)
  {
    $this->path = $path;
    $this->votes = new ArrayCollection();
  }

  /**
   * @param UploadedFile $file
   *
   * @return self
   */
  public static function fromUploadedFile(UploadedFile $file): self
  {
    $artworksDir = dirname(dirname(__DIR__)) . '/public/artworks/';
    $path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $artworksDir . $file->getClientOriginalName());
    $file->move($artworksDir, $file->getClientOriginalName());

    return new self($path);
  }

  /**
   * @param VoteArtwork $vote
   */
  public function addVote(VoteArtwork $vote)
  {
    $vote->artwork = $this;
    $this->votes[] = $vote;
  }

  /**
   * @return int
   */
  public function getVotesTotal(): int
  {
    $result = DB::$entityManager
      ->createQuery(
        'SELECT sum(v.value) as total
        FROM Elements\Model\VoteArtwork v
        WHERE v.artwork = :artwork'
      )
      ->setParameter('artwork', $this)
      ->getOneOrNullResult();

      return $result['total'] ?? 0;
  }
}