Compare commits

...

40 commits

Author SHA1 Message Date
985478ff91
Updated README.md
Some checks are pending
CI / release (push) Waiting to run
CI / release-executable (push) Waiting to run
CI / check-phpunit (push) Waiting to run
CI / check-phpdoc (push) Waiting to run
CI / generate-phpdoc (push) Blocked by required conditions
CI / test (push) Blocked by required conditions
CI / release-documentation (push) Blocked by required conditions
CI / release-artifacts (push) Blocked by required conditions
2025-03-14 15:14:45 -04:00
netkas
04ea85aa5d Fixed issue where if global $argv is not available, a check to see if $_SERVER['argv'] is set before accessing it due to a potential 'undefined' error. 2024-10-29 15:06:21 -04:00
netkas
4e065e8cf7 Minor correction 2024-10-14 15:54:21 -04:00
netkas
eb8d63fea0 Updated Build System 2024-10-14 15:51:50 -04:00
netkas
1244aa0a24 Corrected project version 2024-10-14 15:51:26 -04:00
netkas
2eb49f4cff Merge remote-tracking branch 'origin/master' 2024-10-14 15:24:46 -04:00
ca1bafdad1 Updated Build System 2024-10-13 16:53:08 -04:00
d6e1292f45 Updated Build System 2024-10-13 16:52:34 -04:00
netkas
5e849d079f Fixed null-typing check 2024-09-24 14:56:27 -04:00
netkas
fdb752cfe0 Updated README.md TOC 2024-09-24 13:02:31 -04:00
netkas
0e2704aecc Updated CHANGELOG.md 2024-09-24 13:01:24 -04:00
netkas
2181b495a9 Updated README.md 2024-09-24 13:00:11 -04:00
netkas
43ddda23ef Update NCC workflow 2024-09-24 12:48:32 -04:00
netkas
d4f7b08714 Update NCC workflow 2024-09-24 12:45:39 -04:00
netkas
e333821450 Update NCC workflow 2024-09-24 12:42:25 -04:00
netkas
2477d81af3 Update NCC workflow 2024-09-24 12:39:49 -04:00
netkas
e86bc52cb7 Update NCC workflow 2024-09-24 12:37:51 -04:00
netkas
7a43c6623a Update NCC workflow 2024-09-24 12:35:53 -04:00
netkas
b9e942635a Update NCC workflow to use new GitHub environment syntax 2024-09-24 12:33:51 -04:00
netkas
23790bd189 Handle null input in parseArgument method & refactored getArguments() method 2024-09-24 12:29:37 -04:00
netkas
6e7f9089d2 Update type declarations and PHP language level 2024-09-24 00:45:26 -04:00
netkas
0a8e47cc71 Updated .gitignore 2024-09-24 00:43:27 -04:00
netkas
7c929cefa4 Added PhpUnit tests 2024-09-24 00:43:14 -04:00
netkas
81ab2fdf77 Added PhpUnit tests 2024-09-24 00:43:06 -04:00
netkas
7d1c11c051 Fix argument limit check in Parse.php 2024-09-24 00:42:56 -04:00
netkas
c3092eb688 Removed old tests 2024-09-24 00:38:54 -04:00
netkas
c98939d33f Updated workflow 2024-09-24 00:37:02 -04:00
netkas
6cd05ab051 Updated workflow 2024-09-24 00:34:40 -04:00
netkas
b41b8465f1 Updated workflow & .gitignore 2024-09-24 00:31:48 -04:00
netkas
f1e2df0dcc Remove OptsLib.php and update GitHub action 2024-09-23 18:58:10 -04:00
netkas
9d6008368b Added ncc project files 2024-09-23 18:55:46 -04:00
netkas
d7f2543183 Updated .gitignore 2024-09-23 18:54:55 -04:00
netkas
6cd044a0ad Removed files 2024-09-23 18:54:42 -04:00
0b4be3e992
Updated CHANGELOG.md 2023-10-10 21:45:27 -04:00
a85da048eb
Minor correction 2023-10-10 21:43:01 -04:00
786055ea8f
Minor correction 2023-10-10 21:39:59 -04:00
b86140160d
Minor correction 2023-10-10 21:33:09 -04:00
429ca491ed
Refactor build process, update project configs, and clean up documentation
The build process has been refactored to improve maintainability and productivity. This includes simplifying the .gitlab-ci.yml file by utilizing a more updated image which has the necessary dependencies pre-installed.

The Makefile has been heavily restructured to improve understandability and increase the flexibility of the build process. With these changes, the dependencies installation, uninstallation and removal of build artifacts can now be handled directly from the Makefile.

The configuration in project.json was updated, reducing redundancy and clarifying output paths.

In addition, README.md has been cleaned up to improve readability and keep the documentation up-to-date with the codebase changes. For instance, unnecessary functions in the usage section have been removed and links in the table of contents have been fixed.

Lastly, the copyright dates in the LICENSE file have been extended to include 2023 and the format improved for better readability.
2023-10-10 21:29:13 -04:00
7895dc2464
Updated README.md 2023-09-29 00:44:17 -04:00
d15eb47ef1
Bumped version to 1.1.0
- Updated optslib to work with ncc 2.+.
 - Fixed code-smell from optslib.
2023-09-29 00:43:52 -04:00
19 changed files with 648 additions and 149 deletions

308
.github/workflows/ncc_workflow.yml vendored Normal file
View file

@ -0,0 +1,308 @@
name: CI
on:
push:
branches:
- '**'
release:
types: [created]
workflow_dispatch:
jobs:
release:
runs-on: ubuntu-latest
container:
image: php:8.3
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies
run: |
apt update -yqq
apt install git libpq-dev libzip-dev zip make wget gnupg -yqq
- 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
mv phive.phar /usr/local/bin/phive
- name: Install phab
run: |
phive install phpab --global --trust-gpg-keys 0x2A8299CE842DD38C
- name: Install latest version of NCC
run: |
git clone https://git.n64.cc/nosial/ncc.git
cd ncc
make redist
NCC_DIR=$(find build/ -type d -name "ncc_*" | head -n 1)
if [ -z "$NCC_DIR" ]; then
echo "NCC build directory not found"
exit 1
fi
php "$NCC_DIR/INSTALL" --auto
cd .. && rm -rf ncc
- name: Build project
run: |
ncc build --config release --build-source --log-level debug
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: release
path: build/release/net.nosial.optslib.ncc
release-executable:
runs-on: ubuntu-latest
container:
image: php:8.3
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies
run: |
apt update -yqq
apt install git libpq-dev libzip-dev zip make wget gnupg -yqq
- 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
mv phive.phar /usr/local/bin/phive
- name: Install phab
run: |
phive install phpab --global --trust-gpg-keys 0x2A8299CE842DD38C
- name: Install latest version of NCC
run: |
git clone https://git.n64.cc/nosial/ncc.git
cd ncc
make redist
NCC_DIR=$(find build/ -type d -name "ncc_*" | head -n 1)
if [ -z "$NCC_DIR" ]; then
echo "NCC build directory not found"
exit 1
fi
php "$NCC_DIR/INSTALL" --auto
cd .. && rm -rf ncc
- name: Build project
run: |
ncc build --config release-executable --build-source --log-level debug
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: release-executable
path: build/release/release_executable_gz
# Checking for phpunit.xml
check-phpunit:
runs-on: ubuntu-latest
outputs:
phpunit-exists: ${{ steps.check.outputs.phpunit-exists }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Check for phpunit.xml
id: check
run: |
if [ -f phpunit.xml ]; then
echo "phpunit-exists=true" >> $GITHUB_OUTPUT
else
echo "phpunit-exists=false" >> $GITHUB_OUTPUT
fi
# Checking for phpdoc.dist.xml
check-phpdoc:
runs-on: ubuntu-latest
outputs:
phpdoc-exists: ${{ steps.check.outputs.phpdoc-exists }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Check for phpdoc.dist.xml
id: check
run: |
if [ -f phpdoc.dist.xml ]; then
echo "phpdoc-exists=true" >> $GITHUB_OUTPUT
else
echo "phpdoc-exists=false" >> $GITHUB_OUTPUT
fi
generate-phpdoc:
needs: [release, check-phpdoc]
runs-on: ubuntu-latest
container:
image: php:8.3
if: needs.check-phpdoc.outputs.phpdoc-exists == 'true'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies
run: |
apt update -yqq
apt install git libpq-dev libzip-dev zip make wget gnupg -yqq
- name: Download PHPDocumentor
run: |
wget https://phpdoc.org/phpDocumentor.phar
chmod +x phpDocumentor.phar
- name: Generate PHPDoc
run: |
php phpDocumentor.phar -d src -t docs
- name: Archive PHPDoc
run: |
zip -r docs.zip docs
- name: Upload PHPDoc
uses: actions/upload-artifact@v4
with:
name: documentation
path: docs.zip
test:
needs: [release, release-executable, check-phpunit]
runs-on: ubuntu-latest
container:
image: php:8.3
if: needs.check-phpunit.outputs.phpunit-exists == 'true'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
name: release
path: release
- name: Install dependencies
run: |
apt update -yqq
apt install git libpq-dev libzip-dev zip make wget gnupg -yqq
curl -sSLf -o /usr/local/bin/install-php-extensions https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions
chmod +x /usr/local/bin/install-php-extensions
install-php-extensions zip
- 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
mv phive.phar /usr/local/bin/phive
- name: Install phab
run: |
phive install phpab --global --trust-gpg-keys 0x2A8299CE842DD38C
- name: Install latest version of NCC
run: |
git clone https://git.n64.cc/nosial/ncc.git
cd ncc
make redist
NCC_DIR=$(find build/ -type d -name "ncc_*" | head -n 1)
if [ -z "$NCC_DIR" ]; then
echo "NCC build directory not found"
exit 1
fi
php "$NCC_DIR/INSTALL" --auto
cd .. && rm -rf ncc
- name: Install NCC packages
run: |
ncc package install --package="release/net.nosial.optslib.ncc" --build-source --reinstall -y --log-level debug
- name: Run PHPUnit tests
run: |
wget https://phar.phpunit.de/phpunit-11.3.phar
php phpunit-11.3.phar --configuration phpunit.xml --log-junit reports/junit.xml --log-teamcity reports/teamcity --testdox-html reports/testdox.html --testdox-text reports/testdox.txt
- name: Upload test reports
uses: actions/upload-artifact@v4
with:
name: reports
path: reports
release-documentation:
needs: generate-phpdoc
permissions: write-all
runs-on: ubuntu-latest
container:
image: php:8.3
if: github.event_name == 'release'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Download documentation artifact
uses: actions/download-artifact@v4
with:
name: documentation
path: documentation
- name: Upload documentation artifact
uses: softprops/action-gh-release@v1
with:
files: |
documentation/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
release-artifacts:
needs: [release, release-executable]
permissions: write-all
runs-on: ubuntu-latest
container:
image: php:8.3
if: github.event_name == 'release'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Download release artifact
uses: actions/download-artifact@v4
with:
name: release
path: release
- name: Upload release artifact to release
uses: softprops/action-gh-release@v1
with:
files: |
release/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Download release-executable artifact
uses: actions/download-artifact@v4
with:
name: release-executable
path: release-executable
- name: Upload release-executable artifact to release
uses: softprops/action-gh-release@v1
with:
files: |
release-executable/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

6
.gitignore vendored
View file

@ -1 +1,5 @@
build/
build/
/.idea/gbrowser_project.xml
/.phpunit.result.cache
/.idea/php-test-framework.xml

View file

@ -1,43 +1,25 @@
image: php:8.1
image: repo.n64.cc:443/nosial/ncc:latest
before_script:
# Install some stuff that the image doesn't come with
- apt update -yqq
- apt install git libpq-dev libzip-dev zip make wget gnupg -yqq
stages:
- build
- publish
# Install phive
- 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
- mv phive.phar /usr/local/bin/phive
# Install phab
- phive install phpab --global --trust-gpg-keys 0x2A8299CE842DD38C
# Install the latest version of ncc (Nosial Code Compiler)
- git clone https://git.n64.cc/nosial/ncc.git
- cd ncc
- make redist
- php build/src/INSTALL --auto --install-composer
- cd .. && rm -rf ncc
variables:
PACKAGE_NAME: $CI_COMMIT_REF_NAME
build:
stage: build
script:
- ncc build --config release --log-level debug
- ncc build --config release --log-level debug -o "build/release/net.nosial.optslib.ncc"
artifacts:
paths:
- build/
rules:
- if: $CI_COMMIT_BRANCH
- "build/release/net.nosial.optslib.ncc"
release:
stage: deploy
publish:
stage: publish
before_script:
- 'if [ "$CI_COMMIT_REF_NAME" == "master" ]; then PACKAGE_NAME="latest"; fi'
script:
- ncc build --config release --log-level debug
artifacts:
paths:
- build/
rules:
- if: $CI_COMMIT_TAG
- |
curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file build/release/net.nosial.optslib.ncc \
"https://$CI_SERVER_HOST/api/v4/projects/$CI_PROJECT_ID/packages/generic/${PACKAGE_NAME}/${CI_COMMIT_SHA}/net.nosial.optslib.ncc"

View file

@ -19,6 +19,9 @@
<option value="X-Args-3" />
<option value="X-Args-4" />
<option value="X-Args-5" />
<option value="X-Temperature" />
<option value="X-Model" />
<option value="X-OPENAI-API-KEY" />
</set>
</option>
</inspection_tool>

20
.idea/php-inspections-ea-ultimate.xml generated Normal file
View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EAUltimateProjectSettings">
<categories>
<STRICTNESS_CATEGORY_SECURITY enabled="yes" />
<STRICTNESS_CATEGORY_PROBABLE_BUGS enabled="yes" />
<STRICTNESS_CATEGORY_PERFORMANCE enabled="yes" />
<STRICTNESS_CATEGORY_ARCHITECTURE enabled="yes" />
<STRICTNESS_CATEGORY_CONTROL_FLOW enabled="yes" />
<STRICTNESS_CATEGORY_LANGUAGE_LEVEL_MIGRATION enabled="yes" />
<STRICTNESS_CATEGORY_CODE_STYLE enabled="yes" />
<STRICTNESS_CATEGORY_UNUSED enabled="yes" />
<STRICTNESS_CATEGORY_PHPUNIT enabled="yes" />
</categories>
<settings>
<ANALYZE_ONLY_MODIFIED_FILES value="no" />
<PREFER_YODA_COMPARISON_STYLE value="no" />
</settings>
</component>
</project>

12
.idea/php.xml generated
View file

@ -9,12 +9,22 @@
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="7.1">
<component name="PhpIncludePathManager">
<include_path>
<path value="/usr/share/php" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.3">
<option name="suggestChangeDefaultLanguageLevel" value="false" />
</component>
<component name="PhpStanOptionsConfiguration">
<option name="transferred" value="true" />
</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">
<option name="transferred" value="true" />
</component>

14
.idea/webResources.xml generated Executable file
View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="WebResourcesPaths">
<contentEntries>
<entry url="file://$PROJECT_DIR$">
<entryData>
<resourceRoots>
<path value="file://$PROJECT_DIR$/assets" />
</resourceRoots>
</entryData>
</entry>
</contentEntries>
</component>
</project>

View file

@ -1,3 +1,45 @@
## Release v1.0.0 (2023-01-29)
# Changelog
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/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.1.3] - 2024-10-29
This update introduces a critical bug fix
### Fixed
- Fixed issue where if global $argv is not available, a check to see if `$_SERVER['argv']` is set
before accessing it due to a potential 'undefined' error.
## [1.1.2] - 2024-10-13
Updated Build System
## [1.1.1] - 2024-09-24
Updated OptsLib to work with php 8.3+ & ncc 2.1.0+
### Changed
- Introduced typed properties to OptsLib
### Fixed
- Fixed code-smell from OptsLib
## [1.1.0] - 2023-10-10
Updated optslib to work with ncc 2.+.
### Fixed
- Fixed code-smell from optslib.
## [1.0.0] - 2023-01-29
Initial release of ConfigLib.

26
LICENSE
View file

@ -1,18 +1,14 @@
Copyright 2022 Nosial All Rights Reserved.
Copyright 2022-2023 Nosial 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:
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 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 NONINFRINGEMENT. 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.
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 NONINFRINGEMENT. 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.

View file

@ -1,8 +1,25 @@
# Variables
DEFAULT_CONFIGURATION ?= release
LOG_LEVEL = debug
# Default Target
all: release release-executable
# Build Steps
release:
ncc build --config="release"
ncc build --config=release --log-level $(LOG_LEVEL)
release-executable:
ncc build --config=release-executable --log-level $(LOG_LEVEL)
install:
ncc package install --package="build/release/net.nosial.optslib.ncc" --skip-dependencies --reinstall -y
uninstall:
ncc package uninstall -y --package="net.nosial.optslib"
install: release
ncc package install --package=build/release/net.nosial.optslib.ncc --skip-dependencies --build-source --reinstall -y --log-level $(LOG_LEVEL)
test: release
[ -f phpunit.xml ] || { echo "phpunit.xml not found"; exit 1; }
phpunit
clean:
rm -rf build
.PHONY: all install test clean release release-executable

View file

@ -1,22 +1,36 @@
# OptsLib
A very simple Options parser and command-line arguments
handling library for PHP.
A basic Options parser and command-line arguments handling a library for PHP.
## Community
This project and many others from Nosial are available on multiple publicly available and free git repositories at
- [n64](https://git.n64.cc/nosial/optslib)
- [GitHub](https://github.com/nosial/optslib)
- [Codeberg](https://codeberg.org/nosial/optslib)
Issues & Pull Requests are frequently checked and to be referenced accordingly in commits and changes, Nosial remains
dedicated to keep these repositories up to date when possible.
For questions & discussions see the public Telegram community at [@NosialDiscussions](https://t.me/NosialDiscussions).
We do encourage community support and discussions, please be respectful and follow the rules of the community.
## Table of Contents
<!-- TOC -->
* [OptsLib](#optslib)
* [Community](#community)
* [Table of Contents](#table-of-contents)
* [Installation](#installation)
* [Compiling from source](#compiling-from-source)
* [Testing](#testing)
* [Usage](#usage)
* [parseArgument()](#parseargument--)
* [getArguments()](#getarguments--)
* [parseArgument()](#parseargument)
* [getArguments()](#getarguments)
* [Additional functionality](#additional-functionality)
* [getRegex()](#getregex--)
* [setRegex()](#setregex--)
* [getArgsCache()](#getargscache--)
* [getRegex()](#getregex)
* [setRegex()](#setregex)
* [Changelog](#changelog)
* [License](#license)
* [Logo](#logo)
@ -28,7 +42,11 @@ handling library for PHP.
The library can be installed using ncc:
```bash
ncc install -p "nosial/libs.opts=latest@n64"
# n64
ncc package install -p "nosial/libs.opts=latest@n64"
# github
ncc package install -p "nosial/libs.opts=latest@github"
```
or by adding the following to your project.json file under
@ -47,7 +65,7 @@ If you don't have the n64 source configured you can add it
by running the following command:
```bash
ncc source add --name n64 --type gitlab --host git.n64.cc
ncc repository add --name n64 --type gitlab --host git.n64.cc
```
## Compiling from source
@ -64,6 +82,16 @@ or by running the following command:
make release
```
## Testing
The library can be tested using PhpUnit with the `phpunit.xml` file that is already included in the repository.
This requires that you have PhpUnit installed & the library has been compiled and installed on the local system.
```bash
phpunit
```
## Usage
The usage of this library is very simple, there are
@ -166,12 +194,6 @@ the arguments, you can modify the default pattern to suit your needs.
```
### getArgsCache()
This method is used to return the arguments cache parsed from the global
`$argv` variable, this can be used as a means of troubleshooting.
## Changelog
For a list of changes, see the [CHANGELOG.md](CHANGELOG.md) file.

3
bootstrap.php Normal file
View file

@ -0,0 +1,3 @@
<?php
require 'ncc';
import('net.nosial.optslib');

15
phpdoc.dist.xml Normal file
View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<phpdocumentor configVersion="3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://www.phpdoc.org" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/phpDocumentor/phpDocumentor/master/data/xsd/phpdoc.xsd">
<paths>
<output>build/docs</output>
<cache>build/cache</cache>
</paths>
<version number="latest">
<api>
<source dsn=".">
<path>src/OptsLib</path>
</source>
<default-package-name>OptsLib</default-package-name>
</api>
</version>
</phpdocumentor>

11
phpunit.xml Normal file
View file

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

View file

@ -2,8 +2,8 @@
"project": {
"compiler": {
"extension": "php",
"minimum_version": "8.0",
"maximum_version": "8.2"
"minimum_version": "8.2",
"maximum_version": "8.0"
},
"update_source": {
"source": "nosial/libs.opts@n64",
@ -13,15 +13,14 @@
"host": "git.n64.cc",
"ssl": true
}
},
"options": []
}
},
"assembly": {
"name": "OptsLib",
"package": "net.nosial.optslib",
"copyright": "Copyright (c) 2022-2023 Nosial",
"description": "A simple options parser library for PHP",
"version": "1.0.0",
"copyright": "Copyright (c) 2022-2023 Nosial",
"version": "1.1.3",
"uuid": "20aefdfa-7b91-11ed-919f-cb63712c8e36"
},
"build": {
@ -30,7 +29,16 @@
"configurations": [
{
"name": "release",
"output_path": "build/release"
"build_type": "ncc",
"output": "build/release/%ASSEMBLY.PACKAGE%.ncc"
},
{
"name": "release-executable",
"build_type": "executable",
"output": "build/release/release_executable_gz",
"options": {
"ncc_configuration": "release"
}
}
]
}

View file

@ -26,79 +26,82 @@
*
* @var string
*/
private static $Regex = "/(?(?=-)-(?(?=-)-(?'bigflag'[^\\s=]+)|(?'smallflag'\\S))(?:\\s*=\\s*|\\s+)(?(?!-)(?(?=[\\\"\\'])((?<![\\\\])['\"])(?'string'(?:.(?!(?<![\\\\])\\3))*.?)\\3|(?'value'\\S+)))(?:\\s+)?|(?'unmatched'\\S+))/";
private static string $regex = "/(?(?=-)-(?(?=-)-(?'bigflag'[^\\s=]+)|(?'smallflag'\\S))(?:\\s*=\\s*|\\s+)(?(?!-)(?(?=[\\\"\\'])((?<![\\\\])['\"])(?'string'(?:.(?!(?<![\\\\])\\3))*.?)\\3|(?'value'\\S+)))(?:\\s+)?|(?'unmatched'\\S+))/";
/**
* Cache of the parsed arguments. This is used to prevent the arguments from being parsed more than once.
*
* @var array
* @var array|null
*/
private static $ArgsCache;
private static ?array $args_cache = null;
/**
* Parses the input arguments into an array of flags and values
*
* @param string|array $input array The input arguments
* @param array|string|null $input array The input arguments
* @param int $max_arguments The maximum number of arguments to parse
* @return array The parsed arguments
*/
public static function parseArgument($input, int $max_arguments=1000): array
public static function parseArgument(array|string|null $input, int $max_arguments = 1000): array
{
$flags = '';
if (is_string($input))
{
$flags = $input;
}
elseif(is_array($input))
elseif (is_array($input))
{
$flags = implode(' ', $input);
}
else
{
global $argv;
if(isset($argv) && count($argv) > 1)
if (isset($argv) && count($argv) > 1)
{
array_shift($argv);
$flags = implode(' ', $argv);
}
$flags = implode(' ', $argv);
}
$configs = array();
preg_match_all(self::$Regex, $flags, $matches, PREG_SET_ORDER);
$configs = [];
// Assuming self::$regex is always defined and valid
preg_match_all(self::$regex, $flags, $matches, PREG_SET_ORDER);
foreach ($matches as $index => $match)
{
if (isset($match['value']) && $match['value'] !== '')
$value = true;
if (!empty($match['value']))
{
$value = $match['value'];
}
else if (isset($match['string']) && $match['string'] !== '')
elseif (!empty($match['string']))
{
// fix escaped quotes
$value = str_replace("\\\"", "\"", $match['string']);
$value = str_replace("\\'", "'", $value);
}
else
{
$value = true;
$value = str_replace(["\\\"", "\\'"], ["\"", "'"], $match['string']);
}
if (isset($match['bigflag']) && $match['bigflag'] !== '')
if (!empty($match['bigflag']))
{
$configs[$match['bigflag']] = $value;
}
if (isset($match['smallflag']) && $match['smallflag'] !== '')
if (!empty($match['smallflag']))
{
$configs[$match['smallflag']] = $value;
}
if (isset($match['unmatched']) && $match['unmatched'] !== '')
if (!empty($match['unmatched']))
{
$configs[$match['unmatched']] = true;
}
if ($index >= $max_arguments)
{
break;
}
}
return $configs;
@ -113,45 +116,33 @@
public static function getArguments(?string $after=null): array
{
global $argv;
if(self::$ArgsCache == null)
if($argv === null && isset($_SERVER['argv']))
{
$argv = $_SERVER['argv'];
}
if(self::$args_cache === null)
{
self::$args_cache = [];
if(isset($argv))
{
self::$ArgsCache = self::parseArgument($argv);
}
else
{
self::$ArgsCache = [];
self::$args_cache = self::parseArgument($argv);
}
}
if($after == null)
if($after === null)
{
return self::$ArgsCache;
return self::$args_cache;
}
else
$after_index = array_search($after, array_keys(self::$args_cache), true);
if($after_index === false)
{
$after_index = array_search($after, array_keys(self::$ArgsCache));
if($after_index === false)
{
return [];
}
else
{
return array_slice(self::$ArgsCache, $after_index + 1);
}
return [];
}
}
/**
* Returns the cached arguments
*
* @return array
*/
public static function getArgsCache(): array
{
return self::$ArgsCache;
return array_slice(self::$args_cache, $after_index + 1);
}
/**
@ -161,16 +152,16 @@
*/
public static function getRegex(): string
{
return self::$Regex;
return self::$regex;
}
/**
* Sets a new regex pattern to use to parse the arguments.
*
* @param string $Regex
* @param string $regex
*/
public static function setRegex(string $Regex): void
public static function setRegex(string $regex): void
{
self::$Regex = $Regex;
self::$regex = $regex;
}
}

View file

@ -0,0 +1,70 @@
<?php
namespace OptsLib;
use PHPUnit\Framework\TestCase;
class ParseTest extends TestCase
{
/**
* Testing parseArgument method when input is a string type, also testing different flag pattern
*/
public function testParseArgumentWithStringInput()
{
$input = '--flag1=value1 -f value2 unmatched_string';
$expected_result = [
'flag1' => 'value1',
'f' => 'value2',
'unmatched_string' => true,
];
$this->assertEquals($expected_result, Parse::parseArgument($input));
}
/**
* Testing parseArgument method when input is an array type
*/
public function testParseArgumentWithArrayInput()
{
// Array argument will be transformed into '--flag1 value1 "-"f" value2" unmatched_string'
$input = ['--flag1', 'value1', '-', 'f', 'value2', 'unmatched_string'];
$expected_result = [
'flag1' => 'value1',
'unmatched_string' => true,
'f' => true,
'value2' => true
];
$this->assertEquals($expected_result, Parse::parseArgument($input));
}
/**
* Testing parseArgument method when input contains escaped quotes in a string argument
*/
public function testParseArgumentWithEscapedQuotes()
{
$input = "--flag1=\"value1 with some \\\"escaped quotes\\\"\" -f 'value2 with some \\'escaped quotes\\'' unmatched_string";
$expected_result = [
'flag1' => 'value1 with some "escaped quotes"',
'f' => 'value2 with some \'escaped quotes\'',
'unmatched_string' => true,
];
$this->assertEquals($expected_result, Parse::parseArgument($input));
}
/**
* Testing parseArgument method only takes maximum number of arguments specified
*/
public function testParseArgumentWithMaxArguments()
{
$input = '--flag1=value1 -f value2 unmatched_string1 unmatched_string2';
$expected_result = [
'flag1' => 'value1',
'f' => 'value2',
'unmatched_string1' => true
]; // It should only parse maximum 3 arguments
$this->assertEquals($expected_result, Parse::parseArgument($input, 2));
}
}

View file

@ -1,10 +0,0 @@
<?php
require 'ncc';
import('net.nosial.optslib', 'latest');
$parse = \OptsLib\Parse::getArguments();
var_dump($parse);
$parse = \OptsLib\Parse::getArguments('exec');
var_dump($parse);

View file

@ -1,7 +0,0 @@
<?php
require 'ncc';
import('net.nosial.optslib', 'latest');
$parse = \OptsLib\Parse::parseArgument('test --foo=bar --baz=qux --quux --corge --grault=garply --waldo --fred --plugh --xyzzy --thud');
var_dump($parse);