|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Php\Pie\Util; |
| 6 | + |
| 7 | +use Composer\InstalledVersions; |
| 8 | + |
| 9 | +use function class_exists; |
| 10 | + |
| 11 | +/** @internal This is not public API for PIE, so should not be depended upon unless you accept the risk of BC breaks */ |
| 12 | +final class PieVersion |
| 13 | +{ |
| 14 | + /** |
| 15 | + * Note: magic constant that causes Symfony Console to not display a version |
| 16 | + * {@see Application::getLongVersion()} |
| 17 | + */ |
| 18 | + private const SYMFONY_MAGIC_CONST_UNKNOWN = 'UNKNOWN'; |
| 19 | + |
| 20 | + /** |
| 21 | + * A static method to try to find the version of PIE you are currently |
| 22 | + * running. If running in the PHAR built with Box, this should return a |
| 23 | + * realistic-looking version; usually either a tag (e.g. `2.0.0`), or a tag |
| 24 | + * and following commit short hash (e.g. `2.0.0@e558e33`). If not this will |
| 25 | + * fall back to some other techniques to try to determine a version. |
| 26 | + */ |
| 27 | + public static function get(): string |
| 28 | + { |
| 29 | + /** |
| 30 | + * This value is replaced dynamically by Box with the real version when |
| 31 | + * we build the PHAR. It is based on the Git tag and/or version |
| 32 | + * |
| 33 | + * It will be replaced with `2.0.0` on an exact tag match, or something |
| 34 | + * like `2.0.0@e558e33` on a commit following a tag. |
| 35 | + * |
| 36 | + * When running not in a PHAR, this will not be replaced, so this |
| 37 | + * method needs additional logic to determine the version. |
| 38 | + * |
| 39 | + * @link https://box-project.github.io/box/configuration/#pretty-git-tag-placeholder-git |
| 40 | + */ |
| 41 | + $pieVersion = '@pie_version@'; |
| 42 | + |
| 43 | + /** |
| 44 | + * @psalm-suppress RedundantCondition |
| 45 | + * @noinspection PhpConditionAlreadyCheckedInspection |
| 46 | + */ |
| 47 | + // phpcs:ignore Generic.Strings.UnnecessaryStringConcat.Found |
| 48 | + if ($pieVersion === '@pie_version' . '@') { |
| 49 | + if (! class_exists(InstalledVersions::class)) { |
| 50 | + return self::SYMFONY_MAGIC_CONST_UNKNOWN; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * This tries to determine the version based on Composer; if we are |
| 55 | + * the root package (i.e. you're developing on it), this will most |
| 56 | + * likely be something like `dev-main` (branch name). |
| 57 | + */ |
| 58 | + $installedVersion = InstalledVersions::getVersion(InstalledVersions::getRootPackage()['name']); |
| 59 | + if ($installedVersion === null) { |
| 60 | + return self::SYMFONY_MAGIC_CONST_UNKNOWN; |
| 61 | + } |
| 62 | + |
| 63 | + return $installedVersion; |
| 64 | + } |
| 65 | + |
| 66 | + /** @psalm-suppress NoValue */ |
| 67 | + return $pieVersion; |
| 68 | + } |
| 69 | +} |
0 commit comments