Skip to content

Commit

Permalink
up: update some helper methods and readme
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 11, 2023
1 parent 088ce28 commit 99803f7
Show file tree
Hide file tree
Showing 10 changed files with 229 additions and 19 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[![License](https://img.shields.io/github/license/php-toolkit/stdlib)](LICENSE)
[![Php Version](https://img.shields.io/badge/php-%3E8.0-brightgreen.svg?maxAge=2592000)](https://packagist.org/packages/toolkit/stdlib)
[![Latest Stable Version](http://img.shields.io/packagist/v/toolkit/stdlib.svg)](https://packagist.org/packages/toolkit/stdlib)
[![Github Actions Status](https://github.com/php-toolkit/stdlib/workflows/Unit-Tests/badge.svg)](https://github.com/php-toolkit/stdlib/actions)
[![Unit Tests](https://github.com/php-toolkit/stdlib/actions/workflows/php.yml/badge.svg)](https://github.com/php-toolkit/stdlib/actions)
[![Docs on pages](https://img.shields.io/badge/DocsOn-Pages-brightgreen.svg?maxAge=2592000)](https://php-toolkit.github.io/stdlib/)

🧰 Stdlib - Useful basic tools library for PHP development.
Expand Down
197 changes: 197 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
# StdLib

[![License](https://img.shields.io/github/license/php-toolkit/stdlib)](LICENSE)
[![Php Version](https://img.shields.io/badge/php-%3E8.0-brightgreen.svg?maxAge=2592000)](https://packagist.org/packages/toolkit/stdlib)
[![Latest Stable Version](http://img.shields.io/packagist/v/toolkit/stdlib.svg)](https://packagist.org/packages/toolkit/stdlib)
[![Unit Tests](https://github.com/php-toolkit/stdlib/actions/workflows/php.yml/badge.svg)](https://github.com/php-toolkit/stdlib/actions)
[![Docs on pages](https://img.shields.io/badge/DocsOn-Pages-brightgreen.svg?maxAge=2592000)](https://php-toolkit.github.io/stdlib/)

🧰 Stdlib - Useful basic tools library for PHP development.

**Contains**:

- array, string, number, object helper
- common php, OS env information

**More Utils**

- `PhpDotEnv` Dotenv(`.env`) file load
- `AutoLoader` Simple autoloader
- `ObjectBox` simple object container
- `Optional` like java `java.util.Optional`
- and more ...

## Install

```bash
composer require toolkit/stdlib
```

## Strings

### StrBuffer

```php
use Toolkit\Stdlib\Str\StrBuffer;

$buf = StrBuffer::new("c");
$buf->prepend('ab')
$buf->append('de')

$str = (string)$buf; // "abcde"
$str = $buf->toString(); // "abcde"
// get and clean.
$str = $buf->fetch(); // "abcde"
$str = $buf->join(','); // "ab,c,de"
```

## Objects

### Object box

`ObjectBox` - Simple object container.

```php
use Toolkit\Stdlib\Obj\ObjectBox;

$box = ObjectBox::global();

// set
$box->set('router', function () {
return new MyRouter();
});

$box->set('renderer', [
'class' => MyRenderer::class,
'tplDir' => 'path/to/dir',
]);

// with options for create
$box->set('somObj', [
'class' => MyObject::class,
'__opt' => [
// will always create new object.
'objType' => ObjectBox::TYPE_PROTOTYPE,
],
]);

// get
/** @var MyRouter $router */
$router = $box->get('router');
/** @var MyRenderer $renderer */
$renderer = $box->get('renderer');
```

## Util classes

### AutoLoader

`AutoLoader` - an simple psr4 loader, can use for tests.

```php
AutoLoader::addFiles([
// alone files
]);

$loader = AutoLoader::getLoader();
$loader->addPsr4Map([
'namespace' => 'path'
]);

$loader->addClassMap([
'name' => 'class file'
]);
```

### Optional

It aims to eliminate excessive if judgments.

Not use Optional:

```php
use Toolkit\Stdlib\Util\Optional;

$userModel = UserModel::findOne(23);

if ($userModel) {
$username = $userModel->name;
} else {
$username = 'unknown';
}
```

Use Optional:

```php
use Toolkit\Stdlib\Util\Optional;

$username = Optional::ofNullable($userModel)
->map(function ($userModel) {
return $userModel->name;
})->orElse('unknown');
```

Use arrow syntax:

```php
use Toolkit\Stdlib\Util\Optional;

$username = Optional::ofNullable($userModel)
->map(fn($userModel) => $userModel->name)
->orElse('unknown');
```

### Php DotEnv

`PhpDotEnv` - a simple dont env file loader.

The env config file `.env` (must is 'ini' format):

```ini
APP_ENV=dev
DEBUG=true
; ... ...
```

Usage:

```php
PhpDotEnv::load(__DIR__, '.env');

env('DEBUG', false);
env('APP_ENV', 'prod');
```

### Stream

```php
use Toolkit\Stdlib\Util\Stream\DataStream;
use Toolkit\Stdlib\Util\Stream\ListStream;

$userList = ListStream::of($userModels)
->filter(fn($userModel) => $userModel->age > 20) // only need age > 20
->map(function ($userModel) {
// only need field: age, name
return [
'age' => $userModel->age,
'name' => $userModel->name,
];
})
->toArray();

vdump($userList);
```

### PipeFilters

```php
$pf = PipeFilters::newWithDefaultFilters();

$val = $pf->applyString('inhere', 'upper'); // 'INHERE'
$val = $pf->applyString('inhere', 'upper|substr:0,3'); // 'INH'
```

## License

[MIT](LICENSE)
2 changes: 1 addition & 1 deletion src/Helper/Assert.php
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ public static function isFile(string $path, string $errMsg = ''): void
*
* @return void
*/
public static function isResource($res, string $errMsg = ''): void
public static function isResource(mixed $res, string $errMsg = ''): void
{
if (!is_resource($res)) {
throw static::createEx($errMsg ?: 'Excepted an resource');
Expand Down
7 changes: 5 additions & 2 deletions src/Helper/IntHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

use function is_array;
use function is_int;
use function max;
use function min;
use function pack;

/**
* Class IntHelper
Expand All @@ -27,7 +30,7 @@ class IntHelper
*/
public static function getMax(int $val1, int $val2): int
{
return $val1 > $val2 ? $val1 : $val2;
return max($val1, $val2);
}

/**
Expand All @@ -38,7 +41,7 @@ public static function getMax(int $val1, int $val2): int
*/
public static function getMin(int $val1, int $val2): int
{
return $val1 < $val2 ? $val1 : $val2;
return min($val1, $val2);
}

// ----- http://cn2.php.net/manual/zh/function.pack.php#119402
Expand Down
4 changes: 1 addition & 3 deletions src/OS.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,6 @@ public static function name(): string
if (defined('PHP_OS_FAMILY')) {
return PHP_OS_FAMILY;
}

return PHP_OS;
}

Expand Down Expand Up @@ -363,7 +362,6 @@ public static function getNullDevice(): string
if (self::isUnix()) {
return '/dev/null';
}

return 'NUL';
}

Expand Down Expand Up @@ -420,6 +418,6 @@ public static function writeFile(string $filepath, string $contents, int $flags
*/
public static function mkdir(string $path, int $mode = 0775, bool $recursive = true): bool
{
return (is_dir($path) || !(!@mkdir($path, $mode, $recursive) && !is_dir($path))) && is_writable($path);
return (is_dir($path) || !(!mkdir($path, $mode, $recursive) && !is_dir($path))) && is_writable($path);
}
}
4 changes: 2 additions & 2 deletions src/Obj/Traits/ObjectPoolTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ trait ObjectPoolTrait
/**
* @param string $class
*
* @return mixed
* @return object of $class
*/
public static function get(string $class): mixed
public static function get(string $class): object
{
$stack = self::getStack($class);

Expand Down
6 changes: 4 additions & 2 deletions src/Util/Contract/PipelineInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

namespace Toolkit\Stdlib\Util\Contract;

use Closure;

/**
* Interface PipelineInterface
*
Expand All @@ -19,11 +21,11 @@ interface PipelineInterface
/**
* Adds stage to the pipeline
*
* @param callable $stage
* @param Closure $stage
*
* @return $this
*/
public function add(callable $stage): PipelineInterface;
public function add(Closure $stage): PipelineInterface;

/**
* Runs pipeline with initial value
Expand Down
4 changes: 2 additions & 2 deletions src/Util/Pipeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Toolkit\Stdlib\Util;

use Closure;
use SplObjectStorage;
use Toolkit\Stdlib\Util\Contract\PipelineInterface;
use function is_callable;
Expand All @@ -34,7 +35,7 @@ public function __construct()
/**
* {@inheritdoc}
*/
public function add(callable $stage): PipelineInterface
public function add(Closure $stage): PipelineInterface
{
if ($stage instanceof $this) {
$stage->add(fn ($payload) => $this->invokeStage($payload));
Expand All @@ -50,7 +51,6 @@ public function add(callable $stage): PipelineInterface
public function run(mixed $payload): mixed
{
$this->stages->rewind();

return $this->invokeStage($payload);
}

Expand Down
2 changes: 2 additions & 0 deletions src/Util/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@

/**
* Usage:
*
* $user = $db->query(['name' => $_POST['name'] ]);
*
* 1.
* gen:
* $password = Token::gen('123456');
Expand Down
20 changes: 14 additions & 6 deletions test/_navbar.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
* PhpPkg
* [EasyTpl](https://phppkg.github.io/easytpl/ "template engine")
* [Validate](https://inhere.github.io/php-validate/ "data validate engine")
* Toolkit
* [PFlag](https://php-toolkit.github.io/pflag/ "console option and argument parse")
* [Stdlib](https://php-toolkit.github.io/stdlib/ "Useful basic tools library for PHP development.")
* [English](/README.md)
* [中文说明](/README.zh-CN.md)
* **[PHPPkg](https://github.com/phppkg)**
* [Config](https://phppkg.github.io/config/ "🗂 Config load, management, merge, get, set and more.")
* [EasyTpl](https://phppkg.github.io/easytpl/ "⚡️ Simple and fastly template engine for PHP")
* [Http-client](https://phppkg.github.io/http-client/ "An easy-to-use HTTP client library for PHP")
* [PhpGit](https://phppkg.github.io/phpgit/ "A Git wrapper library for PHP")
* [Ini](https://phppkg.github.io/ini/ "💪 An enhanced INI format parser written in PHP")
* [Jenkins-client](https://phppkg.github.io/jenkins-client/ "Designed to interact with Jenkins CI using its API")
* [Console](https://inhere.github.io/php-console/ "🖥 PHP CLI library, provide console options, arguments parse")
* [Validate](https://inhere.github.io/php-validate/ "php data validate engine")
* **[Toolkit](https://github.com/php-toolkit)**
* [PFlag](https://php-toolkit.github.io/pflag/ "console option and argument parse")
* [Stdlib](https://php-toolkit.github.io/stdlib/ "Useful basic tools library for PHP development.")

0 comments on commit 99803f7

Please sign in to comment.