Merge branch 'master' into dev

# Conflicts:
#	CHANGELOG.md
#	src/ncc/CLI/Commands/BuildCommand.php
#	src/ncc/Classes/GithubExtension/GithubRepository.php
#	src/ncc/Managers/PackageManager.php
#	src/ncc/VERSION
#	src/ncc/version.json
This commit is contained in:
netkas 2024-09-20 20:10:15 -04:00
commit 87290232f5
492 changed files with 15261 additions and 12722 deletions

View file

@ -13,7 +13,7 @@
$third_party_path = __DIR__ . DIRECTORY_SEPARATOR . 'ThirdParty' . DIRECTORY_SEPARATOR;
$target_files = [
__DIR__ . DIRECTORY_SEPARATOR . 'autoload_spl.php',
$third_party_path . 'composer' . DIRECTORY_SEPARATOR . 'semver' . DIRECTORY_SEPARATOR . 'autoload_spl.php',
$third_party_path . 'composer' . DIRECTORY_SEPARATOR . 'Semver' . DIRECTORY_SEPARATOR . 'autoload_spl.php',
$third_party_path . 'defuse' . DIRECTORY_SEPARATOR . 'php-encryption' . DIRECTORY_SEPARATOR . 'autoload_spl.php',
$third_party_path . 'jelix' . DIRECTORY_SEPARATOR . 'version' . DIRECTORY_SEPARATOR . 'autoload_spl.php',
$third_party_path . 'nikic' . DIRECTORY_SEPARATOR . 'PhpParser' . DIRECTORY_SEPARATOR . 'autoload_spl.php',

View file

@ -75,7 +75,7 @@
if($output_path !== null)
{
$options[BuildConfigurationOptions::OUTPUT_FILE] = $output_path;
$options[BuildConfigurationOptions::OUTPUT_FILE->value] = $output_path;
}
// Load the project
@ -89,43 +89,19 @@
return 1;
}
$build_configuration = $args['config'] ?? $args['c'] ?? BuildConfigurationValues::DEFAULT;
if($build_configuration === BuildConfigurationValues::ALL)
// Build the project
try
{
// Build all configurations
foreach($project_manager->getProjectConfiguration()->getBuild()->getBuildConfigurations() as $configuration_name)
{
Console::out(sprintf('Building configuration \'%s\'', $configuration_name));
try
{
$output = $project_manager->build($configuration_name, $options);
}
catch (Exception $e)
{
Console::outException('Failed to build project', $e, 1);
return 1;
}
Console::out($output);
}
$build_configuration = $args['config'] ?? $args['c'] ?? BuildConfigurationValues::DEFAULT->value;
$output = $project_manager->build($build_configuration, $options);
}
else
catch (Exception $e)
{
// Build the project
try
{
$output = $project_manager->build($build_configuration, $options);
}
catch (Exception $e)
{
Console::outException('Failed to build project', $e, 1);
return 1;
}
Console::out($output);
Console::outException('Failed to build project', $e, 1);
return 1;
}
Console::out($output);
return 0;
}

View file

@ -24,9 +24,11 @@
use Exception;
use ncc\Classes\Runtime;
use ncc\CLI\Main;
use ncc\Objects\CliHelpSection;
use ncc\Utilities\Console;
use ncc\Utilities\Functions;
use ncc\Utilities\Resolver;
class ExecCommand
{
@ -40,6 +42,12 @@
{
$package = $args['package'] ?? null;
$version = $args['exec-version'] ?? 'latest';
$program_arguments = [];
if(isset($args['exec-args']))
{
$program_arguments = Resolver::splitArguments(Main::getRawArgs(), '--exec-args');
}
if($package === null)
{
@ -58,7 +66,7 @@
try
{
return Runtime::execute($package_name);
return Runtime::execute($package_name, $program_arguments);
}
catch(Exception $e)
{

View file

@ -50,7 +50,12 @@
private static $args;
/**
* @var string|null
* @var array
*/
private static $raw_args;
/**
* @var LogLevel|null
*/
private static $log_level;
@ -63,6 +68,7 @@
public static function start(array $argv): int
{
self::$args = Resolver::parseArguments(implode(' ', $argv));
self::$raw_args = $argv;
if(!isset(self::$args['ncc-cli']))
{
@ -91,30 +97,14 @@
if(isset(self::$args['l']) || isset(self::$args['log-level']))
{
switch(strtolower(self::$args['l'] ?? self::$args['log-level']))
{
case LogLevel::SILENT:
case LogLevel::FATAL:
case LogLevel::ERROR:
case LogLevel::WARNING:
case LogLevel::INFO:
case LogLevel::DEBUG:
case LogLevel::VERBOSE:
self::$log_level = strtolower(self::$args['l'] ?? self::$args['log-level']);
break;
default:
Console::outWarning('Unknown log level: ' . (self::$args['l'] ?? self::$args['log-level']) . ', using \'info\'');
self::$log_level = LogLevel::INFO;
break;
}
self::$log_level = LogLevel::fromOrDefault(strtolower(self::$args['l'] ?? self::$args['log-level']));
}
else
{
self::$log_level = LogLevel::INFO;
}
if(Resolver::checkLogLevel(self::$log_level, LogLevel::DEBUG))
if(self::$log_level->checkLogLevel(LogLevel::DEBUG))
{
Console::outDebug('Debug logging enabled');
@ -125,12 +115,12 @@
Console::outDebug(sprintf('args: %s', json_encode(self::$args, JSON_UNESCAPED_SLASHES)));
}
if(in_array(NccBuildFlags::UNSTABLE, NCC_VERSION_FLAGS, true))
if(in_array(NccBuildFlags::UNSTABLE->value, NCC_VERSION_FLAGS, true))
{
Console::outWarning('This is an unstable build of ncc, expect some features to not work as expected');
}
if(in_array(NccBuildFlags::BETA, NCC_VERSION_FLAGS, true))
if(in_array(NccBuildFlags::BETA->value, NCC_VERSION_FLAGS, true))
{
Console::outWarning('This is a beta build of ncc, expect some features to not work as expected');
}
@ -230,9 +220,19 @@
}
/**
* @return string
* Returns the raw arguments passed to ncc
*
* @return array
*/
public static function getLogLevel(): string
public static function getRawArgs(): array
{
return self::$raw_args;
}
/**
* @return LogLevel
*/
public static function getLogLevel(): LogLevel
{
if(self::$log_level === null)
{

View file

@ -101,7 +101,7 @@
if(isset($args['v']))
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('Insufficient permissions, cannot modify configuration values', true, 1);
return 1;

View file

@ -187,7 +187,7 @@
{
$ResolvedScope = Resolver::resolveScope();
if($ResolvedScope !== Scopes::SYSTEM)
if($ResolvedScope !== Scopes::SYSTEM->value)
{
Console::outError('Insufficient permissions to add entries');
}
@ -313,7 +313,7 @@
{
$ResolvedScope = Resolver::resolveScope();
if($ResolvedScope !== Scopes::SYSTEM)
if($ResolvedScope !== Scopes::SYSTEM->value)
{
Console::outError('Insufficient permissions to remove entries');
}

View file

@ -132,7 +132,7 @@
*/
private static function installPackage(array $args): int
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('You cannot install packages in a user scope, please run this command as root', true, 1);
return 1;
@ -155,17 +155,22 @@
if(isset($args['reinstall']))
{
$options[InstallPackageOptions::REINSTALL] = true;
$options[InstallPackageOptions::REINSTALL->value] = true;
}
if(isset($args['prefer-static']) || isset($args['static']))
{
$options[InstallPackageOptions::PREFER_STATIC] = true;
$options[InstallPackageOptions::PREFER_STATIC->value] = true;
}
if(isset($args['skip-dependencies']))
{
$options[InstallPackageOptions::SKIP_DEPENDENCIES] = true;
$options[InstallPackageOptions::SKIP_DEPENDENCIES->value] = true;
}
if(isset($args['build-source']))
{
$options[InstallPackageOptions::BUILD_SOURCE->value] = true;
}
if($authentication !== null)
@ -199,7 +204,7 @@
$authentication_entry = $entry->getPassword();
}
if(preg_match(RegexPatterns::REMOTE_PACKAGE, $package) === 1)
if(preg_match(RegexPatterns::REMOTE_PACKAGE->value, $package) === 1)
{
$package_input = RemotePackageInput::fromString($package);
@ -388,7 +393,7 @@
*/
private static function uninstallPackage($args): int
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('You cannot uninstall packages in a user scope, please run this command as root', true, 1);
return 1;
@ -419,7 +424,7 @@
*/
private static function uninstallAllPackages(array $args): int
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('You cannot uninstall all packages in a user scope, please run this command as root', true, 1);
return 1;
@ -455,7 +460,7 @@
*/
private static function fixBrokenPackages(array $args): int
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('You cannot fix broken packages in a user scope, please run this command as root', true, 1);
return 1;
@ -560,6 +565,7 @@
new CliHelpSection(['install', '-p', '--skip-dependencies'], 'Installs a specified ncc package but skips the installation of dependencies'),
new CliHelpSection(['install', '-p', '--reinstall'], 'Installs a specified ncc package, reinstall if already installed'),
new CliHelpSection(['install', '--prefer-static', '--static'], 'Installs a static version of the package from the remote repository if available'),
new CliHelpSection(['install', '--build-source'], 'Forces ncc to build the packages from source rather than trying to use a pre-built binary'),
new CliHelpSection(['uninstall', '--package', '-p'], 'Uninstalls a specified ncc package'),
new CliHelpSection(['uninstall', '--package', '-p', '--version', '-v'], 'Uninstalls a specified ncc package version'),
new CliHelpSection(['uninstall-all'], 'Uninstalls all packages'),

View file

@ -23,6 +23,7 @@
namespace ncc\CLI\Management;
use Exception;
use ncc\Enums\CompilerExtensions;
use ncc\Enums\ProjectTemplates;
use ncc\Enums\Scopes;
use ncc\Managers\CredentialManager;
@ -102,7 +103,12 @@
if(isset($args['ext']))
{
$compiler_extension = $args['ext'];
$compiler_extension = CompilerExtensions::tryFrom($args['ext']);
if($compiler_extension === null)
{
Console::outError('Invalid compiler extension, please specify a valid compiler extension', true, 1);
return 1;
}
}
else
{
@ -134,7 +140,7 @@
*/
private static function installProject(array $args): int
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('You cannot install packages in a user scope, please run this command as root', true, 1);
return 1;
@ -292,9 +298,9 @@
}
Console::out(PHP_EOL . 'Available Templates:');
foreach(ProjectTemplates::ALL as $template)
foreach(ProjectTemplates::cases() as $template)
{
Console::out(' ' . $template);
Console::out(' ' . $template->value);
}
return 0;

View file

@ -25,6 +25,7 @@
use Exception;
use ncc\Enums\ConsoleColors;
use ncc\Enums\Scopes;
use ncc\Enums\Types\RepositoryType;
use ncc\Managers\RepositoryManager;
use ncc\Objects\CliHelpSection;
use ncc\Objects\RepositoryConfiguration;
@ -141,7 +142,7 @@
*/
private static function addEntry(array $args): int
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('You must be running as root to add a new repository', true, 1);
return 1;
@ -164,6 +165,13 @@
return 1;
}
$parsed_type = RepositoryType::tryFrom($type);
if($parsed_type === null)
{
Console::outError(sprintf('Unknown repository type \'%s\'.', $type), true, 1);
return 1;
}
if($host === null)
{
Console::outError(sprintf('Missing required argument \'%s\'.', 'host'), true, 1);
@ -172,7 +180,7 @@
try
{
(new RepositoryManager())->addRepository(new RepositoryConfiguration($name, $host, $type, $ssl));
(new RepositoryManager())->addRepository(new RepositoryConfiguration($name, $host, $parsed_type, $ssl));
}
catch(Exception $e)
{
@ -230,7 +238,7 @@
*/
private static function removeEntry(array $args): int
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
Console::outError('You must be running as root to remove a repository', true, 1);
return 1;

View file

@ -54,11 +54,11 @@
{
$bin = match($unit->getExecutionPolicy()->getRunner())
{
Runners::PHP => (new ExecutableFinder())->find('php'),
Runners::BASH => (new ExecutableFinder())->find('bash'),
Runners::PYTHON => (new ExecutableFinder())->find('python'),
Runners::LUA => (new ExecutableFinder())->find('lua'),
Runners::PERL => (new ExecutableFinder())->find('perl'),
Runners::PHP->value => (new ExecutableFinder())->find('php'),
Runners::BASH->value => (new ExecutableFinder())->find('bash'),
Runners::PYTHON->value => (new ExecutableFinder())->find('python'),
Runners::LUA->value => (new ExecutableFinder())->find('lua'),
Runners::PERL->value => (new ExecutableFinder())->find('perl'),
default => throw new NotSupportedException(sprintf('The execution policy %s is not supported because it uses the %s runner', $unit->getExecutionPolicy()->getName(), $unit->getExecutionPolicy()->getRunner()))
};
@ -117,8 +117,8 @@
$execution_unit = ExecutionUnit::fromArray(ZiProto::decode(IO::fread($unit_path)));
return match ($execution_unit->getExecutionPolicy()->getRunner())
{
Runners::PHP => PhpRunner::executeUnit($execution_unit, $args),
Runners::BASH => BashRunner::executeUnit($execution_unit, $args),
Runners::PHP->value => PhpRunner::executeUnit($execution_unit, $args),
Runners::BASH->value => BashRunner::executeUnit($execution_unit, $args),
default => throw new NotSupportedException(sprintf('The execution policy %s is not supported because it uses the %s runner', $execution_unit->getExecutionPolicy()->getName(), $execution_unit->getExecutionPolicy()->getRunner())),
};
}
@ -146,8 +146,8 @@
{
return match ($execution_unit->getExecutionPolicy()->getRunner())
{
Runners::PHP => PhpRunner::executeUnit($execution_unit, $args, false),
Runners::BASH => BashRunner::executeUnit($execution_unit, $args),
Runners::PHP->value => PhpRunner::executeUnit($execution_unit, $args, false),
Runners::BASH->value => BashRunner::executeUnit($execution_unit, $args),
default => throw new NotSupportedException(sprintf('The execution policy %s is not supported because it uses the %s runner', $execution_unit->getExecutionPolicy()->getName(), $execution_unit->getExecutionPolicy()->getRunner())),
};
}

View file

@ -48,7 +48,7 @@
/**
* @inheritDoc
*/
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST->value, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
{
try
{
@ -65,7 +65,7 @@
/**
* @inheritDoc
*/
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST->value, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
{
return self::getReleasePackage($repository, $vendor, $project, $version, $authentication, $options);
}
@ -112,7 +112,7 @@
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -169,7 +169,7 @@
*/
private static function getTagArchive(RepositoryConfiguration $repository, string $group, string $project, string $tag, ?AuthenticationInterface $authentication=null): RepositoryResult
{
if($tag === Versions::LATEST)
if($tag === Versions::LATEST->value)
{
$tag = self::getLatestTag($repository, $group, $project, $authentication);
}
@ -203,7 +203,7 @@
curl_setopt_array($curl, [
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -212,11 +212,11 @@
if(isset($response['zipball_url']))
{
$result = new RepositoryResult($response['zipball_url'], RepositoryResultType::SOURCE, $tag);
$result = new RepositoryResult($response['zipball_url'], RepositoryResultType::SOURCE->value, $tag);
}
elseif(isset($response['tarball_url']))
{
$result = new RepositoryResult($response['tarball_url'], RepositoryResultType::SOURCE, $tag);
$result = new RepositoryResult($response['tarball_url'], RepositoryResultType::SOURCE->value, $tag);
}
else
{
@ -270,7 +270,7 @@
curl_setopt_array($curl, [
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -328,7 +328,7 @@
private static function getReleasePackage(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null, array $options=[]): RepositoryResult
{
/** @noinspection DuplicatedCode */
if($release === Versions::LATEST)
if($release === Versions::LATEST->value)
{
$release = self::getLatestRelease($repository, $group, $project, $authentication);
}
@ -368,7 +368,7 @@
curl_setopt_array($curl, [
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -383,7 +383,7 @@
$release, $group, $project));
}
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC]);
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC->value]);
$preferred_asset = null;
$fallback_asset = null;
@ -407,7 +407,7 @@
if($asset_url)
{
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE, $release);
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE->value, $release);
RuntimeCache::set($endpoint, $result);
return $result;
@ -437,7 +437,7 @@
private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null): RepositoryResult
{
/** @noinspection DuplicatedCode */
if ($release === Versions::LATEST)
if ($release === Versions::LATEST->value)
{
$release = self::getLatestRelease($repository, $group, $project, $authentication);
}
@ -471,7 +471,7 @@
curl_setopt_array($curl, [
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -480,11 +480,11 @@
if(isset($response['zipball_url']))
{
$results = new RepositoryResult($response['zipball_url'], RepositoryResultType::SOURCE, $release);
$results = new RepositoryResult($response['zipball_url'], RepositoryResultType::SOURCE->value, $release);
}
elseif(isset($response['tarball_url']))
{
$results = new RepositoryResult($response['tarball_url'], RepositoryResultType::SOURCE, $release);
$results = new RepositoryResult($response['tarball_url'], RepositoryResultType::SOURCE->value, $release);
}
else
{
@ -515,7 +515,7 @@
break;
}
throw new AuthenticationException(sprintf('Invalid authentication type for Access Token, got %s instead', $authentication->getAuthenticationType()));
throw new AuthenticationException(sprintf('Invalid authentication type for Access Token, got %s instead', $authentication->getAuthenticationType()->value));
case AuthenticationType::USERNAME_PASSWORD:
if($authentication instanceof UsernamePassword)
@ -524,7 +524,7 @@
break;
}
throw new AuthenticationException(sprintf('Invalid authentication type for Username/Password, got %s instead', $authentication->getAuthenticationType()));
throw new AuthenticationException(sprintf('Invalid authentication type for Username/Password, got %s instead', $authentication->getAuthenticationType()->value));
}
return $headers;

View file

@ -39,7 +39,6 @@
use ncc\Objects\Vault\Password\AccessToken;
use ncc\Objects\Vault\Password\UsernamePassword;
use ncc\Utilities\Console;
use ncc\Utilities\Resolver;
use ncc\Utilities\RuntimeCache;
use RuntimeException;
@ -48,7 +47,7 @@
/**
* @inheritDoc
*/
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST->value, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
{
try
{
@ -65,7 +64,7 @@
/**
* @inheritDoc
*/
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version = Versions::LATEST, ?AuthenticationType $authentication = null, array $options=[]): RepositoryResult
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version = Versions::LATEST->value, ?AuthenticationType $authentication = null, array $options=[]): RepositoryResult
{
return self::getReleasePackage($repository, $vendor, $project, $version, $authentication, $options);
}
@ -103,16 +102,9 @@
$headers = self::injectAuthentication($authentication, $curl, $headers);
}
$resolved_host = Resolver::getResolveOption($endpoint);
if($resolved_host !== null)
{
curl_setopt($curl, CURLOPT_RESOLVE, [$resolved_host]);
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -169,7 +161,7 @@
*/
private static function getTagArchive(RepositoryConfiguration $repository, string $group, string $project, string $tag, ?AuthenticationInterface $authentication = null): RepositoryResult
{
if($tag === Versions::LATEST)
if($tag === Versions::LATEST->value)
{
$tag = self::getLatestTag($repository, $group, $project, $authentication);
}
@ -191,17 +183,10 @@
$headers = self::injectAuthentication($authentication, $curl, $headers);
}
$resolved_host = Resolver::getResolveOption($endpoint);
if($resolved_host !== null)
{
curl_setopt($curl, CURLOPT_RESOLVE, [$resolved_host]);
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_NOBODY => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true
]);
@ -222,7 +207,7 @@
throw new NetworkException(sprintf('Server responded with HTTP code %s when getting tag archive for %s/%s/%s', $http_code, $group, $project, $tag));
}
$result = new RepositoryResult(curl_getinfo($curl, CURLINFO_EFFECTIVE_URL), RepositoryResultType::SOURCE, $tag);
$result = new RepositoryResult(curl_getinfo($curl, CURLINFO_EFFECTIVE_URL), RepositoryResultType::SOURCE->value, $tag);
curl_close($curl);
RuntimeCache::set($endpoint, $result);
@ -262,16 +247,9 @@
$headers = self::injectAuthentication($authentication, $curl, $headers);
}
$resolved_host = Resolver::getResolveOption($endpoint);
if($resolved_host !== null)
{
curl_setopt($curl, CURLOPT_RESOLVE, [$resolved_host]);
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -329,7 +307,7 @@
private static function getReleasePackage(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null, array $options=[]): RepositoryResult
{
/** @noinspection DuplicatedCode */
if($release === Versions::LATEST)
if($release === Versions::LATEST->value)
{
$release = self::getLatestRelease($repository, $group, $project, $authentication);
}
@ -353,18 +331,7 @@
$headers = self::injectAuthentication($authentication, $curl, $headers);
}
$resolved_host = Resolver::getResolveOption($endpoint);
if($resolved_host !== null)
{
curl_setopt($curl, CURLOPT_RESOLVE, [$resolved_host]);
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_HTTPHEADER => $headers
]);
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value, CURLOPT_HTTPHEADER => $headers]);
Console::outDebug(sprintf('Fetching release package for %s/%s/%s from %s', $group, $project, $release, $endpoint));
$response = self::processHttpResponse($curl, $group, $project);
@ -374,7 +341,7 @@
throw new NetworkException(sprintf('Failed to get release package for %s/%s/%s: No assets found', $group, $project, $release));
}
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC]);
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC->value]);
$preferred_asset = null;
$fallback_asset = null;
@ -396,7 +363,7 @@
{
$asset_url = $target_asset['browser_download_url'];
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE, $release);
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE->value, $release);
RuntimeCache::set($endpoint, $result);
return $result;
@ -422,7 +389,7 @@
private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication = null): RepositoryResult
{
/** @noinspection DuplicatedCode */
if($release === Versions::LATEST)
if($release === Versions::LATEST->value)
{
$release = self::getLatestRelease($repository, $group, $project, $authentication);
}
@ -446,16 +413,9 @@
$headers = self::injectAuthentication($authentication, $curl, $headers);
}
$resolved_host = Resolver::getResolveOption($endpoint);
if($resolved_host !== null)
{
curl_setopt($curl, CURLOPT_RESOLVE, [$resolved_host]);
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -465,11 +425,11 @@
if(isset($response['zipball_url']))
{
$result = new RepositoryResult($response['zipball_url'], RepositoryResultType::SOURCE, $release);
$result = new RepositoryResult($response['zipball_url'], RepositoryResultType::SOURCE->value, $release);
}
elseif(isset($response['tarball_url']))
{
$result = new RepositoryResult($response['tarball_url'], RepositoryResultType::SOURCE, $release);
$result = new RepositoryResult($response['tarball_url'], RepositoryResultType::SOURCE->value, $release);
}
else
{
@ -499,7 +459,7 @@
$headers[] = 'Authorization: Bearer ' . $authentication->getAccessToken();
break;
}
throw new AuthenticationException(sprintf('Invalid authentication type for Access Token, got %s instead', $authentication->getAuthenticationType()));
throw new AuthenticationException(sprintf('Invalid authentication type for Access Token, got %s instead', $authentication->getAuthenticationType()->value));
case AuthenticationType::USERNAME_PASSWORD:
if($authentication instanceof UsernamePassword)
@ -508,7 +468,7 @@
break;
}
throw new AuthenticationException(sprintf('Invalid authentication type for Username/Password, got %s instead', $authentication->getAuthenticationType()));
throw new AuthenticationException(sprintf('Invalid authentication type for Username/Password, got %s instead', $authentication->getAuthenticationType()->value));
}
return $headers;

View file

@ -48,7 +48,7 @@
/**
* @inheritDoc
*/
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST->value, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
{
try
{
@ -65,7 +65,7 @@
/**
* @inheritDoc
*/
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST->value, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult
{
return self::getReleasePackage($repository, $vendor, $project, $version, $authentication, $options);
}
@ -114,7 +114,7 @@
curl_setopt_array($curl, [
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -172,7 +172,7 @@
*/
private static function getTagArchive(RepositoryConfiguration $repository, string $group, string $project, string $tag, ?AuthenticationInterface $authentication=null): RepositoryResult
{
if($tag === Versions::LATEST)
if($tag === Versions::LATEST->value)
{
$tag = self::getLatestTag($repository, $group, $project, $authentication);
}
@ -205,7 +205,7 @@
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_NOBODY => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true
]);
@ -225,7 +225,7 @@
throw new NetworkException(sprintf('Server responded with HTTP code %s when getting tag archive for %s/%s/%s', $http_code, $group, $project, $tag));
}
$results = new RepositoryResult(curl_getinfo($curl, CURLINFO_EFFECTIVE_URL), RepositoryResultType::SOURCE, $tag);
$results = new RepositoryResult(curl_getinfo($curl, CURLINFO_EFFECTIVE_URL), RepositoryResultType::SOURCE->value, $tag);
RuntimeCache::set($endpoint, $results);
return $results;
@ -274,7 +274,7 @@
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -330,7 +330,7 @@
*/
private static function getReleasePackage(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null, array $options=[]): RepositoryResult
{
if($release === Versions::LATEST)
if($release === Versions::LATEST->value)
{
$release = self::getLatestRelease($repository, $group, $project, $authentication);
}
@ -364,12 +364,12 @@
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
$response = self::processHttpResponse($curl, $group, $project);
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC]);
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC->value]);
$preferred_asset = null;
$fallback_asset = null;
@ -393,7 +393,7 @@
if ($asset_url)
{
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE, $release);
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE->value, $release);
RuntimeCache::set($endpoint, $result);
return $result;
@ -422,7 +422,7 @@
private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null): RepositoryResult
{
/** @noinspection DuplicatedCode */
if($release === Versions::LATEST)
if($release === Versions::LATEST->value)
{
$release = self::getLatestRelease($repository, $group, $project, $authentication);
}
@ -456,7 +456,7 @@
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -476,11 +476,11 @@
if($asset['format'] === 'zip')
{
$results = new RepositoryResult($asset['url'], RepositoryResultType::SOURCE, $release);
$results = new RepositoryResult($asset['url'], RepositoryResultType::SOURCE->value, $release);
}
elseif($asset['format'] === 'tar')
{
$results = new RepositoryResult($asset['url'], RepositoryResultType::SOURCE, $release);
$results = new RepositoryResult($asset['url'], RepositoryResultType::SOURCE->value, $release);
}
else
{
@ -507,23 +507,23 @@
{
switch($authentication->getAuthenticationType())
{
case AuthenticationType::ACCESS_TOKEN:
case AuthenticationType::ACCESS_TOKEN->value:
if($authentication instanceof AccessToken)
{
$headers[] = 'Private-Token: ' . $authentication->getAccessToken();
break;
}
throw new AuthenticationException(sprintf('Invalid authentication type for Access Token, got %s instead', $authentication->getAuthenticationType()));
throw new AuthenticationException(sprintf('Invalid authentication type for Access Token, got %s instead', $authentication->getAuthenticationType()->value));
case AuthenticationType::USERNAME_PASSWORD:
case AuthenticationType::USERNAME_PASSWORD->value:
if($authentication instanceof UsernamePassword)
{
curl_setopt($curl, CURLOPT_USERPWD, $authentication->getUsername() . ':' . $authentication->getPassword());
break;
}
throw new AuthenticationException(sprintf('Invalid authentication type for Username/Password, got %s instead', $authentication->getAuthenticationType()));
throw new AuthenticationException(sprintf('Invalid authentication type for Username/Password, got %s instead', $authentication->getAuthenticationType()->value));
}
return $headers;

View file

@ -67,10 +67,10 @@
$input = str_replace(
[
AssemblyConstants::ASSEMBLY_NAME,
AssemblyConstants::ASSEMBLY_PACKAGE,
AssemblyConstants::ASSEMBLY_VERSION,
AssemblyConstants::ASSEMBLY_UID
AssemblyConstants::ASSEMBLY_NAME->value,
AssemblyConstants::ASSEMBLY_PACKAGE->value,
AssemblyConstants::ASSEMBLY_VERSION->value,
AssemblyConstants::ASSEMBLY_UID->value
],
[
$assembly->getName(),
@ -81,27 +81,27 @@
if($assembly->getDescription() !== null)
{
$input = str_replace(AssemblyConstants::ASSEMBLY_DESCRIPTION, $assembly->getDescription(), $input);
$input = str_replace(AssemblyConstants::ASSEMBLY_DESCRIPTION->value, $assembly->getDescription(), $input);
}
if($assembly->getCompany() !== null)
{
$input = str_replace(AssemblyConstants::ASSEMBLY_COMPANY, $assembly->getCompany(), $input);
$input = str_replace(AssemblyConstants::ASSEMBLY_COMPANY->value, $assembly->getCompany(), $input);
}
if($assembly->getProduct() !== null)
{
$input = str_replace(AssemblyConstants::ASSEMBLY_PRODUCT, $assembly->getProduct(), $input);
$input = str_replace(AssemblyConstants::ASSEMBLY_PRODUCT->value, $assembly->getProduct(), $input);
}
if($assembly->getCopyright() !== null)
{
$input = str_replace(AssemblyConstants::ASSEMBLY_COPYRIGHT, $assembly->getCopyright(), $input);
$input = str_replace(AssemblyConstants::ASSEMBLY_COPYRIGHT->value, $assembly->getCopyright(), $input);
}
if($assembly->getTrademark() !== null)
{
$input = str_replace(AssemblyConstants::ASSEMBLY_TRADEMARK, $assembly->getTrademark(), $input);
$input = str_replace(AssemblyConstants::ASSEMBLY_TRADEMARK->value, $assembly->getTrademark(), $input);
}
return $input;
}
@ -121,10 +121,10 @@
return str_replace(
[
BuildConstants::COMPILE_TIMESTAMP,
BuildConstants::NCC_BUILD_VERSION,
BuildConstants::NCC_BUILD_FLAGS,
BuildConstants::NCC_BUILD_BRANCH
BuildConstants::COMPILE_TIMESTAMP->value,
BuildConstants::NCC_BUILD_VERSION->value,
BuildConstants::NCC_BUILD_FLAGS->value,
BuildConstants::NCC_BUILD_BRANCH->value
],
[
time(),
@ -150,10 +150,10 @@
return str_replace(
[
InstallConstants::INSTALL_PATH,
InstallConstants::INSTALL_PATH_BIN,
InstallConstants::INSTALL_PATH_SRC,
InstallConstants::INSTALL_PATH_DATA
InstallConstants::INSTALL_PATH->value,
InstallConstants::INSTALL_PATH_BIN->value,
InstallConstants::INSTALL_PATH_SRC->value,
InstallConstants::INSTALL_PATH_DATA->value
],
[
$installation_paths->getInstallationpath(),
@ -178,36 +178,36 @@
}
return str_replace([
DateTimeConstants::d,
DateTimeConstants::D,
DateTimeConstants::j,
DateTimeConstants::l,
DateTimeConstants::N,
DateTimeConstants::S,
DateTimeConstants::w,
DateTimeConstants::z,
DateTimeConstants::W,
DateTimeConstants::F,
DateTimeConstants::m,
DateTimeConstants::M,
DateTimeConstants::n,
DateTimeConstants::t,
DateTimeConstants::L,
DateTimeConstants::o,
DateTimeConstants::Y,
DateTimeConstants::y,
DateTimeConstants::a,
DateTimeConstants::A,
DateTimeConstants::B,
DateTimeConstants::g,
DateTimeConstants::G,
DateTimeConstants::h,
DateTimeConstants::H,
DateTimeConstants::i,
DateTimeConstants::s,
DateTimeConstants::c,
DateTimeConstants::r,
DateTimeConstants::u
DateTimeConstants::d->value,
DateTimeConstants::D->value,
DateTimeConstants::j->value,
DateTimeConstants::l->value,
DateTimeConstants::N->value,
DateTimeConstants::S->value,
DateTimeConstants::w->value,
DateTimeConstants::z->value,
DateTimeConstants::W->value,
DateTimeConstants::F->value,
DateTimeConstants::m->value,
DateTimeConstants::M->value,
DateTimeConstants::n->value,
DateTimeConstants::t->value,
DateTimeConstants::L->value,
DateTimeConstants::o->value,
DateTimeConstants::Y->value,
DateTimeConstants::y->value,
DateTimeConstants::a->value,
DateTimeConstants::A->value,
DateTimeConstants::B->value,
DateTimeConstants::g->value,
DateTimeConstants::G->value,
DateTimeConstants::h->value,
DateTimeConstants::H->value,
DateTimeConstants::i->value,
DateTimeConstants::s->value,
DateTimeConstants::c->value,
DateTimeConstants::r->value,
DateTimeConstants::u->value
],
[
date('d', $timestamp),
@ -257,7 +257,7 @@
if(function_exists('getcwd'))
{
$input = str_replace(RuntimeConstants::CWD, getcwd(), $input);
$input = str_replace(RuntimeConstants::CWD->value, getcwd(), $input);
}
else
{
@ -266,7 +266,7 @@
if(function_exists('getmypid'))
{
$input = str_replace(RuntimeConstants::PID, getmypid(), $input);
$input = str_replace(RuntimeConstants::PID->value, getmypid(), $input);
}
else
{
@ -275,7 +275,7 @@
if(function_exists('getmyuid'))
{
$input = str_replace(RuntimeConstants::UID, getmyuid(), $input);
$input = str_replace(RuntimeConstants::UID->value, getmyuid(), $input);
}
else
{
@ -284,7 +284,7 @@
if(function_exists('getmygid'))
{
$input = str_replace(RuntimeConstants::GID, getmygid(), $input);
$input = str_replace(RuntimeConstants::GID->value, getmygid(), $input);
}
else
{
@ -293,7 +293,7 @@
if(function_exists('get_current_user'))
{
$input = str_replace(RuntimeConstants::USER, get_current_user(), $input);
$input = str_replace(RuntimeConstants::USER->value, get_current_user(), $input);
}
else
{

View file

@ -93,17 +93,17 @@
* @throws PathNotFoundException
* @noinspection UnusedFunctionResultInspection
*/
public function build(string $build_configuration=BuildConfigurationValues::DEFAULT, array $options=[]): string
public function build(string $build_configuration=BuildConfigurationValues::DEFAULT->value, array $options=[]): string
{
$this->merged_dependencies = [];
$configuration = $this->project_manager->getProjectConfiguration()->getBuild()->getBuildConfiguration($build_configuration);
$configuration->setOptions(array_merge($configuration->getOptions(), $options));
$static_dependencies = isset($configuration->getOptions()[BuildConfigurationOptions::STATIC_DEPENDENCIES]);
$static_dependencies = isset($configuration->getOptions()[BuildConfigurationOptions::STATIC_DEPENDENCIES->value]);
if(isset($configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE]))
if(isset($configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE->value]))
{
$package_path = ConstantCompiler::compileConstants(
$this->project_manager->getProjectConfiguration(), $configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE]
$this->project_manager->getProjectConfiguration(), $configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE->value]
);
}
else
@ -129,7 +129,7 @@
}
// Debugging information
if(Resolver::checkLogLevel(LogLevel::DEBUG, Main::getLogLevel()))
if(LogLevel::DEBUG->checkLogLevel(Main::getLogLevel()))
{
foreach($this->project_manager->getProjectConfiguration()->getAssembly()->toArray() as $prop => $value)
{
@ -269,25 +269,25 @@
{
$package_writer = new PackageWriter($path);
if(isset($build_configuration->getOptions()[BuildConfigurationOptions::COMPRESSION]))
if(isset($build_configuration->getOptions()[BuildConfigurationOptions::COMPRESSION->value]))
{
$package_writer->addFlag(PackageFlags::COMPRESSION);
switch(strtolower($build_configuration->getOptions()[BuildConfigurationOptions::COMPRESSION]))
switch(strtolower($build_configuration->getOptions()[BuildConfigurationOptions::COMPRESSION->value]))
{
case BuildConfigurationOptions\CompressionOptions::HIGH:
case BuildConfigurationOptions\CompressionOptions::HIGH->value:
$package_writer->addFlag(PackageFlags::HIGH_COMPRESSION);
break;
case BuildConfigurationOptions\CompressionOptions::MEDIUM:
case BuildConfigurationOptions\CompressionOptions::MEDIUM->value:
$package_writer->addFlag(PackageFlags::MEDIUM_COMPRESSION);
break;
case BuildConfigurationOptions\CompressionOptions::LOW:
case BuildConfigurationOptions\CompressionOptions::LOW->value:
$package_writer->addFlag(PackageFlags::LOW_COMPRESSION);
break;
default:
throw new NotSupportedException(sprintf('The compression level \'%s\' is not supported', $build_configuration->getOptions()[BuildConfigurationOptions::COMPRESSION]));
throw new NotSupportedException(sprintf('The compression level \'%s\' is not supported', $build_configuration->getOptions()[BuildConfigurationOptions::COMPRESSION->value]));
}
}
@ -335,29 +335,38 @@
* @param string $build_configuration
* @return void
*/
public function processMetadata(PackageWriter $package_writer, string $build_configuration=BuildConfigurationValues::DEFAULT): void
public function processMetadata(PackageWriter $package_writer, string $build_configuration=BuildConfigurationValues::DEFAULT->value): void
{
$metadata = new Metadata($this->project_manager->getProjectConfiguration()->getProject()->getCompiler());
$metadata->addOptions($this->project_manager->getProjectConfiguration()->getBuild()->getOptions($build_configuration));
$metadata->addOptions($this->project_manager->getProjectConfiguration()->getProject()->getOptions());
$metadata->addConstants($this->project_manager->getConstants($build_configuration));
$metadata->setUpdateSource($this->project_manager->getProjectConfiguration()->getProject()->getUpdateSource());
$metadata->setMainExecutionPolicy($this->project_manager->getProjectConfiguration()->getBuild()->getMain());
$metadata->setInstaller($this->project_manager->getProjectConfiguration()->getInstaller());
// Strip out 'output_file' build artifact.
if(isset($metadata->getOptions()[BuildConfigurationOptions::OUTPUT_FILE]))
if(isset($metadata->getOptions()[BuildConfigurationOptions::OUTPUT_FILE->value]))
{
$metadata->removeOption(BuildConfigurationOptions::OUTPUT_FILE);
$metadata->removeOption(BuildConfigurationOptions::OUTPUT_FILE->value);
}
// Strip out 'static' build artifact, PackageFlags::STATIC_DEPENDENCIES is used instead
// Making this option redundant.
if(isset($metadata->getOptions()[BuildConfigurationOptions::STATIC_DEPENDENCIES]))
if(isset($metadata->getOptions()[BuildConfigurationOptions::STATIC_DEPENDENCIES->value]))
{
$metadata->removeOption(BuildConfigurationOptions::STATIC_DEPENDENCIES);
$metadata->removeOption(BuildConfigurationOptions::STATIC_DEPENDENCIES->value);
}
$compiled_constants = [];
foreach($this->project_manager->getConstants() as $constant => $value)
{
$compiled_constants[$constant] = ConstantCompiler::compileConstants($this->project_manager->getProjectConfiguration(), $value);
}
$metadata->addConstants($compiled_constants);
/** @noinspection UnusedFunctionResultInspection */
$package_writer->setMetadata($metadata);
}

View file

@ -175,7 +175,7 @@
throw new IOException(sprintf('File \'%s\' is not a valid package file (corrupted header)', $file_path), $e);
}
if(!isset($this->headers[PackageStructure::FILE_VERSION]))
if(!isset($this->headers[PackageStructure::FILE_VERSION->value]))
{
throw new IOException(sprintf('File \'%s\' is not a valid package file (invalid header)', $file_path));
}
@ -231,7 +231,7 @@
*/
public function getFileVersion(): string
{
return $this->headers[PackageStructure::FILE_VERSION];
return $this->headers[PackageStructure::FILE_VERSION->value];
}
/**
@ -241,7 +241,7 @@
*/
public function getFlags(): array
{
return $this->headers[PackageStructure::FLAGS];
return $this->headers[PackageStructure::FLAGS->value];
}
/**
@ -252,7 +252,7 @@
*/
public function getFlag(string $name): bool
{
return in_array($name, $this->headers[PackageStructure::FLAGS], true);
return in_array($name, $this->headers[PackageStructure::FLAGS->value], true);
}
/**
@ -262,7 +262,7 @@
*/
public function getDirectory(): array
{
return $this->headers[PackageStructure::DIRECTORY];
return $this->headers[PackageStructure::DIRECTORY->value];
}
/**
@ -273,15 +273,15 @@
*/
public function get(string $name): string
{
if(!isset($this->headers[PackageStructure::DIRECTORY][$name]))
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$name]))
{
throw new RuntimeException(sprintf('File \'%s\' not found in package \'%s\'', $name, $this->package_path));
}
$location = explode(':', $this->headers[PackageStructure::DIRECTORY][$name]);
$location = explode(':', $this->headers[PackageStructure::DIRECTORY->value][$name]);
fseek($this->package_file, ($this->data_offset + (int)$location[0]));
if(in_array(PackageFlags::COMPRESSION, $this->headers[PackageStructure::FLAGS], true))
if(in_array(PackageFlags::COMPRESSION->value, $this->headers[PackageStructure::FLAGS->value], true))
{
return gzuncompress(fread($this->package_file, (int)$location[1]));
}
@ -297,12 +297,12 @@
*/
public function getPointer(string $name): array
{
if(!isset($this->headers[PackageStructure::DIRECTORY][$name]))
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$name]))
{
throw new RuntimeException(sprintf('Resource \'%s\' not found in package \'%s\'', $name, $this->package_path));
}
$location = explode(':', $this->headers[PackageStructure::DIRECTORY][$name]);
$location = explode(':', $this->headers[PackageStructure::DIRECTORY->value][$name]);
return [(int)$location[0], (int)$location[1]];
}
@ -314,7 +314,7 @@
*/
public function exists(string $name): bool
{
return isset($this->headers[PackageStructure::DIRECTORY][$name]);
return isset($this->headers[PackageStructure::DIRECTORY->value][$name]);
}
/**
@ -339,14 +339,14 @@
*/
public function getAssembly(): Assembly
{
$directory = sprintf('@%s', PackageDirectory::ASSEMBLY);
$directory = sprintf('@%s', PackageDirectory::ASSEMBLY->value);
if(isset($this->cache[$directory]))
{
return $this->cache[$directory];
}
if(!isset($this->headers[PackageStructure::DIRECTORY][$directory]))
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$directory]))
{
throw new ConfigurationException(sprintf('Assembly object not found in package \'%s\'', $this->package_path));
}
@ -373,14 +373,14 @@
*/
public function getMetadata(): Metadata
{
$directory = sprintf('@%s', PackageDirectory::METADATA);
$directory = sprintf('@%s', PackageDirectory::METADATA->value);
if(isset($this->cache[$directory]))
{
return $this->cache[$directory];
}
if(!isset($this->headers[PackageStructure::DIRECTORY][$directory]))
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$directory]))
{
throw new ConfigurationException(sprintf('Metadata object not found in package \'%s\'', $this->package_path));
}
@ -411,14 +411,14 @@
*/
public function getInstaller(): ?Installer
{
$directory = sprintf('@%s', PackageDirectory::INSTALLER);
$directory = sprintf('@%s', PackageDirectory::INSTALLER->value);
if(isset($this->cache[$directory]))
{
return $this->cache[$directory];
}
if(!isset($this->headers[PackageStructure::DIRECTORY][$directory]))
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$directory]))
{
return null;
}
@ -444,9 +444,9 @@
public function getDependencies(): array
{
$dependencies = [];
$directory = sprintf('@%s:', PackageDirectory::DEPENDENCIES);
$directory = sprintf('@%s:', PackageDirectory::DEPENDENCIES->value);
foreach($this->headers[PackageStructure::DIRECTORY] as $name => $location)
foreach($this->headers[PackageStructure::DIRECTORY->value] as $name => $location)
{
if(str_starts_with($name, $directory))
{
@ -467,8 +467,8 @@
*/
public function getDependency(string $name): Dependency
{
$dependency_name = sprintf('@%s:%s', PackageDirectory::DEPENDENCIES, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$dependency_name]))
$dependency_name = sprintf('@%s:%s', PackageDirectory::DEPENDENCIES->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$dependency_name]))
{
throw new ConfigurationException(sprintf('Dependency \'%s\' not found in package \'%s\'', $name, $this->package_path));
}
@ -511,9 +511,9 @@
public function getExecutionUnits(): array
{
$execution_units = [];
$directory = sprintf('@%s:', PackageDirectory::EXECUTION_UNITS);
$directory = sprintf('@%s:', PackageDirectory::EXECUTION_UNITS->value);
foreach($this->headers[PackageStructure::DIRECTORY] as $name => $location)
foreach($this->headers[PackageStructure::DIRECTORY->value] as $name => $location)
{
if(str_starts_with($name, $directory))
{
@ -534,8 +534,8 @@
*/
public function getExecutionUnit(string $name): ExecutionUnit
{
$execution_unit_name = sprintf('@%s:%s', PackageDirectory::EXECUTION_UNITS, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$execution_unit_name]))
$execution_unit_name = sprintf('@%s:%s', PackageDirectory::EXECUTION_UNITS->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$execution_unit_name]))
{
throw new ConfigurationException(sprintf('Execution unit \'%s\' not found in package \'%s\'', $name, $this->package_path));
}
@ -578,9 +578,9 @@
public function getComponents(): array
{
$components = [];
$directory = sprintf('@%s:', PackageDirectory::COMPONENTS);
$directory = sprintf('@%s:', PackageDirectory::COMPONENTS->value);
foreach($this->headers[PackageStructure::DIRECTORY] as $name => $location)
foreach($this->headers[PackageStructure::DIRECTORY->value] as $name => $location)
{
if(str_starts_with($name, $directory))
{
@ -599,9 +599,9 @@
public function getClassMap(): array
{
$class_map = [];
$directory = sprintf('@%s:', PackageDirectory::CLASS_POINTER);
$directory = sprintf('@%s:', PackageDirectory::CLASS_POINTER->value);
foreach($this->headers[PackageStructure::DIRECTORY] as $name => $location)
foreach($this->headers[PackageStructure::DIRECTORY->value] as $name => $location)
{
if(str_starts_with($name, $directory))
{
@ -622,8 +622,8 @@
*/
public function getComponent(string $name): Component
{
$component_name = sprintf('@%s:%s', PackageDirectory::COMPONENTS, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$component_name]))
$component_name = sprintf('@%s:%s', PackageDirectory::COMPONENTS->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$component_name]))
{
throw new ConfigurationException(sprintf('Component \'%s\' not found in package \'%s\'', $name, $this->package_path));
}
@ -668,8 +668,8 @@
*/
public function getComponentByClass(string $class): Component
{
$class_name = sprintf('@%s:%s', PackageDirectory::CLASS_POINTER, $class);
if(!isset($this->headers[PackageStructure::DIRECTORY][$class_name]))
$class_name = sprintf('@%s:%s', PackageDirectory::CLASS_POINTER->value, $class);
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$class_name]))
{
throw new ConfigurationException(sprintf('Class map \'%s\' not found in package \'%s\'', $class, $this->package_path));
}
@ -692,9 +692,9 @@
public function getResources(): array
{
$resources = [];
$directory = sprintf('@%s:', PackageDirectory::RESOURCES);
$directory = sprintf('@%s:', PackageDirectory::RESOURCES->value);
foreach($this->headers[PackageStructure::DIRECTORY] as $name => $location)
foreach($this->headers[PackageStructure::DIRECTORY->value] as $name => $location)
{
if(str_starts_with($name, $directory))
{
@ -715,8 +715,8 @@
*/
public function getResource(string $name): Resource
{
$resource_name = sprintf('@%s:%s', PackageDirectory::RESOURCES, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$resource_name]))
$resource_name = sprintf('@%s:%s', PackageDirectory::RESOURCES->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY->value][$resource_name]))
{
throw new ConfigurationException(sprintf('Resource \'%s\' not found in package \'%s\'', $name, $this->package_path));
}
@ -759,7 +759,7 @@
*/
public function find(string $filename): string|false
{
foreach($this->headers[PackageStructure::DIRECTORY] as $name => $location)
foreach($this->headers[PackageStructure::DIRECTORY->value] as $name => $location)
{
if(str_ends_with($name, $filename))
{

View file

@ -25,6 +25,7 @@
namespace ncc\Classes;
use InvalidArgumentException;
use ncc\Enums\Flags\PackageFlags;
use ncc\Enums\PackageDirectory;
use ncc\Enums\PackageStructure;
@ -108,9 +109,9 @@
$this->temp_file = @fopen($this->temporary_path, 'wb'); // Create a temporary data file
$this->package_file = @fopen($file_path, 'wb');
$this->headers = [
PackageStructure::FILE_VERSION => PackageStructureVersions::_2_0,
PackageStructure::FLAGS => [],
PackageStructure::DIRECTORY => []
PackageStructure::FILE_VERSION->value => PackageStructureVersions::_2_0->value,
PackageStructure::FLAGS->value => [],
PackageStructure::DIRECTORY->value => []
];
if($this->temp_file === false || $this->package_file === false)
@ -126,7 +127,7 @@
*/
public function getFileVersion(): string
{
return (string)$this->headers[PackageStructure::FILE_VERSION];
return (string)$this->headers[PackageStructure::FILE_VERSION->value];
}
/**
@ -137,7 +138,7 @@
*/
public function setFileVersion(string $version): void
{
$this->headers[PackageStructure::FILE_VERSION] = $version;
$this->headers[PackageStructure::FILE_VERSION->value] = $version;
}
/**
@ -147,13 +148,13 @@
*/
public function getFlags(): array
{
return (array)$this->headers[PackageStructure::FLAGS];
return (array)$this->headers[PackageStructure::FLAGS->value];
}
/**
* Sets the package flags
*
* @param array $flags
* @param string[]|PackageFlags[] $flags
* @return void
* @throws IOException
*/
@ -164,26 +165,47 @@
throw new IOException('Cannot set flags after data has been written to the package');
}
$this->headers[PackageStructure::FLAGS] = $flags;
foreach($flags as $flag)
{
if(is_string($flag))
{
$flag = PackageFlags::tryFrom($flag);
if($flag === null)
{
throw new InvalidArgumentException(sprintf('Unexpected flag: %s', $flag));
}
}
$this->headers[PackageStructure::FLAGS->value] = $flag->value;
}
}
/**
* Adds a flag to the package
*
* @param string $flag
* @param PackageFlags|string $flag
* @return void
* @throws IOException
*/
public function addFlag(string $flag): void
public function addFlag(PackageFlags|string $flag): void
{
if(is_string($flag))
{
$flag = PackageFlags::tryFrom($flag);
if($flag === null)
{
throw new InvalidArgumentException(sprintf('Unexpected flag: %s', $flag));
}
}
if($this->data_written)
{
throw new IOException('Cannot add a flag after data has been written to the package');
}
if(!in_array($flag, $this->headers[PackageStructure::FLAGS], true))
if(!in_array($flag, $this->headers[PackageStructure::FLAGS->value], true))
{
$this->headers[PackageStructure::FLAGS][] = $flag;
$this->headers[PackageStructure::FLAGS->value][] = $flag->value;
}
}
@ -194,14 +216,23 @@
* @return void
* @throws IOException
*/
public function removeFlag(string $flag): void
public function removeFlag(PackageFlags|string $flag): void
{
if(is_string($flag))
{
$flag = PackageFlags::tryFrom($flag);
if($flag === null)
{
throw new InvalidArgumentException(sprintf('Unexpected flag: %s', $flag));
}
}
if($this->data_written)
{
throw new IOException('Cannot remove a flag after data has been written to the package');
}
$this->headers[PackageStructure::FLAGS] = array_diff($this->headers[PackageStructure::FLAGS], [$flag]);
$this->headers[PackageStructure::FLAGS->value] = array_diff($this->headers[PackageStructure::FLAGS->value], [$flag->value]);
}
/**
@ -213,22 +244,22 @@
*/
public function add(string $name, string $data): array
{
if(isset($this->headers[PackageStructure::DIRECTORY][$name]))
if(isset($this->headers[PackageStructure::DIRECTORY->value][$name]))
{
return explode(':', $this->headers[PackageStructure::DIRECTORY][$name]);
return explode(':', $this->headers[PackageStructure::DIRECTORY->value][$name]);
}
if(in_array(PackageFlags::COMPRESSION, $this->headers[PackageStructure::FLAGS], true))
if(in_array(PackageFlags::COMPRESSION->value, $this->headers[PackageStructure::FLAGS->value], true))
{
if(in_array(PackageFlags::LOW_COMPRESSION, $this->headers[PackageStructure::FLAGS], true))
if(in_array(PackageFlags::LOW_COMPRESSION->value, $this->headers[PackageStructure::FLAGS->value], true))
{
$data = gzcompress($data, 1);
}
else if(in_array(PackageFlags::MEDIUM_COMPRESSION, $this->headers[PackageStructure::FLAGS], true))
else if(in_array(PackageFlags::MEDIUM_COMPRESSION->value, $this->headers[PackageStructure::FLAGS->value], true))
{
$data = gzcompress($data, 6);
}
else if(in_array(PackageFlags::HIGH_COMPRESSION, $this->headers[PackageStructure::FLAGS], true))
else if(in_array(PackageFlags::HIGH_COMPRESSION->value, $this->headers[PackageStructure::FLAGS->value], true))
{
$data = gzcompress($data, 9);
}
@ -239,7 +270,7 @@
}
$pointer = sprintf("%d:%d", ftell($this->temp_file), strlen($data));
$this->headers[PackageStructure::DIRECTORY][$name] = $pointer;
$this->headers[PackageStructure::DIRECTORY->value][$name] = $pointer;
$this->data_written = true;
fwrite($this->temp_file, $data);
@ -256,12 +287,12 @@
*/
public function addPointer(string $name, int $offset, int $length): void
{
if(isset($this->headers[PackageStructure::DIRECTORY][$name]))
if(isset($this->headers[PackageStructure::DIRECTORY->value][$name]))
{
return;
}
$this->headers[PackageStructure::DIRECTORY][$name] = sprintf("%d:%d", $offset, $length);
$this->headers[PackageStructure::DIRECTORY->value][$name] = sprintf("%d:%d", $offset, $length);
}
/**
@ -272,7 +303,7 @@
*/
public function setAssembly(Assembly $assembly): array
{
return $this->add(sprintf('@%s', PackageDirectory::ASSEMBLY), ZiProto::encode($assembly->toArray(true)));
return $this->add(sprintf('@%s', PackageDirectory::ASSEMBLY->value), ZiProto::encode($assembly->toArray(true)));
}
/**
@ -283,7 +314,7 @@
*/
public function setMetadata(Metadata $metadata): array
{
return $this->add(sprintf('@%s', PackageDirectory::METADATA), ZiProto::encode($metadata->toArray(true)));
return $this->add(sprintf('@%s', PackageDirectory::METADATA->value), ZiProto::encode($metadata->toArray(true)));
}
/**
@ -294,7 +325,7 @@
*/
public function setInstaller(Installer $installer): array
{
return $this->add(sprintf('@%s', PackageDirectory::INSTALLER), ZiProto::encode($installer->toArray(true)));
return $this->add(sprintf('@%s', PackageDirectory::INSTALLER->value), ZiProto::encode($installer->toArray(true)));
}
/**
@ -305,7 +336,7 @@
*/
public function addDependencyConfiguration(Dependency $dependency): array
{
return $this->add(sprintf('@%s:%s', PackageDirectory::DEPENDENCIES, $dependency->getName()), ZiProto::encode($dependency->toArray(true)));
return $this->add(sprintf('@%s:%s', PackageDirectory::DEPENDENCIES->value, $dependency->getName()), ZiProto::encode($dependency->toArray(true)));
}
/**
@ -316,7 +347,7 @@
*/
public function addExecutionUnit(ExecutionUnit $unit): array
{
return $this->add(sprintf('@%s:%s', PackageDirectory::EXECUTION_UNITS, $unit->getExecutionPolicy()->getName()), ZiProto::encode($unit->toArray(true)));
return $this->add(sprintf('@%s:%s', PackageDirectory::EXECUTION_UNITS->value, $unit->getExecutionPolicy()->getName()), ZiProto::encode($unit->toArray(true)));
}
/**
@ -327,7 +358,7 @@
*/
public function addComponent(Component $component): array
{
return $this->add(sprintf('@%s:%s', PackageDirectory::COMPONENTS, $component->getName()), ZiProto::encode($component->toArray(true)));
return $this->add(sprintf('@%s:%s', PackageDirectory::COMPONENTS->value, $component->getName()), ZiProto::encode($component->toArray(true)));
}
/**
@ -338,7 +369,7 @@
*/
public function addResource(Resource $resource): array
{
return $this->add(sprintf('@%s:%s', PackageDirectory::RESOURCES, $resource->getName()), ZiProto::encode($resource->toArray(true)));
return $this->add(sprintf('@%s:%s', PackageDirectory::RESOURCES->value, $resource->getName()), ZiProto::encode($resource->toArray(true)));
}
/**
@ -351,7 +382,7 @@
*/
public function mapClass(string $class, int $offset, int $length): void
{
$this->addPointer(sprintf('@%s:%s', PackageDirectory::CLASS_POINTER, $class), $offset, $length);
$this->addPointer(sprintf('@%s:%s', PackageDirectory::CLASS_POINTER->value, $class), $offset, $length);
}
/**
@ -372,10 +403,10 @@
switch((int)substr(explode(':', $name, 2)[0], 1))
{
case PackageDirectory::METADATA:
case PackageDirectory::ASSEMBLY:
case PackageDirectory::INSTALLER:
case PackageDirectory::EXECUTION_UNITS:
case PackageDirectory::METADATA->value:
case PackageDirectory::ASSEMBLY->value:
case PackageDirectory::INSTALLER->value:
case PackageDirectory::EXECUTION_UNITS->value:
Console::outDebug(sprintf('Skipping %s', $name));
break;

View file

@ -35,8 +35,8 @@
use ncc\Interfaces\RepositoryInterface;
use ncc\Objects\RepositoryConfiguration;
use ncc\Objects\RepositoryResult;
use ncc\ThirdParty\composer\Semver\Comparator;
use ncc\ThirdParty\composer\Semver\Semver;
use ncc\ThirdParty\composer\semver\Comparator;
use ncc\ThirdParty\composer\semver\Semver;
use ncc\Utilities\Console;
use ncc\Utilities\Resolver;
use ncc\Utilities\RuntimeCache;
@ -47,9 +47,9 @@
/**
* @inheritDoc
*/
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version = Versions::LATEST, ?AuthenticationType $authentication = null, array $options=[]): RepositoryResult
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version = Versions::LATEST->value, ?AuthenticationType $authentication = null, array $options=[]): RepositoryResult
{
if($version === Versions::LATEST)
if($version === Versions::LATEST->value)
{
$version = self::getLatestVersion($repository, $vendor, $project);
}
@ -80,7 +80,7 @@
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -99,14 +99,14 @@
throw new NetworkException(sprintf('Invalid response from %s/%s, version %s does not have a dist URL', $vendor, $project, $version));
}
return new RepositoryResult($response['package']['versions'][$version]['dist']['url'], RepositoryResultType::SOURCE, $version);
return new RepositoryResult($response['package']['versions'][$version]['dist']['url'], RepositoryResultType::SOURCE->value, $version);
}
/**
* @inheritDoc
* @throws NotSupportedException
*/
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version = Versions::LATEST, ?AuthenticationType $authentication = null, array $options=[]): RepositoryResult
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version = Versions::LATEST->value, ?AuthenticationType $authentication = null, array $options=[]): RepositoryResult
{
throw new NotSupportedException('Fetching ncc packages from Packagist is not supported');
}
@ -147,7 +147,7 @@
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers
]);
@ -178,23 +178,21 @@
{
$versions = self::getVersions($repository, $vendor, $project);
/** @noinspection KeysFragmentationWithArrayFunctionsInspection */
// Filter out pre-release versions such as alpha, beta, rc, dev
$versions = array_filter($versions, static function($version)
{
return !preg_match('/-alpha|-beta|-rc|dev/i', $version);
});
usort($versions, static function($a, $b)
{
return Comparator::lessThanOrEqualTo($a, $b) ? 1 : -1;
});
// Sort versions in descending order using Semver::rsort
$versions = Semver::rsort($versions);
if($versions[0] === null)
if (!isset($versions[0]))
{
throw new NetworkException(sprintf('Failed to resolve latest version for %s/%s', $vendor, $project));
}
return $versions[0];
return $versions[0]; // The first version in the sorted array is the latest
}
/**

View file

@ -31,27 +31,6 @@
class AstWalker
{
/**
* Returns an array representation of the node recursively
*
* @param array|Node $node
* @return array
*/
public static function serialize(array|Node $node): array
{
if(is_array($node))
{
$serialized = [];
foreach($node as $sub_node)
{
$serialized[] = $sub_node->jsonSerialize();
}
return $serialized;
}
return $node->jsonSerialize();
}
/**
* Returns an array of classes associated with the node recursively
*
@ -112,161 +91,4 @@
return $classes;
}
/**
* Reconstructs nodes from an array representation recursively
*
* @param $value
* @return array|Comment|Node
* @noinspection PhpMissingReturnTypeInspection
* @throws ReflectionException
*/
public static function decodeRecursive($value)
{
if (is_array($value))
{
if (isset($value['nodeType']))
{
if ($value['nodeType'] === 'Comment' || $value['nodeType'] === 'Comment_Doc')
{
return self::decodeComment($value);
}
return self::decodeNode($value);
}
return self::decodeArray($value);
}
return $value;
}
/**
* Decodes an array by recursively decoding each value
*
* @param array $array
* @return array
* @throws ReflectionException
*/
private static function decodeArray(array $array) : array
{
$decoded_array = [];
foreach ($array as $key => $value)
{
$decoded_array[$key] = self::decodeRecursive($value);
}
return $decoded_array;
}
/**
* Returns the node from the node type
*
* @param array $value
* @return Node
* @throws ReflectionException
*/
private static function decodeNode(array $value) : Node
{
$node_type = $value['nodeType'];
if (!is_string($node_type))
{
throw new RuntimeException('Node type must be a string');
}
/** @var Node $node */
$node = self::reflectionClassFromNodeType($node_type)->newInstanceWithoutConstructor();
if (isset($value['attributes'])) {
if (!is_array($value['attributes']))
{
throw new RuntimeException('Attributes must be an array');
}
$node->setAttributes(self::decodeArray($value['attributes']));
}
foreach ($value as $name => $sub_node) {
if ($name === 'nodeType' || $name === 'attributes')
{
continue;
}
$node->$name = self::decodeRecursive($sub_node);
}
return $node;
}
/**
* Returns the comment from the node type
*
* @param array $value
* @return Comment
*/
private static function decodeComment(array $value): Comment
{
$class_name = $value['nodeType'] === 'Comment' ? Comment::class : Comment\Doc::class;
if (!isset($value['text']))
{
throw new RuntimeException('Comment must have text');
}
return new $class_name(
$value['text'],
$value['line'] ?? -1, $value['filePos'] ?? -1, $value['tokenPos'] ?? -1,
$value['endLine'] ?? -1, $value['endFilePos'] ?? -1, $value['endTokenPos'] ?? -1
);
}
/**
* Returns the reflection class from the node type
*
* @param string $node_type
* @return ReflectionClass
* @throws ReflectionException
*/
private static function reflectionClassFromNodeType(string $node_type): ReflectionClass
{
return new ReflectionClass(self::classNameFromNodeType($node_type));
}
/**
* Returns the class name from the node type
*
* @param string $nodeType
* @return string
*/
private static function classNameFromNodeType(string $nodeType): string
{
$class_name = 'ncc\\ThirdParty\\nikic\\PhpParser\\Node\\' . str_replace('_', '\\', $nodeType);
if (class_exists($class_name))
{
return $class_name;
}
$class_name .= '_';
if (class_exists($class_name))
{
return $class_name;
}
throw new RuntimeException("Unknown node type \"$nodeType\"");
}
/**
* Transforms include, include_once, require and require_once statements into function calls.
*
* @param Node|array $stmts The AST node or array of nodes to transform.
* @param string|null $package Optionally. The package name to pass to the transformed function calls.
* @return Node|array The transformed AST node or array of nodes.
*/
public static function transformRequireCalls(Node|array $stmts, ?string $package=null): Node|array
{
$traverser = new NodeTraverser();
$traverser->addVisitor(new ExpressionTraverser($package));
return $traverser->traverse($stmts);
}
}

View file

@ -41,7 +41,7 @@
* @inheritDoc
* @throws BuildException
*/
public function build(string $build_configuration = BuildConfigurationValues::DEFAULT, array $options=[]): string
public function build(string $build_configuration = BuildConfigurationValues::DEFAULT->value, array $options=[]): string
{
$configuration = $this->getProjectManager()->getProjectConfiguration()->getBuild()->getBuildConfiguration($build_configuration);
@ -50,14 +50,14 @@
$configuration->setOptions(array_merge($configuration->getOptions(), $options));
}
if(!isset($configuration->getOptions()[BuildConfigurationOptions::NCC_CONFIGURATION]))
if(!isset($configuration->getOptions()[BuildConfigurationOptions::NCC_CONFIGURATION->value]))
{
throw new BuildException(sprintf("Unable to compile the binary, the build configuration '%s' does not have a ncc_configuration.", $build_configuration));
}
// Build the ncc package first
Console::outVerbose('Building ncc package.');
$ncc_package = parent::build($configuration->getOptions()[BuildConfigurationOptions::NCC_CONFIGURATION]);
$ncc_package = parent::build($configuration->getOptions()[BuildConfigurationOptions::NCC_CONFIGURATION->value]);
// Prepare the ncc package for compilation
$hex_dump_file = PathFinder::getCachePath() . DIRECTORY_SEPARATOR . $this->getProjectManager()->getProjectConfiguration()->getAssembly()->getName() . '.c';
@ -72,11 +72,11 @@
// Prepare the gcc command
$gcc_path = (new ExecutableFinder())->find('gcc');
if(isset($configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE]))
if(isset($configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE->value]))
{
$binary_path = ConstantCompiler::compileConstants(
$this->getProjectManager()->getProjectConfiguration(),
$configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE]
$configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE->value]
);
}
else

View file

@ -30,7 +30,9 @@
use ncc\Exceptions\PathNotFoundException;
use ncc\Extensions\ZiProto\ZiProto;
use ncc\Objects\Package\Component;
use ncc\ThirdParty\nikic\PhpParser\NodeDumper;
use ncc\ThirdParty\nikic\PhpParser\ParserFactory;
use ncc\ThirdParty\nikic\PhpParser\PhpVersion;
use ncc\Utilities\Base64;
use ncc\Utilities\Console;
use ncc\Utilities\Functions;
@ -52,13 +54,9 @@
try
{
$stmts = (new ParserFactory())->create(ParserFactory::PREFER_PHP7)->parse(IO::fread($file_path));
$stmts = AstWalker::transformRequireCalls(
$stmts, $this->getProjectManager()->getProjectConfiguration()->getAssembly()->getPackage()
);
$component = new Component($component_name, ZiProto::encode($stmts), ComponentDataType::AST);
$component->addFlag(ComponentFlags::PHP_AST);
$stmts = ((new ParserFactory())->createForNewestSupportedVersion())->parse(IO::fread($file_path));
$component = new Component($component_name, ZiProto::encode(Serializer::nodesToArray($stmts)), ComponentDataType::AST);
$component->addFlag(ComponentFlags::PHP_AST->value);
$pointer = $package_writer->addComponent($component);
foreach(AstWalker::extractClasses($stmts) as $class)
@ -74,7 +72,7 @@
}
$component = new Component($component_name, Base64::encode(IO::fread($file_path)), ComponentDataType::BASE64_ENCODED);
$component->addFlag(ComponentFlags::PHP_B64);
$component->addFlag(ComponentFlags::PHP_B64->value);
$package_writer->addComponent($component);
}
}

View file

@ -44,7 +44,7 @@
*/
public static function executeUnit(ExecutionUnit $unit, array $args=[], bool $local=true): int
{
if($unit->getExecutionPolicy()->getRunner() !== Runners::PHP)
if($unit->getExecutionPolicy()->getRunner() !== Runners::PHP->value)
{
throw new InvalidArgumentException(sprintf('The execution unit %s is not a php execution unit', $unit->getExecutionPolicy()->getName()));
}

View file

@ -0,0 +1,151 @@
<?php
/*
* Copyright (c) Nosial 2022-2024, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Classes\PhpExtension;
use ncc\ThirdParty\nikic\PhpParser\Comment;
use ncc\ThirdParty\nikic\PhpParser\Node;
use ncc\ThirdParty\nikic\PhpParser\NodeAbstract;
use ReflectionClass;
use RuntimeException;
use function is_array;
use function is_string;
class Serializer
{
/** @var ReflectionClass<Node>[] Node type to reflection class map */
private static array $reflectionClassCache;
/**
* @param NodeAbstract[] $nodeAbstracts
* @return array
*/
public static function nodesToArray(array $nodeAbstracts): array
{
$serialized = [];
foreach ($nodeAbstracts as $nodeAbstract)
{
$serialized[] = $nodeAbstract->jsonSerialize();
}
return $serialized;
}
/**
* @param array $nodeAbstracts
* @return NodeAbstract[]
*/
public static function arrayToNodes(array $nodeAbstracts): array
{
return self::decodeRecursive($nodeAbstracts);
}
/**
* @param mixed $value
* @return mixed
*/
private static function decodeRecursive($value) {
if (is_array($value)) {
if (isset($value['nodeType'])) {
if ($value['nodeType'] === 'Comment' || $value['nodeType'] === 'Comment_Doc') {
return self::decodeComment($value);
}
return self::decodeNode($value);
}
return self::decodeArray($value);
}
return $value;
}
private static function decodeArray(array $array): array {
$decodedArray = [];
foreach ($array as $key => $value) {
$decodedArray[$key] = self::decodeRecursive($value);
}
return $decodedArray;
}
private static function decodeNode(array $value): Node {
$nodeType = $value['nodeType'];
if (!is_string($nodeType)) {
throw new RuntimeException('Node type must be a string');
}
$reflectionClass = self::reflectionClassFromNodeType($nodeType);
$node = $reflectionClass->newInstanceWithoutConstructor();
if (isset($value['attributes'])) {
if (!is_array($value['attributes'])) {
throw new RuntimeException('Attributes must be an array');
}
$node->setAttributes(self::decodeArray($value['attributes']));
}
foreach ($value as $name => $subNode) {
if ($name === 'nodeType' || $name === 'attributes') {
continue;
}
$node->$name = self::decodeRecursive($subNode);
}
return $node;
}
private static function decodeComment(array $value): Comment {
$className = $value['nodeType'] === 'Comment' ? Comment::class : Comment\Doc::class;
if (!isset($value['text'])) {
throw new RuntimeException('Comment must have text');
}
return new $className(
$value['text'],
$value['line'] ?? -1, $value['filePos'] ?? -1, $value['tokenPos'] ?? -1,
$value['endLine'] ?? -1, $value['endFilePos'] ?? -1, $value['endTokenPos'] ?? -1
);
}
private static function reflectionClassFromNodeType(string $nodeType): ReflectionClass {
if (!isset(self::$reflectionClassCache[$nodeType])) {
$className = self::classNameFromNodeType($nodeType);
self::$reflectionClassCache[$nodeType] = new ReflectionClass($className);
}
return self::$reflectionClassCache[$nodeType];
}
/** @return class-string<Node> */
private static function classNameFromNodeType(string $nodeType): string {
$className = '\\ncc\\ThirdParty\\nikic\\PhpParser\\Node\\' . strtr($nodeType, '_', '\\');
if (class_exists($className)) {
return $className;
}
$className .= '_';
if (class_exists($className)) {
return $className;
}
throw new RuntimeException("Unknown node type \"$nodeType\"");
}
}

View file

@ -49,27 +49,27 @@
public static function applyTemplate(ProjectManager $project_manager): void
{
$project_manager->getProjectConfiguration()->addExecutionPolicy(
new ExecutionPolicy('main_policy', Runners::PHP, new ExecutionPolicy\Execute('main'))
new ExecutionPolicy('main_policy', Runners::PHP->value, new ExecutionPolicy\Execute('main'))
);
$project_manager->getProjectConfiguration()->getBuild()->setMain('main_policy');
$project_manager->getProjectConfiguration()->getProject()->addOption(ProjectOptions::CREATE_SYMLINK, true);
$project_manager->getProjectConfiguration()->getProject()->addOption(ProjectOptions::CREATE_SYMLINK->value, true);
// Create the release build configuration
$release_executable = new BuildConfiguration('release_executable',
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME->value
);
$release_executable->setBuildType(BuildOutputType::EXECUTABLE);
$release_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION, 'release');
$release_executable->setBuildType(BuildOutputType::EXECUTABLE->value);
$release_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION->value, 'release');
$project_manager->getProjectConfiguration()->getBuild()->addBuildConfiguration($release_executable);
// Create the debug build configuration
$debug_executable = new BuildConfiguration('debug_executable',
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME->value
);
$debug_executable->setDefinedConstant('DEBUG', '1');
$debug_executable->setBuildType(BuildOutputType::EXECUTABLE);
$debug_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION, 'debug');
$debug_executable->setBuildType(BuildOutputType::EXECUTABLE->value);
$debug_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION->value, 'debug');
$project_manager->getProjectConfiguration()->getBuild()->addBuildConfiguration($debug_executable);
self::writeProgramTemplate($project_manager);

View file

@ -44,9 +44,11 @@
use ncc\Utilities\Console;
use ncc\Utilities\IO;
use ncc\Utilities\Resolver;
use ncc\Utilities\RuntimeCache;
use ncc\Utilities\Validate;
use RuntimeException;
use Throwable;
use function trigger_error;
class Runtime
{
@ -82,7 +84,7 @@
* @throws PathNotFoundException
* @throws OperationException
*/
public static function execute(string $package): int
public static function execute(string $package, array $arguments=[]): int
{
if(!self::isImported($package))
{
@ -99,7 +101,7 @@
if(is_string(self::$imported_packages[$package]))
{
$metadata_path = self::$imported_packages[$package] . DIRECTORY_SEPARATOR . FileDescriptor::METADATA;
$metadata_path = self::$imported_packages[$package] . DIRECTORY_SEPARATOR . FileDescriptor::METADATA->value;
if(!is_file($metadata_path))
{
@ -108,7 +110,8 @@
return ExecutionUnitRunner::executeFromSystem(
self::$imported_packages[$package],
Metadata::fromArray(ZiProto::decode(IO::fread($metadata_path)))->getMainExecutionPolicy()
Metadata::fromArray(ZiProto::decode(IO::fread($metadata_path)))->getMainExecutionPolicy(),
$arguments
);
}
@ -121,7 +124,7 @@
* @return string
* @throws ImportException
*/
public static function import(string $package, string $version=Versions::LATEST): string
public static function import(string $package, string $version=Versions::LATEST->value): string
{
if(self::isImported($package))
{
@ -160,7 +163,7 @@
}
}
throw new RuntimeException('Importing from a package name is not supported yet');
throw new RuntimeException(sprintf('Failed to import package "%s" because it does not exist', $package));
}
/**
@ -173,7 +176,7 @@
* @throws NotSupportedException
* @throws PathNotFoundException
*/
private static function importFromSystem(string $package, string $version=Versions::LATEST): string
private static function importFromSystem(string $package, string $version=Versions::LATEST->value): string
{
if(!self::getPackageManager()->getPackageLock()->entryExists($package))
{
@ -189,27 +192,81 @@
self::$class_map[strtolower($class)] = $component_path;
}
if($entry->getMetadata($version)->getOption(BuildConfigurationOptions::REQUIRE_FILES) !== null)
if($entry->getMetadata($version)->getOption(BuildConfigurationOptions::REQUIRE_FILES->value) !== null)
{
foreach($entry->getMetadata($version)->getOption(BuildConfigurationOptions::REQUIRE_FILES) as $item)
foreach($entry->getMetadata($version)->getOption(BuildConfigurationOptions::REQUIRE_FILES->value) as $item)
{
$required_file = $entry->getPath($version) . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . $item;
try
{
// Get the file contents and prepare it
$required_file = IO::fread($entry->getPath($version) . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . $item);
$required_file = preg_replace('/^<\?php|<\?PHP/', '', $required_file, 1);
if(!file_exists($required_file))
{
throw new PathNotFoundException($required_file);
}
eval($required_file);
unset($required_file);
// Get the file contents and prepare it
$evaluated_code = IO::fread($required_file);
// Remove the PHP tags
$evaluated_code = preg_replace('/^<\?php|<\?PHP/', '', $evaluated_code, 1);
// Replace __DIR__ with the actual directory that the file is in
$evaluated_code = str_replace('__DIR__', sprintf('"%s"', dirname($required_file)), $evaluated_code);
set_error_handler(function ($error_number, $message, $file, $line) use ($item, $package)
{
throw new ImportException(sprintf('Fatal Evaluation Error: Failed to import "%s" from %s on %s:%s: %s', $item, $package, $file, $line, $message));
});
// Evaluate the code
eval($evaluated_code);
restore_error_handler();
unset($evaluated_code);
}
catch(ConfigurationException $e)
catch (ConfigurationException $e)
{
throw new ImportException(sprintf('Failed to import "%s" from %s: %s', $item, $package, $e->getMessage()), $e);
throw new ImportException(sprintf('%s: Failed to import "%s" from %s: %s', $required_file, $item, $package, $e->getMessage()), $e);
}
catch(ImportException $e)
{
throw $e;
}
catch (Throwable $e)
{
throw new ImportException(sprintf('%s: Failed to import "%s" from %s: %s', $required_file, $item, $package, $e->getMessage()), $e);
}
}
}
if(isset($entry->getMetadata($version)->getOptions()[PackageFlags::STATIC_DEPENDENCIES]))
$safe_package_name = strtoupper($entry->getAssembly($version)->getName());
foreach($entry->getMetadata($version)->getConstants() as $constant => $value)
{
$constant_full_name = sprintf("%s_%s", $safe_package_name, $constant);
// Skip if already defined.
if(defined($constant_full_name))
{
if(RuntimeCache::get(sprintf("defined_%s", $constant_full_name)))
{
continue;
}
trigger_error(sprintf('Cannot define constant %s from package %s because the constant is already defined', $constant_full_name, $package), E_USER_WARNING);
continue;
}
if(!Validate::constantName($constant_full_name))
{
// trigger warning only
trigger_error(sprintf('Cannot define constant %s from package %s because the constant name is invalid', $constant_full_name, $package), E_USER_WARNING);
continue;
}
RuntimeCache::set(sprintf("defined_%s", $constant_full_name), true);
define($constant_full_name, $value);
}
if(isset($entry->getMetadata($version)->getOptions()[PackageFlags::STATIC_DEPENDENCIES->value]))
{
// Fake import the dependencies
foreach($entry->getVersion($version)->getDependencies() as $dependency)
@ -273,9 +330,9 @@
}
// Import the required files
if($package_reader->getMetadata()->getOption(BuildConfigurationOptions::REQUIRE_FILES) !== null)
if($package_reader->getMetadata()->getOption(BuildConfigurationOptions::REQUIRE_FILES->value) !== null)
{
foreach($package_reader->getMetadata()->getOption(BuildConfigurationOptions::REQUIRE_FILES) as $item)
foreach($package_reader->getMetadata()->getOption(BuildConfigurationOptions::REQUIRE_FILES->value) as $item)
{
try
{
@ -288,7 +345,7 @@
}
}
if($package_reader->getFlag(PackageFlags::STATIC_DEPENDENCIES))
if($package_reader->getFlag(PackageFlags::STATIC_DEPENDENCIES->value))
{
// Fake import the dependencies
foreach($package_reader->getDependencies() as $dependency_name)
@ -480,8 +537,8 @@
return match (Resolver::componentType($acquired_file))
{
PackageDirectory::RESOURCES => self::$imported_packages[$package]->getResource(Resolver::componentName($acquired_file))->getData(),
PackageDirectory::COMPONENTS => self::$imported_packages[$package]->getComponent(Resolver::componentName($acquired_file))->getData([ComponentDecodeOptions::AS_FILE]),
PackageDirectory::RESOURCES->value => self::$imported_packages[$package]->getResource(Resolver::componentName($acquired_file))->getData(),
PackageDirectory::COMPONENTS->value => self::$imported_packages[$package]->getComponent(Resolver::componentName($acquired_file))->getData([ComponentDecodeOptions::AS_FILE->value]),
default => throw new IOException(sprintf('Unable to acquire file "%s" from package "%s" because it is not a resource or component', $path, $package)),
};
}

View file

@ -1,33 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums;
final class CompilerExtensionDefaultVersions
{
// ----------------------------------------------------------------
// [0] = MinimumVersion
// [1] = MaximumVersion
// ----------------------------------------------------------------
public const PHP = ['8.0', '8.2'];
}

View file

@ -24,5 +24,6 @@
final class CompilerExtensionSupportedVersions
{
// TODO: Cannot convert this to enum, try another way
public const PHP = ['8.0', '8.1', '8.2'];
}

View file

@ -22,11 +22,7 @@
namespace ncc\Enums;
final class CompilerExtensions
enum CompilerExtensions : string
{
public const PHP = 'php';
public const ALL = [
CompilerExtensions::PHP
];
case PHP = 'php';
}

View file

@ -1,33 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums;
final class ComponentFileExtensions
{
/**
* The file extensions that the PHP compiler extension will accept as components.
*
* @var array
*/
public const PHP = ['*.php', '*.php3', '*.php4', '*.php5', '*.phtml'];
}

View file

@ -22,39 +22,39 @@
namespace ncc\Enums;
final class ConsoleColors
enum ConsoleColors : string
{
public const DEFAULT = "\e[39m";
case DEFAULT = "\e[39m";
public const BLACK = "\e[30m";
case BLACK = "\e[30m";
public const RED = "\e[31m";
case RED = "\e[31m";
public const GREEN = "\e[32m";
case GREEN = "\e[32m";
public const YELLOW = "\e[33m";
case YELLOW = "\e[33m";
public const BLUE = "\e[34m";
case BLUE = "\e[34m";
public const MAGENTA = "\e[35m";
case MAGENTA = "\e[35m";
public const CYAN = "\e[36m";
case CYAN = "\e[36m";
public const LIGHT_GREY = "\e[37m";
case LIGHT_GREY = "\e[37m";
public const DARK_GREY = "\e[90m";
case DARK_GREY = "\e[90m";
public const LIGHT_RED = "\e[91m";
case LIGHT_RED = "\e[91m";
public const LIGHT_GREEN = "\e[92m";
case LIGHT_GREEN = "\e[92m";
public const LIGHT_YELLOW = "\e[93m";
case LIGHT_YELLOW = "\e[93m";
public const LIGHT_BLUE = "\e[94m";
case LIGHT_BLUE = "\e[94m";
public const LIGHT_MAGENTA = "\e[95m";
case LIGHT_MAGENTA = "\e[95m";
public const LIGHT_CYAN = "\e[96m";
case LIGHT_CYAN = "\e[96m";
public const WHITE = "\e[97m";
case WHITE = "\e[97m";
}

View file

@ -1,36 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums;
final class ConstantReferences
{
public const ASSEMBLY = 'assembly';
public const BUILD = 'build';
public const DATE_TIME = 'date_time';
public const INSTALL = 'install';
public const RUNTIME = 'runtime';
}

View file

@ -26,98 +26,80 @@
* @author Zi Xing Narrakas
* @copyright Copyright (C) 2022-2023. Nosial - All Rights Reserved.
*/
final class ExceptionCodes
enum ExceptionCodes : int
{
/**
* @see RuntimeException
*/
public const RUNTIME = -1706;
case RUNTIME = -1706;
/**
* @see BuildException
*/
public const BUILD_EXCEPTION = -1727;
case BUILD_EXCEPTION = -1727;
/**
* @see IOException
*/
public const IO_EXCEPTION = -1735;
case IO_EXCEPTION = -1735;
/**
* @see ComposerException
*/
public const COMPOSER_EXCEPTION = -1749;
case COMPOSER_EXCEPTION = -1749;
/**
* @see AuthenticationException
*/
public const AUTHENTICATION_EXCEPTION = -1760;
case AUTHENTICATION_EXCEPTION = -1760;
/**
* @see NotSupportedException
*/
public const NOT_SUPPORTED_EXCEPTION = -1761;
case NOT_SUPPORTED_EXCEPTION = -1761;
/**
* @see ArchiveException
*/
public const ARCHIVE_EXCEPTION = -1764;
case ARCHIVE_EXCEPTION = -1764;
/**
* @see PathNotFoundException
*/
public const PATH_NOT_FOUND = -1769;
case PATH_NOT_FOUND = -1769;
/**
* @see GitException
*/
public const GIT_EXCEPTION = -1770;
case GIT_EXCEPTION = -1770;
/**
* @see ConfigurationException
*/
public const CONFIGURATION_EXCEPTION = -1772;
case CONFIGURATION_EXCEPTION = -1772;
/**
* @see PackageException
*/
public const PACKAGE_EXCEPTION = -1773;
case PACKAGE_EXCEPTION = -1773;
/**
* @see NetworkException
*/
public const NETWORK_EXCEPTION = -1774;
case NETWORK_EXCEPTION = -1774;
/**
* @see IntegrityException
*/
public const INTEGRITY_EXCEPTION = -1775;
case INTEGRITY_EXCEPTION = -1775;
/**
* @see OperationException
*/
public const OPERATION_EXCEPTION = -1776;
public const IMPORT_EXCEPTION = -1777;
case OPERATION_EXCEPTION = -1776;
/**
* All the exception codes from NCC
* @see ImportException
*/
public const All = [
self::RUNTIME,
self::BUILD_EXCEPTION,
self::IO_EXCEPTION,
self::COMPOSER_EXCEPTION,
self::AUTHENTICATION_EXCEPTION,
self::NOT_SUPPORTED_EXCEPTION,
self::ARCHIVE_EXCEPTION,
self::PATH_NOT_FOUND,
self::GIT_EXCEPTION,
self::CONFIGURATION_EXCEPTION,
self::PACKAGE_EXCEPTION,
self::NETWORK_EXCEPTION,
self::INTEGRITY_EXCEPTION,
self::OPERATION_EXCEPTION,
self::IMPORT_EXCEPTION
];
case IMPORT_EXCEPTION = -1777;
}

View file

@ -22,17 +22,17 @@
namespace ncc\Enums;
final class FileDescriptor
enum FileDescriptor : string
{
public const ASSEMBLY = 'ASSEMBLY';
case ASSEMBLY = 'ASSEMBLY';
public const METADATA = 'METADATA';
case METADATA = 'METADATA';
public const INSTALLER = 'INSTALLER';
case INSTALLER = 'INSTALLER';
public const CLASS_MAP = 'CLASS_MAP';
case CLASS_MAP = 'CLASS_MAP';
public const UPDATE = 'UPDATE';
case UPDATE = 'UPDATE';
public const SHADOW_PACKAGE = 'SHADOW_PKG';
case SHADOW_PACKAGE = 'SHADOW_PKG';
}

View file

@ -22,23 +22,15 @@
namespace ncc\Enums\Flags;
final class ComponentFlags
enum ComponentFlags : string
{
/**
* Indicates that the component is the AST of a PHP file encoded with msgpack.
*/
public const PHP_AST = 'php_ast';
case PHP_AST = 'php_ast';
/**
* Indicates that the component is a PHP file encoded with base64.
*/
public const PHP_B64 = 'php_b64';
/**
* All the possible flags of a component
*/
public const ALL = [
self::PHP_AST,
self::PHP_B64
];
case PHP_B64 = 'php_b64';
}

View file

@ -22,16 +22,16 @@
namespace ncc\Enums\Flags;
final class NccBuildFlags
enum NccBuildFlags : string
{
/**
* Indicates if the build is currently unstable and some features may not work correctly
* and can cause errors
*/
public const UNSTABLE = 'unstable';
case UNSTABLE = 'unstable';
/**
* Indicates if the build is currently in beta testing phase
*/
public const BETA = 'beta';
case BETA = 'beta';
}

View file

@ -22,15 +22,15 @@
namespace ncc\Enums\Flags;
final class PackageFlags
enum PackageFlags : string
{
public const COMPRESSION = 'gzip';
case COMPRESSION = 'gzip';
public const LOW_COMPRESSION = 'low_gz`';
case LOW_COMPRESSION = 'low_gz`';
public const MEDIUM_COMPRESSION = 'medium_gz';
case MEDIUM_COMPRESSION = 'medium_gz';
public const HIGH_COMPRESSION = 'high_gz';
case HIGH_COMPRESSION = 'high_gz';
public const STATIC_DEPENDENCIES = 'static_dependencies';
case STATIC_DEPENDENCIES = 'static_dependencies';
}

View file

@ -1,124 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums;
final class HttpStatusCodes
{
public const OK = 200;
public const CREATED = 201;
public const ACCEPTED = 202;
public const NO_CONTENT = 204;
public const MOVED_PERMANENTLY = 301;
public const FOUND = 302;
public const SEE_OTHER = 303;
public const NOT_MODIFIED = 304;
public const TEMPORARY_REDIRECT = 307;
public const PERMANENT_REDIRECT = 308;
public const BAD_REQUEST = 400;
public const UNAUTHORIZED = 401;
public const FORBIDDEN = 403;
public const NOT_FOUND = 404;
public const METHOD_NOT_ALLOWED = 405;
public const NOT_ACCEPTABLE = 406;
public const REQUEST_TIMEOUT = 408;
public const CONFLICT = 409;
public const GONE = 410;
public const LENGTH_REQUIRED = 411;
public const PRECONDITION_FAILED = 412;
public const PAYLOAD_TOO_LARGE = 413;
public const URI_TOO_LONG = 414;
public const UNSUPPORTED_MEDIA_TYPE = 415;
public const RANGE_NOT_SATISFIABLE = 416;
public const EXPECTATION_FAILED = 417;
public const IM_A_TEAPOT = 418;
public const MISDIRECTED_REQUEST = 421;
public const UNPROCESSABLE_ENTITY = 422;
public const LOCKED = 423;
public const FAILED_DEPENDENCY = 424;
public const UPGRADE_REQUIRED = 426;
public const PRECONDITION_REQUIRED = 428;
public const TOO_MANY_REQUESTS = 429;
public const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
public const UNAVAILABLE_FOR_LEGAL_REASONS = 451;
public const INTERNAL_SERVER_ERROR = 500;
public const NOT_IMPLEMENTED = 501;
public const BAD_GATEWAY = 502;
public const SERVICE_UNAVAILABLE = 503;
public const GATEWAY_TIMEOUT = 504;
public const HTTP_VERSION_NOT_SUPPORTED = 505;
public const VARIANT_ALSO_NEGOTIATES = 506;
public const INSUFFICIENT_STORAGE = 507;
public const LOOP_DETECTED = 508;
public const NOT_EXTENDED = 510;
public const NETWORK_AUTHENTICATION_REQUIRED = 511;
public const ALL = [
self::OK,
self::CREATED,
self::ACCEPTED,
self::NO_CONTENT,
self::MOVED_PERMANENTLY,
self::FOUND,
self::SEE_OTHER,
self::NOT_MODIFIED,
self::TEMPORARY_REDIRECT,
self::PERMANENT_REDIRECT,
self::BAD_REQUEST,
self::UNAUTHORIZED,
self::FORBIDDEN,
self::NOT_FOUND,
self::METHOD_NOT_ALLOWED,
self::NOT_ACCEPTABLE,
self::REQUEST_TIMEOUT,
self::CONFLICT,
self::GONE,
self::LENGTH_REQUIRED,
self::PRECONDITION_FAILED,
self::PAYLOAD_TOO_LARGE,
self::URI_TOO_LONG,
self::UNSUPPORTED_MEDIA_TYPE,
self::RANGE_NOT_SATISFIABLE,
self::EXPECTATION_FAILED,
self::IM_A_TEAPOT,
self::MISDIRECTED_REQUEST,
self::UNPROCESSABLE_ENTITY,
self::LOCKED,
self::FAILED_DEPENDENCY,
self::UPGRADE_REQUIRED,
self::PRECONDITION_REQUIRED,
self::TOO_MANY_REQUESTS,
self::REQUEST_HEADER_FIELDS_TOO_LARGE,
self::UNAVAILABLE_FOR_LEGAL_REASONS,
self::INTERNAL_SERVER_ERROR,
self::NOT_IMPLEMENTED,
self::BAD_GATEWAY,
self::SERVICE_UNAVAILABLE,
self::GATEWAY_TIMEOUT,
self::HTTP_VERSION_NOT_SUPPORTED,
self::VARIANT_ALSO_NEGOTIATES,
self::INSUFFICIENT_STORAGE,
self::LOOP_DETECTED,
self::NOT_EXTENDED,
self::NETWORK_AUTHENTICATION_REQUIRED
];
}

View file

@ -22,29 +22,65 @@
namespace ncc\Enums;
final class LogLevel
use ncc\Utilities\Validate;
enum LogLevel : string
{
public const SILENT = 'silent';
case SILENT = 'silent';
public const VERBOSE = 'verbose';
case VERBOSE = 'verbose';
public const DEBUG = 'debug';
case DEBUG = 'debug';
public const INFO = 'info';
case INFO = 'info';
public const WARNING = 'warn';
case WARNING = 'warn';
public const ERROR = 'error';
case ERROR = 'error';
public const FATAL = 'fatal';
case FATAL = 'fatal';
public const ALL = [
self::SILENT,
self::VERBOSE,
self::DEBUG,
self::INFO,
self::WARNING,
self::ERROR,
self::FATAL,
];
/**
* Checks if the current log level permits logging at the specified level.
*
* @param LogLevel|null $current_level The log level to be checked. If null, the method returns false.
* @return bool Returns true if logging is permitted at the specified level, otherwise false.
*/
public function checkLogLevel(?LogLevel $current_level): bool
{
if ($current_level === null)
{
return false;
}
return match ($current_level)
{
LogLevel::DEBUG => in_array($this, [LogLevel::DEBUG, LogLevel::VERBOSE, LogLevel::INFO, LogLevel::WARNING, LogLevel::FATAL, LogLevel::ERROR], true),
LogLevel::VERBOSE => in_array($this, [LogLevel::VERBOSE, LogLevel::INFO, LogLevel::WARNING, LogLevel::FATAL, LogLevel::ERROR], true),
LogLevel::INFO => in_array($this, [LogLevel::INFO, LogLevel::WARNING, LogLevel::FATAL, LogLevel::ERROR], true),
LogLevel::WARNING => in_array($this, [LogLevel::WARNING, LogLevel::FATAL, LogLevel::ERROR], true),
LogLevel::ERROR => in_array($this, [LogLevel::FATAL, LogLevel::ERROR], true),
LogLevel::FATAL => $this === LogLevel::FATAL,
default => false,
};
}
/**
* Converts the given string input to a LogLevel.
* If the input is invalid or not found, it defaults to LogLevel::INFO.
*
* @param string $input The input string to be converted to a LogLevel.
* @return LogLevel Returns the corresponding LogLevel for the input string or LogLevel::INFO if not found.
*/
public static function fromOrDefault(string $input): LogLevel
{
$value = self::tryFrom($input);
if($value === null)
{
return self::INFO;
}
return $value;
}
}

View file

@ -22,15 +22,15 @@
namespace ncc\Enums\Options;
final class BuildConfigurationOptions
enum BuildConfigurationOptions : string
{
public const COMPRESSION = 'compression';
case COMPRESSION = 'compression';
public const REQUIRE_FILES = 'require_files';
case REQUIRE_FILES = 'require_files';
public const NCC_CONFIGURATION = 'ncc_configuration';
case NCC_CONFIGURATION = 'ncc_configuration';
public const OUTPUT_FILE = 'output_file';
case OUTPUT_FILE = 'output_file';
public const STATIC_DEPENDENCIES = 'static';
case STATIC_DEPENDENCIES = 'static';
}

View file

@ -22,11 +22,11 @@
namespace ncc\Enums\Options\BuildConfigurationOptions;
final class CompressionOptions
enum CompressionOptions : string
{
public const HIGH = 'high';
case HIGH = 'high';
public const MEDIUM = 'medium';
case MEDIUM = 'medium';
public const LOW = 'low';
case LOW = 'low';
}

View file

@ -22,9 +22,9 @@
namespace ncc\Enums\Options;
final class BuildConfigurationValues
enum BuildConfigurationValues : string
{
public const DEFAULT = 'default';
case DEFAULT = 'default';
public const ALL = 'all';
case ALL = 'all';
}

View file

@ -22,7 +22,7 @@
namespace ncc\Enums\Options;
final class ComponentDecodeOptions
enum ComponentDecodeOptions : string
{
public const AS_FILE = 'as_file';
case AS_FILE = 'as_file';
}

View file

@ -22,25 +22,25 @@
namespace ncc\Enums\Options;
final class InitializeProjectOptions
enum InitializeProjectOptions : string
{
/**
* A custom path to the project's source directory
*/
public const PROJECT_SRC_PATH = 'PROJECT_SRC_PATH';
case PROJECT_SRC_PATH = 'PROJECT_SRC_PATH';
/**
* A boolean option that indicates whether to overwrite the project file if it already exists
*/
public const OVERWRITE_PROJECT_FILE = 'OVERWRITE_PROJECT_FILE';
case OVERWRITE_PROJECT_FILE = 'OVERWRITE_PROJECT_FILE';
/**
* Composer Only, used to define the package's real version
*/
public const COMPOSER_PACKAGE_VERSION = 'COMPOSER_PACKAGE_VERSION';
case COMPOSER_PACKAGE_VERSION = 'COMPOSER_PACKAGE_VERSION';
/**
* Composer Only, used to define the package's update source
*/
public const COMPOSER_REMOTE_SOURCE = 'COMPOSER_REMOTE_SOURCE';
case COMPOSER_REMOTE_SOURCE = 'COMPOSER_REMOTE_SOURCE';
}

View file

@ -22,7 +22,7 @@
namespace ncc\Enums\Options;
final class InstallPackageOptions
enum InstallPackageOptions : string
{
/**
* Skips the installation of dependencies of the package
@ -30,17 +30,23 @@
* @warning This will cause the package to fail to import of
* the dependencies are not met
*/
public const SKIP_DEPENDENCIES = 'skip_dependencies';
case SKIP_DEPENDENCIES = 'skip-dependencies';
/**
* Reinstall all packages if they are already installed,
* Including dependencies if they are being processed.
*/
public const REINSTALL = 'reinstall';
case REINSTALL = 'reinstall';
/**
* Installs a static version of the package if it's available
* otherwise it will install non-static version
*/
public const PREFER_STATIC = 'prefer_static';
case PREFER_STATIC = 'prefer-static';
/**
* Forces ncc to build packages from source rather than trying to obtain
* a pre-built version of the package
*/
case BUILD_SOURCE = 'build-source';
}

View file

@ -22,7 +22,7 @@
namespace ncc\Enums\Options;
final class ProjectOptions
enum ProjectOptions : string
{
public const CREATE_SYMLINK = 'create_symlink';
case CREATE_SYMLINK = 'create_symlink';
}

View file

@ -1,38 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums\Options;
final class RuntimeImportOptions
{
/**
* Indicates if the import should require PHP's autoload.php file
* for the package (Only applies to PHP packages)
*/
public const IMPORT_AUTOLOADER = 'import_autoloader';
/**
* Indicates if the import should require all static files
* for the package (Only applies to PHP packages)
*/
public const IMPORT_STATIC_FILES = 'import_static_files';
}

View file

@ -22,21 +22,21 @@
namespace ncc\Enums;
final class PackageDirectory
enum PackageDirectory : int
{
public const ASSEMBLY = 0x61737365;
case ASSEMBLY = 0x61737365;
public const METADATA = 0x6D657461;
case METADATA = 0x6D657461;
public const INSTALLER = 0x696E7374;
case INSTALLER = 0x696E7374;
public const DEPENDENCIES = 0x64657065;
case DEPENDENCIES = 0x64657065;
public const EXECUTION_UNITS = 0x65786563;
case EXECUTION_UNITS = 0x65786563;
public const COMPONENTS = 0x636F6D70;
case COMPONENTS = 0x636F6D70;
public const RESOURCES = 0x7265736F;
case RESOURCES = 0x7265736F;
public const CLASS_POINTER = 0x636C6173;
case CLASS_POINTER = 0x636C6173;
}

View file

@ -1,28 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums;
final class PackageStandardVersions
{
public const VERSION_1 = '1.0';
}

View file

@ -22,11 +22,11 @@
namespace ncc\Enums;
final class PackageStructure
enum PackageStructure : int
{
public const FILE_VERSION = 0x73746669;
case FILE_VERSION = 0x73746669;
public const FLAGS = 0x73736166;
case FLAGS = 0x73736166;
public const DIRECTORY = 0x6f746365;
case DIRECTORY = 0x6f746365;
}

View file

@ -1,44 +1,36 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums;
namespace ncc\Enums;
final class PackageStructureVersions
enum PackageStructureVersions : string
{
/**
* ncc 1.0.0 to 1.0.3
*/
public const _1_0 = '1.0';
case _1_0 = '1.0';
/**
* ncc 1.0.4 and above
*/
public const _2_0 = '2.0';
/**
* All supported versions
*/
public const ALL = [
self::_1_0,
self::_2_0
];
case _2_0 = '2.0';
}

View file

@ -22,23 +22,15 @@
namespace ncc\Enums;
final class ProjectTemplates
enum ProjectTemplates : string
{
/**
* A template that is used to create a PHP library project
*/
public const PHP_LIBRARY = 'phplib';
case PHP_LIBRARY = 'phplib';
/**
* A template that is used to create a PHP CLI application project
*/
public const PHP_CLI = 'phpcli';
/**
* An array of all the available project templates
*/
public const ALL = [
self::PHP_LIBRARY,
self::PHP_CLI
];
case PHP_CLI = 'phpcli';
}

View file

@ -26,27 +26,27 @@
* @author Zi Xing Narrakas
* @copyright Copyright (C) 2022-2023. Nosial - All Rights Reserved.
*/
final class RegexPatterns
enum RegexPatterns : string
{
public const UUID = '{^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$}Di';
case UUID = '{^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$}Di';
public const PACKAGE_NAME_FORMAT = '/^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+[0-9a-z_]$/';
case PACKAGE_NAME_FORMAT = '/^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+[0-9a-z_]$/';
public const COMPOSER_VERSION_FORMAT = '/^([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/';
case COMPOSER_VERSION_FORMAT = '/^([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/';
public const PYTHON_VERSION_FORMAT = '/^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/';
case PYTHON_VERSION_FORMAT = '/^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/';
public const SEMANTIC_VERSIONING_2 = '/^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/m';
case SEMANTIC_VERSIONING_2 = '/^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/m';
public const UNIX_PATH = '/^(((?:\.\/|\.\.\/|\/)?(?:\.?\w+\/)*)(\.?\w+\.?\w+))$/m';
case UNIX_PATH = '/^(((?:\.\/|\.\.\/|\/)?(?:\.?\w+\/)*)(\.?\w+\.?\w+))$/m';
public const CONSTANT_NAME = '/^([^\x00-\x7F]|[\w_\ \.\+\-]){2,64}$/';
case CONSTANT_NAME = '/^([^\x00-\x7F]|[\w_.+]){2,64}$/';
public const EXECUTION_POLICY_NAME = '/^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/m';
case EXECUTION_POLICY_NAME = '/^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/m';
/**
* @author <purplex>
*/
public const REMOTE_PACKAGE = '/^(?<vendor>[^\/\n]+)\/(?<package>[^:=\n@]+)(?:=(?<version>[^:@\n]+))?(?::(?<branch>[^@\n]+))?@(?<source>.*)$/m';
case REMOTE_PACKAGE = '/^(?<vendor>[^\/\n]+)\/(?<package>[^:=\n@]+)(?:=(?<version>[^:@\n]+))?(?::(?<branch>[^@\n]+))?@(?<source>.*)$/m';
}

View file

@ -22,25 +22,15 @@
namespace ncc\Enums;
final class Runners
enum Runners : string
{
public const PHP = 'php';
case PHP = 'php';
public const BASH = 'bash';
case BASH = 'bash';
public const PYTHON = 'python';
case PYTHON = 'python';
public const PERL = 'perl';
case PERL = 'perl';
public const LUA = 'lua';
public const ALL = [
self::PHP,
self::BASH,
self::PYTHON,
self::PYTHON_3,
self::PYTHON_2,
self::PERL,
self::LUA
];
case LUA = 'lua';
}

View file

@ -22,9 +22,9 @@
namespace ncc\Enums;
final class Scopes
enum Scopes : string
{
public const USER = 'USER';
case USER = 'USER';
public const SYSTEM = 'SYSTEM';
case SYSTEM = 'SYSTEM';
}

View file

@ -22,50 +22,50 @@
namespace ncc\Enums\SpecialConstants;
final class AssemblyConstants
enum AssemblyConstants : string
{
/**
* Assembly's Name Property
*/
public const ASSEMBLY_NAME = '%ASSEMBLY.NAME%';
case ASSEMBLY_NAME = '%ASSEMBLY.NAME%';
/**
* Assembly's Package Property
*/
public const ASSEMBLY_PACKAGE = '%ASSEMBLY.PACKAGE%';
case ASSEMBLY_PACKAGE = '%ASSEMBLY.PACKAGE%';
/**
* Assembly's Description Property
*/
public const ASSEMBLY_DESCRIPTION = '%ASSEMBLY.DESCRIPTION%';
case ASSEMBLY_DESCRIPTION = '%ASSEMBLY.DESCRIPTION%';
/**
* Assembly's Company Property
*/
public const ASSEMBLY_COMPANY = '%ASSEMBLY.COMPANY%';
case ASSEMBLY_COMPANY = '%ASSEMBLY.COMPANY%';
/**
* Assembly's Product Property
*/
public const ASSEMBLY_PRODUCT = '%ASSEMBLY.PRODUCT%';
case ASSEMBLY_PRODUCT = '%ASSEMBLY.PRODUCT%';
/**
* Assembly's Copyright Property
*/
public const ASSEMBLY_COPYRIGHT = '%ASSEMBLY.COPYRIGHT%';
case ASSEMBLY_COPYRIGHT = '%ASSEMBLY.COPYRIGHT%';
/**
* Assembly's Trademark Property
*/
public const ASSEMBLY_TRADEMARK = '%ASSEMBLY.TRADEMARK%';
case ASSEMBLY_TRADEMARK = '%ASSEMBLY.TRADEMARK%';
/**
* Assembly's Version Property
*/
public const ASSEMBLY_VERSION = '%ASSEMBLY.VERSION%';
case ASSEMBLY_VERSION = '%ASSEMBLY.VERSION%';
/**
* Assembly's UUID property
*/
public const ASSEMBLY_UID = '%ASSEMBLY.UID%';
case ASSEMBLY_UID = '%ASSEMBLY.UID%';
}

View file

@ -22,25 +22,25 @@
namespace ncc\Enums\SpecialConstants;
final class BuildConstants
enum BuildConstants : string
{
/**
* The Unix Timestamp for when the package was compiled
*/
public const COMPILE_TIMESTAMP = '%COMPILE_TIMESTAMP%';
case COMPILE_TIMESTAMP = '%COMPILE_TIMESTAMP%';
/**
* The version of NCC that was used to compile the package
*/
public const NCC_BUILD_VERSION = '%NCC_BUILD_VERSION%';
case NCC_BUILD_VERSION = '%NCC_BUILD_VERSION%';
/**
* NCC Build Flags exploded into spaces
*/
public const NCC_BUILD_FLAGS = '%NCC_BUILD_FLAGS%';
case NCC_BUILD_FLAGS = '%NCC_BUILD_FLAGS%';
/**
* NCC Build Branch
*/
public const NCC_BUILD_BRANCH = '%NCC_BUILD_BRANCH%';
case NCC_BUILD_BRANCH = '%NCC_BUILD_BRANCH%';
}

View file

@ -22,49 +22,49 @@
namespace ncc\Enums\SpecialConstants;
final class DateTimeConstants
enum DateTimeConstants : string
{
// Day Format
/**
* Day of the month, 2 digits with leading zeros
*/
public const d = '%d%'; // 01 through 31
case d = '%d%'; // 01 through 31
/**
* A textual representation of a day, three letters
*/
public const D = '%D%'; // Mon through Sun
case D = '%D%'; // Mon through Sun
/**
* Day of the month without leading zeros
*/
public const j = '%j%'; // 1 through 31
case j = '%j%'; // 1 through 31
/**
* A full textual representation of the day of the week
*/
public const l = '%l%'; // Sunday through Saturday
case l = '%l%'; // Sunday through Saturday
/**
* ISO 8601 numeric representation of the day of the week
*/
public const N = '%N%'; // 1 (Monday) to 7 (Sunday)
case N = '%N%'; // 1 (Monday) to 7 (Sunday)
/**
* English ordinal suffix for the day of the month, 2 characters
*/
public const S = '%S%'; // st, nd, rd, th
case S = '%S%'; // st, nd, rd, th
/**
* Numeric representation of the day of the week
*/
public const w = '%w%'; // 0 (sunday) through 6 (Saturday)
case w = '%w%'; // 0 (sunday) through 6 (Saturday)
/**
* The day of the year (starting from 0)
*/
public const z = '%z%'; // 0 through 365
case z = '%z%'; // 0 through 365
@ -73,7 +73,7 @@
/**
* ISO 8601 week number of year, weeks starting on Monday
*/
public const W = '%W%'; // 42 (42nd week in year)
case W = '%W%'; // 42 (42nd week in year)
@ -82,27 +82,27 @@
/**
* A full textual representation of a month, such as January or March
*/
public const F = '%F%'; // January through December
case F = '%F%'; // January through December
/**
* Numeric representation of a month, with leading zeros
*/
public const m = '%m%'; // 01 through 12
case m = '%m%'; // 01 through 12
/**
* A short textual representation of a month, three letters
*/
public const M = '%M%'; // Jan through Dec
case M = '%M%'; // Jan through Dec
/**
* Numeric representation of a month, without leading zeros
*/
public const n = '%n%'; // 1 through 12
case n = '%n%'; // 1 through 12
/**
* Number of days in the given month
*/
public const t = '%t%'; // 28 through 31
case t = '%t%'; // 28 through 31
@ -110,73 +110,73 @@
/**
* Whether it's a leap year
*/
public const L = '%L%'; // 1 (leap year), 0 otherwise
case L = '%L%'; // 1 (leap year), 0 otherwise
/**
* ISO 8601 week-numbering year. This has the same value as Y,
* except that if the ISO week number (W) belongs to the previous
* or next year, that year is used instead.
*/
public const o = '%o%'; // Same as Y, except that it use week number to decide which year it falls onto
case o = '%o%'; // Same as Y, except that it use week number to decide which year it falls onto
/**
* A full numeric representation of a year, at least 4 digits, with - for years BCE.
*/
public const Y = '%Y%'; // 1991, 2012, 2014, ...
case Y = '%Y%'; // 1991, 2012, 2014, ...
/**
* A two digit representation of a year
*/
public const y = '%y%'; // 91, 12, 14, ...
case y = '%y%'; // 91, 12, 14, ...
// Time Format
/**
* Lowercase Ante meridiem and Post meridiem
*/
public const a = '%a%'; // am or pm
case a = '%a%'; // am or pm
/**
* Uppercase Ante meridiem and Post meridiem
*/
public const A = '%A%'; // AM or PM
case A = '%A%'; // AM or PM
/**
* Swatch Internet time
*/
public const B = '%B%'; // 000 through 999
case B = '%B%'; // 000 through 999
/**
* 12-hour format of an hour without leading zeros
*/
public const g = '%g%'; // 1 through 12
case g = '%g%'; // 1 through 12
/**
* 24-hour format of an hour without leading zeros
*/
public const G = '%G%'; // 0 through 23
case G = '%G%'; // 0 through 23
/**
* 12-hour format of an hour with leading zeros
*/
public const h = '%h%'; // 01 through 12
case h = '%h%'; // 01 through 12
/**
* 24-hour format of an hour with leading zeros
*/
public const H = '%H%'; // 01 through 23
case H = '%H%'; // 01 through 23
/**
* Minutes with leading zeros
*/
public const i = '%i%'; // 01 through 59
case i = '%i%'; // 01 through 59
/**
* Seconds with leading zeros
*/
public const s = '%s%'; // 00 through 59
case s = '%s%'; // 00 through 59
// DateTime format
public const c = '%c%'; // 2004-02-12T15:19:21
public const r = '%r%'; // Thu, 21 Dec 2000 16:01:07
public const u = '%u%'; // Unix Timestamp (seconds since Jan 1 1970 00:00:00)
case c = '%c%'; // 2004-02-12T15:19:21
case r = '%r%'; // Thu, 21 Dec 2000 16:01:07
case u = '%u%'; // Unix Timestamp (seconds since Jan 1 1970 00:00:00)
}

View file

@ -22,13 +22,13 @@
namespace ncc\Enums\SpecialConstants;
final class InstallConstants
enum InstallConstants : string
{
public const INSTALL_PATH = '%INSTALL_PATH%';
case INSTALL_PATH = '%INSTALL_PATH%';
public const INSTALL_PATH_BIN = '%INSTALL_PATH.BIN%';
case INSTALL_PATH_BIN = '%INSTALL_PATH.BIN%';
public const INSTALL_PATH_SRC = '%INSTALL_PATH.SRC%';
case INSTALL_PATH_SRC = '%INSTALL_PATH.SRC%';
public const INSTALL_PATH_DATA = '%INSTALL_PATH.DATA%';
case INSTALL_PATH_DATA = '%INSTALL_PATH.DATA%';
}

View file

@ -22,11 +22,11 @@
namespace ncc\Enums\SpecialConstants;
final class RuntimeConstants
enum RuntimeConstants : string
{
public const CWD = '%CWD%';
public const PID = '%PID%';
public const UID = '%UID%';
public const GID = '%GID%';
public const USER = '%USER%';
case CWD = '%CWD%';
case PID = '%PID%';
case UID = '%UID%';
case GID = '%GID%';
case USER = '%USER%';
}

View file

@ -22,15 +22,15 @@
namespace ncc\Enums\Types;
final class AuthenticationType
enum AuthenticationType : int
{
/**
* A combination of a username and password is used for authentication
*/
public const USERNAME_PASSWORD = 1;
case USERNAME_PASSWORD = 1;
/**
* A single private access token is used for authentication
*/
public const ACCESS_TOKEN = 2;
case ACCESS_TOKEN = 2;
}

View file

@ -22,8 +22,8 @@
namespace ncc\Enums\Types;
final class BuildOutputType
enum BuildOutputType : string
{
public const NCC_PACKAGE = 'ncc';
public const EXECUTABLE = 'executable';
case NCC_PACKAGE = 'ncc';
case EXECUTABLE = 'executable';
}

View file

@ -1,37 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums\Types;
final class BuiltinRemoteSourceType
{
/**
* The remote source indicates the package is to be
* fetched using the composer utility.
*/
public const COMPOSER = 'composer';
public const ALL = [
self::COMPOSER
];
}

View file

@ -22,35 +22,25 @@
namespace ncc\Enums\Types;
final class ComponentDataType
enum ComponentDataType : string
{
/**
* Indicates whether the component is represented as an AST representation
*/
public const AST = 'ast';
case AST = 'ast';
/**
* Indicates whether the component is represented as plaintext
*/
public const PLAIN = 'plain';
case PLAIN = 'plain';
/**
* Indicates whether the component is represented as binary or executable
*/
public const BINARY = 'binary';
case BINARY = 'binary';
/**
* Indicates whether the component is represented as as a base64 encoded string (Raw bytes' representation)
*/
public const BASE64_ENCODED = 'b64enc';
/**
* All the possible data types of a component
*/
public const ALL = [
self::AST,
self::PLAIN,
self::BINARY,
self::BASE64_ENCODED
];
case BASE64_ENCODED = 'b64enc';
}

View file

@ -22,12 +22,12 @@
namespace ncc\Enums\Types;
final class ComposerPackageTypes
enum ComposerPackageTypes : string
{
/**
* This is the default. It will copy the files to `vendor`
*/
public const LIBRARY = 'library';
case LIBRARY = 'library';
/**
* This denotes a project rather than a library. For example
@ -37,7 +37,7 @@
* to provide listings of projects to initialize when creating
* a new workspace.
*/
public const PROJECT = 'project';
case PROJECT = 'project';
/**
* An empty package that contains requirements and will trigger
@ -45,11 +45,11 @@
* anything to the filesystem. As such, it does not require a
* a dist or source key to be installable
*/
public const METAPACKAGE = 'metapackage';
case METAPACKAGE = 'metapackage';
/**
* A package of type `composer-plugin` may provide an installer
* for other packages that have a custom type.
*/
public const COMPOSER_PLUGIN = 'composer-plugin';
case COMPOSER_PLUGIN = 'composer-plugin';
}

View file

@ -22,15 +22,15 @@
namespace ncc\Enums\Types;
final class ComposerStabilityTypes
enum ComposerStabilityTypes : string
{
public const DEV = 'dev';
case DEV = 'dev';
public const ALPHA = 'alpha';
case ALPHA = 'alpha';
public const BETA = 'beta';
case BETA = 'beta';
public const RC = 'rc';
case RC = 'rc';
public const STABLE ='stable';
case STABLE ='stable';
}

View file

@ -1,49 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums\Types;
final class DependencySourceType
{
/**
* The dependency pointer does not point to a package
*/
public const NONE = 'none';
/**
* Indicates if the dependency is statically linked and the
* reference points to the compiled package of the dependency
*/
public const STATIC = 'static';
/**
* Indicates if the pointer reference points to a remote source
* to fetch the dependency from
*/
public const REMOTE = 'remote';
/**
* Indicates if the pointer reference points to a relative file with the
* filename format "{package_name}=={version}.ncc" to fetch the dependency from
*/
public const LOCAL = 'local';
}

View file

@ -1,28 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums\Types;
final class EncoderType
{
public const ZI_PROTO = '3';
}

View file

@ -22,10 +22,10 @@
namespace ncc\Enums\Types;
final class HttpRequestType
enum HttpRequestType : string
{
public const GET = 'GET';
public const POST = 'POST';
public const PUT = 'PUT';
public const DELETE = 'DELETE';
case GET = 'GET';
case POST = 'POST';
case PUT = 'PUT';
case DELETE = 'DELETE';
}

View file

@ -22,14 +22,9 @@
namespace ncc\Enums\Types;
final class ProjectType
enum ProjectType : string
{
public const COMPOSER = 'composer';
case COMPOSER = 'composer';
public const NCC = 'ncc';
public const ALL = [
self::COMPOSER,
self::NCC,
];
case NCC = 'ncc';
}

View file

@ -1,56 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Enums\Types;
final class RemoteSourceType
{
/**
* A builtin source type is not defined by the user but handled by
* an extension built into NCC
*/
public const BUILTIN = 'builtin';
/**
* A defined source type is defined by the user in the remote sources file
* and handled by an extension designed by passing on the information of
* the source to the extension
*/
public const DEFINED = 'defined';
/**
* Unsupported or invalid source type
*/
public const UNKNOWN = 'unknown';
/**
* No remote source type
*/
public const NONE = 'none';
public const All = [
self::BUILTIN,
self::DEFINED,
self::UNKNOWN,
self::NONE
];
}

View file

@ -22,9 +22,9 @@
namespace ncc\Enums\Types;
final class RepositoryResultType
enum RepositoryResultType : string
{
public const SOURCE = 'source';
case SOURCE = 'source';
public const PACKAGE = 'package';
case PACKAGE = 'package';
}

View file

@ -22,20 +22,13 @@
namespace ncc\Enums\Types;
final class RepositoryType
enum RepositoryType : string
{
public const GITLAB = 'gitlab';
case GITLAB = 'gitlab';
public const GITHUB = 'github';
case GITHUB = 'github';
public const GITEA = 'gitea';
case GITEA = 'gitea';
public const PACKAGIST = 'packagist';
public const ALL = [
self::GITLAB,
self::GITHUB,
self::GITEA,
self::PACKAGIST
];
case PACKAGIST = 'packagist';
}

View file

@ -22,25 +22,15 @@
namespace ncc\Enums;
final class Versions
enum Versions : string
{
/**
* The current version of the credentials store file format
*/
public const CREDENTIALS_STORE_VERSION = '1.0.0';
/**
* The current version of the package structure file format
*/
public const PACKAGE_STRUCTURE_VERSION = '2.0';
/**
* The current version of the package lock structure file format
*/
public const PACKAGE_LOCK_VERSION = '2.0.0';
case CREDENTIALS_STORE_VERSION = '1.0.0';
/**
* Generic version of the package structure file format (latest)
*/
public const LATEST = 'latest';
case LATEST = 'latest';
}

View file

@ -34,6 +34,6 @@
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::ARCHIVE_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::ARCHIVE_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::AUTHENTICATION_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::AUTHENTICATION_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@ namespace ncc\Exceptions;
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::BUILD_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::BUILD_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@ namespace ncc\Exceptions;
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::COMPOSER_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::COMPOSER_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::CONFIGURATION_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::CONFIGURATION_EXCEPTION->value, $previous);
}
}

View file

@ -30,6 +30,6 @@
{
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::GIT_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::GIT_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@ namespace ncc\Exceptions;
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::IO_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::IO_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::IMPORT_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::IMPORT_EXCEPTION->value, $previous);
}
}

View file

@ -30,6 +30,6 @@
{
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::INTEGRITY_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::INTEGRITY_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::NETWORK_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::NETWORK_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::NOT_SUPPORTED_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::NOT_SUPPORTED_EXCEPTION->value, $previous);
}
}

View file

@ -30,6 +30,6 @@
{
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::OPERATION_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::OPERATION_EXCEPTION->value, $previous);
}
}

View file

@ -34,6 +34,6 @@
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::PACKAGE_EXCEPTION, $previous);
parent::__construct($message, ExceptionCodes::PACKAGE_EXCEPTION->value, $previous);
}
}

View file

@ -41,7 +41,7 @@
*/
public function __construct(string $path, ?Throwable $previous = null)
{
parent::__construct(sprintf('Path "%s" not found', $path), ExceptionCodes::PATH_NOT_FOUND, $previous);
parent::__construct(sprintf('Path "%s" not found', $path), ExceptionCodes::PATH_NOT_FOUND->value, $previous);
$this->path = $path;
}

View file

@ -35,6 +35,6 @@ namespace ncc\Exceptions;
*/
public function __construct(string $message = "", ?Throwable $previous = null)
{
parent::__construct($message, ExceptionCodes::RUNTIME, $previous);
parent::__construct($message, ExceptionCodes::RUNTIME->value, $previous);
}
}

View file

@ -22,12 +22,14 @@
namespace ncc\Interfaces;
use ncc\Enums\Types\AuthenticationType;
interface AuthenticationInterface extends BytecodeObjectInterface
{
/**
* @return string
* @return AuthenticationType
*/
public function getAuthenticationType(): string;
public function getAuthenticationType(): AuthenticationType;
/**
* @return string

View file

@ -41,5 +41,5 @@
* @param array $options Optional. The options to use/override for this build
* @return string
*/
public function build(string $build_configuration=BuildConfigurationValues::DEFAULT, array $options=[]): string;
public function build(string $build_configuration=BuildConfigurationValues::DEFAULT->value, array $options=[]): string;
}

View file

@ -45,7 +45,7 @@
* @throws AuthenticationException If the authentication is invalid
* @throws NetworkException If there was an error getting the source
*/
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult;
public static function fetchSourceArchive(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST->value, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult;
/**
* Returns the archive URL for the ncc package of the specified group and project.
@ -61,5 +61,5 @@
* @throws AuthenticationException If the authentication is invalid
* @throws NetworkException If there was an error getting the package
*/
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult;
public static function fetchPackage(RepositoryConfiguration $repository, string $vendor, string $project, string $version=Versions::LATEST->value, ?AuthenticationType $authentication=null, array $options=[]): RepositoryResult;
}

View file

@ -1,37 +0,0 @@
<?php
/*
* Copyright (c) Nosial 2022-2023, all rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
namespace ncc\Interfaces;
use ncc\Exceptions\IOException;
use ncc\Objects\PackageLock\VersionEntry;
interface RuntimeInterface
{
/**
* @param VersionEntry $versionEntry
* @param array $options
* @return mixed
* @throws IOException
*/
public static function import(VersionEntry $versionEntry, array $options=[]): bool;
}

View file

@ -89,7 +89,7 @@
{
Console::outDebug(sprintf('saving configuration file to %s', PathFinder::getConfigurationFile()));
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new AuthenticationException('Cannot save configuration file, insufficient permissions');
}

View file

@ -51,7 +51,7 @@
*/
public function __construct()
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must have root privileges to access the credentials storage file');
}
@ -86,7 +86,7 @@
{
Console::outVerbose(sprintf('Saving credentials store to %s', PathFinder::getCredentialStorage()));
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must have root privileges to modify the credentials storage file');
}
@ -103,7 +103,7 @@
*/
public static function initializeCredentialStorage(): void
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must have root privileges to initialize the credentials storage file');
}

View file

@ -80,7 +80,7 @@
*/
public function save(): void
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must be running as root to update the system package lock');
}
@ -98,7 +98,7 @@
*/
public static function initializePackageLock(): void
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must be running as root to update the system package lock');
}

View file

@ -151,7 +151,7 @@
*/
public function install(string|PackageReader $input, ?AuthenticationInterface $authentication=null, array $options=[]): array
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must have root privileges to install packages');
}
@ -169,7 +169,7 @@
}
// If the input is a remote package, we can assume it's a remote package input
if(preg_match(RegexPatterns::REMOTE_PACKAGE, $input) === 1)
if(preg_match(RegexPatterns::REMOTE_PACKAGE->value, $input) === 1)
{
return $this->installRemotePackage(RemotePackageInput::fromString($input), $authentication, $options);
}
@ -188,7 +188,7 @@
*/
public function uninstall(string $package_name, ?string $version=null): array
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must have root privileges to uninstall packages');
}
@ -206,7 +206,7 @@
{
Console::outVerbose(sprintf(
'Removing symlink for %s=%s at %s',
$package_name, $this->package_lock->getEntry($package_name)->getVersion(Versions::LATEST)->getVersion(),
$package_name, $this->package_lock->getEntry($package_name)->getVersion(Versions::LATEST->value)->getVersion(),
PathFinder::findBinPath() . DIRECTORY_SEPARATOR . strtolower($package_name)
));
@ -216,7 +216,7 @@
}
catch(Exception $e)
{
throw new IOException(sprintf('Failed to resolve symlink for %s=%s: %s', $package_name, $this->package_lock->getEntry($package_name)->getVersion(Versions::LATEST)->getVersion(), $e->getMessage()), $e);
throw new IOException(sprintf('Failed to resolve symlink for %s=%s: %s', $package_name, $this->package_lock->getEntry($package_name)->getVersion(Versions::LATEST->value)->getVersion(), $e->getMessage()), $e);
}
if(is_file($symlink_path))
@ -285,7 +285,7 @@
*/
public function uninstallAll(): array
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must have root privileges to uninstall packages');
}
@ -405,7 +405,7 @@
Console::out(sprintf('Installing package %s=%s', $package_reader->getAssembly()->getPackage(), $package_reader->getAssembly()->getVersion()));
if($this->package_lock->entryExists($package_reader->getAssembly()->getPackage(), $package_reader->getAssembly()->getVersion()))
{
if(!isset($options[InstallPackageOptions::REINSTALL]))
if(!isset($options[InstallPackageOptions::REINSTALL->value]))
{
Console::outVerbose(sprintf(
'Package %s=%s is already installed, skipping',
@ -453,7 +453,7 @@
throw new IOException(sprintf('Failed to add package to package lock file due to an exception: %s', $e->getMessage()), $e);
}
if($package_reader->getMetadata()->getOption(ProjectOptions::CREATE_SYMLINK) === null)
if($package_reader->getMetadata()->getOption(ProjectOptions::CREATE_SYMLINK->value) === null)
{
// Remove the symlink if it exists
if($this->package_lock->getEntry($package_reader->getAssembly()->getPackage())->isSymlinkRegistered())
@ -505,7 +505,7 @@
$this->saveLock();
if(!isset($options[InstallPackageOptions::SKIP_DEPENDENCIES]))
if(!isset($options[InstallPackageOptions::SKIP_DEPENDENCIES->value]))
{
foreach($this->checkRequiredDependencies($package_reader) as $dependency)
{
@ -521,7 +521,7 @@
));
/** @noinspection SlowArrayOperationsInLoopInspection */
$installed_packages = array_merge($installed_packages, $this->install($dependency->getSource(), $authentication));
$installed_packages = array_merge($installed_packages, $this->install($dependency->getSource(), $authentication, $options));
}
}
@ -550,35 +550,45 @@
Console::out(sprintf('Fetching package %s/%s=%s from %s', $input->getVendor(), $input->getPackage(), $input->getVersion(), $input->getRepository()));
try
if(isset($options[InstallPackageOptions::BUILD_SOURCE->value]))
{
Console::outVerbose(sprintf(
'Attempting to fetch a pre-built ncc package for %s=%s from %s',
$input->getPackage(), $input->getVersion(), $input->getRepository()
'Forcing ncc to build package %s/%s=%s from source',
$input->getVendor(), $input->getPackage(), $input->getVersion()
));
// First try to fetch a pre-built package from the repository
$results = $this->repository_manager->getRepository($input->getRepository())->fetchPackage(
$input->getVendor(), $input->getPackage(), $input->getVersion(), $authentication, $options
);
$package_path = $this->downloadFile($results->getUrl(), PathFinder::getCachePath());
}
catch(Exception $e)
else
{
Console::outVerbose(sprintf(
'Failed to fetch a pre-built ncc package for %s=%s from %s: %s',
$input->getPackage(), $input->getVersion(), $input->getRepository(), $e->getMessage()
));
// Clean up the package file if it exists
if(isset($package_path) && is_file($package_path))
try
{
ShutdownHandler::declareTemporaryPath($package_path);
}
Console::outVerbose(sprintf(
'Attempting to fetch a pre-built ncc package for %s=%s from %s',
$input->getPackage(), $input->getVersion(), $input->getRepository()
));
// This is a warning because we can still attempt to build from source
unset($results, $package_path);
// First try to fetch a pre-built package from the repository
$results = $this->repository_manager->getRepository($input->getRepository())->fetchPackage(
$input->getVendor(), $input->getPackage(), $input->getVersion(), $authentication, $options
);
$package_path = $this->downloadFile($results->getUrl(), PathFinder::getCachePath());
}
catch(Exception $e)
{
Console::outVerbose(sprintf(
'Failed to fetch a pre-built ncc package for %s=%s from %s: %s',
$input->getPackage(), $input->getVersion(), $input->getRepository(), $e->getMessage()
));
// Clean up the package file if it exists
if(isset($package_path) && is_file($package_path))
{
ShutdownHandler::declareTemporaryPath($package_path);
}
// This is a warning because we can still attempt to build from source
unset($results, $package_path);
}
}
if(!isset($package_path))
@ -598,8 +608,8 @@
$archive_path = $this->downloadFile($results->getUrl(), PathFinder::getCachePath());
$package_path = $this->buildFromSource($archive_path, [
InitializeProjectOptions::COMPOSER_PACKAGE_VERSION => $results->getVersion(),
InitializeProjectOptions::COMPOSER_REMOTE_SOURCE => $input->toString()
InitializeProjectOptions::COMPOSER_PACKAGE_VERSION->value => $results->getVersion(),
InitializeProjectOptions::COMPOSER_REMOTE_SOURCE->value => $input->toString()
]);
}
catch(Exception $e)
@ -663,16 +673,16 @@
$progress_bar->increaseValue(1, true);
foreach($package_reader->getComponents() as $component_name)
{
$progress_bar->setMiscText(basename($component_name), true);
$progress_bar->setMiscText($component_name);
if(Resolver::checkLogLevel(LogLevel::VERBOSE, Main::getLogLevel()))
if(LogLevel::VERBOSE->checkLogLevel(Main::getLogLevel()))
{
Console::outVerbose(sprintf('Extracting component %s to %s', $component_name, $bin_path . DIRECTORY_SEPARATOR . $component_name));
}
IO::fwrite(
$bin_path . DIRECTORY_SEPARATOR . $component_name,
$package_reader->getComponent($component_name)->getData([ComponentDecodeOptions::AS_FILE]), 0755
$package_reader->getComponent($component_name)->getData([ComponentDecodeOptions::AS_FILE->value]), 0755
);
//Console::inlineProgressBar(++$current_step, $total_steps);
@ -681,9 +691,9 @@
foreach($package_reader->getResources() as $resource_name)
{
$progress_bar->setMiscText(basename($resource_name), true);
$progress_bar->setMiscText($resource_name);
if(Resolver::checkLogLevel(LogLevel::VERBOSE, Main::getLogLevel()))
if(LogLevel::VERBOSE->checkLogLevel(Main::getLogLevel()))
{
Console::outVerbose(sprintf('Extracting resource %s to %s', $resource_name, $bin_path . DIRECTORY_SEPARATOR . $resource_name));
}
@ -701,7 +711,7 @@
{
$progress_bar->setMiscText($unit);
if(Resolver::checkLogLevel(LogLevel::VERBOSE, Main::getLogLevel()))
if(LogLevel::VERBOSE->checkLogLevel(Main::getLogLevel()))
{
Console::outVerbose(sprintf('Extracting execution unit %s to %s', $unit, $package_path . DIRECTORY_SEPARATOR . 'units' . DIRECTORY_SEPARATOR . $package_reader->getExecutionUnit($unit)->getExecutionPolicy()->getName() . '.unit'));
}
@ -726,7 +736,7 @@
if($package_reader->getInstaller() !== null)
{
$progress_bar->setMiscText('installer');
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::INSTALLER, ZiProto::encode($package_reader->getInstaller()?->toArray(true)));
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::INSTALLER->value, ZiProto::encode($package_reader->getInstaller()?->toArray(true)));
}
//Console::inlineProgressBar(++$current_step, $total_steps);
$progress_bar->increaseValue(1, true);
@ -734,23 +744,23 @@
if(count($class_map) > 0)
{
$progress_bar->setMiscText('class map');
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::CLASS_MAP, ZiProto::encode($class_map));
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::CLASS_MAP->value, ZiProto::encode($class_map));
}
//Console::inlineProgressBar(++$current_step, $total_steps);
$progress_bar->increaseValue(1, true);
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::ASSEMBLY, ZiProto::encode($package_reader->getAssembly()->toArray(true)));
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::METADATA, ZiProto::encode($package_reader->getMetadata()->toArray(true)));
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::ASSEMBLY->value, ZiProto::encode($package_reader->getAssembly()->toArray(true)));
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::METADATA->value, ZiProto::encode($package_reader->getMetadata()->toArray(true)));
if($package_reader->getMetadata()->getUpdateSource() !== null)
{
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::UPDATE, ZiProto::encode($package_reader->getMetadata()->getUpdateSource()?->toArray(true)));
IO::fwrite($package_path . DIRECTORY_SEPARATOR . FileDescriptor::UPDATE->value, ZiProto::encode($package_reader->getMetadata()->getUpdateSource()?->toArray(true)));
}
//Console::inlineProgressBar(++$current_step, $total_steps);
$progress_bar->increaseValue(1, true);
$progress_bar->setMiscText('creating shadowcopy', true);
$package_reader->saveCopy($package_path . DIRECTORY_SEPARATOR . FileDescriptor::SHADOW_PACKAGE);
$package_reader->saveCopy($package_path . DIRECTORY_SEPARATOR . FileDescriptor::SHADOW_PACKAGE->value);
//Console::inlineProgressBar(++$current_step, $total_steps);
$progress_bar->setMiscText('done', true);
@ -804,8 +814,8 @@
try
{
$package_path = (new ProjectManager($project_detection->getProjectFilePath()))->build(
BuildConfigurationValues::DEFAULT,
[BuildConfigurationOptions::OUTPUT_FILE => PathFinder::getCachePath() . DIRECTORY_SEPARATOR . hash('sha1', $archive) . '.ncc']
BuildConfigurationValues::DEFAULT->value,
[BuildConfigurationOptions::OUTPUT_FILE->value => PathFinder::getCachePath() . DIRECTORY_SEPARATOR . hash('sha1', $archive) . '.ncc']
);
ShutdownHandler::declareTemporaryPath($source_directory);
@ -828,8 +838,8 @@
{
$project_manager = ProjectManager::initializeFromComposer(dirname($project_detection->getProjectFilePath()), $options);
$package_path = $project_manager->build(
BuildConfigurationValues::DEFAULT,
[BuildConfigurationOptions::OUTPUT_FILE => PathFinder::getCachePath() . DIRECTORY_SEPARATOR . hash('sha1', $archive) . '.ncc']
BuildConfigurationValues::DEFAULT->value,
[BuildConfigurationOptions::OUTPUT_FILE->value => PathFinder::getCachePath() . DIRECTORY_SEPARATOR . hash('sha1', $archive) . '.ncc']
);
ShutdownHandler::declareTemporaryPath($package_path);
@ -848,7 +858,7 @@
}
default:
throw new NotSupportedException(sprintf('Cannot build from source %s, the project type %s is not supported', $archive, $project_detection->getProjectType()));
throw new NotSupportedException(sprintf('Cannot build from source %s, the project type %s is not supported', $archive, $project_detection->getProjectType()->value));
}
}
@ -861,7 +871,7 @@
* @throws NetworkException
* @noinspection UnusedFunctionResultInspection
*/
private function downloadFile(string $url, string $path, int $retries=3): string
private function downloadFile(string $url, string $path): string
{
$file_path = basename(parse_url($url, PHP_URL_PATH));
$curl = curl_init($url);
@ -886,12 +896,6 @@
$file_handle = fopen($file_path, 'wb');
$end = false;
$progress_bar = new ConsoleProgressBar(sprintf('Downloading %s', $url), 100);
$resolved_host = Resolver::getResolveOption($url);
if($resolved_host !== null)
{
curl_setopt($curl, CURLOPT_RESOLVE, [$resolved_host]);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
@ -902,22 +906,17 @@
]);
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, static function ($resource, $download_size, $downloaded) use ($url, &$end, $progress_bar)
{
if($download_size == 0)
{
return;
}
if($download_size === $downloaded && $end)
{
return;
}
if($download_size === 0)
{
return;
}
if($downloaded > $download_size)
{
$download_size = $downloaded;
}
if(Resolver::checkLogLevel(LogLevel::VERBOSE, Main::getLogLevel()))
if(LogLevel::VERBOSE->checkLogLevel(Main::getLogLevel()))
{
$percentage = round(($downloaded / $download_size) * 100, 2);
Console::out(sprintf('Download progress %s (%s/%s) for %s', $percentage, $downloaded, $download_size, $url));
@ -927,7 +926,6 @@
$progress_bar->setMaxValue($download_size);
$progress_bar->setValue($downloaded);
$progress_bar->setMiscText(sprintf('%s/%s', $downloaded, $download_size));
$progress_bar->update();
}
@ -937,27 +935,16 @@
}
});
unset($progress_bar);
curl_exec($curl);
fclose($file_handle);
if(curl_errno($curl))
{
ShutdownHandler::declareTemporaryPath($file_path);
if($retries === 0)
{
throw new NetworkException(sprintf('Failed to download file from %s: %s', $url, curl_error($curl)));
}
Console::outWarning(sprintf('Failed to download file from %s: %s, retrying', $url, curl_error($curl)));
return $this->downloadFile($url, $path, ($retries - 1));
throw new NetworkException(sprintf('Failed to download file from %s: %s', $url, curl_error($curl)));
}
$progress_bar->setMaxValue(100);
$progress_bar->setValue(100);
$progress_bar->setMiscText('done', true);
unset($progress_bar);
curl_close($curl);
return $file_path;
}

View file

@ -96,6 +96,12 @@
$path = substr($path, 0, -1);
}
if(is_file($path))
{
// We can assume the user is trying to load a project file
$path = dirname($path);
}
// Detect if the folder exists or not
if(!is_dir($path))
{
@ -154,20 +160,20 @@
* @throws NotSupportedException
* @throws PathNotFoundException
*/
public function build(string $build_configuration=BuildConfigurationValues::DEFAULT, array $options=[]): string
public function build(string $build_configuration=BuildConfigurationValues::DEFAULT->value, array $options=[]): string
{
$configuration = $this->project_configuration->getBuild()->getBuildConfiguration($build_configuration);
return match (strtolower($this->project_configuration->getProject()->getCompiler()->getExtension()))
return match ($this->project_configuration->getProject()->getCompiler()->getExtension())
{
CompilerExtensions::PHP => match (strtolower($configuration->getBuildType()))
{
BuildOutputType::NCC_PACKAGE => (new NccCompiler($this))->build($build_configuration, $options),
BuildOutputType::EXECUTABLE => (new ExecutableCompiler($this))->build($build_configuration, $options),
BuildOutputType::NCC_PACKAGE->value => (new NccCompiler($this))->build($build_configuration, $options),
BuildOutputType::EXECUTABLE->value => (new ExecutableCompiler($this))->build($build_configuration, $options),
default => throw new BuildException(sprintf('php cannot produce the build type \'%s\'', $configuration->getBuildType())),
},
default => throw new NotSupportedException(sprintf('The compiler extension \'%s\' is not supported', $this->project_configuration->getProject()->getCompiler()->getExtension())),
default => throw new NotSupportedException(sprintf('The compiler extension \'%s\' is not supported', $this->project_configuration->getProject()->getCompiler()->getExtension()->value)),
};
}
@ -185,11 +191,11 @@
{
switch(strtolower($template_name))
{
case ProjectTemplates::PHP_CLI:
case ProjectTemplates::PHP_CLI->value:
CliTemplate::applyTemplate($this);
break;
case ProjectTemplates::PHP_LIBRARY:
case ProjectTemplates::PHP_LIBRARY->value:
LibraryTemplate::applyTemplate($this);
break;
@ -203,15 +209,14 @@
*
* @param AuthenticationInterface|null $authentication
* @return array Array of installed packages
* @throws OperationException
* @throws IOException
* @throws ConfigurationException
* @throws IOException
* @throws OperationException
* @throws PathNotFoundException
* @throws NotSupportedException
*/
public function installDependencies(?AuthenticationInterface $authentication=null): array
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('Unable to install dependencies, you must be running as root');
}
@ -252,16 +257,12 @@
* Returns an array of file extensions for the components that are part of this project
*
* @return array
* @throws NotSupportedException
*/
public function getComponentFileExtensions(): array
{
return match ($this->getProjectConfiguration()->getProject()->getCompiler()->getExtension())
{
CompilerExtensions::PHP => ComponentFileExtensions::PHP,
default => throw new NotSupportedException(
sprintf('The compiler extension \'%s\' is not supported', $this->getProjectConfiguration()->getProject()->getCompiler()->getExtension())
),
CompilerExtensions::PHP => ['*.php', '*.php3', '*.php4', '*.php5', '*.phtml']
};
}
@ -275,7 +276,7 @@
* @throws IOException
* @throws PathNotFoundException
*/
public function getExecutionUnits(string $build_configuration=BuildConfigurationValues::DEFAULT): array
public function getExecutionUnits(string $build_configuration=BuildConfigurationValues::DEFAULT->value): array
{
$execution_units = [];
@ -299,9 +300,8 @@
*
* @param string $build_configuration
* @return array
* @throws NotSupportedException
*/
public function getComponents(string $build_configuration=BuildConfigurationValues::DEFAULT): array
public function getComponents(string $build_configuration=BuildConfigurationValues::DEFAULT->value): array
{
$configuration = $this->project_configuration->getBuild()->getBuildConfiguration($build_configuration);
@ -315,9 +315,8 @@
*
* @param string $build_configuration
* @return array
* @throws NotSupportedException
*/
public function getResources(string $build_configuration=BuildConfigurationValues::DEFAULT): array
public function getResources(string $build_configuration=BuildConfigurationValues::DEFAULT->value): array
{
$configuration = $this->project_configuration->getBuild()->getBuildConfiguration($build_configuration);
@ -334,14 +333,10 @@
* @param string $build_configuration
* @return array
*/
public function getRuntimeConstants(string $build_configuration=BuildConfigurationValues::DEFAULT): array
public function getConstants(string $build_configuration=BuildConfigurationValues::DEFAULT->value): array
{
$configuration = $this->project_configuration->getBuild()->getBuildConfiguration($build_configuration);
return array_merge(
$configuration->getDefineConstants(),
$this->project_configuration->getBuild()->getDefineConstants()
);
return array_merge($configuration->getDefineConstants(), $this->project_configuration->getBuild()->getDefineConstants());
}
/**
@ -361,7 +356,7 @@
* @param string $project_path The directory for the project to be initialized in
* @param string $name The name of the project eg; ProjectLib
* @param string $package The standard package name eg; com.example.project
* @param string $compiler The compiler to use for this project
* @param CompilerExtensions $extension The compiler to use for this project
* @param array $options An array of options to use when initializing the project
* @return ProjectManager
* @throws ConfigurationException
@ -369,7 +364,7 @@
* @throws NotSupportedException
* @throws PathNotFoundException
*/
public static function initializeProject(string $project_path, string $name, string $package, string $compiler, array $options=[]): ProjectManager
public static function initializeProject(string $project_path, string $name, string $package, CompilerExtensions $extension, array $options=[]): ProjectManager
{
if(str_ends_with($project_path, DIRECTORY_SEPARATOR))
{
@ -378,7 +373,7 @@
if(is_file($project_path . DIRECTORY_SEPARATOR . 'project.json'))
{
if(!isset($options[InitializeProjectOptions::OVERWRITE_PROJECT_FILE]))
if(!isset($options[InitializeProjectOptions::OVERWRITE_PROJECT_FILE->value]))
{
throw new IOException('A project has already been initialized in \'' . $project_path . DIRECTORY_SEPARATOR . 'project.json' . '\'');
}
@ -387,7 +382,7 @@
unlink($project_path . DIRECTORY_SEPARATOR . 'project.json');
}
$project_src = $options[InitializeProjectOptions::PROJECT_SRC_PATH] ?? ('src' . DIRECTORY_SEPARATOR . $name);
$project_src = $options[InitializeProjectOptions::PROJECT_SRC_PATH->value] ?? ('src' . DIRECTORY_SEPARATOR . $name);
if(str_ends_with($project_src, DIRECTORY_SEPARATOR))
{
$project_src = substr($project_src, 0, -1);
@ -406,17 +401,17 @@
// Generate the Debug & Release build configurations
$debug_configuration = new ProjectConfiguration\Build\BuildConfiguration('debug',
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE . '.ncc'
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE->value . '.ncc'
);
$debug_configuration->setDefinedConstant('DEBUG', '1');
$build->addBuildConfiguration(new ProjectConfiguration\Build\BuildConfiguration('release',
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE . '.ncc'
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE->value . '.ncc'
));
$build->addBuildConfiguration($debug_configuration);
$build->setDefaultConfiguration('release');
$project_configuration = new ProjectConfiguration(
new ProjectConfiguration\Project($compiler),
new ProjectConfiguration\Project($extension),
new ProjectConfiguration\Assembly($name, $package),
$build
);
@ -455,7 +450,7 @@
if(is_file($project_file))
{
if(!isset($options[InitializeProjectOptions::OVERWRITE_PROJECT_FILE]))
if(!isset($options[InitializeProjectOptions::OVERWRITE_PROJECT_FILE->value]))
{
throw new IOException('A project has already been initialized in \'' . $project_file . '\'');
}
@ -464,7 +459,7 @@
unlink($project_file);
}
if(!isset($options[InitializeProjectOptions::COMPOSER_PACKAGE_VERSION]))
if(!isset($options[InitializeProjectOptions::COMPOSER_PACKAGE_VERSION->value]))
{
throw new OperationException('Unable to initialize project from composer.json without a version option');
}
@ -485,11 +480,11 @@
throw new IOException(sprintf('Project source directory "%s" was not created', $project_src));
}
$project = new ProjectConfiguration\Project(new ProjectConfiguration\Compiler(CompilerExtensions::PHP));
$project = new ProjectConfiguration\Project(CompilerExtensions::PHP);
$assembly = new ProjectConfiguration\Assembly(
Resolver::composerName($composer_json->getName()),
Resolver::composerNameToPackage($composer_json->getName()),
$options[InitializeProjectOptions::COMPOSER_PACKAGE_VERSION]
$options[InitializeProjectOptions::COMPOSER_PACKAGE_VERSION->value]
);
$assembly->setDescription($composer_json->getDescription());
@ -610,44 +605,44 @@
$required_files[$index] = Functions::removeBasename($file, $project_path);
}
$build->setOption(BuildConfigurationOptions::REQUIRE_FILES, $required_files);
$build->setOption(BuildConfigurationOptions::REQUIRE_FILES->value, $required_files);
}
// Generate debug build configuration
$ncc_debug_configuration = new ProjectConfiguration\Build\BuildConfiguration('debug_ncc',
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE->value
);
$ncc_debug_configuration->setBuildType(BuildOutputType::NCC_PACKAGE);
$ncc_debug_configuration->setBuildType(BuildOutputType::NCC_PACKAGE->value);
$ncc_debug_configuration->setDependencies($require_dev);
$build->addBuildConfiguration($ncc_debug_configuration);
$executable_debug_configuration = new ProjectConfiguration\Build\BuildConfiguration('debug_executable',
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME
'build' . DIRECTORY_SEPARATOR . 'debug' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME->value
);
$executable_debug_configuration->setBuildType(BuildOutputType::EXECUTABLE);
$executable_debug_configuration->setOption(BuildConfigurationOptions::NCC_CONFIGURATION, 'debug_ncc');
$executable_debug_configuration->setBuildType(BuildOutputType::EXECUTABLE->value);
$executable_debug_configuration->setOption(BuildConfigurationOptions::NCC_CONFIGURATION->value, 'debug_ncc');
$executable_debug_configuration->setDependencies($require_dev);
$build->addBuildConfiguration($executable_debug_configuration);
// Generate release build configuration
$ncc_release_configuration = new ProjectConfiguration\Build\BuildConfiguration('release_ncc',
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE . 'ncc'
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_PACKAGE->value . 'ncc'
);
$ncc_release_configuration->setBuildType(BuildOutputType::NCC_PACKAGE);
$ncc_release_configuration->setBuildType(BuildOutputType::NCC_PACKAGE->value);
$build->addBuildConfiguration($ncc_release_configuration);
$executable_release_configuration = new ProjectConfiguration\Build\BuildConfiguration('release_executable',
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME
'build' . DIRECTORY_SEPARATOR . 'release' . DIRECTORY_SEPARATOR . AssemblyConstants::ASSEMBLY_NAME->value
);
$executable_release_configuration->setOption(BuildConfigurationOptions::NCC_CONFIGURATION, 'release_ncc');
$executable_release_configuration->setBuildType(BuildOutputType::EXECUTABLE);
$executable_release_configuration->setOption(BuildConfigurationOptions::NCC_CONFIGURATION->value, 'release_ncc');
$executable_release_configuration->setBuildType(BuildOutputType::EXECUTABLE->value);
$build->addBuildConfiguration($executable_release_configuration);
// Create an update source for the project
if(isset($options[InitializeProjectOptions::COMPOSER_REMOTE_SOURCE]))
if(isset($options[InitializeProjectOptions::COMPOSER_REMOTE_SOURCE->value]))
{
$project->setUpdateSource(new ProjectConfiguration\UpdateSource(
$options[InitializeProjectOptions::COMPOSER_REMOTE_SOURCE],
$options[InitializeProjectOptions::COMPOSER_REMOTE_SOURCE->value],
(new RepositoryManager())->getRepository('packagist')->getProjectRepository()
));
}
@ -680,14 +675,7 @@
$path = substr($path, 0, -1);
}
if($path === '')
{
$destination_path .= DIRECTORY_SEPARATOR . hash('crc32', $project_path);
}
else
{
$destination_path .= DIRECTORY_SEPARATOR . hash('crc32', $path);
}
$destination_path .= DIRECTORY_SEPARATOR . hash('crc32', $project_path);
if(is_file($source_path))
{

View file

@ -109,7 +109,7 @@
*/
public function addRepository(RepositoryConfiguration $source, bool $update=true): void
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must be running as root to add a new repository');
}
@ -119,7 +119,7 @@
throw new InvalidArgumentException(sprintf('The remote source \'%s\' already exists', $source->getName()));
}
Console::outVerbose(sprintf('Adding repository \'%s\' as %s (type: %s)', $source->getHost(), $source->getName(), $source->getType()));
Console::outVerbose(sprintf('Adding repository \'%s\' as %s (type: %s)', $source->getHost(), $source->getName(), $source->getType()->value));
$this->repositories[] = $source;
if($update)
@ -160,7 +160,7 @@
*/
public function removeRepository(string $name, bool $update=true): void
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must be running as root to delete a repository');
}
@ -195,7 +195,7 @@
*/
public function updateDatabase(): void
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must be running as root to update the repository database');
}
@ -221,7 +221,7 @@
*/
public static function initializeDatabase(array $default_repositories=[]): void
{
if(Resolver::resolveScope() !== Scopes::SYSTEM)
if(Resolver::resolveScope() !== Scopes::SYSTEM->value)
{
throw new OperationException('You must be running as root to initialize the repository database');
}

View file

@ -191,8 +191,8 @@
*/
public function __construct()
{
$this->type = ComposerPackageTypes::LIBRARY;
$this->minimum_stability = ComposerStabilityTypes::STABLE;
$this->type = ComposerPackageTypes::LIBRARY->value;
$this->minimum_stability = ComposerStabilityTypes::STABLE->value;
$this->abandoned = false;
}

View file

@ -26,7 +26,7 @@
namespace ncc\Objects\ComposerJson;
use ncc\Interfaces\SerializableObjectInterface;
use ncc\ThirdParty\composer\Semver\VersionParser;
use ncc\ThirdParty\composer\semver\VersionParser;
class PackageLink implements SerializableObjectInterface
{

Some files were not shown because too many files have changed in this diff Show more