summaryrefslogtreecommitdiff
path: root/src/Model/Card.php
blob: ab421abcc6a83ba2bec516b6622f0cd1ceaf50a5 (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
<?php

namespace Elements\Model;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
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\OneToMany;
use Doctrine\ORM\PersistentCollection;
use Elements\DB;

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

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

  /**
   * Card constructor.
   */
  public function __construct()
  {
    $this->meta = new ArrayCollection();
  }

  /**
   * @param CardMeta $meta
   */
  public function addMeta(CardMeta $meta)
  {
    $meta->card = $this;
    $this->meta[] = $meta;
  }

  /**
   * @param string $key
   *
   * @return string
   */
  public function getMeta(string $key): ?string
  {
    // if meta is already hydrated
    if ($this->meta->isInitialized()) {
      $meta = $this->meta->unwrap()
	#->findFirst(fn (CardMeta $item) => $item->key === $key);
	->filter(fn ($item) => $item->key === $key)->first();

      return $meta->value ?? null;
    }

    // get directly from db otherwise
    $result = DB::$entityManager
      ->createQuery(
	'SELECT cm.value
	FROM Elements\Model\CardMeta cm
	WHERE cm.key = :key AND cm.card = :card'
      )
      ->setParameter('key', $key)
      ->setParameter('card', $this)
      ->getOneOrNullResult();

      return $result['value'] ?? null;
  }
}