phar-creator/phar-creator.php

91 lines
2.9 KiB
PHP

<?php
/**
* Phar-creator
*
* This is a (.phar) package creator, allowing you to convert
* your project into an easily transportable and usable PHP package.
*
* Execution : `php -dphar.readonly=0 phar-creator.php`
* Require : PHP version >= 7.4
*
* @version 1.0.0
* @since 08-08-2022
*
* @author Jérémi Nihart <contact@endmove.eu>
* @copyright © 2022 EndMove, All rights reserved.
*
* @link https://git.endmove.eu/EndMove/phar-creator
*/
declare(strict_types=1);
// CONSTANTS - to config
const FILE_NAME = 'hello-world.phar'; // the package name, must end by '.phar'
const SOURCE_FOLDER = '/src'; // the source folder, usualy 'src'
const OUTPUT_FOLDER = '/build'; // the output folder, usualy 'build'
const CLI_ENTRY_POINT = 'main.php'; // the program/library entry point for cli use, usualy 'main.php'
const WEB_ENTRY_POINT = null; // the program entry point for web use, usualy 'web_index.php'
const USE_SHEBANG = false; // use shebang for fast click execution on linux, usualy 'false'
const META_DATA = [ // the meta-data to merge with the phar package.
'version' => '1.0.0',
'author' => 'EndMove',
'website' => 'https://www.endmove.eu'
];
// PROGRAM
try {
$output = __DIR__ . OUTPUT_FOLDER . '/';
// clean
if (!file_exists($output)) {
echo "Build directory has been created\n";
mkdir($output, 0770);
}
// clean & update output
$output .= FILE_NAME;
if (file_exists($output)) {
echo "Cleaning old files...\n";
unlink($output);
}
// create phar
echo "=== Start creating (.phar) package ===\n";
$phar = new Phar($output);
// buffering START
echo "-> Buffering files...\n";
$phar->startBuffering();
// packaging project
echo "-> Packaging project...\n";
$phar->buildFromDirectory(__DIR__ . SOURCE_FOLDER);
echo "-> Packaging project. Done!\n";
// create stub
echo "-> Creating stub...\n";
$stub = $phar->createDefaultStub(CLI_ENTRY_POINT, WEB_ENTRY_POINT);
$phar->setStub(USE_SHEBANG ? "#!/usr/bin/env php \n$stub" : $stub);
echo "-> Creating stub. Done!\n";
// add meta-data
$phar->setMetadata(META_DATA);
echo "-> Meta-data added!\n";
// buffering STOP
$phar->stopBuffering();
echo "-> Buffering files. Done!\n";
// compressing package content
echo "-> compressing package...\n";
$phar->compressFiles(Phar::GZ);
echo "-> compressing package. Done!\n";
// chmod perm
chmod($output, 0770);
echo "OK. Project successfuly packaged into ($output).\n";
echo "Generated phar SHA256 fingerprint : " . hash_file('sha256', $output) . PHP_EOL;
} catch (Exception $e) {
echo("ERROR : " . $e->getMessage());
exit(1);
}
exit(0);