ReleaseAssetSupport.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace YahnisElsts\PluginUpdateChecker\v5p1\Vcs;
  3. if ( !trait_exists(ReleaseAssetSupport::class, false) ) :
  4. trait ReleaseAssetSupport {
  5. /**
  6. * @var bool Whether to download release assets instead of the auto-generated
  7. * source code archives.
  8. */
  9. protected $releaseAssetsEnabled = false;
  10. /**
  11. * @var string|null Regular expression that's used to filter release assets
  12. * by file name or URL. Optional.
  13. */
  14. protected $assetFilterRegex = null;
  15. /**
  16. * How to handle releases that don't have any matching release assets.
  17. *
  18. * @var int
  19. */
  20. protected $releaseAssetPreference = Api::PREFER_RELEASE_ASSETS;
  21. /**
  22. * Enable updating via release assets.
  23. *
  24. * If the latest release contains no usable assets, the update checker
  25. * will fall back to using the automatically generated ZIP archive.
  26. *
  27. * @param string|null $nameRegex Optional. Use only those assets where
  28. * the file name or URL matches this regex.
  29. * @param int $preference Optional. How to handle releases that don't have
  30. * any matching release assets.
  31. */
  32. public function enableReleaseAssets($nameRegex = null, $preference = Api::PREFER_RELEASE_ASSETS) {
  33. $this->releaseAssetsEnabled = true;
  34. $this->assetFilterRegex = $nameRegex;
  35. $this->releaseAssetPreference = $preference;
  36. }
  37. /**
  38. * Disable release assets.
  39. *
  40. * @return void
  41. * @noinspection PhpUnused -- Public API
  42. */
  43. public function disableReleaseAssets() {
  44. $this->releaseAssetsEnabled = false;
  45. $this->assetFilterRegex = null;
  46. }
  47. /**
  48. * Does the specified asset match the name regex?
  49. *
  50. * @param mixed $releaseAsset Data type and structure depend on the host/API.
  51. * @return bool
  52. */
  53. protected function matchesAssetFilter($releaseAsset) {
  54. if ( $this->assetFilterRegex === null ) {
  55. //The default is to accept all assets.
  56. return true;
  57. }
  58. $name = $this->getFilterableAssetName($releaseAsset);
  59. if ( !is_string($name) ) {
  60. return false;
  61. }
  62. return (bool)preg_match($this->assetFilterRegex, $releaseAsset->name);
  63. }
  64. /**
  65. * Get the part of asset data that will be checked against the filter regex.
  66. *
  67. * @param mixed $releaseAsset
  68. * @return string|null
  69. */
  70. abstract protected function getFilterableAssetName($releaseAsset);
  71. }
  72. endif;