Skip to content

Instantly share code, notes, and snippets.

@ilya-dev
Last active March 1, 2016 23:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ilya-dev/9955344 to your computer and use it in GitHub Desktop.
Save ilya-dev/9955344 to your computer and use it in GitHub Desktop.
Raw prototype of an application updater

Usage (don't forget to run artisan down first!)

$updater = new Updater(new Illuminate\Filesystem\Filesystem, app_path());

$updated = $updater->update($path_to_unzziped_code_directory, $path_to_backup_directory);

echo $updated ? "Your application is updated" : "Something went wrong";
<?php namespace Acme;
use Illuminate\Filesystem\Filesystem;
class Updater {
/**
* The Filesystem instance
*
* @var Illuminate\Filesystem\Filesystem
*/
protected $file;
/**
* Full path to the application folder
*
* @var string
*/
protected $app;
/**
* Full path to the backup folder
*
* @var string
*/
protected $backup;
/**
* The constructor
*
* @param Illuminate\Filesystem\Filesystem $file
* @param string $app
* @return void
*/
public function __construct(Filesystem $file, $app)
{
$this->file = $file;
$this->app = $app;
}
/**
* Update the application
*
* @param string $source
* @param string $backup
* @return boolean
*/
public function update($source, $backup)
{
$this->backup = $backup;
// if the process failed, we cannot proceed
if ( ! $this->backup()) return false;
// get all files from the source directory (recursively)
$files = $this->file->allFiles($source);
foreach ($files as $file)
{
$from = $this->path($source, $file); // source path
$to = $this->path($this->app, $file); // and destination path
// attempt to [over]write a file
// if something goes wrong, we rollback all the changes
if ( ! $this->write($from, $to))
{
$this->rollback();
return false;
}
}
return true;
}
/**
* Get the backup directory path
*
* @return string
*/
protected function getBackupPath()
{
return $this->backup;
}
/**
* Backup the whole application
*
* @return boolean
*/
protected function backup()
{
return $this->file->copyDirectory($this->app, $this->getBackupPath());
}
/**
* Rollback all made changes
*
* @return boolean
*/
protected function rollback()
{
return $this->file->copyDirectory($this->getBackupPath(), $this->app);
}
/**
* Write to a file
*
* @param string $from
* @param string $to
* @return boolean
*/
protected function write($from, $to)
{
$directory = dirname($from);
$file = $this->file;
return $file->isWritable($directory) and $file->put($from, $to);
}
/**
* Build a path string
*
* @param dynamic
* @return string
*/
protected function path()
{
$path = implode('/', func_get_args());
return str_replace('//', '/', $path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment