src/App/Entity/ShortenedUrl.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\Entity;
  3. use App\Utility\DateTimeUtility;
  4. use DateTime;
  5. use Doctrine\ORM\Mapping as ORM;
  6. use function bccomp;
  7. use function bcdiv;
  8. use function bcmod;
  9. use function bcsub;
  10. /**
  11. * @ORM\Entity()
  12. *
  13. * @ORM\Table(
  14. * name="shortened_urls",
  15. * )
  16. */
  17. class ShortenedUrl
  18. {
  19. public function __construct(string $id, string $targetUrl)
  20. {
  21. $this->createdAt = DateTimeUtility::createDateTimeUtc();
  22. $this->id = $id;
  23. $this->targetUrl = $targetUrl;
  24. }
  25. /**
  26. * @var string
  27. *
  28. * @ORM\Column(name="id", type="string", length=16)
  29. *
  30. * @ORM\Id
  31. */
  32. protected $id;
  33. public function setId(string $id): void
  34. {
  35. $this->id = $id;
  36. }
  37. public function getId()
  38. {
  39. return $this->id;
  40. }
  41. /**
  42. * @var string
  43. *
  44. * @ORM\Column(name="target_url", type="text", nullable=false)
  45. */
  46. protected $targetUrl;
  47. public function getTargetUrl(): string
  48. {
  49. return $this->targetUrl;
  50. }
  51. /**
  52. * @var DateTime
  53. *
  54. * @ORM\Column(name="created_at", type="datetime", nullable=false)
  55. */
  56. protected $createdAt;
  57. /**
  58. * @return DateTime
  59. */
  60. public function getCreatedAt()
  61. {
  62. return $this->createdAt;
  63. }
  64. /**
  65. * @var DateTime|null
  66. *
  67. * @ORM\Column(name="updated_at", type="datetime", nullable=true)
  68. */
  69. protected $updatedAt;
  70. public function getUpdatedAt(): ?DateTime
  71. {
  72. return $this->updatedAt;
  73. }
  74. public function setUpdatedAt(?DateTime $updatedAt = null)
  75. {
  76. $this->updatedAt = $updatedAt;
  77. }
  78. public static function generateRandomId(): string
  79. {
  80. return substr(self::baseEncode(random_int(0, PHP_INT_MAX)) . self::baseEncode(random_int(0, PHP_INT_MAX)), 0, 16);
  81. }
  82. public static function baseEncode(int $val, int $base = 62, string $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'): string
  83. {
  84. if (!isset($base)) {
  85. $base = strlen($chars);
  86. }
  87. $str = '';
  88. do {
  89. $m = bcmod($val, $base);
  90. $str = $chars[$m] . $str;
  91. $val = bcdiv(bcsub($val, $m), $base);
  92. } while (bccomp($val, 0) > 0);
  93. return $str;
  94. }
  95. }