From 9ccaa1e102e4101150c58b522088c00d3a487a1a Mon Sep 17 00:00:00 2001 From: Stefano Azzolini Date: Thu, 25 Feb 2016 10:25:06 +0100 Subject: [PATCH] 1.2.1 --- .gitattributes | 6 +- .scrutinizer.yml | 2 - composer.json | 2 +- docs/CLI.md | 99 ---------------- docs/CSV.md | 97 --------------- docs/Cache.md | 139 ---------------------- docs/Check.md | 83 ------------- docs/Defer.md | 12 -- docs/Dictionary.md | 151 ------------------------ docs/Email.md | 49 -------- docs/Error.md | 60 ---------- docs/Event.md | 80 ------------- docs/Examples.md | 17 --- docs/File.md | 151 ------------------------ docs/Filters.md | 96 --------------- docs/HTTP.md | 108 ----------------- docs/Hash.md | 123 ------------------- docs/Installation.md | 33 ------ docs/Loader.md | 18 --- docs/Message.md | 92 --------------- docs/Module.md | 21 ---- docs/Password.md | 24 ---- docs/Persistence.md | 59 ---------- docs/README.md | 39 ------ docs/REST.md | 44 ------- docs/Redirect.md | 31 ----- docs/Request.md | 81 ------------- docs/Response.md | 74 ------------ docs/Route.md | 275 ------------------------------------------- docs/SQL.md | 135 --------------------- docs/Session.md | 75 ------------ docs/Shell.md | 210 --------------------------------- docs/String.md | 17 --- docs/View.md | 86 -------------- docs/Work.md | 98 --------------- docs/index.md | 39 ------ docs/template.html | 43 ------- phpci.yml | 17 --- 38 files changed, 2 insertions(+), 2784 deletions(-) delete mode 100644 .scrutinizer.yml delete mode 100644 docs/CLI.md delete mode 100644 docs/CSV.md delete mode 100644 docs/Cache.md delete mode 100644 docs/Check.md delete mode 100644 docs/Defer.md delete mode 100644 docs/Dictionary.md delete mode 100644 docs/Email.md delete mode 100644 docs/Error.md delete mode 100644 docs/Event.md delete mode 100644 docs/Examples.md delete mode 100644 docs/File.md delete mode 100644 docs/Filters.md delete mode 100644 docs/HTTP.md delete mode 100644 docs/Hash.md delete mode 100644 docs/Installation.md delete mode 100644 docs/Loader.md delete mode 100644 docs/Message.md delete mode 100644 docs/Module.md delete mode 100644 docs/Password.md delete mode 100644 docs/Persistence.md delete mode 100644 docs/README.md delete mode 100644 docs/REST.md delete mode 100644 docs/Redirect.md delete mode 100644 docs/Request.md delete mode 100644 docs/Response.md delete mode 100644 docs/Route.md delete mode 100644 docs/SQL.md delete mode 100644 docs/Session.md delete mode 100644 docs/Shell.md delete mode 100644 docs/String.md delete mode 100644 docs/View.md delete mode 100644 docs/Work.md delete mode 100644 docs/index.md delete mode 100755 docs/template.html delete mode 100644 phpci.yml diff --git a/.gitattributes b/.gitattributes index e2985c1..46f0e24 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,11 +1,7 @@ /tests export-ignore -/old-tests export-ignore /vendor export-ignore /docs export-ignore /.gitattributes export-ignore /.gitignore export-ignore /.travis.yml export-ignore -/.scrutinizer.yml export-ignore -/core-logo.png export-ignore -/phpci.yml export-ignore -/.styleci.yml export-ignore +/core-logo.png export-ignore \ No newline at end of file diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index d73cd74..0000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,2 +0,0 @@ -tools: - external_code_coverage: true diff --git a/composer.json b/composer.json index effe010..bcf0ba4 100755 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "description": "Caffeina - Core PHP Toolbox", "keywords": ["framework","core","sdk","toolbox"], "homepage": "http://caffeina.com", - "version": "1.2.0", + "version": "1.2.1", "license": "MIT", "authors": [ { diff --git a/docs/CLI.md b/docs/CLI.md deleted file mode 100644 index 59202b2..0000000 --- a/docs/CLI.md +++ /dev/null @@ -1,99 +0,0 @@ - -You can define a command line interface via "command routes". - -Similar to the [[Route]] module, the [[CLI]] module is responsible for this feature. - -### Create a simple CLI app ---- - -Create a new file and give execution permissions: - -```bash -$ touch myapp && chmod +x myapp -``` - -Write this stub into `myapp` file : - -```php -#!/usr/bin/env php -each(function($row){ - print_r($row); -}); -``` - -### Get all data as an array ---- - -With a CSV object in read-mode, the `each` method will return all data if no parameters are passed to it. - -```php -$all_data = CSV::open('mydata.csv')->each(); -``` - -### Read a single row ---- - -With a CSV object in read-mode, the `read` method will return a single row from the CSV file. - -```php -$my_data = CSV::open('mydata.csv'); - -$first_row = $my_data->read(); -$second_row = $my_data->read(); -``` - -### Create a new CSV file ---- - -You can create a CSV file with the `CSV::create` factory. You can pass an optional separator or a format constant as a second parameter. Default value is `CSV:STANDARD`, that is a comma `,` separated. - -```php -$csv = CSV::create('characters.csv'); -``` - -### Write rows to the CSV ---- - -With a CSV object in write-mode, the `write` method will accept an array or an object and will write it to the CSV file. - -The `schema` method defines the headers of the table to be written (if omitted the first row keys are used instead). - -When a schema is defined, every written row will be reordered and filtered to be coherent with it. - -```php -$csv = CSV::create('characters.csv'); - -$csv->schema(['name','surname','email']); - -$csv->write([ - 'email' => 'punisher@nyc.com', - 'name' => 'Frank', - 'surname' => 'Castle', -]); - -$csv->write([ - 'name' => 'King', - 'surname' => 'Pin', - 'dirty' => 1234, - 'email' => 'the_kingpin@nyc.com', -]); - -echo $csv; -``` - -Returns: - -``` -name,surname,email -Frank,Castle,punisher@nyc.com -King,Pin,the_kingpin@nyc.com -``` - -### Convert a CSV file to a defined format ---- - -```php -// Convert an unknown-CSV to an Excel compatible one. -CSV::open('agents.csv')->convert('agents.xls',CSV::EXCEL); -``` - -This is pratically a shorthand for: - -```php -$csv = CSV::create('agents.xls',CSV::EXCEL); -CSV::open('agents.csv')->each(function($row) use ($csv) { - $csv->write($row); -}); -``` diff --git a/docs/Cache.md b/docs/Cache.md deleted file mode 100644 index af0f68d..0000000 --- a/docs/Cache.md +++ /dev/null @@ -1,139 +0,0 @@ -The [[Cache]] module allow you to handle an object persistence between requests and store heavy-computing persistent data. - - -### Retrieve a value ---- - -The simplest way to retrieve a value from cache is via the `get` method. - -```php -$shares = Cache::get('shares'); -``` - -You can optionally pass a default value and an expire time. The dafault value can be either a mixed or a callable. If you pass the latter it will invoked and the returned value will be used as the default value. - -```php -$help = Cache::get('help',true); - -$shares = Cache::get('shares',function(){ - return calc_user_shares(); -}); -``` - -**Important**: When the default value is used (from a cache miss), the cache value will be setted. - -```php -$value_generator = function(){ - return time(); -}; - -echo Cache::get('memento',$value_generator); // (Cache MISS) returned : 1389122001 ($value_generator called) -echo Cache::get('memento',$value_generator); // (Cache HIT) returned : 1389122001 -echo Cache::get('memento',$value_generator); // (Cache HIT) returned : 1389122001 - -``` - -### Setting a value ---- - -You can set a value for a key with the `set` method. - -```php -Cache::set('friend_or_foe','friend'); -``` - -You can pass an optional `expiration` parameter in seconds. - -```php -Cache::set('friend_or_foe','friend',15); // Expire in 15 sec - -echo Cache::get('friend_or_foe'); // friend -sleep(20); -echo Cache::get('friend_or_foe'); // (no value) - -``` - -### Delete a cached key ---- - -You can delete a cached key with the `delete` method. - -```php -Cache::delete('friend_or_foe'); -``` - -### Flush all cached keys ---- - -You can delete all cached keys with the `flush` method. - -```php -Cache::flush(); -``` - -### Check if a key is cached ---- - -You can delete a cached key with the `exists` method. - -```php -if ( Cache::exists('user_info') ) { ... } -``` - -### Increment/Decrement a value ---- - -You can increment/decrement a cached key value with the `inc` and `dec` methods. - -**Example** - -```php -Event::on('user.login',function(){ - Cache::inc('user.logged'); -}); - -Event::on('user.logout',function(){ - Cache::dec('user.logged'); -}); - -``` - -Default inc/dec value is 1, you can however change it by passing the increment/decrement value as the second parameter of the inc/dec methods. - -```php -Event::on('boss.killed',function(){ - Cache::inc('user.score',1000); -}); -``` - -### Changing caching strategy/driver ---- - -You can choose the Cache driver via the `using` method. The optional second parameter is dictionary of init paramenters to pass to the selected driver. - -The default driver is **Memory**, a request-only persistent storage. - -**Example** - -```php -// Use File-based caching -Cache::using('File',[ - 'cache_dir' => __DIR__ . '/cache' -]); -``` - - -### Enable/Disable cache ---- - -You can bybass all cache by passing `false` to the `Cache::enable` method. - -```php -Cache::enabled(false); -``` - -A common use for this is for disabling cache in debug mode. - -```php -Cache::enabled(!Options::get('debug',false)); -``` diff --git a/docs/Check.md b/docs/Check.md deleted file mode 100644 index aef055d..0000000 --- a/docs/Check.md +++ /dev/null @@ -1,83 +0,0 @@ -The [[Check]] module allow you to validate data in a easy way. - -### Validate data ---- - -The `valid` method check passed keys with the defined methods, in cascade. - -> The methods are a ordered priority list separated by `|`. You can pass comma separated `,` parameters to a method with the `methodname:param1,param2,"param string 3"` syntax. - -```php -if (!Check::valid([ - 'username' => 'required', - 'email' => 'required | email', - 'age' => 'required | numeric | in_range:18,90', - 'phone' => 'numeric', -], $data_to_validate)){ - echo "Errors: " . print_r(Check::errors(),true); -} else { - echo "OK!"; -} -``` - - -### Define a validation method ---- - -You can define a validation method via the `Check::method($name, callable $callback)` method. - -```php -Check::method('required', function($value){ - return empty($value) ? 'This data is required.' : true; -}); -``` - -> You can pass multiple methods in a single call via a `name => callback` associative array. - -Methods are initialized on-demand, so it's preferable to define them in the `core.check.init` event. - -```php -Event::on('core.check.init',function(){ - Check::method('required', function($value){ - return empty($value) ? 'This data is required.' : true; - }); -}); -``` - -Validation methods can have parameters passed to them, you can define them after the first one which is always the full value. - -```php -Check::method('in_range', function($value,$min,$max){ - return (($value>=$min)&&($value<=$max)) ? true : "This value must be in [$min,$max] range."; -}); -``` - -### Built-in methods ---- - -| Method | Parameters | Description | -|--------|------------|-------------| -`required` | | The value is required _(int(0) is accepted)_ -`alphanumeric` | | The value must contains only alphanumeric characters _(RegEx: \w)_ -`numeric` | | The value must be a number -`email` | | The value must be a valid email -`url` | | The value must be a valid URL -`max` | `limit` | The value must be less than `limit` -`min` | `limit` | The value must be greater than `limit` -`words` | `limit` | There must be less or equal than `limit` words. -`length` | `limit` | There must be less or equal than `limit` characters. -`range` | `min` , `max` | The value is must be between or equal to [ `min` , `max` ] range -`true` | | The value must be true (check PHP manual for trueness evaluation) -`false` | | The value must be false (check PHP manual for trueness evaluation) -`same_as` | `field_name` | The value must be the same as the `field_name` value - - -Example: - -```php -Check::valid([ - 'username' => 'required', - 'password' => 'required', - 'password_v' => 'required | same_as:password', -], Request::data()) || echo "Errors: " . print_r(Check::errors(),true); -``` \ No newline at end of file diff --git a/docs/Defer.md b/docs/Defer.md deleted file mode 100644 index 35c7ddf..0000000 --- a/docs/Defer.md +++ /dev/null @@ -1,12 +0,0 @@ -The [[Defer]] module defer execution of code after the client connection has been closed. - -### Run code after closing client connection ---- - -The passed callback will be queued for execution after the client connection has been closed. - -```php -Defer::after(function(){ - some_long_operation(); -}); -``` \ No newline at end of file diff --git a/docs/Dictionary.md b/docs/Dictionary.md deleted file mode 100644 index 9cfa3cf..0000000 --- a/docs/Dictionary.md +++ /dev/null @@ -1,151 +0,0 @@ - -The [[Dictionary]] class defines a multi-level key value repository with dot notation keys accessors. - - -### Building a dictionary ---- - -Dictionary is a behaviour class, it must be extended by another class or the value repository will be shared. - -```php -class Config extends Dictionary {} -``` - -### Setting a value ---- - -You can set a value from a key path via the `get` method. - -A valid key path is a arbitrary deep sequence of `.` separated strings. - -**Examples** - -- `test` -- `alpha.beta` -- `pages.section.text_block.3` - - -```php -Config::set('options.use_cache',false); - -Config::set('users.whitelist',[ - 'frank.ciccio', - 'walter.submarine', - 'pepen.spacca', -]); -``` - -### Getting a value ---- - -You can get a value from a key path via the `get` method. - -```php -echo Config::get('users.whitelist.1'); // walter.submarine -``` -You can optionally pass a default value to be returned when the requested key is not found. If a callable is passed the returned value will be used. - -```php -print_r( Config::get('a.test',['b'=>123]) ); // Array( [b] => 123 ) -echo Config::get('a.test.b'); // 123 -``` - -### Getting all values ---- - -You can get all key-values as an associative array via the `all` method. - -```php -$all_data = Config::all(); -``` - -Results : - -```php -Array ( - [users] => Array ( - [whitelist] => Array( - [0] => frank.ciccio - [1] => walter.submarine - [2] => pepen.spacca - ) - ) -) -``` -### Clearing the dictionary ---- - -You can clear all values from a dictionary via the `clear` method. - -```php -Config::clear(); -``` - -### Merging data ---- -The `merge` method extends the dictionary with values passed via an associative array. The second optional parameter will define the if merge data from right-to-left or backwise (default is false = left-to-right ). - -**Setting initial data** - -```php -Config::clear(); -Config::merge([ - 'user' => [ - 'name' => 'Simon', - 'role' => 'Villain', - ], -]); -``` - - -```php -Array ( - [user] => Array ( - [name] => Simon - [role] => Villain - ) -) -``` - -**Standard merge (left-to-right)** - -```php -Config::merge([ - 'user' => [ - 'name' => 'Frank', - ], - 'happy' => true, -]); -``` - - -```php -Array ( - [user] => Array ( - [name] => Frank - [role] => Villain - ) - [happy] => 1 -) -``` -**Back merge (right-to-left)** - -```php -Config::merge([ - 'user' => [ - 'name' => 'Frank', - ], - 'happy' => true, -],true); -``` - - -```php -Array ( - [user] => Array ( - [name] => Simon - [role] => Villain - ) - [happy] => 1 -) -``` \ No newline at end of file diff --git a/docs/Email.md b/docs/Email.md deleted file mode 100644 index 3f92d6b..0000000 --- a/docs/Email.md +++ /dev/null @@ -1,49 +0,0 @@ -The [[Email]] modules will allow you to send email messages via various services providers. - - -### Choosing the email service ---- - -You can choose the Email service via the `using` method. The optional second parameter is dictionary of init paramenters to pass to the selected driver. - -The default driver is **Native**, the a service that uses the PHP `mail` function. - -```php -Email::using('native'); -``` - -Init a service with parameters : - -```php -Email::using('SMTP',[ - 'host' => 'smtp.starkindustries.com', - 'port' => 25, - 'username' => 'tony', - 'password' => 'pepperpotts', -]); -``` - -### Sending an email ---- - -You can send an email with the chosen service via the `Email::send` method. - -An associative array must be passed with the email definition. - -```php -Email::send([ - 'to' => 'info@shield.com', - 'from' => 'Tony ', - 'subject' => 'About your proposal...', - 'message' => 'NOT interested.', -]); -``` - -### Email address formats ---- - -The `to` and `from` properties accepts one or an array of email addresses in these formats : - -1. `user@host.com` -1. `` -1. `Name Surname ` diff --git a/docs/Error.md b/docs/Error.md deleted file mode 100644 index 5ae36e0..0000000 --- a/docs/Error.md +++ /dev/null @@ -1,60 +0,0 @@ -The [[Error]] module allow you catch and manage errors. - -### Starting the error handler ---- - -You can start the error handler via the `capture` method. - -```php -Error::capture(); -``` - -From now on errors are converted to `ErrorExceptions` and routed to the handler which dispatches them in `core.error.*` events, filtered by kind. - -You can bind directly to these events via the special `Error::on*` methods. - -```php -Event::on('core.error.warning',function($exception){ - syslog(LOG_WARNING,$exception->getMessage()); -}); -``` - -Preferred shortcut : - -```php -Error::onWarning(function($exception){ - syslog(LOG_WARNING,$exception->getMessage()); -}); -``` - -These are the error mapping rules: - -ErrorType | Gravity | Event | Method -----|------|----|---- -`E_NOTICE` | Informational | `core.error.notice` | `Error::onNotice` -`E_USER_NOTICE ` | Informational | `core.error.notice` | `Error::onNotice` -`E_STRICT ` | Informational | `core.error.notice` | `Error::onNotice` -`E_WARNING ` | Warning | `core.error.warning` | `Error::onWarning` -`E_USER_WARNING ` | Warning | `core.error.warning` | `Error::onWarning` -`E_USER_ERROR ` | Fatal | `core.error.fatal` | `Error::onFatal` - -Every error will be **also** dispatched via the `core.error` event. You can bind directly to this event via the `Error::onAny` method. - -> If a single error handler returns `true`, the current error will be silenced and not propagated any more. - -### Setting the display mode ---- - -Errors can be displayed with various formats: - -Modes | Description | Example -----|------|---- -`Error::SIMPLE` | Prints the error message in plain text | `Notice: undefined variable x.` -`Error::HTML` | Prints the error message wrapped in html | `
Notice: undefined variable x.
` -`Error::SILENT` | Don't print anything | -`Error::JSON` | Print a JSON string of an error envelope | `{"error":"Notice: undefined variable x."}` - - -```php -Error::mode(Error::HTML); -``` diff --git a/docs/Event.md b/docs/Event.md deleted file mode 100644 index 2bd2d45..0000000 --- a/docs/Event.md +++ /dev/null @@ -1,80 +0,0 @@ - -The [[Event]] module allow you to bind callbacks to custom events. - -### Attach an handler ---- - -You can attach an handler to a named event via the `on` method. - -```php -Event::on('myevent',function(){ - echo 'Hello, Friend!'; -}); -``` - -Multiple handlers can be attached to the event, they will be sequentially executed when the event will be triggered. - -```php -Event::on('my.event',function(){ - echo 'First!'; -}); - -Event::on('my.event',function(){ - echo 'Second!'; -}); -``` -You can attach handlers to any event name. - - -### Trigger an event ---- - -You can trigger an event via the `trigger` method. - -```php -Event::trigger('my.event'); -``` -The `trigger` method will return an array containing the return values of all the handler attached to the event. - -**Example** - -```php -Event::on('my.event',function(){ - return 'Hello!'; -}); - -Event::on('my.event',function(){ - return time(); -}); - -$results = Event::trigger('my.event'); -``` - -The `$results` variable contains : - -```php -array(2) { - [0] => string(6) "Hello!" - [1] => int(1389115191) -} -``` - -`NULL` will be returned if no handlers are attached to the event. - -You can run a trigger only one time with the `triggerOnce` method. - -### Passing parameters to event handlers ---- - -You can pass a variable number of parameter to event handlers appending them after the event name in the `trigger` method. - -```php -Event::on('eat',function($who,$what,$where){ - echo "$who ate a $what, in the $where."; -}); - -Event::trigger('eat','Simon','Burrito','Kitchen'); - -// Result : Simon ate a Burrito, in the Kitchen - -``` diff --git a/docs/Examples.md b/docs/Examples.md deleted file mode 100644 index 462e5de..0000000 --- a/docs/Examples.md +++ /dev/null @@ -1,17 +0,0 @@ -# Basic Routing - -```php - sys_get_temp_dir(), -]); - -// Mount ./app/uploads directory to 'uploads' handle -File::mount('uploads','native', [ - 'root' => __DIR__.'/app/uploads', -]); -``` - -### Virtual Filesystems ---- - -#### Memory - -> The Memory VFS is a volatile (non persistent) read/write temporary filesystem. - -#### Native - -> The Native VFS is proxy for the OS provided filesystem. - -| Option | Description | Default | Mandatory | -|---|---|---|---| -| `root` | The local filesystem root absolute path | `/` | NO | - - -#### ZIP - -> The ZIP VFS permits read/write access to the files inside a ZIP archive. - -| Option | Description | Default | Mandatory | -|---|---|---|---| -| `root` | The absolute path of the ZIP archive | `TEMP-ZIP-ARCHIVE` | NO | - - -### File Operations ---- - -#### Check if a file exists : `File::exists($path)` - -```php -if (! File::exists("assets://images/logo.png") ) echo "File not found."; -``` - -#### Read a file : `File::read($path)` - -```php -$content = File::read("assets://images/logo.png"); -``` - -#### Write a file : `File::write($path, $data)` - -```php -File::write("assets://text/lorem.txt","Lorem Ipsum Dolor Sit Amet"); -``` - -#### Append to a file : `File::append($path, $data)` - -```php -File::append("assets://foobar.txt","Foo"); -File::append("assets://foobar.txt","Bar"); - -echo File::read("assets://foobar.txt"); -// FooBar - -``` - -#### Delete a file : `File::delete($path)` - -```php -File::delete("assets://useless_file.txt"); -``` - -#### Move/Rename a file : `File::move($old_path, $new_path)` - -```php -File::move("assets://files/old.txt", "assets://files/new.txt"); -``` - -#### Search/Locate : `File::search($file_glob)` - -```php -/** - * We have 2 mounted VFS : ["mem","assets"] - * mem has the following tree : - * - /test/alpha.txt - * - /test/beta.png - * - /info.txt - * - * assets has the following tree : - * - /img/1.jpg - * - /img/2.jpg - * - /info.txt - */ - -$texts = File::search("*.txt"); -``` - -**Results:** - -```json -[ - "mem://test/alpha.txt", - "mem://info.txt" - "assets://info.txt" -] -``` -If a VFS handle is not provided an implicit search is resolved with the first result. -The priority order is the mount order of the VFS. - -**Example:** - -```php -File::mount('mem-1','memory'); -File::mount('mem-2','memory'); - -File::write('mem-2://test.txt',"MEMORY 2"); -File::write('mem-1://test.txt',"MEMORY 1"); - -echo File::read('test.txt'); -``` - -**Results:** - -```json -MEMORY 1 -``` diff --git a/docs/Filters.md b/docs/Filters.md deleted file mode 100644 index 7850bd7..0000000 --- a/docs/Filters.md +++ /dev/null @@ -1,96 +0,0 @@ - -The [[Filters]] module allow you to permit user overrides to certain values. - -### Adding a filter ---- - -You can attach a filter function to a custom named group via the `add` method. - -```php -Filter::add('title',function($title){ - return strtoupper($title); -}); -``` - -Multiple calls to the same group attach multiple filter functions. - - -### Removing a filter ---- - -You can remove an attached filter function to a custom named group via the `remove` method. - -```php -$the_filter = function($title){ - return strtoupper($title); -}; - -Filter::add('title',$the_filter); - -... - -Filter::remove('title',$the_filter); -``` - -You can remove all filters attached to a group by not passing the filter function. - - -```php -Filter::remove('title'); -``` - -### Applying a filter ---- - -You can apply a filter to a value via the `with` method. - -```php -Filter::with('title','This was a triumph') -``` - -**Example** - -```php -Filter::add('title',function($title){ - return strtoupper($title); -}); - -Filter::add('title',function($title){ - return $title . '!'; -}); - -echo Filter::with('title','This was a triumph'); - -// THIS WAS A TRIUMPH! -``` - -Multiple fallback keys can be passed, the first non-empty queue will be used for the current filter. - -```php -Filter::with(["document.title", "title"],'This was a triumph') -``` - -**Example** - -```php -Filter::add("title", "strtoupper"); -echo Filter::with(["document.title", "title"],'This was a triumph'); -``` - -The `title` filter will be executed instead of the empty `document.title`. - -``` -THIS WAS A TRIUMPH -``` - -```php -Filter::add("title", "strtoupper"); -Filter::add("document.title", "str_rot13"); -echo Filter::with(["document.title", "title"],'This was a triumph'); -``` - -Here the `document.title` filter will be executed instead of `title`. - -``` -Guvf jnf n gevhzcu -``` \ No newline at end of file diff --git a/docs/HTTP.md b/docs/HTTP.md deleted file mode 100644 index c780dac..0000000 --- a/docs/HTTP.md +++ /dev/null @@ -1,108 +0,0 @@ - -The [[HTTP]] module allow you to make request via cURL. - -### Request an URL ---- - -You can perform an HTTP request (`GET`,`POST`,`PUT`,`DELETE`) on a passed URL via the `HTTP::get/post/put/delete` methods. - -```php -$homepage = HTTP::get("http://www.caffeinalab.com"); -``` - -If the response header `Content-Type: application/json` is present, returned payload will be automatically decoded to a PHP object. - -```php -$caffeina = HTTP::get('http://graph.facebook.com/caffeinalab'); -echo $caffeina->website; -``` - -``` -http://caffeinalab.com -``` - - -### Passing data to a request ---- - -You can pass data to the request defining an associative array as the **second** parameter for the call. - -```php -HTTP::post("http://api.example.com/user",[ - 'name' => 'Frank', - 'surname' => 'Castle', - 'email' => 'punisher@vengeance.com', -]); -``` - -By default, POST/PUT data is sended via `application/x-www-form-urlencoded`, you can switch to a `application/json` encoding by passing `true` to the `HTTP::useJSON` method. - -```php -HTTP::useJSON(true); -HTTP::post("http://api.example.com/user",[ - 'name' => 'Frank', - 'surname' => 'Castle', - 'email' => 'punisher@vengeance.com', -]); -``` - -``` -POST http://api.example.com/user -Content-Type: application/json -``` -```json -{ - "name": "Frank", - "surname": "Castle", - "email": "punisher@vengeance.com" -} -``` - -### Adding headers ---- - -You can pass extra headers per request defining an associative array as the **third** parameter for the call. - -```php -$results = HTTP::get("http://api.example.com/item",[],[ - 'Authorization' => 'Bearer d7033f287da887b1d463830ba48b9982', -]); -``` - -``` -GET http://api.example.com/item -Authorization: Bearer d7033f287da887b1d463830ba48b9982 -``` - -A global header can be appended to **every** request by using the `HTTP::addHeader($name, $value)` method. - -```php -HTTP::addHeader('X-Extra','Howdy'); -$results = HTTP::get("http://api.example.com/item",[],[ - 'Authorization' => 'Bearer d7033f287da887b1d463830ba48b9982', -]); -``` - -``` -GET http://api.example.com/item -X-Extra: Howdy -Authorization: Bearer d7033f287da887b1d463830ba48b9982 -``` - -A global header can be removed via the `HTTP::removeHeader($name)` method. - -```php -HTTP::removeHeader('X-Extra'); -``` - -By default the current user-agent is used in all requests : - -``` -Mozilla/4.0 (compatible; Core::HTTP; Windows NT 6.1) -``` - -You can however change it with the `HTTP::userAgent($value)` method. - -```php -HTTP::userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36'); -``` \ No newline at end of file diff --git a/docs/Hash.md b/docs/Hash.md deleted file mode 100644 index 195d72c..0000000 --- a/docs/Hash.md +++ /dev/null @@ -1,123 +0,0 @@ -The [[Hash]] module allow you to make hashes of variables. - -### Create an hash from a value ---- - -```php -$data = [1,2,3]; -$hash = Hash::make($data); -echo $hash; -``` -``` -262bbc0aa0dc62a93e350f1f7df792b9 -``` - -### Verify if an hash matches a value ---- - -```php -var_dump( - Hash::verify([1,2,3],'262bbc0aa0dc62a93e350f1f7df792b9'), - Hash::verify([1,2,3,4],'262bbc0aa0dc62a93e350f1f7df792b9') -); -``` -``` -bool(true) -bool(false) -``` - -### Create an hash with a specified algorithm ---- - -You can pass the hashing algorithm name as second optional parameter of the `make` method. - -```php -$data = [1,2,3]; -$hash = Hash::make($data,'sha256'); -echo $hash; -``` -``` -5a7c86cf345a733f16365dfaa43fe6b5dbf0d4cfb192fa3186b11795edaab62c -``` - -As shorthand, you can use the callStatic magic method and pass the alghoritm name as the method name. - -```php -$data = [1,2,3]; -$hash = Hash::crc32($data); -echo $hash; -``` -``` -d109fdce -``` - -### List all registered hashing algorithms ---- - -```php -print_r( Hash::methods() ); -``` - -``` -Array -( - [0] => md2 - [1] => md4 - [2] => md5 - [3] => sha1 - [4] => sha224 - [5] => sha256 - [6] => sha384 - [7] => sha512 - [8] => ripemd128 - [9] => ripemd160 - [10] => ripemd256 - [11] => ripemd320 - [12] => whirlpool - [13] => tiger128,3 - [14] => tiger160,3 - [15] => tiger192,3 - [16] => tiger128,4 - [17] => tiger160,4 - [18] => tiger192,4 - [19] => snefru - [20] => snefru256 - [21] => gost - [22] => adler32 - [23] => crc32 - [24] => crc32b - [25] => fnv132 - [26] => fnv164 - [27] => joaat - [28] => haval128,3 - [29] => haval160,3 - [30] => haval192,3 - [31] => haval224,3 - [32] => haval256,3 - [33] => haval128,4 - [34] => haval160,4 - [35] => haval192,4 - [36] => haval224,4 - [37] => haval256,4 - [38] => haval128,5 - [39] => haval160,5 - [40] => haval192,5 - [41] => haval224,5 - [42] => haval256,5 -) -``` - -### Check if you can use an algorithm ---- - -```php -var_dump( - Hash::can('whirlpool'), - Hash::can('funny_encoding') -); -``` - -``` -bool(true) -bool(false) -``` \ No newline at end of file diff --git a/docs/Installation.md b/docs/Installation.md deleted file mode 100644 index 6820d55..0000000 --- a/docs/Installation.md +++ /dev/null @@ -1,33 +0,0 @@ -Add package to your **composer.json**: - -```json -{ - "require": { - "caffeina-core/core": "dev-master" - } -} -``` - -Run [composer](https://getcomposer.org/download/): - -```bash -$ php composer.phar install -o -``` - -Now the entire toolchain is already available upon the vendor autoloader inclusion. - -```php - string(17) "This is an error." - [1]=> string(14) "Another error?" -} -array(1) { - ["info"]=> array(1) { - [0]=> string(18) "Testing messages!." - } -} -array(0) { -} -``` - -### Add a message ---- - -Messages must be registered to a container - -```php -Message::add('error',"There was an error!"); -Message::add('error',"Another one!"); -``` - -### Get all messages ---- - -Get (and remove from stash) all the messages. - -```php -$all_messages = Message::all(); - -print_r(Message::all()); -``` - -``` -false -``` - -### Get all messages of a kind - -You can retrieve only messages of a specified container. - -```php -foreach( Message::all('error') as $error ){ - echo "$error\n"; -}; -``` - -### Clear all messages - -```php -Message::clear(); -``` - -### Using messages in views ---- - -You can add a read-only accessor as a global view variable. - -```php -View::addGlobal('Message', Message::readOnly() ); -``` - -Now you can access messages directly in view templates via the `Message` global. - -```html -{% for type,messages in Message.all() %} - {% for text in messages %} -
{{ text }}
- {% endfor %} -{% endfor %} -``` - -The messages are one-shot only, only consumed they are deleted from the stash. - diff --git a/docs/Module.md b/docs/Module.md deleted file mode 100644 index 863f66f..0000000 --- a/docs/Module.md +++ /dev/null @@ -1,21 +0,0 @@ -The [[Module]] trait provides a way to extend classes, even static with new methods. - -### Extend a class with new methods ---- - -```php -class Test { - use Module; - public static function Foo(){ echo "Foo"; } -} - -Test::Foo(); // Foo -Test::Bar(); // Fatal error: Call to undefined method Test::Bar - -Test::extend([ - 'Bar' => function(){ echo "Bar"; }, -]); - -Test::Bar(); // Bar - -``` \ No newline at end of file diff --git a/docs/Password.md b/docs/Password.md deleted file mode 100644 index 4a049db..0000000 --- a/docs/Password.md +++ /dev/null @@ -1,24 +0,0 @@ -The [[Password]] module allow you securely hash/verify password. - -### Hash a password ---- - -```php -$hashed_passwd = Password::make('my_secret_password'); -echo $hashed_passwd; -``` -``` -$2y$12$s88T0ByrVDPEILP2GfJUWeSqHUCFMWGFwx1XmyCguHmO2L20XuR3W -``` - -### Verify password ---- - -```php -var_dump( - Password::verify('my_secret_password','$2y$12$s88T0ByrVDPEILP2GfJUWeSqHUCFMWGFwx1XmyCguHmO2L20XuR3W') -); -``` -``` -bool(true) -``` \ No newline at end of file diff --git a/docs/Persistence.md b/docs/Persistence.md deleted file mode 100644 index 0243d7b..0000000 --- a/docs/Persistence.md +++ /dev/null @@ -1,59 +0,0 @@ -The [[Persistence]] module allow you to augment a class with a database persistence layer. - -### Standard persistence ---- - -```php - -class User { - // Add persistence feat - use Persistence; - - public $id, $email, $name; - -} - -// Enable persistence defining the target database table -User::persistOn('users',[ - 'key' => 'id' // The primary key, 'id' is the default. -]); - -$me = new User(); -$me->id = 1000; -$me->email = 'john@email.com'; -$me->name = 'John Appleseed'; - -// Save data on database -$me->save(); - -// Retrieve an user by it's primary key -$current_user = User::load(1000); -echo $current_user->email; -``` - -``` -john@email.com -``` - -### Override Save/Load callbacks ---- - -You can override the save/load callback with custom methods. - -```php -// Persist on files instead of Database - -User::onLoad(function($id, $table, $options){ - $keyname = $options['key']; - $path = '/data/' . $table . '/' . Hash::md5($id) . '.php'; - $obj = null; - if (file_exists($path)) $obj = unserialize(file_get_contents($path)); - return $obj; -}); - -User::onSave(function($table, $options){ - // The current object is binded on $this variable - $keyname = $options['key']; - $path = '/data/' . $table . '/' . Hash::md5( $this->$keyname ) . '.php'; - return file_put_contents(serialize($this)) > 0; -}); diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index f434f68..0000000 --- a/docs/README.md +++ /dev/null @@ -1,39 +0,0 @@ - - -# Documentation - - -## Table of Contents - -- [[Cache]] : Save time-consuming data -- [[Check]] : Validate data -- [[CLI]] : Route commands to functions -- [[CSV]] : Comma Separated Values tools -- [[Defer]] : Execute code after closing the client connection -- [[Dictionary]] : Key-Value repository -- [[Email]] : Send messages via Email services -- [[Error]] : Handle errors -- [[Event]] : Execute code on events -- [[File]] : Utility for accessing stored data on virtual filesystems -- [[Filters]] : Overrides values -- [[Hash]] : Hashes object, arrays, strings -- [[HTTP]] : HTTP client -- [[Installation]] : Startup a project -- [[Loader]] : Enable class autoloading -- [[Message]] : Pass cross-request messages -- [[Options]] : Loads and merge options from various formats -- [[Module]] : Extends class with new methods -- [[Password]] : Create/Verify secure password hashes -- [[Persistence]] : Provides to a class a way to persist data -- [[Redirect]] : Redirect the request agent to other locations -- [[Request]] : Retrieve input data -- [[Response]] : Wrap headers/body HTTP/CLI response -- [[REST]] : REST API utilities -- [[Route]] : Route URLs to functions -- [[Session]] : Manage a session-persistent data stash -- [[Shell]] : Run shell commands -- [[String]] : Tool for text processing -- [[SQL]] : Access SQL Databases -- [[Token]] : Encode signed data in JWT tokens -- [[View]] : HTML Templates -- [[Work]] : Execute multiple jobs via cooperative multitasking diff --git a/docs/REST.md b/docs/REST.md deleted file mode 100644 index cef6aca..0000000 --- a/docs/REST.md +++ /dev/null @@ -1,44 +0,0 @@ -The [[REST]] module allow you to expose a resource via CRUD methods mapped to a RESTful API. - -You must require the [API Core Bundle](/caffeina-core/api). - -### Expose a resource ---- - -You can expose a resource via the `expose` method. - -```php -REST::expose('bucket',[ - 'create' => function() { echo "NEW bucket"; }, - 'read' => function($id){ echo "SHOW bucket($id)"; }, - 'update' => function($id){ echo "MODIFY bucket($id)"; }, - 'delete' => function($id){ echo "DELETE bucket($id)"; }, - 'list' => function() { echo "LIST buckets"; }, - 'clear' => function() { echo "CLEAR all buckets"; }, -]); -``` - -Request: - -``` -HTTP/1.1 GET /bucket/123 -``` - -Response: - -``` -SHOW bucket(123) -``` - -Example: - -```php -REST::expose('post',[ - 'create' => function() { return SQL::insert('posts', Input::data()); }, - 'read' => function($id){ return SQL::single('select * from posts where id=:id', ['id'=>$id]); }, - 'update' => function($id){ return SQL::update('posts', ['id'=>$id] + Input::data()); }, - 'delete' => function($id){ return SQL::delete('posts', $id); }, - 'list' => function() { return SQL::each('select * from posts'); }, - 'clear' => function() { return SQL::delete('posts'); }, -]); -``` diff --git a/docs/Redirect.md b/docs/Redirect.md deleted file mode 100644 index e732d8b..0000000 --- a/docs/Redirect.md +++ /dev/null @@ -1,31 +0,0 @@ -The [[Redirect]] module handles request agent redirection to other locations. - -### HTTP Redirect ---- - -A simple `Location` header redirection can be achieved via the `Redirect::to($url)` method. - -```php -if ( ! Session::get('loggedUser') ) Redirect::to('/login'); -``` - -**Warning :** -> The `to` method performs an immediate exit. - -### JavaScript Redirect ---- - -The `Redirect::viaJavaScript($url)` method send to the browser a script for `location` redirection. - -```php -Redirect::viaJavaScript('/login'); -``` - -This outputs : - -```html - -``` - -> If the optional boolean parameter `$parent` is passed as `true` the `parent.location` object is used. This is useful for redirecting inside iframes, like in Facebook Page Tab apps. - diff --git a/docs/Request.md b/docs/Request.md deleted file mode 100644 index c1d8118..0000000 --- a/docs/Request.md +++ /dev/null @@ -1,81 +0,0 @@ - -Handles the HTTP [[request]] for the current execution. - -### Getting an input parameter ---- - -Inputs passed to the request can be retrieved with the `Request::input($key=null, $default=null)` method. - -The function searches for an input named `$key` in the `$_REQUEST` superglobal, if not found returns the `$default` value passed (resolved if `$default` is callable). - -If you call `Request::input()` it will returns an associative array of all `$_REQUEST` content. - -`$_GET`, `$_POST`, `$_FILES`, `$_COOKIE` can be accessed directly with the `Request::get/post/files/cookie` methods. - -```php -echo "Hello, ", Request::input('name','Friend'), '!'; -``` - -``` -GET /?name=Alyx -``` -``` -Hello, Alyx! -``` - -### Getting the URL / URI ---- - -The `Request::URL()` method returns the current request URL, complete with host and protocol. - -The `Request::URI()` method returns the current request URL, without host and protocol and relative to the front controller path. - -``` -DocumentRoot : /web/mysite.com/public -Front Controller Path : /web/mysite.com/public/foo/bar/index.php - -Request::URL() –> http://mysite.com/foo/bar/someroute -Request::URI() –> /someroute -``` - -### Getting the HTTP method ---- - -The `Request::method()` method returns the current request HTTP method, lowercase. - -```php -echo Request::method(); -``` - -``` -get -``` - -### Getting RAW/JSON data ---- - -If data was passed with the request, the method `Request::data($key=null, $default=null)` will retrieve all (if called with no parameters) data or a single property if `$key` is passed. - -If requested data was empty, `$default` will be returned (resolved if callable is passed). - -If request data is passed with the `Content-Type: application/json` header, will be automatically decoded. - -```bash -POST / -Content-Type: application/json - -{ - "name": "Chell" -} -``` - -```php -print_r( Response::data() ); -``` - -```php -stdClass Object -( - [name] => Chell -) -``` \ No newline at end of file diff --git a/docs/Response.md b/docs/Response.md deleted file mode 100644 index c95de04..0000000 --- a/docs/Response.md +++ /dev/null @@ -1,74 +0,0 @@ - -The [[Response]] module wrap and handles the payload sended to the request agent. - -### Appending data to the response ---- - -Append a string to the response buffer via the `add` method. - -```php -Response::add('Hello world!'); -``` - -### Changing the content type ---- - -The `type` method accepts a MIME type string (or a `Response::TYPE_*` constant) for the body content type. - -```php -Response::send(); -``` - - -### Adding an header to the response ---- - -The `header($name, $value)` method set an header for being sended to the request agent. - -```php -Response::header('Authorization','Bearer mF_9.B5f-4.1JqM'); -``` - -``` -Authorization: Bearer mF_9.B5f-4.1JqM -``` - -### Get all defined headers ---- - -```php -$response_headers = Response::headers(); -``` - -### Get response body ---- - -```php -$response_body = Response::body(); -``` - -### Set the entire response body ---- - -You can set the entire response body by passing a parameter to the `body` method. - -```php -Response::body($new_body); -``` - -### Set the HTTP response status ---- - -You can set the HTTP response status with the `status` method. - -```php -Response::status(401); -``` - -The `error($code, $message='')` method is used to pass errors. - -> This method triggers the `core.response.error` event. - -```php -Response::error(401, "User not authorized"); -``` \ No newline at end of file diff --git a/docs/Route.md b/docs/Route.md deleted file mode 100644 index 51d4c73..0000000 --- a/docs/Route.md +++ /dev/null @@ -1,275 +0,0 @@ -The [[Route]] module allow you to bind callbacks to HTTP requests. - -### URL mapping ---- - -You can define a route via the `on` method. - -```php -Route::on('/hello',function(){ - echo 'Hello, Friend!'; -}); -``` - -This is the simplest form to define an `HTTP GET` route responding on URL `/hello`. -You can map the same route to multiple request methods using the fluent api interface. - -```php -Route::on('/hello') - ->via('get','post') - ->with(function(){ - echo 'Hello, Friend!'; - }); -``` -The `via` method accepts an array of string for handled HTTP request methods. - -The `with` method binds a callable function to the route. - -If you need to map various HTTP methods to different callbacks for a single URL _(like exposing a resource via a REST API)_ the `map` method allows you to pass a `method` => `callback` dictionary. - -```php -Route::map('/entity(/:id)/?',[ - 'get' => function($id=null){ - // READ: fetch the $id element or all if $id === null - }, - 'post' => function($id=null){ - // CREATE: build a new element - }, - 'put' => function($id=null){ - // UPDATE: modify $id element's properties - }, - 'delete' => function($id=null){ - // DELETE: delete $id element - }, -]) -``` - -### URL pattern matching and parameters extraction ---- -The route pattern is essentially a Regular Expression with some slight differencies. - -The pattern is **ALWAYS** matched against the **end** of the `REQUEST_URI` parameter (stripped of the query string). - -**Rules:** - -- every `(...)` group becomes optional -- you can extract parameters via `:named_parameter` -- the pattern can't contain the `#` character - -**Examples:** - -```php -Route::on('/element(/:id)/?',function($id=null){ - if (null === $id){ - $result = get_all_elements(); - } else { - $result = get_element_by_id($id); - } - print_r($result); -}); -``` - -In this example the optional (is in a `(...)` group) `:id` is extracted when present, and the route can be optionally terminated by a `/`. - -This route handles all of these request: - -- `/element` -- `/element/` -- `/element/123` -- `/element/123/` -- `/element/1919191` -- `/element/462635` -- etc.. - -But, as you can see, this example handles also `/element/fooo`. -If we want to give format rules to an extracted parameters we can use the `rules` method. - -The `rules` method accepts a `named_parameter` => `regex` dictionary. - -`rules([ 'parameter_name' => 'parameter_regex_pattern' ])` - -We can strenghten the former example adding rules to the `id` parameter for accepting only integer values _(defined by the \d+ regex pattern)_. - -**Example:** - -```php -Route::on('/element(/:id)/?',function($id=null){ - if (null === $id){ - $result = get_all_elements(); - } else { - $result = get_element_by_id($id); - } - print_r($result); -}) -->rules([ 'id' => '\d+' ]); -``` - -### Route groups ---- -You can encapsulate routes based on a prefix pattern. -If the current request doesn't match the group URL pattern, relative routes definition are **not** registered. - -This feature can be used for response-time optimization and for mounting route trees to a dynamic URL prefix. - -You can define *nested route groups*. - -**Examples:** - -**Admin section** - -```php -Route::group('/admin',function(){ - - Route::on('/',function(){ - echo "Admin Index"; - }); - - Route::on('/login') - ->via('get','post') - ->with(function(){ - // Handle login - }); - - Route::on('/logout',function(){ - // handle logout - }); - - Route::group('/dashboard',function(){ - - Route::on('/',function(){ - // Dashboard - }); - - Route::on('/details',function(){ - // Dashboard Details - }); - - }); - -}); -``` - -### Route middlewares ---- -You can append a list of middlewares `before` and `after` a Route, or a RouteGroup. - -> If a middleware returns `false` the entire route execution halts. - -Middlewares can be chained, the `before`s will be executed in *reverse declaration order* (FIFO), the `after`s in *direct declaration order* (LIFO). - - -```php -Route::on('/', - "[TEST]" -) -->before(function(){ - echo "(B1)"; -}) -->before(function(){ - echo "(B2)"; -}) -->after(function(){ - echo "(A1)"; -}) -->after(function(){ - echo "(A2)"; -}); -``` - -Gives this output : - -``` -(B2)(B1)[TEST](A1)(A2) -``` - -You can apply a middleware to multiple routes a single time using a RouteGroup : - -```php -Route::group('/private',function(){ - - Route::on('/', ... ); - Route::on('/dashboard', ... ); - Route::on('/profile', ... ); - Route::on('/settings', ... ); - -})->before(function(){ - if ( ! user_authorized() ) { - Response::error(403,"Forbidden"); - return false; - } -}); -``` - -### Dispatching routes ---- - -Remember to invoke the `dispatch` method before script end for route execution. - -```php -Route::on('/hello',function(){ - echo 'Hello, Friend!'; -}); - -// Run the route dispatcher. -Route::dispatch(); -``` - - -### Route can't find a match. (HTTP 404) ---- - -When no routes matches the current request, the `404` event is triggered. - -You can append a view to the `Response` to show a courtesy page. - -```php -Event::on(404,function(){ - Response::html( View::from('errors/404') ); -}); -``` - -### Render shortcuts ---- - -Instead of the rendering callback, you can also pass a string or a view, for direct rendering. - -**Closure** - -```php -Route::on('/',function(){ - return View::from('index'); -}); -``` -``` -

I'm the index!

-``` - -**A `View`** - -```php -Route::on('/', View::from('index') ); -``` -``` -

I'm the index!

-``` - -**A string _(not a callable one)_** - -```php -Route::on('/', 'Not a callable string' ); -``` -``` -Not a callable string -``` - -**An object** - -```php -Route::on('/',(object)[ - 'alpha' => 123, - 'beta' => [1,2,3] -]); -``` -``` -{"alpha":123,"beta":[1,2,3]} -``` \ No newline at end of file diff --git a/docs/SQL.md b/docs/SQL.md deleted file mode 100644 index 0381871..0000000 --- a/docs/SQL.md +++ /dev/null @@ -1,135 +0,0 @@ -The [[SQL]] module expose a shorthand for common database methods extending the PDO layer. - -### Bind to database ---- - -You can bind the SQL module to a database with a DSN (Data Source Name) string via the `connect` method. -Connection is lazy-loaded at the first database access. - -```php -SQL::connect('mysql:host=localhost;dbname=test','root','password'); -``` - -The event `core.sql.connect` si fired upon database connection. - -```php -Event::on('core.sql.connect',function(){ - SQL::exec('SET NAMES "UTF8"'); -}); -``` -### Execute a SQL statement ---- - -You can execute a SQL statement with the `exec` method. The query will be prepared and you can pass optional binding parameters as last function argument. - -```php -SQL::exec('TRUNCATE TABLE `users`'); - -SQL::exec('DELETE FROM `users` WHERE `age` < 16'); -``` - -### Retrieve a single value ---- - -The `value` method executes the query, with the optional parameters and returns the first column of the first row of the results. - -```php -$total_users = SQL::value('SELECT COUNT(1) FROM `users`'); - -$user_is_registered = !!SQL::value('SELECT 1 FROM `users` WHERE username = :usr_name',[ - 'usr_name' => $username -]); -``` - - -### Retrieve a single row ---- - -The `single` method executes the query, with the optional parameters and runs the passed callback with the current row object. - -```php -SQL::single('SELECT username, points FROM `rankings` LIMIT 1',function($rank){ - echo 'The Winner is : ',$rank->username,' with ',$rank->points,' points!'; -}); -``` -### Retrieve rows ---- - -The `each` method executes the query, with the optional parameters and runs the passed callback with the current row object for every row of the results. - -```php -SQL::each('SELECT * FROM `users`',function($user){ - echo '
  • ', $user->name ,'
  • '; -}); -``` - -### Retrieve all results ---- - -The `all` method is used to retrieve all results in a single call. - -```php -echo json_encode( SQL::all('SELECT `name` , `email` FROM `users`') ); -``` - - -### Insert a new row ---- - -The `insert` method is used to insert into a defined table a new row, passed as an associative array. - -```php -$inserted_item_id = SQL::insert('users',[ - 'name' => 'Stannis Baratheon', - 'password' => 'im_the_one_true_king', -]); -``` - -### Update a single row ---- - -The `update` method is used to change a single row data, passed as an associative array. - -```php -SQL::update('users',[ - 'id' => 321, - 'name' => 'King Stannis Baratheon', -]); -``` - -You can also override the name of the primary key column as the third function parameter, default is `id` - -```php -SQL::update('users',[ - 'email' => 'stannis@baratheon.com', - 'name' => 'King Stannis Baratheon', -],'email'); -``` - -### Delete a single row ---- - -The `delete` method is used to remove a single row data. - -```php -SQL::delete( 'users', [ 321, 432 ] ); -``` - -You can also override the name of the primary key column as the third function parameter, default is `id` - -```php -SQL::delete( 'users', [ 'mario@rossi.it', 'sara@rossi.it' ], 'email' ); -``` - -### Debug queries ---- - -You can bind a function to the `core.sql.query` event for listening every executed query. - -```php -Event::on('core.sql.query',function($query,$params,$statement){ - echo "SQL Query : $query \n"; - echo "Parameters : ", print_r($params,true), "\n"; - echo "Success : ", ($statement?'Yes':'No'), "\n"; -}); -``` diff --git a/docs/Session.md b/docs/Session.md deleted file mode 100644 index 1764775..0000000 --- a/docs/Session.md +++ /dev/null @@ -1,75 +0,0 @@ -The [[Session]] module allow you to make hashes of variables. - -### Create a new session - -Start the session handler with the `Session::start` method. - -```php -Session::start(); -``` - -You can pass a custom SID string as parameter. - -```php -Session::start("AWESOME_APP_SID"); -``` - -### Close and clear session - -All saved data and the session can be deleted with the `Session::clear` method. - -```php -Session::clear(); -``` - -### Retrieve a session value - -You can retrieve a value from session stash via the `Session::get` method. An optional second parameter can be passed for a default value if the requested one is missing. - -```php -$mydata = Session::get('mydata',"some default data"); -``` - -### Set a session value - -You can set a value into session stash via the `Session::set` method. - -```php -$mydata = Session::get('my_options',[ - 'a' => 1, - 'b' => 2, -]); - -$mydata['a']++; - -print_r( Session::set('my_options',$mydata) ); -``` - -First run - -``` -Array -( - [a] => 1 - [b] => 2 -) -``` - -Second run - -``` -Array -( - [a] => 2 - [b] => 2 -) -``` - -### Check if a key is in session stash - -You can check if a variable is in session stash with the `Session::exists` method. - -```php -if(!Session::exists('user')) Redirect::to('/login'); -``` - diff --git a/docs/Shell.md b/docs/Shell.md deleted file mode 100644 index 069dfef..0000000 --- a/docs/Shell.md +++ /dev/null @@ -1,210 +0,0 @@ - -The [[Shell]] class can be used to execute OS commands. - -### Executing a command ---- - -The Shell class permits the invocation of shell commands via dynamic static methods. - -**Examples :** - -Run the `cal` command : - -```php -echo Shell::cal(); -``` - -This outputs : - -```bash - Agosto 2014 -Do Lu Ma Me Gi Ve Sa - 1 2 - 3 4 5 6 7 8 9 -10 11 12 13 14 15 16 -17 18 19 20 21 22 23 -24 25 26 27 28 29 30 -31 -``` - -#### Passing a string - -You can send multiple arguments to the command by passing parameters to the method. - -```php -echo Shell::ls('-la ./'); - -// or - -echo Shell::ls('-la', './'); -``` - -#### Passing an array - -If an array is passed as an argument it will be interpreted as an options map : - -```php -echo Shell::example_command([ - 'silent', - 'username' => 'Gordon Freeman', - 'debug' => false, - 'profile' => true, -],'other commands'); -``` - -Compiles to : - -```bash -/usr/bin/env example_command --silent --username='Gordon Freeman' --profile other commands -``` - -#### Passing a Shell object - -If a Shell object is passed as an argument it will be compiled ad a direct evaluation subcommand : - -```php -Shell::pipe( - Shell::cal(), - Shell::grep(Shell::date('+%d')) -); -``` - -Compiles to : - -```bash -cal | /usr/bin/env grep $(/usr/bin/env date +%d) -``` - -#### Lazy Execution - -Shell command are not invoked immediately, but only on result evaluation (lazy invocation). You can store the prepared command in a variable for multiple use. - -To invoke the command you must force the evaluation to string or call the `run` method; - -```php -// Not executed. -$command = Shell::cal(); - -// Not executed. -$command; - -// Not executed. -!$command; - -// Executed. -$command->run(); - -// Executed. -(string)$command; - -// Executed. -$x = $command . ''; -``` - -### Get the compiled shell command ---- - -You can retrieve the compiled shell command via the `getShellCommand` method. - -```php -echo Shell::sed('-e','"s/^ *//"','-e','"s/ *$//"')->getShellCommand(); -``` - -Returns: - -``` -/usr/bin/env sed -e "s/^ *//" -e "s/ *$//" -``` - -### Command piping ---- - -If you want to concatenate multiple commands in a pipeline you must use the `pipe` method. - -```php -echo Shell::pipe( - Shell::cal(), - Shell::grep('-E','"\d{4}"'), - Shell::sed('-e','"s/^ *//"','-e','"s/ *$//"') -); -``` - -The compiled command is : - -```bash -cal | /usr/bin/env grep -E "\d{4}" | /usr/bin/env sed -e "s/^ *//" -e "s/ *$//" -``` - -The output : - -``` -August 2014 -``` - -### Command sequencing ---- - -Similar to command piping you can concatenate multiple shell commands via logical implication ( && ) using the `sequence` method. - -```php -echo Shell::sequence( - Shell::nginx('-t'), - Shell::nginx('-s reload') -); -``` - -The compiled command is : - -```bash -/usr/bin/env nginx -t && /usr/bin/env nginx -s reload -``` - -### Command aliases ---- - -You can create an alias to a complex or dynamic shell command via the `alias` method. - -```php -Shell::alias('trim',function(){ - return Shell::sed('-e','"s/^ *//"','-e','"s/ *$//"'); -}); -``` - -Now you can use the alias `trim` as if it was a real command, when invoked the the callback will be called and the resulting Shell object (or raw command if you return a string) will be used in place of the alias. - -**Example:** - -```php -echo Shell::pipe( - Shell::cal(), - Shell::grep('-E','"\d{4}"'), - Shell::trim() -); -``` - -Compiles as : - -```bash -cal | /usr/bin/env grep -E "\d{4}" | /usr/bin/env sed -e "s/^ *//" -e "s/ *$//" -``` - -Another example are some git aliases for an easy deploy system: - -```php -Shell::alias('gitCommit',function($commit_message = 'Save'){ - return Shell::sequence( - Shell::git('add -A'), - Shell::git('commit -am',Shell::escape($commit_message)) - ); -}); - -Shell::alias('gitCommitAndPush',function($commit_message = 'Save'){ - return Shell::sequence( - Shell::gitCommit($commit_message), - Shell::git('pull'), - Shell::git('push') - ); -}); -``` - -Now you can "save" your work with : `Shell::gitCommit()` or with a commit message `Shell::gitCommit("Latest fixes.")`; diff --git a/docs/String.md b/docs/String.md deleted file mode 100644 index d1e1720..0000000 --- a/docs/String.md +++ /dev/null @@ -1,17 +0,0 @@ -The [[String]] module contains text related utility. - -### Render a string template ---- - -Fast string templating, it uses a dot notation path for retrieving value. - -Values must be enclosed in `{{ }}` double curly braces. - -```php -echo String::render('Your IP is : {{ server.REMOTE_HOST }}',[ - 'server' => $_SERVER -]); -``` -``` -Your IP is : 192.30.252.131 -``` \ No newline at end of file diff --git a/docs/View.md b/docs/View.md deleted file mode 100644 index f6f51eb..0000000 --- a/docs/View.md +++ /dev/null @@ -1,86 +0,0 @@ -The [[View]] module handles the rendering of templates via various engines. - -Core ships a vanilla PHP template engine ([[PHPView]]), you can find other bridges in the [caffeina-core](https://github.com/caffeina-core) repository - -### Init view engine ---- - -You can select a view engine with the `View::using($engine_instance)` method. - -```php -View::using(new PHPView(__DIR__.'/templates')); -``` - -### Create a view ---- - -You can create a view object the `View::from($template_name)` factory method. - -The `$template_name` is the relative path of the template inside the template directory. - -> Extension **must be omitted**, it's automatically handled by the engine. - -```php -// Prepares /templates/index.php -$index_page = View::from('index'); - -// Prepares /templates/errors/404.error.php -$error_page = View::from('errors/404.error'); -``` - -### Rendering a view ---- - -A view renders itself when casted to a string. - -```php -echo View::from('index'); -``` - -### Passing data to a view ---- - -You can pass data to a view via the `with(array $variables)` method. - -```php -echo View::from('index')->with([ - 'title' => 'Index page', - 'toc' => [ - 'First', - 'Second', - 'Third', - ], -]); -``` - -You can use the passed variables directly in the template (example uses the [twig engine](https://github.com/caffeina-core/twig) ) - -```html -

    {{ title }}

    -
      - {% for item in toc %} -
    • {{ item }}
    • - {% endfor %} -
    -``` - -Renders - -```html -

    Index page

    -
      -
    • First
    • -
    • Second
    • -
    • Third
    • -
    -``` - -### Create a view with parameters shorthand ---- - -As a shorthand you can pass parameters to the view directly to the `from` factory method. - -```php -echo View::from('index',[ - 'title' => 'Index page', -]); \ No newline at end of file diff --git a/docs/Work.md b/docs/Work.md deleted file mode 100644 index eb13c06..0000000 --- a/docs/Work.md +++ /dev/null @@ -1,98 +0,0 @@ -The [[Work]] module allow you to execute multiple jobs in parallel, via [cooperative multitasking](http://en.wikipedia.org/wiki/Cooperative_multitasking). - -**Notice:** -> This feature needs [Generators](http://php.net/manual/it/language.generators.overview.php), so PHP version must be at least 5.5 to be used, a fatal error is triggered if version requirement is not met. - -### Add a worker ---- - -Workers must be generators, so the `yield` keywords must be present. When a worker is registered, an object of class `TaskCoroutine` is returned. - -```php -Work::add(function(){ - for ($i = 0; $i <= 10; $i++) { - echo "Value: $i \n"; - yield; // Pass control to other workers - } -}); -``` - -You can also assign a name to the worker : - -```php -Work::add('the_counter',function(){ - for ($i = 0; $i <= 10; $i++) { - echo "Value: $i \n"; - yield; // Pass control to other workers - } -}); -``` - - -### Run and resolve all workers ---- - -All registered workers will be executed and the method will release control after all of the workers have finished their job. - -```php -Work::run(); -``` - -### Example ---- - -```php -Work::add(function(){ - for ($i = 0; $i <= 20; $i++) { - echo "A: $i \n"; - yield; - } -}); - -Work::add(function(){ - for ($i = 0; $i <= 10; $i++) { - echo "B: $i \n"; - yield; - } -}); - -// Run the workers -Work::run(); -``` - -Output: - -``` -A:0 -B:0 -A:1 -B:1 -A:2 -B:2 -A:3 -B:3 -A:4 -B:4 -A:5 -B:5 -A:6 -B:6 -A:7 -B:7 -A:8 -B:8 -A:9 -B:9 -A:10 -B:10 -A:11 -A:12 -A:13 -A:14 -A:15 -A:16 -A:17 -A:18 -A:19 -A:20 -``` \ No newline at end of file diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index f434f68..0000000 --- a/docs/index.md +++ /dev/null @@ -1,39 +0,0 @@ - - -# Documentation - - -## Table of Contents - -- [[Cache]] : Save time-consuming data -- [[Check]] : Validate data -- [[CLI]] : Route commands to functions -- [[CSV]] : Comma Separated Values tools -- [[Defer]] : Execute code after closing the client connection -- [[Dictionary]] : Key-Value repository -- [[Email]] : Send messages via Email services -- [[Error]] : Handle errors -- [[Event]] : Execute code on events -- [[File]] : Utility for accessing stored data on virtual filesystems -- [[Filters]] : Overrides values -- [[Hash]] : Hashes object, arrays, strings -- [[HTTP]] : HTTP client -- [[Installation]] : Startup a project -- [[Loader]] : Enable class autoloading -- [[Message]] : Pass cross-request messages -- [[Options]] : Loads and merge options from various formats -- [[Module]] : Extends class with new methods -- [[Password]] : Create/Verify secure password hashes -- [[Persistence]] : Provides to a class a way to persist data -- [[Redirect]] : Redirect the request agent to other locations -- [[Request]] : Retrieve input data -- [[Response]] : Wrap headers/body HTTP/CLI response -- [[REST]] : REST API utilities -- [[Route]] : Route URLs to functions -- [[Session]] : Manage a session-persistent data stash -- [[Shell]] : Run shell commands -- [[String]] : Tool for text processing -- [[SQL]] : Access SQL Databases -- [[Token]] : Encode signed data in JWT tokens -- [[View]] : HTML Templates -- [[Work]] : Execute multiple jobs via cooperative multitasking diff --git a/docs/template.html b/docs/template.html deleted file mode 100755 index cfdb6b8..0000000 --- a/docs/template.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - {{NAME}} :: viewdocs.io - - - - - - - -
    -
    -

    {{NAME}} :: index

    -
    -
    - {{CONTENT}} -
    -
    - - - - - - \ No newline at end of file diff --git a/phpci.yml b/phpci.yml deleted file mode 100644 index ef21498..0000000 --- a/phpci.yml +++ /dev/null @@ -1,17 +0,0 @@ -build_settings: - verbose: true - -test: - lint: - shell: - - "cd tests && php run_tests.php" - -failure: - email: - committer: true - - slack_notify: - webhook_url: "https://hooks.slack.com/services/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" - room: "#commits" - username: "Arbiter" - icon: ":ghost:"