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

136
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,136 @@
name: CI Pipeline
on:
push:
branches:
- '**'
pull_request:
branches:
- '**'
release:
types:
- created
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, ctype, common, zip
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y git libpq-dev libzip-dev zip make wget gnupg
- name: Install Phive
run: |
wget -O phive.phar https://phar.io/releases/phive.phar
wget -O phive.phar.asc https://phar.io/releases/phive.phar.asc
gpg --keyserver hkps://keys.openpgp.org --recv-keys 0x9D8A98B29B2D5D79
gpg --verify phive.phar.asc phive.phar
chmod +x phive.phar
sudo mv phive.phar /usr/local/bin/phive
- name: Install PHPAB
run: sudo phive install phpab --global --trust-gpg-keys 0x2A8299CE842DD38C
- name: Build project
run: make redist
- name: Find NCC build directory
id: find-ncc-dir
run: echo "NCC_DIR=$(find build/ -type d -name 'ncc_*' | head -n 1)" >> $GITHUB_ENV
- name: Upload NCC build directory
uses: actions/upload-artifact@v3
with:
name: ncc-build
path: ${{ env.NCC_DIR }}
- name: Create redist.zip
run: zip -r redist.zip ${{ env.NCC_DIR }}
- name: Upload redist.zip
uses: actions/upload-artifact@v3
with:
name: redist-zip
path: redist.zip
- name: Build Debian package
run: make deb
- name: Find Debian package
id: find-deb
run: echo "DEB_FILE=$(find build/ -type f -name '*.deb' | head -n 1)" >> $GITHUB_ENV
- name: Upload Debian package
uses: actions/upload-artifact@v3
with:
name: ncc-deb
path: ${{ env.DEB_FILE }}
test-install:
runs-on: ubuntu-latest
needs: build
steps:
- name: Download NCC build directory
uses: actions/download-artifact@v3
with:
name: ncc-build
path: build
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, ctype, common, zip
- name: Test NCC installation
run: |
ls -l build
sudo php build/INSTALL --auto
upload-release:
runs-on: ubuntu-latest
needs: build
if: github.event_name == 'release' && github.event.action == 'created'
permissions: write-all
steps:
- name: Download redist.zip
uses: actions/download-artifact@v3
with:
name: redist-zip
path: .
- name: Download Debian package
uses: actions/download-artifact@v3
with:
name: ncc-deb
path: .
- name: Set DEB_FILE environment variable
run: echo "DEB_FILE=$(find . -type f -name '*.deb' | head -n 1)" >> $GITHUB_ENV
- name: Upload redist.zip to release
uses: softprops/action-gh-release@v1
with:
files: redist.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload ncc.deb to release
uses: softprops/action-gh-release@v1
with:
files: ${{ env.DEB_FILE }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

6
.gitignore vendored
View file

@ -8,7 +8,7 @@
build build
# Autoload files # Autoload files
src/ncc/ThirdParty/composer/semver/autoload_spl.php src/ncc/ThirdParty/composer/Semver/autoload_spl.php
src/ncc/ThirdParty/defuse/php-encryption/autoload_spl.php src/ncc/ThirdParty/defuse/php-encryption/autoload_spl.php
src/ncc/ThirdParty/jelix/version/autoload_spl.php src/ncc/ThirdParty/jelix/version/autoload_spl.php
src/ncc/ThirdParty/nikic/PhpParser/autoload_spl.php src/ncc/ThirdParty/nikic/PhpParser/autoload_spl.php
@ -28,4 +28,6 @@ src/ncc/autoload.php
# Test files # Test files
tests/example_project/project.json tests/example_project/project.json
tests/example_project/ncc tests/example_project/ncc
tests/example_project/build tests/example_project/build
/.phpunit.result.cache
/.idea/php-test-framework.xml

8
.idea/php.xml generated
View file

@ -12,10 +12,9 @@
<component name="PhpIncludePathManager"> <component name="PhpIncludePathManager">
<include_path> <include_path>
<path value="/usr/share/php" /> <path value="/usr/share/php" />
<path value="$PROJECT_DIR$/../loglib" />
</include_path> </include_path>
</component> </component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.2"> <component name="PhpProjectSharedConfiguration" php_language_level="8.3">
<option name="suggestChangeDefaultLanguageLevel" value="false" /> <option name="suggestChangeDefaultLanguageLevel" value="false" />
</component> </component>
<component name="PhpRuntimeConfiguration"> <component name="PhpRuntimeConfiguration">
@ -26,6 +25,11 @@
<component name="PhpStanOptionsConfiguration"> <component name="PhpStanOptionsConfiguration">
<option name="transferred" value="true" /> <option name="transferred" value="true" />
</component> </component>
<component name="PhpUnit">
<phpunit_settings>
<PhpUnitSettings load_method="PHPUNIT_PHAR" custom_loader_path="" phpunit_phar_path="$USER_HOME$/phpunit.phar" />
</phpunit_settings>
</component>
<component name="PsalmOptionsConfiguration"> <component name="PsalmOptionsConfiguration">
<option name="transferred" value="true" /> <option name="transferred" value="true" />
</component> </component>

View file

@ -5,37 +5,92 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.1.0] - 2024-09-20
## [2.0.4] - 2023-10-25 This update introduces a refactored code-base, code quality improvements, and better exception handling.
This update introduces minor bug fixes.
### Added ### Added
- Added host resolving in network calls to improve the handling of invalid or unreachable URLs - Added Test unit tests/ncc/Objects/Package/ComponentTest.php
- Added the ability to use 'all' as a build configuration when running `ncc build`, to build all build configurations - Added Test unit tests/ncc/Utilities/ResolverTest.php
in the project. - Added Test unit tests/ncc/Utilities/SecurityTest.php
- Added Test unit tests/ncc/Utilities/ValidateTest.php
- Add support for runtime constants
### Changed ### Changed
- Update progress bar text to display basename only - Convert Versions constants to enum cases
- Updated exception handling in PackageReader - Update Scopes to enum and adjust scope checks
- Updated the Download function to attempt to retry the download upon an error for at least 3 times. - Convert Runners class to enum with string cases
- Convert RegexPatterns constants to enum cases
- Convert ProjectTemplates constants to enum cases
- Convert PackageStructureVersions constants to enum cases
- Convert PackageStructure constants to enum cases
- Convert PackageDirectory constants to enum cases
- Convert LogLevel constants to enum cases
- Convert FileDescriptor constants to enum cases
- Convert ExceptionCodes constants to enum cases
- Convert ConsoleColors constants to enum cases
- Convert CompilerExtensions constants to enum cases
- Convert RepositoryType constants to enum cases
- Convert RepositoryResultType constants to enum cases
- Convert ProjectType constants to enum cases
- Convert HttpRequestType constants to enum cases
- Convert ComposerStabilityTypes constants to enum cases
- Convert ComposerPackageTypes constants to enum cases
- Convert ComponentDataType constants to enum cases
- Convert BuildOutputType constants to enum cases
- Convert AuthenticationType constants to enum cases
- Convert RuntimeConstants constants to enum cases
- Convert InstallConstants constants to enum cases
- Convert DateTimeConstants constants to enum cases
- Convert BuildConstants constants to enum cases
- Convert AssemblyConstants constants to enum cases
- Convert ProjectOptions constants to enum cases
- Convert InstallPackageOptions constants to enum cases
- Convert InitializeProjectOptions constants to enum cases
- Convert ComponentDecodeOptions constants to enum cases
- Convert BuildConfigurationValues constants to enum cases
- Convert BuildConfigurationOptions constants to enum cases
- Convert CompressionOptions constants to enum cases
- Convert PackageFlags constants to enum cases
- Convert NccBuildFlags constants to enum cases
- Convert ComponentFlags constants to enum cases
- Refactor flag handling to use PackageFlags enum directly
- Refactor checkLogLevel to correctly utilize LogLevel cases
- Refactor code to improve readability in Resolver.php
- Update PHP include paths in project configuration
- Refactor logging level checks to use LogLevel enum directly
- Refactor log level parsing with enum method
- Refactor log level checking to enum method
- Updated Symfony/Filesystem from version 6.3.1 to 7.1.2
- Refactor ProjectType handling
- Validate and enforce repository type enum usage
- Updated Composer/Semver to 3.4.3
- Rename 'semver' directory to 'Semver' in composer package
- Refactor project constants handling in NccCompiler
- Updated Symfony/Yaml to version 7.1.4
- Updated Symfony/Uid to version 7.1.4
- Updated Symfony/Process to version 7.1.3
- Updated Symfony/polyfill-ctype to version 1.31.0
- Updated Symfony/polyfill-mbstring to version 1.31.0
- Updated Symfony/polyfill-uuid to version 1.31.0
- Updated nikic/PhpParser to version 5.2.0
### Fixed ### Fixed
- Improve build efficiency by preventing duplicate merges - Fixed Division by zero in PackageManager
- Updated file tracking in Runtime class - Fixed runner argument passing for ExecCommand
- Fixed division by zero in ConsoleProgressBar
- Fixed issue where progress bar is displayed in VERBOSE mode
- Set default process timeouts to null
- Fixed issue where a newline is sometimes added to the end of a download output due to how short the download process
was, mitigated the issue by enforcing a "done" update at the end of the download process
- Fixed issue where all development dependencies were not correctly being added to debug builds in composer projects,
instead these dependencies were added globally to the build configuration. This issue was fixed by adding all the
development dependencies to the debug build configurations only.
- Fixed issue when creating a shadow copy of a package, if the universe aligns together and the cosmos unit together to
produce a package length exactly to where the end-of-package byte sequence is cut in half, the shadow copy will fail
to be created due to the end-of-package byte sequence being cut in half, this issue was fixed by reading the package
in chunks to determine the end-of-package byte sequence.
### Removed
- Removed EncoderType enum file, unused.
- Removed PackageStandardVersions.php
- Removed ConstantReferences.php
- Removed HttpStatusCodes.php
- Removed CompilerExtensionDefaultVersions.php
- Removed RemoteSourceType
- Removed DependencySourceType
- Removed BuiltinRemoteSourceType
- Removed RuntimeImportOptions
- Remove ComponentFileExtensions enum
- Remove unused import and redundant scope validation method
## [2.0.3] - 2023-10-17 ## [2.0.3] - 2023-10-17
@ -47,12 +102,12 @@ The changes improve the system's efficiency, error resilience, and user experien
- Implemented support in the AST traversal for the PHP statements `include`, `include_once`, `require`, and - Implemented support in the AST traversal for the PHP statements `include`, `include_once`, `require`, and
`require_once`. These statements are transformed into function calls. With this change, ncc can correctly handle and `require_once`. These statements are transformed into function calls. With this change, ncc can correctly handle and
import files from system packages or direct binary package files. import files from system packages or direct binary package files.
- Added new `ConsoleProgressBar` class for UI improvement, improved the CLI Progress Bar inspired by - Added new `ConsoleProgressBar` class for UI improvement, imrpoved the CLI Progress Bar inspired by
[pacman](https://wiki.archlinux.org/title/pacman) [pacman](https://wiki.archlinux.org/title/pacman)
### Fixed ### Fixed
- When finding package versions in the package lock, ncc will try to find a satisfying version rather than the exact - When finding package versions in the package lock, ncc will try to find a satisfying version rather than the exact
version, this is to prevent errors when the package lock contains a version that is not available in the repository. version, this is to prevent[CHANGELOG.md](CHANGELOG.md) errors when the package lock contains a version that is not available in the repository.
- Fixed issue when registering ncc's extension, when using the INSTALLER, the installation path used in the process - Fixed issue when registering ncc's extension, when using the INSTALLER, the installation path used in the process
appears to be incorrect, added a optional parameter to the `registerExtension` method to allow the installer to pass appears to be incorrect, added a optional parameter to the `registerExtension` method to allow the installer to pass
the correct installation path. the correct installation path.

View file

@ -18,7 +18,7 @@ DEBIAN_PACKAGE_BUILD_PATH := $(BUILD_PATH)/ncc_$(BUILD_VERSION)_all.deb
# List of paths for autoloading # List of paths for autoloading
AUTOLOAD_PATHS := $(addprefix $(SRC_PATH)/ncc/ThirdParty/, \ AUTOLOAD_PATHS := $(addprefix $(SRC_PATH)/ncc/ThirdParty/, \
composer/semver \ composer/Semver \
defuse/php-encryption \ defuse/php-encryption \
jelix/version \ jelix/version \
nikic/PhpParser \ nikic/PhpParser \

9
bootstrap.php Normal file
View file

@ -0,0 +1,9 @@
<?php
$autoload_path = __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'ncc' . DIRECTORY_SEPARATOR . 'autoload.php';
if(!file_exists($autoload_path))
{
throw new Exception("Autoload file not found");
}
require $autoload_path;

11
phpunit.xml Normal file
View file

@ -0,0 +1,11 @@
<phpunit bootstrap="bootstrap.php">
<testsuites>
<testsuite name="ncc Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<php>
<ini name="error_reporting" value="-1"/>
<server name="KERNEL_DIR" value="app/"/>
</php>
</phpunit>

View file

@ -13,7 +13,7 @@
$third_party_path = __DIR__ . DIRECTORY_SEPARATOR . 'ThirdParty' . DIRECTORY_SEPARATOR; $third_party_path = __DIR__ . DIRECTORY_SEPARATOR . 'ThirdParty' . DIRECTORY_SEPARATOR;
$target_files = [ $target_files = [
__DIR__ . DIRECTORY_SEPARATOR . 'autoload_spl.php', __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 . '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 . 'jelix' . DIRECTORY_SEPARATOR . 'version' . DIRECTORY_SEPARATOR . 'autoload_spl.php',
$third_party_path . 'nikic' . DIRECTORY_SEPARATOR . 'PhpParser' . 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) if($output_path !== null)
{ {
$options[BuildConfigurationOptions::OUTPUT_FILE] = $output_path; $options[BuildConfigurationOptions::OUTPUT_FILE->value] = $output_path;
} }
// Load the project // Load the project
@ -89,43 +89,19 @@
return 1; return 1;
} }
$build_configuration = $args['config'] ?? $args['c'] ?? BuildConfigurationValues::DEFAULT; // Build the project
try
if($build_configuration === BuildConfigurationValues::ALL)
{ {
// Build all configurations $build_configuration = $args['config'] ?? $args['c'] ?? BuildConfigurationValues::DEFAULT->value;
foreach($project_manager->getProjectConfiguration()->getBuild()->getBuildConfigurations() as $configuration_name) $output = $project_manager->build($build_configuration, $options);
{
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);
}
} }
else catch (Exception $e)
{ {
// Build the project Console::outException('Failed to build project', $e, 1);
try return 1;
{
$output = $project_manager->build($build_configuration, $options);
}
catch (Exception $e)
{
Console::outException('Failed to build project', $e, 1);
return 1;
}
Console::out($output);
} }
Console::out($output);
return 0; return 0;
} }

View file

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

View file

@ -50,7 +50,12 @@
private static $args; private static $args;
/** /**
* @var string|null * @var array
*/
private static $raw_args;
/**
* @var LogLevel|null
*/ */
private static $log_level; private static $log_level;
@ -63,6 +68,7 @@
public static function start(array $argv): int public static function start(array $argv): int
{ {
self::$args = Resolver::parseArguments(implode(' ', $argv)); self::$args = Resolver::parseArguments(implode(' ', $argv));
self::$raw_args = $argv;
if(!isset(self::$args['ncc-cli'])) if(!isset(self::$args['ncc-cli']))
{ {
@ -91,30 +97,14 @@
if(isset(self::$args['l']) || isset(self::$args['log-level'])) if(isset(self::$args['l']) || isset(self::$args['log-level']))
{ {
switch(strtolower(self::$args['l'] ?? self::$args['log-level'])) self::$log_level = LogLevel::fromOrDefault(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;
}
} }
else else
{ {
self::$log_level = LogLevel::INFO; 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'); Console::outDebug('Debug logging enabled');
@ -125,12 +115,12 @@
Console::outDebug(sprintf('args: %s', json_encode(self::$args, JSON_UNESCAPED_SLASHES))); 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'); 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'); 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) if(self::$log_level === null)
{ {

View file

@ -101,7 +101,7 @@
if(isset($args['v'])) 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); Console::outError('Insufficient permissions, cannot modify configuration values', true, 1);
return 1; return 1;

View file

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

View file

@ -132,7 +132,7 @@
*/ */
private static function installPackage(array $args): int 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); Console::outError('You cannot install packages in a user scope, please run this command as root', true, 1);
return 1; return 1;
@ -155,17 +155,22 @@
if(isset($args['reinstall'])) if(isset($args['reinstall']))
{ {
$options[InstallPackageOptions::REINSTALL] = true; $options[InstallPackageOptions::REINSTALL->value] = true;
} }
if(isset($args['prefer-static']) || isset($args['static'])) if(isset($args['prefer-static']) || isset($args['static']))
{ {
$options[InstallPackageOptions::PREFER_STATIC] = true; $options[InstallPackageOptions::PREFER_STATIC->value] = true;
} }
if(isset($args['skip-dependencies'])) 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) if($authentication !== null)
@ -199,7 +204,7 @@
$authentication_entry = $entry->getPassword(); $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); $package_input = RemotePackageInput::fromString($package);
@ -388,7 +393,7 @@
*/ */
private static function uninstallPackage($args): int 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); Console::outError('You cannot uninstall packages in a user scope, please run this command as root', true, 1);
return 1; return 1;
@ -419,7 +424,7 @@
*/ */
private static function uninstallAllPackages(array $args): int 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); Console::outError('You cannot uninstall all packages in a user scope, please run this command as root', true, 1);
return 1; return 1;
@ -455,7 +460,7 @@
*/ */
private static function fixBrokenPackages(array $args): int 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); Console::outError('You cannot fix broken packages in a user scope, please run this command as root', true, 1);
return 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', '--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', '-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', '--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'], 'Uninstalls a specified ncc package'),
new CliHelpSection(['uninstall', '--package', '-p', '--version', '-v'], 'Uninstalls a specified ncc package version'), new CliHelpSection(['uninstall', '--package', '-p', '--version', '-v'], 'Uninstalls a specified ncc package version'),
new CliHelpSection(['uninstall-all'], 'Uninstalls all packages'), new CliHelpSection(['uninstall-all'], 'Uninstalls all packages'),

View file

@ -23,6 +23,7 @@
namespace ncc\CLI\Management; namespace ncc\CLI\Management;
use Exception; use Exception;
use ncc\Enums\CompilerExtensions;
use ncc\Enums\ProjectTemplates; use ncc\Enums\ProjectTemplates;
use ncc\Enums\Scopes; use ncc\Enums\Scopes;
use ncc\Managers\CredentialManager; use ncc\Managers\CredentialManager;
@ -102,7 +103,12 @@
if(isset($args['ext'])) 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 else
{ {
@ -134,7 +140,7 @@
*/ */
private static function installProject(array $args): int 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); Console::outError('You cannot install packages in a user scope, please run this command as root', true, 1);
return 1; return 1;
@ -292,9 +298,9 @@
} }
Console::out(PHP_EOL . 'Available Templates:'); 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; return 0;

View file

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

View file

@ -54,11 +54,11 @@
{ {
$bin = match($unit->getExecutionPolicy()->getRunner()) $bin = match($unit->getExecutionPolicy()->getRunner())
{ {
Runners::PHP => (new ExecutableFinder())->find('php'), Runners::PHP->value => (new ExecutableFinder())->find('php'),
Runners::BASH => (new ExecutableFinder())->find('bash'), Runners::BASH->value => (new ExecutableFinder())->find('bash'),
Runners::PYTHON => (new ExecutableFinder())->find('python'), Runners::PYTHON->value => (new ExecutableFinder())->find('python'),
Runners::LUA => (new ExecutableFinder())->find('lua'), Runners::LUA->value => (new ExecutableFinder())->find('lua'),
Runners::PERL => (new ExecutableFinder())->find('perl'), 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())) 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))); $execution_unit = ExecutionUnit::fromArray(ZiProto::decode(IO::fread($unit_path)));
return match ($execution_unit->getExecutionPolicy()->getRunner()) return match ($execution_unit->getExecutionPolicy()->getRunner())
{ {
Runners::PHP => PhpRunner::executeUnit($execution_unit, $args), Runners::PHP->value => PhpRunner::executeUnit($execution_unit, $args),
Runners::BASH => BashRunner::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())), 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()) return match ($execution_unit->getExecutionPolicy()->getRunner())
{ {
Runners::PHP => PhpRunner::executeUnit($execution_unit, $args, false), Runners::PHP->value => PhpRunner::executeUnit($execution_unit, $args, false),
Runners::BASH => BashRunner::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())), 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 * @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 try
{ {
@ -65,7 +65,7 @@
/** /**
* @inheritDoc * @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); return self::getReleasePackage($repository, $vendor, $project, $version, $authentication, $options);
} }
@ -112,7 +112,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -169,7 +169,7 @@
*/ */
private static function getTagArchive(RepositoryConfiguration $repository, string $group, string $project, string $tag, ?AuthenticationInterface $authentication=null): RepositoryResult 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); $tag = self::getLatestTag($repository, $group, $project, $authentication);
} }
@ -203,7 +203,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_URL => $endpoint, CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -212,11 +212,11 @@
if(isset($response['zipball_url'])) 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'])) 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 else
{ {
@ -270,7 +270,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_URL => $endpoint, CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers 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 private static function getReleasePackage(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null, array $options=[]): RepositoryResult
{ {
/** @noinspection DuplicatedCode */ /** @noinspection DuplicatedCode */
if($release === Versions::LATEST) if($release === Versions::LATEST->value)
{ {
$release = self::getLatestRelease($repository, $group, $project, $authentication); $release = self::getLatestRelease($repository, $group, $project, $authentication);
} }
@ -368,7 +368,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_URL => $endpoint, CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -383,7 +383,7 @@
$release, $group, $project)); $release, $group, $project));
} }
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC]); $static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC->value]);
$preferred_asset = null; $preferred_asset = null;
$fallback_asset = null; $fallback_asset = null;
@ -407,7 +407,7 @@
if($asset_url) if($asset_url)
{ {
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE, $release); $result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE->value, $release);
RuntimeCache::set($endpoint, $result); RuntimeCache::set($endpoint, $result);
return $result; return $result;
@ -437,7 +437,7 @@
private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null): RepositoryResult private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null): RepositoryResult
{ {
/** @noinspection DuplicatedCode */ /** @noinspection DuplicatedCode */
if ($release === Versions::LATEST) if ($release === Versions::LATEST->value)
{ {
$release = self::getLatestRelease($repository, $group, $project, $authentication); $release = self::getLatestRelease($repository, $group, $project, $authentication);
} }
@ -471,7 +471,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_URL => $endpoint, CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -480,11 +480,11 @@
if(isset($response['zipball_url'])) 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'])) 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 else
{ {
@ -515,7 +515,7 @@
break; 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:
if($authentication instanceof UsernamePassword) if($authentication instanceof UsernamePassword)
@ -524,7 +524,7 @@
break; 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; return $headers;

View file

@ -39,7 +39,6 @@
use ncc\Objects\Vault\Password\AccessToken; use ncc\Objects\Vault\Password\AccessToken;
use ncc\Objects\Vault\Password\UsernamePassword; use ncc\Objects\Vault\Password\UsernamePassword;
use ncc\Utilities\Console; use ncc\Utilities\Console;
use ncc\Utilities\Resolver;
use ncc\Utilities\RuntimeCache; use ncc\Utilities\RuntimeCache;
use RuntimeException; use RuntimeException;
@ -48,7 +47,7 @@
/** /**
* @inheritDoc * @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 try
{ {
@ -65,7 +64,7 @@
/** /**
* @inheritDoc * @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); return self::getReleasePackage($repository, $vendor, $project, $version, $authentication, $options);
} }
@ -103,16 +102,9 @@
$headers = self::injectAuthentication($authentication, $curl, $headers); $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, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -169,7 +161,7 @@
*/ */
private static function getTagArchive(RepositoryConfiguration $repository, string $group, string $project, string $tag, ?AuthenticationInterface $authentication = null): RepositoryResult 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); $tag = self::getLatestTag($repository, $group, $project, $authentication);
} }
@ -191,17 +183,10 @@
$headers = self::injectAuthentication($authentication, $curl, $headers); $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, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_NOBODY => true, CURLOPT_NOBODY => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers, CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true 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)); 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); curl_close($curl);
RuntimeCache::set($endpoint, $result); RuntimeCache::set($endpoint, $result);
@ -262,16 +247,9 @@
$headers = self::injectAuthentication($authentication, $curl, $headers); $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, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers 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 private static function getReleasePackage(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null, array $options=[]): RepositoryResult
{ {
/** @noinspection DuplicatedCode */ /** @noinspection DuplicatedCode */
if($release === Versions::LATEST) if($release === Versions::LATEST->value)
{ {
$release = self::getLatestRelease($repository, $group, $project, $authentication); $release = self::getLatestRelease($repository, $group, $project, $authentication);
} }
@ -353,18 +331,7 @@
$headers = self::injectAuthentication($authentication, $curl, $headers); $headers = self::injectAuthentication($authentication, $curl, $headers);
} }
$resolved_host = Resolver::getResolveOption($endpoint); curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value, CURLOPT_HTTPHEADER => $headers]);
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
]);
Console::outDebug(sprintf('Fetching release package for %s/%s/%s from %s', $group, $project, $release, $endpoint)); Console::outDebug(sprintf('Fetching release package for %s/%s/%s from %s', $group, $project, $release, $endpoint));
$response = self::processHttpResponse($curl, $group, $project); $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)); 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; $preferred_asset = null;
$fallback_asset = null; $fallback_asset = null;
@ -396,7 +363,7 @@
{ {
$asset_url = $target_asset['browser_download_url']; $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); RuntimeCache::set($endpoint, $result);
return $result; return $result;
@ -422,7 +389,7 @@
private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication = null): RepositoryResult private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication = null): RepositoryResult
{ {
/** @noinspection DuplicatedCode */ /** @noinspection DuplicatedCode */
if($release === Versions::LATEST) if($release === Versions::LATEST->value)
{ {
$release = self::getLatestRelease($repository, $group, $project, $authentication); $release = self::getLatestRelease($repository, $group, $project, $authentication);
} }
@ -446,16 +413,9 @@
$headers = self::injectAuthentication($authentication, $curl, $headers); $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, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -465,11 +425,11 @@
if(isset($response['zipball_url'])) 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'])) 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 else
{ {
@ -499,7 +459,7 @@
$headers[] = 'Authorization: Bearer ' . $authentication->getAccessToken(); $headers[] = 'Authorization: Bearer ' . $authentication->getAccessToken();
break; 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:
if($authentication instanceof UsernamePassword) if($authentication instanceof UsernamePassword)
@ -508,7 +468,7 @@
break; 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; return $headers;

View file

@ -48,7 +48,7 @@
/** /**
* @inheritDoc * @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 try
{ {
@ -65,7 +65,7 @@
/** /**
* @inheritDoc * @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); return self::getReleasePackage($repository, $vendor, $project, $version, $authentication, $options);
} }
@ -114,7 +114,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_URL => $endpoint, CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -172,7 +172,7 @@
*/ */
private static function getTagArchive(RepositoryConfiguration $repository, string $group, string $project, string $tag, ?AuthenticationInterface $authentication=null): RepositoryResult 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); $tag = self::getLatestTag($repository, $group, $project, $authentication);
} }
@ -205,7 +205,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_NOBODY => true, CURLOPT_NOBODY => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers, CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true 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)); 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); RuntimeCache::set($endpoint, $results);
return $results; return $results;
@ -274,7 +274,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers 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 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); $release = self::getLatestRelease($repository, $group, $project, $authentication);
} }
@ -364,12 +364,12 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
$response = self::processHttpResponse($curl, $group, $project); $response = self::processHttpResponse($curl, $group, $project);
$static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC]); $static_preferred = isset($options[InstallPackageOptions::PREFER_STATIC->value]);
$preferred_asset = null; $preferred_asset = null;
$fallback_asset = null; $fallback_asset = null;
@ -393,7 +393,7 @@
if ($asset_url) if ($asset_url)
{ {
$result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE, $release); $result = new RepositoryResult($asset_url, RepositoryResultType::PACKAGE->value, $release);
RuntimeCache::set($endpoint, $result); RuntimeCache::set($endpoint, $result);
return $result; return $result;
@ -422,7 +422,7 @@
private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null): RepositoryResult private static function getReleaseArchive(RepositoryConfiguration $repository, string $group, string $project, string $release, ?AuthenticationInterface $authentication=null): RepositoryResult
{ {
/** @noinspection DuplicatedCode */ /** @noinspection DuplicatedCode */
if($release === Versions::LATEST) if($release === Versions::LATEST->value)
{ {
$release = self::getLatestRelease($repository, $group, $project, $authentication); $release = self::getLatestRelease($repository, $group, $project, $authentication);
} }
@ -456,7 +456,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -476,11 +476,11 @@
if($asset['format'] === 'zip') 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') elseif($asset['format'] === 'tar')
{ {
$results = new RepositoryResult($asset['url'], RepositoryResultType::SOURCE, $release); $results = new RepositoryResult($asset['url'], RepositoryResultType::SOURCE->value, $release);
} }
else else
{ {
@ -507,23 +507,23 @@
{ {
switch($authentication->getAuthenticationType()) switch($authentication->getAuthenticationType())
{ {
case AuthenticationType::ACCESS_TOKEN: case AuthenticationType::ACCESS_TOKEN->value:
if($authentication instanceof AccessToken) if($authentication instanceof AccessToken)
{ {
$headers[] = 'Private-Token: ' . $authentication->getAccessToken(); $headers[] = 'Private-Token: ' . $authentication->getAccessToken();
break; 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) if($authentication instanceof UsernamePassword)
{ {
curl_setopt($curl, CURLOPT_USERPWD, $authentication->getUsername() . ':' . $authentication->getPassword()); curl_setopt($curl, CURLOPT_USERPWD, $authentication->getUsername() . ':' . $authentication->getPassword());
break; 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; return $headers;

View file

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

View file

@ -93,17 +93,17 @@
* @throws PathNotFoundException * @throws PathNotFoundException
* @noinspection UnusedFunctionResultInspection * @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 = []; $this->merged_dependencies = [];
$configuration = $this->project_manager->getProjectConfiguration()->getBuild()->getBuildConfiguration($build_configuration); $configuration = $this->project_manager->getProjectConfiguration()->getBuild()->getBuildConfiguration($build_configuration);
$configuration->setOptions(array_merge($configuration->getOptions(), $options)); $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( $package_path = ConstantCompiler::compileConstants(
$this->project_manager->getProjectConfiguration(), $configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE] $this->project_manager->getProjectConfiguration(), $configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE->value]
); );
} }
else else
@ -129,7 +129,7 @@
} }
// Debugging information // 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) foreach($this->project_manager->getProjectConfiguration()->getAssembly()->toArray() as $prop => $value)
{ {
@ -269,25 +269,25 @@
{ {
$package_writer = new PackageWriter($path); $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); $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); $package_writer->addFlag(PackageFlags::HIGH_COMPRESSION);
break; break;
case BuildConfigurationOptions\CompressionOptions::MEDIUM: case BuildConfigurationOptions\CompressionOptions::MEDIUM->value:
$package_writer->addFlag(PackageFlags::MEDIUM_COMPRESSION); $package_writer->addFlag(PackageFlags::MEDIUM_COMPRESSION);
break; break;
case BuildConfigurationOptions\CompressionOptions::LOW: case BuildConfigurationOptions\CompressionOptions::LOW->value:
$package_writer->addFlag(PackageFlags::LOW_COMPRESSION); $package_writer->addFlag(PackageFlags::LOW_COMPRESSION);
break; break;
default: 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 * @param string $build_configuration
* @return void * @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 = new Metadata($this->project_manager->getProjectConfiguration()->getProject()->getCompiler());
$metadata->addOptions($this->project_manager->getProjectConfiguration()->getBuild()->getOptions($build_configuration)); $metadata->addOptions($this->project_manager->getProjectConfiguration()->getBuild()->getOptions($build_configuration));
$metadata->addOptions($this->project_manager->getProjectConfiguration()->getProject()->getOptions()); $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->setUpdateSource($this->project_manager->getProjectConfiguration()->getProject()->getUpdateSource());
$metadata->setMainExecutionPolicy($this->project_manager->getProjectConfiguration()->getBuild()->getMain()); $metadata->setMainExecutionPolicy($this->project_manager->getProjectConfiguration()->getBuild()->getMain());
$metadata->setInstaller($this->project_manager->getProjectConfiguration()->getInstaller()); $metadata->setInstaller($this->project_manager->getProjectConfiguration()->getInstaller());
// Strip out 'output_file' build artifact. // 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 // Strip out 'static' build artifact, PackageFlags::STATIC_DEPENDENCIES is used instead
// Making this option redundant. // 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 */ /** @noinspection UnusedFunctionResultInspection */
$package_writer->setMetadata($metadata); $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); 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)); throw new IOException(sprintf('File \'%s\' is not a valid package file (invalid header)', $file_path));
} }
@ -231,7 +231,7 @@
*/ */
public function getFileVersion(): string 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 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 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 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 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)); 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])); 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])); return gzuncompress(fread($this->package_file, (int)$location[1]));
} }
@ -297,12 +297,12 @@
*/ */
public function getPointer(string $name): array 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)); 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]]; return [(int)$location[0], (int)$location[1]];
} }
@ -314,7 +314,7 @@
*/ */
public function exists(string $name): bool 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 public function getAssembly(): Assembly
{ {
$directory = sprintf('@%s', PackageDirectory::ASSEMBLY); $directory = sprintf('@%s', PackageDirectory::ASSEMBLY->value);
if(isset($this->cache[$directory])) if(isset($this->cache[$directory]))
{ {
return $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)); throw new ConfigurationException(sprintf('Assembly object not found in package \'%s\'', $this->package_path));
} }
@ -373,14 +373,14 @@
*/ */
public function getMetadata(): Metadata public function getMetadata(): Metadata
{ {
$directory = sprintf('@%s', PackageDirectory::METADATA); $directory = sprintf('@%s', PackageDirectory::METADATA->value);
if(isset($this->cache[$directory])) if(isset($this->cache[$directory]))
{ {
return $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)); throw new ConfigurationException(sprintf('Metadata object not found in package \'%s\'', $this->package_path));
} }
@ -411,14 +411,14 @@
*/ */
public function getInstaller(): ?Installer public function getInstaller(): ?Installer
{ {
$directory = sprintf('@%s', PackageDirectory::INSTALLER); $directory = sprintf('@%s', PackageDirectory::INSTALLER->value);
if(isset($this->cache[$directory])) if(isset($this->cache[$directory]))
{ {
return $this->cache[$directory]; return $this->cache[$directory];
} }
if(!isset($this->headers[PackageStructure::DIRECTORY][$directory])) if(!isset($this->headers[PackageStructure::DIRECTORY->value][$directory]))
{ {
return null; return null;
} }
@ -444,9 +444,9 @@
public function getDependencies(): array public function getDependencies(): array
{ {
$dependencies = []; $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)) if(str_starts_with($name, $directory))
{ {
@ -467,8 +467,8 @@
*/ */
public function getDependency(string $name): Dependency public function getDependency(string $name): Dependency
{ {
$dependency_name = sprintf('@%s:%s', PackageDirectory::DEPENDENCIES, $name); $dependency_name = sprintf('@%s:%s', PackageDirectory::DEPENDENCIES->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$dependency_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)); throw new ConfigurationException(sprintf('Dependency \'%s\' not found in package \'%s\'', $name, $this->package_path));
} }
@ -511,9 +511,9 @@
public function getExecutionUnits(): array public function getExecutionUnits(): array
{ {
$execution_units = []; $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)) if(str_starts_with($name, $directory))
{ {
@ -534,8 +534,8 @@
*/ */
public function getExecutionUnit(string $name): ExecutionUnit public function getExecutionUnit(string $name): ExecutionUnit
{ {
$execution_unit_name = sprintf('@%s:%s', PackageDirectory::EXECUTION_UNITS, $name); $execution_unit_name = sprintf('@%s:%s', PackageDirectory::EXECUTION_UNITS->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$execution_unit_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)); throw new ConfigurationException(sprintf('Execution unit \'%s\' not found in package \'%s\'', $name, $this->package_path));
} }
@ -578,9 +578,9 @@
public function getComponents(): array public function getComponents(): array
{ {
$components = []; $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)) if(str_starts_with($name, $directory))
{ {
@ -599,9 +599,9 @@
public function getClassMap(): array public function getClassMap(): array
{ {
$class_map = []; $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)) if(str_starts_with($name, $directory))
{ {
@ -622,8 +622,8 @@
*/ */
public function getComponent(string $name): Component public function getComponent(string $name): Component
{ {
$component_name = sprintf('@%s:%s', PackageDirectory::COMPONENTS, $name); $component_name = sprintf('@%s:%s', PackageDirectory::COMPONENTS->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$component_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)); 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 public function getComponentByClass(string $class): Component
{ {
$class_name = sprintf('@%s:%s', PackageDirectory::CLASS_POINTER, $class); $class_name = sprintf('@%s:%s', PackageDirectory::CLASS_POINTER->value, $class);
if(!isset($this->headers[PackageStructure::DIRECTORY][$class_name])) 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)); throw new ConfigurationException(sprintf('Class map \'%s\' not found in package \'%s\'', $class, $this->package_path));
} }
@ -692,9 +692,9 @@
public function getResources(): array public function getResources(): array
{ {
$resources = []; $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)) if(str_starts_with($name, $directory))
{ {
@ -715,8 +715,8 @@
*/ */
public function getResource(string $name): Resource public function getResource(string $name): Resource
{ {
$resource_name = sprintf('@%s:%s', PackageDirectory::RESOURCES, $name); $resource_name = sprintf('@%s:%s', PackageDirectory::RESOURCES->value, $name);
if(!isset($this->headers[PackageStructure::DIRECTORY][$resource_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)); 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 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)) if(str_ends_with($name, $filename))
{ {

View file

@ -25,6 +25,7 @@
namespace ncc\Classes; namespace ncc\Classes;
use InvalidArgumentException;
use ncc\Enums\Flags\PackageFlags; use ncc\Enums\Flags\PackageFlags;
use ncc\Enums\PackageDirectory; use ncc\Enums\PackageDirectory;
use ncc\Enums\PackageStructure; use ncc\Enums\PackageStructure;
@ -108,9 +109,9 @@
$this->temp_file = @fopen($this->temporary_path, 'wb'); // Create a temporary data file $this->temp_file = @fopen($this->temporary_path, 'wb'); // Create a temporary data file
$this->package_file = @fopen($file_path, 'wb'); $this->package_file = @fopen($file_path, 'wb');
$this->headers = [ $this->headers = [
PackageStructure::FILE_VERSION => PackageStructureVersions::_2_0, PackageStructure::FILE_VERSION->value => PackageStructureVersions::_2_0->value,
PackageStructure::FLAGS => [], PackageStructure::FLAGS->value => [],
PackageStructure::DIRECTORY => [] PackageStructure::DIRECTORY->value => []
]; ];
if($this->temp_file === false || $this->package_file === false) if($this->temp_file === false || $this->package_file === false)
@ -126,7 +127,7 @@
*/ */
public function getFileVersion(): string 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 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 public function getFlags(): array
{ {
return (array)$this->headers[PackageStructure::FLAGS]; return (array)$this->headers[PackageStructure::FLAGS->value];
} }
/** /**
* Sets the package flags * Sets the package flags
* *
* @param array $flags * @param string[]|PackageFlags[] $flags
* @return void * @return void
* @throws IOException * @throws IOException
*/ */
@ -164,26 +165,47 @@
throw new IOException('Cannot set flags after data has been written to the package'); 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 * Adds a flag to the package
* *
* @param string $flag * @param PackageFlags|string $flag
* @return void * @return void
* @throws IOException * @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) if($this->data_written)
{ {
throw new IOException('Cannot add a flag after data has been written to the package'); 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 * @return void
* @throws IOException * @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) if($this->data_written)
{ {
throw new IOException('Cannot remove a flag after data has been written to the package'); 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 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); $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); $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); $data = gzcompress($data, 9);
} }
@ -239,7 +270,7 @@
} }
$pointer = sprintf("%d:%d", ftell($this->temp_file), strlen($data)); $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; $this->data_written = true;
fwrite($this->temp_file, $data); fwrite($this->temp_file, $data);
@ -256,12 +287,12 @@
*/ */
public function addPointer(string $name, int $offset, int $length): void 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; 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 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 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 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 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 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 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 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 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)) switch((int)substr(explode(':', $name, 2)[0], 1))
{ {
case PackageDirectory::METADATA: case PackageDirectory::METADATA->value:
case PackageDirectory::ASSEMBLY: case PackageDirectory::ASSEMBLY->value:
case PackageDirectory::INSTALLER: case PackageDirectory::INSTALLER->value:
case PackageDirectory::EXECUTION_UNITS: case PackageDirectory::EXECUTION_UNITS->value:
Console::outDebug(sprintf('Skipping %s', $name)); Console::outDebug(sprintf('Skipping %s', $name));
break; break;

View file

@ -35,8 +35,8 @@
use ncc\Interfaces\RepositoryInterface; use ncc\Interfaces\RepositoryInterface;
use ncc\Objects\RepositoryConfiguration; use ncc\Objects\RepositoryConfiguration;
use ncc\Objects\RepositoryResult; use ncc\Objects\RepositoryResult;
use ncc\ThirdParty\composer\Semver\Comparator; use ncc\ThirdParty\composer\semver\Comparator;
use ncc\ThirdParty\composer\Semver\Semver; use ncc\ThirdParty\composer\semver\Semver;
use ncc\Utilities\Console; use ncc\Utilities\Console;
use ncc\Utilities\Resolver; use ncc\Utilities\Resolver;
use ncc\Utilities\RuntimeCache; use ncc\Utilities\RuntimeCache;
@ -47,9 +47,9 @@
/** /**
* @inheritDoc * @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); $version = self::getLatestVersion($repository, $vendor, $project);
} }
@ -80,7 +80,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers 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)); 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 * @inheritDoc
* @throws NotSupportedException * @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'); throw new NotSupportedException('Fetching ncc packages from Packagist is not supported');
} }
@ -147,7 +147,7 @@
curl_setopt_array($curl, [ curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => HttpRequestType::GET, CURLOPT_CUSTOMREQUEST => HttpRequestType::GET->value,
CURLOPT_HTTPHEADER => $headers CURLOPT_HTTPHEADER => $headers
]); ]);
@ -178,23 +178,21 @@
{ {
$versions = self::getVersions($repository, $vendor, $project); $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) $versions = array_filter($versions, static function($version)
{ {
return !preg_match('/-alpha|-beta|-rc|dev/i', $version); return !preg_match('/-alpha|-beta|-rc|dev/i', $version);
}); });
usort($versions, static function($a, $b) // Sort versions in descending order using Semver::rsort
{ $versions = Semver::rsort($versions);
return Comparator::lessThanOrEqualTo($a, $b) ? 1 : -1;
});
if($versions[0] === null) if (!isset($versions[0]))
{ {
throw new NetworkException(sprintf('Failed to resolve latest version for %s/%s', $vendor, $project)); 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 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 * Returns an array of classes associated with the node recursively
* *
@ -112,161 +91,4 @@
return $classes; 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 * @inheritDoc
* @throws BuildException * @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); $configuration = $this->getProjectManager()->getProjectConfiguration()->getBuild()->getBuildConfiguration($build_configuration);
@ -50,14 +50,14 @@
$configuration->setOptions(array_merge($configuration->getOptions(), $options)); $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)); 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 // Build the ncc package first
Console::outVerbose('Building ncc package.'); 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 // Prepare the ncc package for compilation
$hex_dump_file = PathFinder::getCachePath() . DIRECTORY_SEPARATOR . $this->getProjectManager()->getProjectConfiguration()->getAssembly()->getName() . '.c'; $hex_dump_file = PathFinder::getCachePath() . DIRECTORY_SEPARATOR . $this->getProjectManager()->getProjectConfiguration()->getAssembly()->getName() . '.c';
@ -72,11 +72,11 @@
// Prepare the gcc command // Prepare the gcc command
$gcc_path = (new ExecutableFinder())->find('gcc'); $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( $binary_path = ConstantCompiler::compileConstants(
$this->getProjectManager()->getProjectConfiguration(), $this->getProjectManager()->getProjectConfiguration(),
$configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE] $configuration->getOptions()[BuildConfigurationOptions::OUTPUT_FILE->value]
); );
} }
else else

View file

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

View file

@ -44,7 +44,7 @@
*/ */
public static function executeUnit(ExecutionUnit $unit, array $args=[], bool $local=true): int 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())); 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 public static function applyTemplate(ProjectManager $project_manager): void
{ {
$project_manager->getProjectConfiguration()->addExecutionPolicy( $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()->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 // Create the release build configuration
$release_executable = new BuildConfiguration('release_executable', $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->setBuildType(BuildOutputType::EXECUTABLE->value);
$release_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION, 'release'); $release_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION->value, 'release');
$project_manager->getProjectConfiguration()->getBuild()->addBuildConfiguration($release_executable); $project_manager->getProjectConfiguration()->getBuild()->addBuildConfiguration($release_executable);
// Create the debug build configuration // Create the debug build configuration
$debug_executable = new BuildConfiguration('debug_executable', $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->setDefinedConstant('DEBUG', '1');
$debug_executable->setBuildType(BuildOutputType::EXECUTABLE); $debug_executable->setBuildType(BuildOutputType::EXECUTABLE->value);
$debug_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION, 'debug'); $debug_executable->setOption(BuildConfigurationOptions::NCC_CONFIGURATION->value, 'debug');
$project_manager->getProjectConfiguration()->getBuild()->addBuildConfiguration($debug_executable); $project_manager->getProjectConfiguration()->getBuild()->addBuildConfiguration($debug_executable);
self::writeProgramTemplate($project_manager); self::writeProgramTemplate($project_manager);

View file

@ -44,9 +44,11 @@
use ncc\Utilities\Console; use ncc\Utilities\Console;
use ncc\Utilities\IO; use ncc\Utilities\IO;
use ncc\Utilities\Resolver; use ncc\Utilities\Resolver;
use ncc\Utilities\RuntimeCache;
use ncc\Utilities\Validate; use ncc\Utilities\Validate;
use RuntimeException; use RuntimeException;
use Throwable; use Throwable;
use function trigger_error;
class Runtime class Runtime
{ {
@ -82,7 +84,7 @@
* @throws PathNotFoundException * @throws PathNotFoundException
* @throws OperationException * @throws OperationException
*/ */
public static function execute(string $package): int public static function execute(string $package, array $arguments=[]): int
{ {
if(!self::isImported($package)) if(!self::isImported($package))
{ {
@ -99,7 +101,7 @@
if(is_string(self::$imported_packages[$package])) 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)) if(!is_file($metadata_path))
{ {
@ -108,7 +110,8 @@
return ExecutionUnitRunner::executeFromSystem( return ExecutionUnitRunner::executeFromSystem(
self::$imported_packages[$package], 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 * @return string
* @throws ImportException * @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)) 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 NotSupportedException
* @throws PathNotFoundException * @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)) if(!self::getPackageManager()->getPackageLock()->entryExists($package))
{ {
@ -189,27 +192,81 @@
self::$class_map[strtolower($class)] = $component_path; 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 try
{ {
// Get the file contents and prepare it if(!file_exists($required_file))
$required_file = IO::fread($entry->getPath($version) . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . $item); {
$required_file = preg_replace('/^<\?php|<\?PHP/', '', $required_file, 1); throw new PathNotFoundException($required_file);
}
eval($required_file); // Get the file contents and prepare it
unset($required_file); $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 // Fake import the dependencies
foreach($entry->getVersion($version)->getDependencies() as $dependency) foreach($entry->getVersion($version)->getDependencies() as $dependency)
@ -273,9 +330,9 @@
} }
// Import the required files // 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 try
{ {
@ -288,7 +345,7 @@
} }
} }
if($package_reader->getFlag(PackageFlags::STATIC_DEPENDENCIES)) if($package_reader->getFlag(PackageFlags::STATIC_DEPENDENCIES->value))
{ {
// Fake import the dependencies // Fake import the dependencies
foreach($package_reader->getDependencies() as $dependency_name) foreach($package_reader->getDependencies() as $dependency_name)
@ -480,8 +537,8 @@
return match (Resolver::componentType($acquired_file)) return match (Resolver::componentType($acquired_file))
{ {
PackageDirectory::RESOURCES => self::$imported_packages[$package]->getResource(Resolver::componentName($acquired_file))->getData(), PackageDirectory::RESOURCES->value => 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::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)), 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 final class CompilerExtensionSupportedVersions
{ {
// TODO: Cannot convert this to enum, try another way
public const PHP = ['8.0', '8.1', '8.2']; public const PHP = ['8.0', '8.1', '8.2'];
} }

View file

@ -22,11 +22,7 @@
namespace ncc\Enums; namespace ncc\Enums;
final class CompilerExtensions enum CompilerExtensions : string
{ {
public const PHP = 'php'; case PHP = 'php';
public const ALL = [
CompilerExtensions::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; 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 * @author Zi Xing Narrakas
* @copyright Copyright (C) 2022-2023. Nosial - All Rights Reserved. * @copyright Copyright (C) 2022-2023. Nosial - All Rights Reserved.
*/ */
final class ExceptionCodes enum ExceptionCodes : int
{ {
/** /**
* @see RuntimeException * @see RuntimeException
*/ */
public const RUNTIME = -1706; case RUNTIME = -1706;
/** /**
* @see BuildException * @see BuildException
*/ */
public const BUILD_EXCEPTION = -1727; case BUILD_EXCEPTION = -1727;
/** /**
* @see IOException * @see IOException
*/ */
public const IO_EXCEPTION = -1735; case IO_EXCEPTION = -1735;
/** /**
* @see ComposerException * @see ComposerException
*/ */
public const COMPOSER_EXCEPTION = -1749; case COMPOSER_EXCEPTION = -1749;
/** /**
* @see AuthenticationException * @see AuthenticationException
*/ */
public const AUTHENTICATION_EXCEPTION = -1760; case AUTHENTICATION_EXCEPTION = -1760;
/** /**
* @see NotSupportedException * @see NotSupportedException
*/ */
public const NOT_SUPPORTED_EXCEPTION = -1761; case NOT_SUPPORTED_EXCEPTION = -1761;
/** /**
* @see ArchiveException * @see ArchiveException
*/ */
public const ARCHIVE_EXCEPTION = -1764; case ARCHIVE_EXCEPTION = -1764;
/** /**
* @see PathNotFoundException * @see PathNotFoundException
*/ */
public const PATH_NOT_FOUND = -1769; case PATH_NOT_FOUND = -1769;
/** /**
* @see GitException * @see GitException
*/ */
public const GIT_EXCEPTION = -1770; case GIT_EXCEPTION = -1770;
/** /**
* @see ConfigurationException * @see ConfigurationException
*/ */
public const CONFIGURATION_EXCEPTION = -1772; case CONFIGURATION_EXCEPTION = -1772;
/** /**
* @see PackageException * @see PackageException
*/ */
public const PACKAGE_EXCEPTION = -1773; case PACKAGE_EXCEPTION = -1773;
/** /**
* @see NetworkException * @see NetworkException
*/ */
public const NETWORK_EXCEPTION = -1774; case NETWORK_EXCEPTION = -1774;
/** /**
* @see IntegrityException * @see IntegrityException
*/ */
public const INTEGRITY_EXCEPTION = -1775; case INTEGRITY_EXCEPTION = -1775;
/** /**
* @see OperationException * @see OperationException
*/ */
public const OPERATION_EXCEPTION = -1776; case OPERATION_EXCEPTION = -1776;
public const IMPORT_EXCEPTION = -1777;
/** /**
* All the exception codes from NCC * @see ImportException
*/ */
public const All = [ case IMPORT_EXCEPTION = -1777;
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
];
} }

View file

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

View file

@ -22,16 +22,16 @@
namespace ncc\Enums\Flags; namespace ncc\Enums\Flags;
final class NccBuildFlags enum NccBuildFlags : string
{ {
/** /**
* Indicates if the build is currently unstable and some features may not work correctly * Indicates if the build is currently unstable and some features may not work correctly
* and can cause errors * and can cause errors
*/ */
public const UNSTABLE = 'unstable'; case UNSTABLE = 'unstable';
/** /**
* Indicates if the build is currently in beta testing phase * 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; 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; 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, * Checks if the current log level permits logging at the specified level.
self::VERBOSE, *
self::DEBUG, * @param LogLevel|null $current_level The log level to be checked. If null, the method returns false.
self::INFO, * @return bool Returns true if logging is permitted at the specified level, otherwise false.
self::WARNING, */
self::ERROR, public function checkLogLevel(?LogLevel $current_level): bool
self::FATAL, {
]; 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; 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; 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; 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; 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; namespace ncc\Enums\Options;
final class InitializeProjectOptions enum InitializeProjectOptions : string
{ {
/** /**
* A custom path to the project's source directory * 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 * 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 * 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 * 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; namespace ncc\Enums\Options;
final class InstallPackageOptions enum InstallPackageOptions : string
{ {
/** /**
* Skips the installation of dependencies of the package * Skips the installation of dependencies of the package
@ -30,17 +30,23 @@
* @warning This will cause the package to fail to import of * @warning This will cause the package to fail to import of
* the dependencies are not met * the dependencies are not met
*/ */
public const SKIP_DEPENDENCIES = 'skip_dependencies'; case SKIP_DEPENDENCIES = 'skip-dependencies';
/** /**
* Reinstall all packages if they are already installed, * Reinstall all packages if they are already installed,
* Including dependencies if they are being processed. * 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 * Installs a static version of the package if it's available
* otherwise it will install non-static version * 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; 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; 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; 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 <?php
/* /*
* Copyright (c) Nosial 2022-2023, all rights reserved. * 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 * 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 * 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 * 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 * Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions: * conditions:
* *
* The above copyright notice and this permission notice shall be included in all copies or substantial portions * The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software. * of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * 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 * 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 * 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 * 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 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE. * DEALINGS IN THE SOFTWARE.
* *
*/ */
namespace ncc\Enums; namespace ncc\Enums;
final class PackageStructureVersions enum PackageStructureVersions : string
{ {
/** /**
* ncc 1.0.0 to 1.0.3 * 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 * ncc 1.0.4 and above
*/ */
public const _2_0 = '2.0'; case _2_0 = '2.0';
/**
* All supported versions
*/
public const ALL = [
self::_1_0,
self::_2_0
];
} }

View file

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

View file

@ -26,27 +26,27 @@
* @author Zi Xing Narrakas * @author Zi Xing Narrakas
* @copyright Copyright (C) 2022-2023. Nosial - All Rights Reserved. * @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> * @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; 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'; case LUA = 'lua';
public const ALL = [
self::PHP,
self::BASH,
self::PYTHON,
self::PYTHON_3,
self::PYTHON_2,
self::PERL,
self::LUA
];
} }

View file

@ -22,9 +22,9 @@
namespace ncc\Enums; 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; namespace ncc\Enums\SpecialConstants;
final class AssemblyConstants enum AssemblyConstants : string
{ {
/** /**
* Assembly's Name Property * Assembly's Name Property
*/ */
public const ASSEMBLY_NAME = '%ASSEMBLY.NAME%'; case ASSEMBLY_NAME = '%ASSEMBLY.NAME%';
/** /**
* Assembly's Package Property * Assembly's Package Property
*/ */
public const ASSEMBLY_PACKAGE = '%ASSEMBLY.PACKAGE%'; case ASSEMBLY_PACKAGE = '%ASSEMBLY.PACKAGE%';
/** /**
* Assembly's Description Property * Assembly's Description Property
*/ */
public const ASSEMBLY_DESCRIPTION = '%ASSEMBLY.DESCRIPTION%'; case ASSEMBLY_DESCRIPTION = '%ASSEMBLY.DESCRIPTION%';
/** /**
* Assembly's Company Property * Assembly's Company Property
*/ */
public const ASSEMBLY_COMPANY = '%ASSEMBLY.COMPANY%'; case ASSEMBLY_COMPANY = '%ASSEMBLY.COMPANY%';
/** /**
* Assembly's Product Property * Assembly's Product Property
*/ */
public const ASSEMBLY_PRODUCT = '%ASSEMBLY.PRODUCT%'; case ASSEMBLY_PRODUCT = '%ASSEMBLY.PRODUCT%';
/** /**
* Assembly's Copyright Property * Assembly's Copyright Property
*/ */
public const ASSEMBLY_COPYRIGHT = '%ASSEMBLY.COPYRIGHT%'; case ASSEMBLY_COPYRIGHT = '%ASSEMBLY.COPYRIGHT%';
/** /**
* Assembly's Trademark Property * Assembly's Trademark Property
*/ */
public const ASSEMBLY_TRADEMARK = '%ASSEMBLY.TRADEMARK%'; case ASSEMBLY_TRADEMARK = '%ASSEMBLY.TRADEMARK%';
/** /**
* Assembly's Version Property * Assembly's Version Property
*/ */
public const ASSEMBLY_VERSION = '%ASSEMBLY.VERSION%'; case ASSEMBLY_VERSION = '%ASSEMBLY.VERSION%';
/** /**
* Assembly's UUID property * 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; namespace ncc\Enums\SpecialConstants;
final class BuildConstants enum BuildConstants : string
{ {
/** /**
* The Unix Timestamp for when the package was compiled * 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 * 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 * NCC Build Flags exploded into spaces
*/ */
public const NCC_BUILD_FLAGS = '%NCC_BUILD_FLAGS%'; case NCC_BUILD_FLAGS = '%NCC_BUILD_FLAGS%';
/** /**
* NCC Build Branch * 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; namespace ncc\Enums\SpecialConstants;
final class DateTimeConstants enum DateTimeConstants : string
{ {
// Day Format // Day Format
/** /**
* Day of the month, 2 digits with leading zeros * 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 * 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 * 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 * 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 * 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 * 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 * 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) * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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, * ISO 8601 week-numbering year. This has the same value as Y,
* except that if the ISO week number (W) belongs to the previous * except that if the ISO week number (W) belongs to the previous
* or next year, that year is used instead. * 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. * 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 * A two digit representation of a year
*/ */
public const y = '%y%'; // 91, 12, 14, ... case y = '%y%'; // 91, 12, 14, ...
// Time Format // Time Format
/** /**
* Lowercase Ante meridiem and Post meridiem * 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 * Uppercase Ante meridiem and Post meridiem
*/ */
public const A = '%A%'; // AM or PM case A = '%A%'; // AM or PM
/** /**
* Swatch Internet time * 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 * 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 * 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 * 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 * 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 * Minutes with leading zeros
*/ */
public const i = '%i%'; // 01 through 59 case i = '%i%'; // 01 through 59
/** /**
* Seconds with leading zeros * Seconds with leading zeros
*/ */
public const s = '%s%'; // 00 through 59 case s = '%s%'; // 00 through 59
// DateTime format // DateTime format
public const c = '%c%'; // 2004-02-12T15:19:21 case c = '%c%'; // 2004-02-12T15:19:21
public const r = '%r%'; // Thu, 21 Dec 2000 16:01:07 case r = '%r%'; // Thu, 21 Dec 2000 16:01:07
public const u = '%u%'; // Unix Timestamp (seconds since Jan 1 1970 00:00:00) case u = '%u%'; // Unix Timestamp (seconds since Jan 1 1970 00:00:00)
} }

View file

@ -22,13 +22,13 @@
namespace ncc\Enums\SpecialConstants; 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; namespace ncc\Enums\SpecialConstants;
final class RuntimeConstants enum RuntimeConstants : string
{ {
public const CWD = '%CWD%'; case CWD = '%CWD%';
public const PID = '%PID%'; case PID = '%PID%';
public const UID = '%UID%'; case UID = '%UID%';
public const GID = '%GID%'; case GID = '%GID%';
public const USER = '%USER%'; case USER = '%USER%';
} }

View file

@ -22,15 +22,15 @@
namespace ncc\Enums\Types; namespace ncc\Enums\Types;
final class AuthenticationType enum AuthenticationType : int
{ {
/** /**
* A combination of a username and password is used for authentication * 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 * 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; namespace ncc\Enums\Types;
final class BuildOutputType enum BuildOutputType : string
{ {
public const NCC_PACKAGE = 'ncc'; case NCC_PACKAGE = 'ncc';
public const EXECUTABLE = 'executable'; 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; namespace ncc\Enums\Types;
final class ComponentDataType enum ComponentDataType : string
{ {
/** /**
* Indicates whether the component is represented as an AST representation * 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 * 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 * 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) * Indicates whether the component is represented as as a base64 encoded string (Raw bytes' representation)
*/ */
public const BASE64_ENCODED = 'b64enc'; case BASE64_ENCODED = 'b64enc';
/**
* All the possible data types of a component
*/
public const ALL = [
self::AST,
self::PLAIN,
self::BINARY,
self::BASE64_ENCODED
];
} }

View file

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

View file

@ -22,14 +22,9 @@
namespace ncc\Enums\Types; namespace ncc\Enums\Types;
final class ProjectType enum ProjectType : string
{ {
public const COMPOSER = 'composer'; case COMPOSER = 'composer';
public const NCC = 'ncc'; case NCC = 'ncc';
public const ALL = [
self::COMPOSER,
self::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; 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; 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'; case PACKAGIST = 'packagist';
public const ALL = [
self::GITLAB,
self::GITHUB,
self::GITEA,
self::PACKAGIST
];
} }

View file

@ -22,25 +22,15 @@
namespace ncc\Enums; namespace ncc\Enums;
final class Versions enum Versions : string
{ {
/** /**
* The current version of the credentials store file format * The current version of the credentials store file format
*/ */
public const CREDENTIALS_STORE_VERSION = '1.0.0'; case 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';
/** /**
* Generic version of the package structure file format (latest) * 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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; $this->path = $path;
} }

View file

@ -35,6 +35,6 @@ namespace ncc\Exceptions;
*/ */
public function __construct(string $message = "", ?Throwable $previous = null) 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; namespace ncc\Interfaces;
use ncc\Enums\Types\AuthenticationType;
interface AuthenticationInterface extends BytecodeObjectInterface interface AuthenticationInterface extends BytecodeObjectInterface
{ {
/** /**
* @return string * @return AuthenticationType
*/ */
public function getAuthenticationType(): string; public function getAuthenticationType(): AuthenticationType;
/** /**
* @return string * @return string

View file

@ -41,5 +41,5 @@
* @param array $options Optional. The options to use/override for this build * @param array $options Optional. The options to use/override for this build
* @return string * @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 AuthenticationException If the authentication is invalid
* @throws NetworkException If there was an error getting the source * @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. * 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 AuthenticationException If the authentication is invalid
* @throws NetworkException If there was an error getting the package * @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())); 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'); throw new AuthenticationException('Cannot save configuration file, insufficient permissions');
} }

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