PHPackages                             koda/koda - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. koda/koda

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

koda/koda
=========

Utility classes for analyse code and invoking callables with verification of arguments and type casting

2.0.2(8y ago)033.7k1[1 PRs](https://github.com/bzick/koda/pulls)2MITPHPPHP &gt;=7.0

Since Dec 23Pushed 8y ago2 watchersCompare

[ Source](https://github.com/bzick/koda)[ Packagist](https://packagist.org/packages/koda/koda)[ RSS](/packages/koda-koda/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (5)Dependencies (2)Versions (7)Used By (2)

Koda
====

[](#koda)

[![Build Status](https://camo.githubusercontent.com/96ce0da7a0d5f61d707d0b34ec0055efb2a1d3f05319657e5ec22d54bc2968f2/68747470733a2f2f7472617669732d63692e6f72672f627a69636b2f6b6f64612e737667)](https://travis-ci.org/bzick/koda) [![Coverage Status](https://camo.githubusercontent.com/3c536db5d29ff7624e51408f44ece521efe20e97e157e989501cbe8024e36b4a/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f627a69636b2f6b6f64612f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/bzick/koda?branch=master)

Koda allows to analyse code entries, call functions, methods and objects with validation of arguments and type casting. This is similar to [call\_user\_func](http://php.net/call_user_func) and [call\_user\_func\_array](http://php.net/call_user_func_array), but more smarter. For example calculate hypotenuse using method:

```
class Math {
	/**
	 * @param float $leg1 (unsigned) first cathetus of triangle
	 * @param float $leg2 (unsigned) second cathetus of triangle
	 * @return float
	 */
    public static function hypotenuse($leg1, $leg2, $round = 2) {
        // ...
    }
}
```

all arguments we gets from associative (or plain) array (e.g. `$_GET`).

If use classic way with `call_user_func`:

```
if(isset($_GET['leg1'])) {
    $leg1 = floatval($_GET['leg1']);
    if($leg1 < 0) {
        throw new LogicException("leg1 should be greater than 0");
    }
} else {
    throw new RuntimeException("No leg1 parameter");
}
if(isset($_GET['leg2'])) {
    $leg2 = floatval($_GET['leg2']);
    if($leg2 < 0) {
        throw new LogicException("leg2 should be greater than 0");
    }
} else {
    throw new RuntimeException("No leg2 parameter");
}

return call_user_func('Math::hypotenuse', $leg1, $leg2);
```

But if use `Koda` we get one line of code:

```
return Koda::call('Math::hypotenuse', $_GET);
```

Koda find all arguments from associative (or plain) array `$_GET`, change type, validate and invoke method.

Method call
-----------

[](#method-call)

```
/**
 * Method description
 * @param int $arg1 some integer value
 * @param string $arg2 some string value
 * @param float[] $arg3 array of floating point values
 * @return bool method result
 **/
public function doSomething($arg1, $arg2, array $arg3 = array()) {
    // ...
}
```

Перед вызовом метода система проверит на наличие всех аргументов в запросе и приведет к нужному типу, согласно описанию метода. Бывает недостаточно простого приведения типа, может потребоваться привинтивная проверка самих данных. В этом случае в системе есть набор готовых проверок. Все проверки указываются так же в doc-блоке в скобках, через запятую сразу после названия аргумента:

```
/**
 * Method description
 * @param int $arg1 (value 0..100) некий числовой аргумент, значения которого находится между 0 и 100 включительно
 * @param string $arg2 (keyword, length < 100) некий стоковый аргумент, длина которого меньше 100 символов и состоит из `a-z0-9-_`
 * @param float[] $arg3 (count 0..10) массив чисел с плавующей точкой, массив может содержать от 0 до 10 элементов
 **/
public function doSomethingAction($arg1, $arg2, array $arg3) {
    // ...
}
```

List of verifications (class `Koda\Filter`):

- `unsigned` - value is unsigned **integer**
- `positive` - **integer** value **greater than zero**
- `negative` - **integer** value **less than zero**
- `smalltext` - **string** value less than or equal to **256 bytes**
- `text` - **string** value less than or equal to **64KiB**.
- `largetext` - **string** value less than or equal to **2MiB**.
- `date [FORMAT]` - string value is a **date**. `FORMAT` - the [format](http://php.net/manual/datetime.createfromformat.php#refsect1-datetime.createfromformat-parameters) that the passed in string should be in. `FORMAT` - optional parameter, by default function [strtotime](http://docs.php.net/strtotime) parse string.
- `length RANGE` - specifies the **maximum number of bytes** allowed in the **string** value. Maybe range `length 1..6`, equality `length = 6` or inequality `length
