Skip to content

Repository files navigation

CIcodecov

Neuron-PHP Core

The foundational component of the Neuron PHP framework, providing essential utilities, string and array manipulation classes, and a comprehensive exception hierarchy for PHP 8.4+ applications.

Table of Contents

Installation

Requirements

  • PHP 8.4 or higher
  • Extensions: curl, json
  • Composer

Install via Composer

composer require neuron-php/core

Quick Start

String Manipulation

useNeuron\Core\NString;
// Create a string object$str = newNString('hello_world_example');
// Case conversionsecho$str->toPascalCase(); // 'HelloWorldExample'echo$str->toCamelCase(); // 'helloWorldExample'echo$str->toSnakeCase(); // 'hello_world_example'// String extractionecho$str->left(5); // 'hello'echo$str->right(7); // 'example'echo$str->mid(6, 10); // 'world'

Array Manipulation

useNeuron\Core\NArray;
// Create an array object$arr = newNArray(['apple', 'banana', 'cherry']);
// Safe element access with defaults$first = $arr->getElement(0, 'default'); // 'apple'$missing = $arr->getElement(10, 'none'); // 'none'// Transformations with method chaining$result = $arr->filter(fn($item) => strlen($item) > 5)
->map(fn($item) => ucfirst($item))
->sort();

Core Features

  • String Utilities: Object-oriented string manipulation with fluent interface
  • Array Utilities: Enhanced array operations with safe access and transformations
  • Exception Hierarchy: Comprehensive typed exceptions for better error handling
  • Error Constants: PHP implementation of standard C error codes
  • Modern PHP 8.4+: Property hooks, union types, and modern syntax
  • Type Safety: Strongly typed interfaces and return types
  • Method Chaining: Fluent interfaces for readable code

String Manipulation (NString)

The NString class provides powerful string manipulation capabilities with an object-oriented approach.

Basic Operations

useNeuron\Core\NString;
$str = newNString(' Hello World ');
// Length operationsecho$str->length(); // 15// Trimmingecho$str->trim(); // 'Hello World'

String Extraction

$str = newNString('The quick brown fox');
// Position-based extractionecho$str->left(9); // 'The quick'echo$str->right(3); // 'fox'echo$str->mid(4, 8); // 'quick'

Case Conversions

$str = newNString(' Hello World ');
echo$str->toUpper(); // ' HELLO WORLD 'echo$str->toLower(); // ' hello world '$str = newNString('hello_world_example');
// Snake case to PascalCase and camelCaseecho$str->toPascalCase(); // 'HelloWorldExample'echo$str->toCamelCase(); // 'helloWorldExample'// PascalCase/camelCase to snake case$camel = newNString('HelloWorldExample');
echo$camel->toSnakeCase(); // 'hello_world_example'// Mixed case handling$mixed = newNString('getUserID');
echo$mixed->toSnakeCase(); // 'get_user_id'

String Formatting

$str = newNString('example text');
// Quote handlingecho$str->quote(); // '"example text"'$quoted = newNString('"quoted text"');
echo$quoted->deQuote(); // 'quoted text'

Advanced Features

// Property hooks (PHP 8.4+)$str = newNString('test');
$str->value = 'new value'; // Uses setter hookecho$str->value; // Uses getter hook// Note: NString methods return strings, not NString objects,// so method chaining is not directly supported

Array Manipulation (NArray)

The NArray class provides comprehensive array manipulation with safe access and functional programming features.

Basic Operations

useNeuron\Core\NArray;
$arr = newNArray([1, 2, 3, 4, 5]);
// Array informationecho$arr->count(); // 5echo$arr->isEmpty(); // falseecho$arr->isNotEmpty(); // true// Element checksecho$arr->contains(3); // trueecho$arr->hasKey(2); // true// Get first and last elementsecho$arr->first(); // 1echo$arr->last(); // 5// Find index of elementecho$arr->indexOf(3); // 2// Remove element by value$arr->remove(3); // Removes 3 from array

Safe Element Access

$arr = newNArray(['a' => 1, 'b' => 2, 'c' => 3]);
// Get element with default fallback$value = $arr->getElement('a', 0); // 1$missing = $arr->getElement('d', -1); // -1 (default)// Check and getif ($arr->hasKey('b')) {
$value = $arr->getElement('b');
}

Transformation Methods

$arr = newNArray([1, 2, 3, 4, 5]);
// Map transformation$doubled = $arr->map(fn($x) => $x * 2);
// Result: [2, 4, 6, 8, 10]// Filter operation$evens = $arr->filter(fn($x) => $x % 2 === 0);
// Result: [2, 4]// Reduce operation$sum = $arr->reduce(fn($carry, $item) => $carry + $item, 0);
// Result: 15// Execute callback for each element$arr->each(function($value, $key) {
echo"[$key] => $value\n";
});

Array Operations

$arr1 = newNArray([1, 2, 3]);
$arr2 = newNArray([3, 4, 5]);
// Merge arrays$merged = $arr1->merge($arr2);
// Result: [1, 2, 3, 3, 4, 5]// Unique values$unique = $merged->unique();
// Result: [1, 2, 3, 4, 5]// Get keys and values$keys = $arr1->keys(); // [0, 1, 2]$values = $arr1->values(); // [1, 2, 3]// Mathematical operations$numbers = newNArray([1, 2, 3, 4, 5]);
echo$numbers->sum(); // 15echo$numbers->avg(); // 3echo$numbers->min(); // 1echo$numbers->max(); // 5// Convert to other formatsecho$numbers->toJson(); // "[1,2,3,4,5]"echo$numbers->implode(', '); // "1, 2, 3, 4, 5"$raw = $numbers->toArray(); // Get raw PHP array

Collection Operations

// Working with associative arrays$users = newNArray([
['id' => 1, 'name' => 'Alice', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 25],
['id' => 3, 'name' => 'Charlie', 'age' => 35]
]);
// Pluck values$names = $users->pluck('name');
// Result: ['Alice', 'Bob', 'Charlie']// Find by property$user = $users->findBy('age', 25);
// Result: ['id' => 2, 'name' => 'Bob', 'age' => 25]// Filter by property value$youngUsers = $users->where('age', 25);
// Result: Array containing users with age = 25// Find first matching element$adult = $users->find(fn($u) => $u['age'] >= 30);
// Result: ['id' => 1, 'name' => 'Alice', 'age' => 30]

Sorting and Ordering

$arr = newNArray([3, 1, 4, 1, 5, 9]);
// Sort ascending$sorted = $arr->sort();
// Result: [1, 1, 3, 4, 5, 9]// Sort by keys$arr = newNArray(['c' => 3, 'a' => 1, 'b' => 2]);
$sortedKeys = $arr->sortKeys();
// Result: ['a' => 1, 'b' => 2, 'c' => 3]// Reverse array$reversed = $arr->reverse();

Array Slicing and Chunking

$arr = newNArray([1, 2, 3, 4, 5, 6, 7, 8, 9]);
// Get slice (offset, length)$slice = $arr->slice(2, 4);
// Result: [3, 4, 5, 6]// Split into chunks$chunks = $arr->chunk(3);
// Result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Exception System

The core component provides a comprehensive exception hierarchy for consistent error handling across the framework.

Base Exception

useNeuron\Core\Exceptions\Base;
// All Neuron exceptions extend Baseclass CustomException extends Base
{
publicfunction__construct($message = "")
{
parent::__construct($message, 0, null);
}
}
try {
thrownewCustomException("Something went wrong");
} catch (Base$e) {
// Handle any Neuron exceptionecho$e->getMessage();
}

NotFound Exceptions

useNeuron\Core\Exceptions\NotFound;
useNeuron\Core\Exceptions\PropertyNotFound;
useNeuron\Core\Exceptions\CommandNotFound;
useNeuron\Core\Exceptions\MapNotFound;
// Generic not foundthrownewNotFound("Resource not found");
// Property not found on objectthrownewPropertyNotFound("Property 'email' not found on User object");
// Command not found in CLIthrownewCommandNotFound("Command 'deploy' not found");
// Route map not foundthrownewMapNotFound("Route '/api/users' not found");

Validation Exception

useNeuron\Core\Exceptions\Validation;
// Validation failure with details$errors = [
'email' => 'Invalid email format',
'age' => 'Must be 18 or older'
];
thrownewValidation("Validation failed", $errors);

Method and Request Exceptions

useNeuron\Core\Exceptions\MissingMethod;
useNeuron\Core\Exceptions\BadRequestMethod;
// Method missing on classthrownewMissingMethod("Method 'save' not found on class User");
// Invalid HTTP request methodthrownewBadRequestMethod("Method DELETE not allowed for this endpoint");

Route Parameter Exception

useNeuron\Core\Exceptions\RouteParam;
// Missing or invalid route parameterthrownewRouteParam("Required parameter 'id' missing from route");

Empty Action Parameter

useNeuron\Core\Exceptions\EmptyActionParameter;
// Action called with empty required parameterthrownewEmptyActionParameter("Parameter 'userId' cannot be empty");

Error Constants

The H\Error class provides PHP implementations of standard C error codes:

useNeuron\Core\H\Error;
// File system errors$code = Error::ENOENT; // 2 - No such file or directory$code = Error::EACCES; // 13 - Permission denied$code = Error::EEXIST; // 17 - File exists// Memory errors$code = Error::ENOMEM; // 12 - Out of memory// I/O errors$code = Error::EIO; // 5 - I/O error$code = Error::EBUSY; // 16 - Device or resource busy$code = Error::ENOSPC; // 28 - No space left on device// Example usagefunctionreadFile($path) {
if (!file_exists($path)) {
return ['error' => Error::ENOENT, 'message' => 'File not found'];
}
if (!is_readable($path)) {
return ['error' => Error::EACCES, 'message' => 'Permission denied'];
}
// Read file...
}

Testing

Running Tests

# Run all tests
./vendor/bin/phpunit tests
# Run with coverage
./vendor/bin/phpunit tests --coverage-text
# Run specific test
./vendor/bin/phpunit tests/NStringTest.php

Writing Tests

usePHPUnit\Framework\TestCase;
useNeuron\Core\NString;
class NStringTest extends TestCase
{
publicfunctiontestCamelCase(): void
{
$str = newNString('hello_world');
$this->assertEquals('HelloWorld', $str->toCamelCase());
$this->assertEquals('helloWorld', $str->toCamelCase(false));
}
publicfunctiontestStringExtraction(): void
{
$str = newNString('Hello World');
$this->assertEquals('Hello', $str->left(5));
$this->assertEquals('World', $str->right(5));
$this->assertEquals('llo W', $str->mid(2, 6));
}
}

Best Practices

String Operations

// Use NString for complex string manipulation$email = newNString(' USER@EXAMPLE.COM ');
$normalized = $email->trim()->toLower();
// Chain operations for readability$slug = (newNString('Product Name 2024'))
->toLower()
->replace('', '-')
->replace('2024', '');

Array Operations

// Use NArray for safe array access$config = newNArray($configData);
$dbHost = $config->getElement('host', 'localhost');
// Leverage functional programming$activeUsers = (newNArray($users))
->filter(fn($u) => $u['active'])
->map(fn($u) => $u['email'])
->unique();

Exception Handling

// Use specific exceptions for claritytry {
$property = $object->getProperty('nonexistent');
} catch (PropertyNotFound$e) {
// Handle missing property$property = $defaultValue;
} catch (Base$e) {
// Handle other Neuron exceptions$logger->error($e->getMessage());
}

Type Safety

// Leverage PHP 8.4+ featuresfunctionprocessArray(NArray$data): NArray
{
return$data->filter(fn($item) => $item !== null)
->map(fn($item) => processItem($item));
}

Integration with Other Components

The Core component serves as the foundation for all other Neuron components:

// Used by Validation componentuseNeuron\Core\Exceptions\Validation;
class EmailValidator
{
publicfunctionvalidate($value): void
{
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
thrownewValidation("Invalid email format");
}
}
}
// Used by Data componentuseNeuron\Core\NArray;
class DataFilter
{
publicfunctionfilterData(array$data): NArray
{
return (newNArray($data))
->filter(fn($item) => $item !== null)
->unique();
}
}

More Information

License

MIT License - see LICENSE file for details

About

Core library for Neuron-PHP components.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages