<?php
namespace WpDownloader\Component;
use WpDownloader\GitApi;
use WpDownloader\Log;
use WpDownloader\Utility;
class GithubPlugin extends Plugin
{
private $requiredFields = ['repo', 'owner'];
private $latestCommit; // Latest commit data array obtained from API
public function getSourcePath()
{
$latestSha = $this->getLatestVersion();
$shaPrefix = substr($latestSha, 0, 7);
$path = "{$this->localPath}/{$this->componentData['owner']}-{$this->componentData['repo']}-{$shaPrefix}";
if ($this->isMuPlugin()) {
$path .= "/{$this->componentData['file']}";
}
return $path;
}
public function getActivationFile()
{
return "{$this->componentData['repo']}/{$this->componentData['file']}";
}
public function getLatestCommit()
{
if (isset($this->latestCommit)) {
return $this->latestCommit;
}
$this->latestCommit = GitApi::getLatestCommitForBranch(
$this->componentData['owner'],
$this->componentData['repo'],
$this->componentData['branch']
);
return $this->latestCommit;
}
public function getLatestVersion()
{
$this->getLatestCommit();
$version = $this->latestCommit['sha'];
if (empty($version)) {
Log::throwException("Failed to obtain sha hash from commit data. Data was:".print_r($this->latestCommit, 1));
}
return $version;
}
public function afterSetData()
{
$unsetFields = array_filter($this->requiredFields, function ($field) {
return !isset($this->componentData[$field]);
});
if (count($unsetFields) > 0) {
Log::throwException('Attempted to set data for a "Github Plugin" without specifying required fields:'.implode(',', $unsetFields));
}
$this->slug = $this->getSlug();
}
public function getDownloadUrl()
{
return GitApi::getDownloadUrl(
$this->componentData['owner'],
$this->componentData['repo'],
$this->componentData['branch']
);
}
public function getSlug()
{
return "git:{$this->componentData['owner']}:{$this->componentData['repo']}";
}
public function downloadLatestVersion()
{
$downloadUrl = $this->getDownloadUrl();
$fileName = $this->getSlug() . '.zip';
$localFile = $this->downloadFile($downloadUrl, "{$this->temporaryDirectory}/{$fileName}");
if (!$localFile || !file_exists($localFile)) {
Log::throwException("Downloaded failed or local file {$localFile} does not exist.");
}
$this->extractArchive($localFile);
$this->commitTempToPersistent();
$this->version = $this->getLatestVersion();
$this->appendLocalData([
'version' => $this->version,
'commit_data' => $this->latestCommit['commit']
]);
return $this->version;
}
public function hasUpdateAvailable()
{
if (empty($this->getCurrentLocalVersion())) {
return true;
}
return $this->getCurrentLocalVersion() !== $this->getLatestVersion();
}
}