Version20180913205455.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. namespace ShlinkMigrations;
  4. use Doctrine\DBAL\Exception;
  5. use Doctrine\DBAL\Schema\Schema;
  6. use Doctrine\Migrations\AbstractMigration;
  7. use PDO;
  8. use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
  9. use Shlinkio\Shlink\Common\Util\IpAddress;
  10. /**
  11. * Auto-generated Migration: Please modify to your needs!
  12. */
  13. final class Version20180913205455 extends AbstractMigration
  14. {
  15. public function up(Schema $schema): void
  16. {
  17. // Nothing to create
  18. }
  19. /**
  20. * @throws Exception
  21. */
  22. public function postUp(Schema $schema): void
  23. {
  24. $qb = $this->connection->createQueryBuilder();
  25. $qb->select('id', 'remote_addr')
  26. ->from('visits');
  27. $st = $this->connection->executeQuery($qb->getSQL());
  28. $qb = $this->connection->createQueryBuilder();
  29. $qb->update('visits', 'v')
  30. ->set('v.remote_addr', ':obfuscatedAddr')
  31. ->where('v.id=:id');
  32. while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
  33. $addr = $row['remote_addr'] ?? null;
  34. if ($addr === null) {
  35. continue;
  36. }
  37. $qb->setParameters([
  38. 'id' => $row['id'],
  39. 'obfuscatedAddr' => $this->determineAddress((string) $addr),
  40. ])->execute();
  41. }
  42. }
  43. private function determineAddress(string $addr): ?string
  44. {
  45. if ($addr === IpAddress::LOCALHOST) {
  46. return $addr;
  47. }
  48. try {
  49. return (string) IpAddress::fromString($addr)->getAnonymizedCopy();
  50. } catch (InvalidArgumentException $e) {
  51. return null;
  52. }
  53. }
  54. public function down(Schema $schema): void
  55. {
  56. // Nothing to rollback
  57. }
  58. /**
  59. * @fixme Workaround for https://github.com/doctrine/migrations/issues/1104
  60. */
  61. public function isTransactional(): bool
  62. {
  63. return false;
  64. }
  65. }