|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Services; |
| 4 | + |
| 5 | +class DockerImageParser |
| 6 | +{ |
| 7 | + private string $registryUrl = ''; |
| 8 | + |
| 9 | + private string $imageName = ''; |
| 10 | + |
| 11 | + private string $tag = 'latest'; |
| 12 | + |
| 13 | + public function parse(string $imageString): self |
| 14 | + { |
| 15 | + // First split by : to handle the tag, but be careful with registry ports |
| 16 | + $lastColon = strrpos($imageString, ':'); |
| 17 | + $hasSlash = str_contains($imageString, '/'); |
| 18 | + |
| 19 | + // If the last colon appears after the last slash, it's a tag |
| 20 | + // Otherwise it might be a port in the registry URL |
| 21 | + if ($lastColon !== false && (! $hasSlash || $lastColon > strrpos($imageString, '/'))) { |
| 22 | + $mainPart = substr($imageString, 0, $lastColon); |
| 23 | + $this->tag = substr($imageString, $lastColon + 1); |
| 24 | + } else { |
| 25 | + $mainPart = $imageString; |
| 26 | + $this->tag = 'latest'; |
| 27 | + } |
| 28 | + |
| 29 | + // Split the main part by / to handle registry and image name |
| 30 | + $pathParts = explode('/', $mainPart); |
| 31 | + |
| 32 | + // If we have more than one part and the first part contains a dot or colon |
| 33 | + // it's likely a registry URL |
| 34 | + if (count($pathParts) > 1 && (str_contains($pathParts[0], '.') || str_contains($pathParts[0], ':'))) { |
| 35 | + $this->registryUrl = array_shift($pathParts); |
| 36 | + $this->imageName = implode('/', $pathParts); |
| 37 | + } else { |
| 38 | + $this->imageName = $mainPart; |
| 39 | + } |
| 40 | + |
| 41 | + return $this; |
| 42 | + } |
| 43 | + |
| 44 | + public function getFullImageNameWithoutTag(): string |
| 45 | + { |
| 46 | + return $this->registryUrl.'/'.$this->imageName; |
| 47 | + } |
| 48 | + |
| 49 | + public function getRegistryUrl(): string |
| 50 | + { |
| 51 | + return $this->registryUrl; |
| 52 | + } |
| 53 | + |
| 54 | + public function getImageName(): string |
| 55 | + { |
| 56 | + return $this->imageName; |
| 57 | + } |
| 58 | + |
| 59 | + public function getTag(): string |
| 60 | + { |
| 61 | + return $this->tag; |
| 62 | + } |
| 63 | + |
| 64 | + public function toString(): string |
| 65 | + { |
| 66 | + $parts = []; |
| 67 | + if ($this->registryUrl) { |
| 68 | + $parts[] = $this->registryUrl; |
| 69 | + } |
| 70 | + $parts[] = $this->imageName; |
| 71 | + |
| 72 | + return implode('/', $parts).':'.$this->tag; |
| 73 | + } |
| 74 | +} |
0 commit comments