Update v1.0.6

This commit is contained in:
Bhanu Slathia
2016-02-16 23:24:52 +05:30
parent c710c20b9e
commit b1f62846ab
7662 changed files with 1361647 additions and 0 deletions

22
vendor/chumper/datatable/.gitattributes vendored Normal file
View File

@@ -0,0 +1,22 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

6
vendor/chumper/datatable/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
/vendor
composer.phar
composer.lock
datatable.sublime-project
.DS_Store
.idea

12
vendor/chumper/datatable/.travis.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
language: php
php:
- 5.3
- 5.4
- 5.5
before_script:
- curl -s http://getcomposer.org/installer | php
- php composer.phar install --dev
script: phpunit

614
vendor/chumper/datatable/README.md vendored Normal file
View File

@@ -0,0 +1,614 @@
Datatable
=========
This is a __Laravel 5 package__ for the server and client side of datatables at http://datatables.net/
![Image](https://raw.githubusercontent.com/Chumper/Datatable/master/datatable.jpg)
##Known Issues
* none i know of so far
##TODO
* fix incoming bugs
* code documentaion
##Features
This package supports:
* Support for Collections and Query Builder
* Easy to add and order columns
* Includes a simple helper for the HTML side
* Use your own functions and presenters in your columns
* Search in your custom defined columns ( Collection only!!! )
* Define your specific fields for searching and ordering
* Add custom javascript values for the table
* Tested! (Ok, maybe not fully, but I did my best :) )
## Please note!
There are some differences between the collection part and the query part of this package.
The differences are:
| Difference | Collection | Query |
| --- |:----------:| :----:|
|Speed | - | + |
Custom fields | + | +
Search in custom fields | + | -
Order by custom fields | + | -
Search outside the shown data (e.g.) database | - | +
For a detailed explanation please see the video below.
http://www.youtube.com/watch?v=c9fao_5Jo3Y
Please let me know any issues or features you want to have in the issues section.
I would be really thankful if you can provide a test that points to the issue.
##Installation
This package is available on http://packagist.org, just add it to your composer.json
"chumper/datatable": "dev-develop"
Alternatively, you can install it using the `composer` command:
composer require chumper/datatable "dev-develop"
In Config/App.php: Add line Provider:
```php
'Chumper\Datatable\DatatableServiceProvider',
```
__If using Laravel 5.1:__ you will want to add:
```php
Chumper\Datatable\DatatableServiceProvider::class,
```
Add line Alias:
```php
//new
'Datatable' => 'Chumper\Datatable\Facades\DatatableFacade',
```
You can then access it under the `Datatable` alias.
##Basic Usage
There are two ways you can use the plugin, within one route or within two routes:
###Two routes
* Create two routes: One to deliver the view to the user, the other for datatable data, eg:
```php
Route::resource('users', 'UsersController');
Route::get('api/users', array('as'=>'api.users', 'uses'=>'UsersController@getDatatable'));
```
* Your main route will deliver a view to the user. This view should include references to your local copy of [datatables](http://datatables.net/). In the example below, files were copied from the datatables/media directories and written to public/assets. Please note that the scripts must be located above the call to Datatable:
```php
<link rel="stylesheet" type="text/css" href="/assets/css/jquery.dataTables.css">
<script type="text/javascript" src="/assets/js/jquery.js"></script>
<script type="text/javascript" src="/assets/js/jquery.dataTables.min.js"></script>
{!! Datatable::table()
->addColumn('id','Name') // these are the column headings to be shown
->setUrl(route('api.users')) // this is the route where data will be retrieved
->render() !!}
```
* Create a controller function to return your data in a way that can be read by Datatables:
```php
public function getDatatable()
{
return Datatable::collection(User::all(array('id','name')))
->showColumns('id', 'name')
->searchColumns('name')
->orderColumns('id','name')
->make();
}
```
You should now have a working datatable on your page.
###One route
In your route you should use the Datatable::shouldHandle method which will check whether the plugin should handle the request or not.
```php
if(Datatable::shouldHandle())
{
return Datatable::collection(User::all(array('id','name')))
->showColumns('id', 'name')
->searchColumns('name')
->orderColumns('id','name')
->make();
}
```
The plugin will then query the same url for information. The shouldHandle method just checks for an ajax request and if sEcho is set.
##HTML Example
```php
Datatable::table()
->addColumn('id',Lang::get('user.lastname'))
->setUrl(URL::to('auth/users/table'))
->render();
```
With seperate table and script:
```php
$table = Datatable::table()
->addColumn('Email2','Email', "Test")
->noScript();
// to render the table:
$table->render()
// later in the view you can render the javascript:
$table->script();
```
This will generate a HTML table with two columns (id, lastname -> your translation) and will set the URL for the ajax request.
> Note: This package will **NOT** include the `datatable.js`, that is your work to do.
> The reason is that for example i use Basset and everybody wants to do it their way...
If you want to provide your own template for the table just provide the path to the view in laravel style.
```php
Datatable::table()
->addColumn('id',Lang::get('user.lastname'))
->setUrl(URL::to('auth/users/table'))
->render('views.templates.datatable');
```
##Server Example
```php
Datatable::collection(User::all())
->showColumns('id')
->addColumn('name',function($model)
{
return $model->getPresenter()->yourProperty;
}
)->make();
```
This will generate a server side datatable handler from the collection `User::all()`.
It will add the `id` column to the result and also a custom column called `name`.
Please note that we need to pass a function as a second parameter, it will **always** be called
with the object the collection holds. In this case it would be the `User` model.
You could now also access all relationship, so it would be easy for a book model to show the author relationship.
```php
Datatable::collection(User::all())
->showColumns('id')
->addColumn('name',function($model)
{
return $model->author->name;
}
)->make();
```
> Note: If you pass a collection of arrays to the `collection` method you will have an array in the function, not a model.
The order of the columns is always defined by the user and will be the same order the user adds the columns to the Datatable.
##Query or Collection?
There is a difference between query() and collection().
A collection will be compiled before any operation - like search or order - will be performed so that it can also include your custom fields.
This said the collection method is not as performing as the query method where the search and order will be tackled before we query the database.
So if you have a lot of Entries (100k+) a collection will not perform well because we need to compile the whole amount of entries to provide accurate sets.
A query on the other side is not able to perform a search or orderBy correctly on your custom field functions.
> TLTR: If you have no custom fields, then use query() it will be much faster
> If you have custom fields but don't want to provide search and/or order on the fields use query().
> Collection is the choice if you have data from somewhere else, just wrap it into a collection and you are good to go.
> If you have custom fields and want to provide search and/or order on these, you need to use a collection.
Please also note that there is a significant difference betweeen the search and order functionality if you use query compared to collections.
Please see the following video for more details.
http://www.youtube.com/watch?v=c9fao_5Jo3Y
##Available functions
This package is separated into two smaller parts:
1. Datatable::table()
2. Datatable::collection()
3. Datatable::query()
The second and third one is for the server side, the first one is a helper to generate the needed table and javascript calls.
###Collection & Query
**collection($collection)**
Will set the internal engine to the collection.
For further performance improvement you can limit the number of columns and rows, i.e.:
$users = User::activeOnly()->get('id','name');
Datatable::collection($users)->...
**query($query)**
This will set the internal engine to a Eloquent query...
E.g.:
$users = DB::table('users');
Datatable::query($users)->...
The query engine is much faster than the collection engine but also lacks some functionality,
for further information look at the table above.
**showColumns(...$columns)**
This will add the named columns to the result.
> Note: You need to pass the name in the format you would access it on the model or array.
> example: in the db: `last_name`, on the model `lastname` -> showColumns('lastname')
You can provide as many names as you like
**searchColumns(..$fields)**
Will enable the table to allow search only in the given columns.
Please note that a collection behaves different to a builder object.
Note: If you want to search on number columns with the query engine, then you can also pass a search column like this
```
//mysql
->searchColumns(array('id:char:255', 'first_name', 'last_name', 'address', 'email', 'age:char:255'))
//postgree
->searchColumns(array('id:text', 'first_name', 'last_name', 'address', 'email', 'age:text'))
```
This will cast the columns int the given types when searching on this columns
**orderColumns(..$fields)**
Will enable the table to allow ordering only in the given columns.
Please note that a collection behaves different to a builder object.
**addColumn($name, $function)**
Will add a custom field to the result set, in the function you will get the whole model or array for that row
E.g.:
```php
Datatable::collection(User::all())
->addColumn('name',function($model)
{
return $model->author->name;
}
)->make();
```
You can also just add a predefined Column, like a DateColumn, a FunctionColumn, or a TextColumn
E.g.:
```php
$column = new TextColumn('foo', 'bar'); // Will always return the text bar
//$column = new FunctionColumn('foo', function($model){return $model->bar}); // Will return the bar column
//$column = new DateColumn('foo', DateColumn::TIME); // Will return the foo date object as toTimeString() representation
//$column = new DateColumn('foo', DateColumn::CUSTOM, 'd.M.Y H:m:i'); // Will return the foo date object as custom representation
Datatable::collection(User::all())
->addColumn($column)
->make();
```
You can also overwrite the results returned by the QueryMethod by using addColumn in combination with showColumns.
You must name the column exactly like the database column that you're displaying using showColumns in order for this to work.
```php
$column = new FunctionColumn('foo', function ($row) { return strtolower($row->foo); }
Datatable::query(DB::table('table')->lists('foo'))
->showColumns('foo')
->addColumn($column)
->orderColumns('foo')
->searchColumns('foo')
->make()
```
This will allow you to have sortable and searchable columns using the QueryEngine while also allowing you to modify the return value of that database column entry.
Eg: linking an user_id column to it's page listing
```php
$column = new FunctionColumn('user_id', function ($row) { return link_to('users/'.$row->user_id, $row->username) }
Datatable::query(DB::table('table')->lists('user_id', 'username'))
->showColumns('user_id')
->addColumn($column)
->orderColumns('user_id')
->searchColumns('user_id')
```
Please look into the specific Columns for further information.
**setAliasMapping()**
Will advise the Datatable to return the data mapped with the column name.
So instead of
```javascript
{
"aaData":[
[3,"name","2014-02-02 23:28:14"]
],
"sEcho":9,
"iTotalRecords":2,
"iTotalDisplayRecords":1
}
```
you will get something like this as response
```javascript
{
"aaData":[
{"id":2,"name":"Datatable","created_at":"Sun, Feb 2, 2014 7:17 PM"}
],
"sEcho":2,
"iTotalRecords":2,
"iTotalDisplayRecords":1
}
```
**make()**
This will handle the input data of the request and provides the result set.
> Without this command no response will be returned.
**clearColumns()**
This will reset all columns, mainly used for testing and debugging, not really useful for you.
> If you don't provide any column with `showColumn` or `addColumn` then no column will be shown.
> The columns in the query or collection do not have any influence which column will be shown.
**getOrder()**
This will return an array with the columns that will be shown, mainly used for testing and debugging, not really useful for you.
**getColumn($name)**
Will get a column by its name, mainly used for testing and debugging, not really useful for you.
###Specific QueryEngine methods
**setSearchWithAlias()**
If you want to use an alias column on the query engine and you don't get the correct results back while searching then you should try this flag.
E.g.:
```php
Datatable::from(DB::table("users")->select('firstname', "users.email as email2")->join('partners','users.partner_id','=','partners.id'))
->showColumns('firstname','email2')
->setSearchWithAlias()
->searchColumns("email2")
```
In SQL it is not allowed to have an alias in the where part (used for searching) and therefore the results will not counted correctly.
With this flag you enable aliases in the search part (email2 in searchColumns).
Please be aware that this flag will slow down your application, since we are getting the results back twice to count them manually.
**setSearchOperator($value = "LIKE")**
With this method you can set the operator on searches like "ILIKE" on PostgreSQL for case insensitivity.
**setExactWordSearch**
Will advice the engines only to search for the exact given search string.
###Specific CollectionEngine methods
**setSearchStrip() & setOrderStrip()**
If you use the search functionality then you can advice
all columns to strip any HTML and PHP tags before searching this column.
This can be useful if you return a link to the model detail but still want to provide search ability in this column.
**setCaseSensitive($boolean = 'false')**
Set the search method to case sensitive or not, default is false
###Table
**noScript()**
With setting this property the Table will not render the javascript part.
You can render it manually with
**script($view = null)**
Will render the javascript if no view is given or the default one and will pass the class name, the options and the callbacks.
Example:
```php
$table = Datatable::table()
->addColumn('Email2','Email', "Test")
->noScript();
// to render the table:
$table->render()
// later in the view you can render the javascript:
$table->script();
```
**setUrl($url)**
Will set the URL and options for fetching the content via ajax.
**setOptions($name, $value) OR setOptions($array)**
Will set a single option or an array of options for the jquery call.
You can pass as paramater something like this ('MyOption', 'ValueMyOption') or an Array with parameters, but some values in DataTable is a JSON so how can i pass a JSON in values? Use another array, like that:
setOptions(array("MyOption"=> array('MyAnotherOption'=> 'MyAnotherValue', 'MyAnotherOption2'=> 'MyAnotherValue2')));
```js
//GENERATE
jQuery(.Myclass).DataTable({
MyOption: {
MyAnotherOption: MyAnotherValue,
MyAnotherOption2: MyAnotherValue2,
}
});
```
As a sugestion, take a look at this 2 files javascript.blade.php && template.blade.php in vendor/Chumper/datatable/src/views. You'll understand all the logic and see why it's important to pass the parameter like an array (json_encode and others stuffs).
**setCallbacks($name, $value) OR setCallbacks($array)**
Will set a single callback function or an array of callbacks for the jquery call. DataTables callback functions are described at https://datatables.net/usage/callbacks. For example,
```php
->setCallbacks(
'fnServerParams', 'function ( aoData ) {
aoData.push( { "name": "more_data", "value": "my_value" } );
}'
)
```
**addColumn($name)**
Will add a column to the table, where the name will be rendered on the table head.
So you can provide the string that should be shown.
if you want to use the alias mapping feature of the server side table then you need to add an array like this
```php
Datatable::table()
->addColumn(array(
'id' => 'ID',
'name' => 'Name',
'created_at' => 'Erstellt'
))
->render();
```
Please note that passing an assosiative array to the addColumn function will automatically enable the alias function on the table
**setAliasMapping(boolean)**
Here you can explicitly set if the table should be aliased or not.
**countColumns()**
This will return the number of columns that will be rendered later. Mainly for testing and debugging.
**getData()**
Will return the data that will be rendered into the table as an array.
**getOptions()**
Get all options as an array.
**render($view = template.blade)**
Renders the table. You can customize this by passing a view name.
Please see the template inside the package for further information of how the data is passed to the view.
**setData($data)**
Expects an array of arrays and will render this data when the table is shown.
**setCustomValues($name, $value) OR setCustomValues($array)**
Will set a single custom value, or an array of custom values, which will be passed to the view. You can access these values in your custom view file. For example, if you wanted to click anywhere on a row to go to a record (where the record id is in the first column of the table):
In the calling view:
```php
{{ DataTable::table()
->addColumn($columns)
->setUrl($ajaxRouteToTableData)
->setCustomValues('table-url', $pathToTableDataLinks)
->render('my.datatable.template') }}
```
In the datatable view (eg, 'my.datatable.template'):
```js
@if (isset($values['table-url']))
$('.{{$class}}').hover(function() {
$(this).css('cursor', 'pointer');
});
$('.{{$class}}').on('click', 'tbody tr', function(e) {
$id = e.currentTarget.children[0].innerHTML;
$url = e.currentTarget.baseURI;
document.location.href = "{{ $values['table-url'] }}/" + $id;
});
@endif
```
**setOrder(array $order)**
Defines the order that a datatable will be ordered by on first page load.
```php
{{ DataTable::table()
->addColumn('ID', 'First Name', 'Last Name')
->setUrl($ajaxRouteToTableData)
->setOrder(array(2=>'asc', 1=>'asc')) // sort by last name then first name
->render('my.datatable.template') }}
```
##Extras
Some extras features, using the Datatables api.
### - TableTools
To use TableTools you will need to add some files in your project (https://datatables.net/extensions/tabletools/), if you want some help download the datatable's package and inside the extension folder go to /tabletools and study the examples. After, all the files include, don't forget to pass the parameters like this:
```js
//In view:
{{
Datatable::table()
->addColumn('your columns here separated by comma')
->setUrl('your URL for server side')
->setOptions(array(
'dom' =>"T<'clear'>lfrtip",
'tabletools' => array(
"aSwfPath" => "your/path/to/swf/copy_csv_cls_pdf.swf",
"aButtons" => array("copy", "pdf", "xls")
)
))
}}
```
If you want to get some properties like "which row did i click?", see the javascript.blade.php and the variable $values.
##Contributors
* [jgoux](https://github.com/jgoux) for helping with searching on number columns in the database
* [jijoel](https://github.com/jijoel) for helping with callback options and documentation
##Changelog
* 2.0.0:
* Seperated Query and Collection Engine
* Added single column search
* Code cleanup
##Applications
https://github.com/hillelcoren/invoice-ninja (by Hillel Coren)
##License
This package is licensed under the MIT License

38
vendor/chumper/datatable/composer.json vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "chumper/datatable",
"description": "This is a laravel 4 package for the server and client side of datatablaes at http://datatables.net/",
"keywords" : ["laravel","datatables", "ajax", "jquery"],
"license": "MIT",
"homepage": "http://github.com/Chumper/datatable",
"authors": [
{
"name": "Nils Plaschke",
"email": "github@nilsplaschke.de",
"homepage": "http://nilsplaschke.de",
"role": "Developer"
}
],
"require": {
"php": ">=5.3.0",
"illuminate/support": "~5.0",
"illuminate/view": "~5.0",
"illuminate/config": "~5.0"
},
"require-dev": {
"phpunit/phpunit": "3.7.*",
"mockery/mockery": "dev-master",
"orchestra/testbench": "3.1.*"
},
"autoload": {
"psr-0": {
"Chumper\\Datatable": "src/"
}
},
"minimum-stability": "dev",
"repositories": [
{
"type": "vcs",
"url": "git://github.com/orchestral/phpseclib.git"
}
]
}

BIN
vendor/chumper/datatable/datatable.jpg vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

18
vendor/chumper/datatable/phpunit.xml vendored Normal file
View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@@ -0,0 +1,37 @@
<?php namespace Chumper\Datatable\Columns;
/**
* Class BaseColumn
* @package Chumper\Datatable\Columns
*/
abstract class BaseColumn {
/**
* @var String name of the column
*/
protected $name;
/**
* @param $name
*/
function __construct($name)
{
$this->name = $name;
}
/**
* @param mixed $model The data to pass to the column,
* could be a model or an array
* @return mixed the return value of the implementation,
* should be text in most of the cases
*/
public abstract function run($model);
/**
* @return String The name of the column
*/
public function getName()
{
return $this->name;
}
}

View File

@@ -0,0 +1,69 @@
<?php namespace Chumper\Datatable\Columns;
class DateColumn extends BaseColumn {
/**
* Constants for the time representation
*/
const DATE = 0;
const TIME = 1;
const DATE_TIME = 2;
const CUSTOM = 4;
const FORMATTED_DATE = 5;
const DAY_DATE = 6;
/**
* @var int The format to show
*/
private $format;
/**
* @var string custom show string if chosen
*/
private $custom;
function __construct($name, $format = 2, $custom = "")
{
parent::__construct($name);
$this->format = $format;
$this->custom = $custom;
}
/**
* @param mixed $model The data to pass to the column,
* could be a model or an array
* @return mixed the return value of the implementation,
* should be text in most of the cases
*/
public function run($model)
{
if(is_string(is_array($model) ? $model[$this->name]: $model->{$this->name}))
{
return is_array($model) ? $model[$this->name]: $model->{$this->name};
}
switch($this->format)
{
case DateColumn::DATE:
return is_array($model) ? $model[$this->name]->toDateString(): $model->{$this->name}->toDateString();
break;
case DateColumn::TIME:
return is_array($model) ? $model[$this->name]->toTimeString(): $model->{$this->name}->toTimeString();
break;
case DateColumn::DATE_TIME:
return is_array($model) ? $model[$this->name]->toDateTimeString(): $model->{$this->name}->toDateTimeString();
break;
case DateColumn::CUSTOM:
return is_array($model) ? $model[$this->name]->format($this->custom): $model->{$this->name}->format($this->custom);
break;
case DateColumn::FORMATTED_DATE:
return is_array($model) ? $model[$this->name]->toFormattedDateString(): $model->{$this->name}->toFormattedDateString();
break;
case DateColumn::DAY_DATE:
return is_array($model) ? $model[$this->name]->toDayDateTimeString(): $model->{$this->name}->toDayDateTimeString();
break;
}
}
}

View File

@@ -0,0 +1,17 @@
<?php namespace Chumper\Datatable\Columns;
class FunctionColumn extends BaseColumn {
private $callable;
function __construct($name, $callable)
{
parent::__construct($name);
$this->callable = $callable;
}
public function run($model)
{
return call_user_func($this->callable,$model);
}
}

View File

@@ -0,0 +1,17 @@
<?php namespace Chumper\Datatable\Columns;
class TextColumn extends BaseColumn {
private $text;
function __construct($name, $text)
{
parent::__construct($name);
$this->text = $text;
}
public function run($model)
{
return $this->text;
}
}

View File

@@ -0,0 +1,57 @@
<?php namespace Chumper\Datatable;
use Chumper\Datatable\Engines\CollectionEngine;
use Chumper\Datatable\Engines\QueryEngine;
use Input;
use Request;
/**
* Class Datatable
* @package Chumper\Datatable
*/
class Datatable {
private $columnNames = array();
/**
* @param $query
* @return \Chumper\Datatable\Engines\QueryEngine
*/
public function query($query)
{
$class = config('chumper.datatable.classmap.QueryEngine');
return new $class($query);
}
/**
* @param $collection
* @return \Chumper\Datatable\Engines\CollectionEngine
*/
public function collection($collection)
{
$class = config('chumper.datatable.classmap.CollectionEngine');
return new $class($collection);
}
/**
* @return \Chumper\Datatable\Table
*/
public function table()
{
$class = config('chumper.datatable.classmap.Table');
return new $class();
}
/**
* @return bool True if the plugin should handle this request, false otherwise
*/
public function shouldHandle()
{
$echo = Input::get('sEcho',null);
if(/*Request::ajax() && */!is_null($echo) && is_numeric($echo))
{
return true;
}
return false;
}
}

View File

@@ -0,0 +1,58 @@
<?php namespace Chumper\Datatable;
use Illuminate\Support\ServiceProvider;
use View;
class DatatableServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../../config/config.php' => config_path('chumper.datatable.php'),
__DIR__.'/../../views' => base_path('resources/views/vendor/chumper.datatable'),
]);
$this->loadViewsFrom(__DIR__ . '/../../views', 'chumper.datatable');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../../config/config.php', 'chumper.datatable');
$this->app['datatable'] = $this->app->share(function($app)
{
return new Datatable;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('datatable');
}
}

View File

@@ -0,0 +1,553 @@
<?php namespace Chumper\Datatable\Engines;
use Exception;
use Assetic\Extension\Twig\AsseticFilterFunction;
use Chumper\Datatable\Columns\DateColumn;
use Chumper\Datatable\Columns\FunctionColumn;
use Chumper\Datatable\Columns\TextColumn;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Config;
/**
* Class BaseEngine
* @package Chumper\Datatable\Engines
*/
abstract class BaseEngine {
const ORDER_ASC = 'asc';
const ORDER_DESC = 'desc';
/**
* @var array
*/
protected $config = array();
/**
* @var mixed
*/
protected $rowClass = null;
/**
* @var mixed
*/
protected $rowId = null;
/**
* @var array
*/
protected $rowData = null;
/**
* @var array
*/
protected $columnSearches = array();
/**
* @var array
* support for DB::raw fields on where
*/
protected $fieldSearches = array();
/**
* @var array
* support for DB::raw fields on where
* sburkett - added for column-based exact matching
*/
protected $columnSearchExact = array();
/**
* @var
*/
protected $sEcho;
/**
* @var \Illuminate\Support\Collection
*/
protected $columns;
/**
* @var array
*/
protected $searchColumns = array();
/**
* @var array
*/
protected $showColumns = array();
/**
* @var array
*/
protected $orderColumns = array();
/**
* @var int
*/
protected $skip = 0;
/**
* @var null
*/
protected $limit = null;
/**
* @var null
*/
protected $search = null;
/**
* @var null
* Will be an array if order is set
* array(
* 0 => column
* 1 => name:cast:length
* )
*/
protected $orderColumn = null;
/**
* @var string
*/
protected $orderDirection = BaseEngine::ORDER_ASC;
/**
* @var boolean If the return should be alias mapped
*/
protected $aliasMapping = false;
/**
* @var bool If the search should be done with exact matching
*/
protected $exactWordSearch = false;
function __construct()
{
$this->columns = new Collection();
$this->config = Config::get('chumper.datatable.engine');
$this->setExactWordSearch( $this->config['exactWordSearch'] );
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function addColumn()
{
if(func_num_args() != 2 && func_num_args() != 1)
throw new Exception('Invalid number of arguments');
if(func_num_args() == 1)
{
//add a predefined column
$this->columns->put(func_get_arg(0)->getName(), func_get_arg(0));
}
else if(is_callable(func_get_arg(1)))
{
$this->columns->put(func_get_arg(0), new FunctionColumn(func_get_arg(0), func_get_arg(1)));
}
else
{
$this->columns->put(func_get_arg(0), new TextColumn(func_get_arg(0),func_get_arg(1)));
}
return $this;
}
/**
* @param $name
* @return mixed
*/
public function getColumn($name)
{
return $this->columns->get($name,null);
}
/**
* @return array
*/
public function getOrder()
{
return array_keys($this->columns->toArray());
}
/**
* @return array
*/
public function getOrderingColumns()
{
return $this->orderColumns;
}
/**
* @return array
*/
public function getSearchingColumns()
{
return $this->searchColumns;
}
/**
* @return $this
*/
public function clearColumns()
{
$this->columns = new Collection();
return $this;
}
/**
* @param $cols
* @return $this
*/
public function showColumns($cols)
{
if ( ! is_array($cols)) {
$cols = func_get_args();
}
foreach ($cols as $property) {
//quick fix for created_at and updated_at columns
if(in_array($property, array('created_at', 'updated_at')))
{
$this->columns->put($property, new DateColumn($property, DateColumn::DAY_DATE));
}
else
{
$this->columns->put($property, new FunctionColumn($property, function($model) use($property){
try{return is_array($model)?$model[$property]:$model->$property;}catch(Exception $e){return null;}
}));
}
$this->showColumns[] = $property;
}
return $this;
}
/**
* @return \Illuminate\Http\JsonResponse
*/
public function make()
{
//TODO Handle all inputs
$this->handleInputs();
$this->prepareSearchColumns();
$output = array(
"aaData" => $this->internalMake($this->columns, $this->searchColumns)->toArray(),
"sEcho" => intval($this->sEcho),
"iTotalRecords" => $this->totalCount(),
"iTotalDisplayRecords" => $this->count(),
);
return Response::json($output);
}
/**
* @param $cols
* @return $this
*/
public function searchColumns($cols)
{
if ( ! is_array($cols)) {
$cols = func_get_args();
}
$this->searchColumns = $cols;
return $this;
}
/**
* @param $cols
* @return $this
*/
public function orderColumns($cols)
{
if ( ! is_array($cols)) {
$cols = func_get_args();
}
if (count($cols) == 1 && $cols[0] == '*')
$cols = $this->showColumns;
$this->orderColumns = $cols;
return $this;
}
/**
* @param $function Set a function for a dynamic row class
* @return $this
*/
public function setRowClass($function)
{
$this->rowClass = $function;
return $this;
}
/**
* @param $function Set a function for a dynamic row id
* @return $this
*/
public function setRowId($function)
{
$this->rowId = $function;
return $this;
}
/**
* @param $function Set a function for dynamic html5 data attributes
* @return $this
*/
public function setRowData($function)
{
$this->rowData = $function;
return $this;
}
public function setAliasMapping($value = true)
{
$this->aliasMapping = $value;
return $this;
}
public function setExactWordSearch($value = true)
{
$this->exactWordSearch = $value;
return $this;
}
/**
* @param $columnNames Sets up a lookup table for which columns should use exact matching -sburkett
* @return $this
*/
public function setExactMatchColumns($columnNames)
{
foreach($columnNames as $columnIndex)
$this->columnSearchExact[ $columnIndex ] = true;
return $this;
}
public function getRowClass()
{
return $this->rowClass;
}
public function getRowId()
{
return $this->rowId;
}
public function getRowData()
{
return $this->rowData;
}
public function getAliasMapping()
{
return $this->aliasMapping;
}
//-------------protected functionS-------------------
/**
* @param $value
*/
protected function handleiDisplayStart($value)
{
//skip
$this->skip($value);
}
/**
* @param $value
*/
protected function handleiDisplayLength($value)
{
//limit nicht am query, sondern den ganzen
//holen und dann dynamisch in der Collection taken und skippen
$this->take($value);
}
/**
* @param $value
*/
protected function handlesEcho($value)
{
$this->sEcho = $value;
}
/**
* @param $value
*/
protected function handlesSearch($value)
{
//handle search on columns sSearch, bRegex
$this->search($value);
}
/**
* @param $value
*/
protected function handleiSortCol_0($value)
{
if(Input::get('sSortDir_0') == 'desc')
$direction = BaseEngine::ORDER_DESC;
else
$direction = BaseEngine::ORDER_ASC;
//check if order is allowed
if(empty($this->orderColumns))
{
$this->order(array(0 => $value, 1 => $this->getNameByIndex($value)), $direction);
return;
}
//prepare order array
$cleanNames = array();
foreach($this->orderColumns as $c)
{
if(strpos($c,':') !== FALSE)
{
$cleanNames[] = substr($c, 0, strpos($c,':'));
}
else
{
$cleanNames[] = $c;
}
}
$i = 0;
foreach($this->columns as $name => $column)
{
if($i == $value && in_array($name, $cleanNames))
{
$this->order(array(0 => $value, 1 => $this->orderColumns[array_search($name,$cleanNames)]), $direction);
return;
}
$i++;
}
}
/**
* @param int $columnIndex
* @param string $searchValue
*
* @return void
*/
protected function handleSingleColumnSearch($columnIndex, $searchValue)
{
//dd($columnIndex, $searchValue, $this->searchColumns);
if (!isset($this->searchColumns[$columnIndex])) return;
if (empty($searchValue) && $searchValue !== '0') return;
$columnName = $this->searchColumns[$columnIndex];
$this->searchOnColumn($columnName, $searchValue);
}
/**
*
*/
protected function handleInputs()
{
//Handle all inputs magically
foreach (Input::all() as $key => $input) {
// handle single column search
if ($this->isParameterForSingleColumnSearch($key))
{
$columnIndex = str_replace('sSearch_','',$key);
$this->handleSingleColumnSearch($columnIndex, $input);
continue;
}
if(method_exists($this, $function = 'handle'.$key))
$this->$function($input);
}
}
/**
* @param $parameterName
*
* @return bool
*/
protected function isParameterForSingleColumnSearch($parameterName)
{
static $parameterNamePrefix = 'sSearch_';
return str_contains($parameterName, $parameterNamePrefix);
}
protected function prepareSearchColumns()
{
if(count($this->searchColumns) == 0 || empty($this->searchColumns))
$this->searchColumns = $this->showColumns;
}
/**
* @param $column
* @param $order
*/
protected function order($column, $order = BaseEngine::ORDER_ASC)
{
$this->orderColumn = $column;
$this->orderDirection = $order;
}
/**
* @param $value
*/
protected function search($value)
{
$this->search = $value;
}
/**
* @param string $columnName
* @param mixed $value
*/
protected function searchOnColumn($columnName, $value)
{
$this->fieldSearches[] = $columnName;
$this->columnSearches[] = $value;
}
/**
* @param $value
*/
protected function skip($value)
{
$this->skip = $value;
}
/**
* @param $value
*/
protected function take($value)
{
$this->limit = $value;
}
public function getNameByIndex($index)
{
$i = 0;
foreach($this->columns as $name => $col)
{
if($index == $i)
{
return $name;
}
$i++;
}
}
public function getExactWordSearch()
{
return $this->exactWordSearch;
}
abstract protected function totalCount();
abstract protected function count();
abstract protected function internalMake(Collection $columns, array $searchColumns = array());
}

View File

@@ -0,0 +1,324 @@
<?php namespace Chumper\Datatable\Engines;
use Illuminate\Support\Collection;
/**
* This handles the collections,
* it needs to compile first, so we wait for the make command and then
* do all the operations
*
* Class CollectionEngine
* @package Chumper\Datatable\Engines
*/
class CollectionEngine extends BaseEngine {
/**
* Constant for OR queries in internal search
*
* @var string
*/
const OR_CONDITION = 'OR';
/**
* Constant for AND queries in internal search
*
* @var string
*/
const AND_CONDITION = 'AND';
/**
* @var \Illuminate\Support\Collection
*/
private $workingCollection;
/**
* @var \Illuminate\Support\Collection
*/
private $collection;
/**
* @var array Different options
*/
private $options = array(
'sortFlags' => SORT_NATURAL,
'stripOrder' => false,
'stripSearch' => false,
'caseSensitive' => false,
);
/**
* @param Collection $collection
*/
function __construct(Collection $collection)
{
parent::__construct();
$this->collection = $collection;
$this->workingCollection = $collection;
}
/**
* @return int
*/
public function count()
{
return $this->workingCollection->count();
}
/**
* @return int
*/
public function totalCount()
{
return $this->collection->count();
}
/**
* @return array
*/
public function getArray()
{
$this->handleInputs();
$this->compileArray($this->columns);
$this->doInternalSearch(new Collection(), array());
$this->doInternalOrder();
return array_values($this->workingCollection
->slice($this->skip,$this->limit)
->toArray()
);
}
/**
* Resets all operations performed on the collection
*/
public function reset()
{
$this->workingCollection = $this->collection;
return $this;
}
public function stripSearch()
{
$this->options['stripSearch'] = true;
return $this;
}
public function stripOrder($callback = true)
{
$this->options['stripOrder'] = $callback;
return $this;
}
public function setSearchStrip()
{
$this->options['stripSearch'] = true;
return $this;
}
public function setOrderStrip($callback = true)
{
return $this->stripOrder($callback);
}
/**
* Set the sort behaviour of the doInternalOrder() function.
*
* @param int $sort_flags For details see: http://php.net/manual/en/function.sort.php
* @return $this
*/
public function setOrderFlags($sort_flags = SORT_NATURAL)
{
$this->options['sortFlags'] = $sort_flags;
return $this;
}
public function setCaseSensitive($value)
{
$this->options['caseSensitive'] = $value;
return $this;
}
public function getOption($value)
{
return $this->options[$value];
}
//--------------PRIVATE FUNCTIONS-----------------
protected function internalMake(Collection $columns, array $searchColumns = array())
{
$this->compileArray($columns);
$this->doInternalSearch($columns, $searchColumns);
$this->doInternalOrder();
return $this->workingCollection->slice($this->skip,$this->limit);
}
/**
* Filter a collection based on the DataTables search parameters (sSearch_0 etc)
* See http://legacy.datatables.net/usage/server-side
*
* @param Collection $columns All the columns in the DataTable
* @param array $searchColumns Columns to search on - values are case-sensitive (must match definition from $columns)
*/
private function doInternalSearch(Collection $columns, array $searchColumns)
{
if((is_null($this->search) || empty($this->search)) && empty($this->fieldSearches))
return;
$value = $this->search;
$caseSensitive = $this->options['caseSensitive'];
$toSearch = array();
$searchType = self::AND_CONDITION;
// Map the searchColumns to the real columns
$ii = 0;
foreach($columns as $i => $col)
{
if(in_array($columns->get($i)->getName(), $searchColumns) || in_array($columns->get($i)->getName(), $this->fieldSearches))
{
// map values to columns, where there is no value use the global value
if(($field = array_search($columns->get($i)->getName(), $this->fieldSearches)) !== FALSE)
{
$toSearch[$ii] = $this->columnSearches[$field];
}
else
{
if($value)
$searchType = self::OR_CONDITION;
$toSearch[$ii] = $value;
}
}
$ii++;
}
$self = $this;
$this->workingCollection = $this->workingCollection->filter(function($row) use ($toSearch, $caseSensitive, $self, $searchType)
{
for($i=0, $stack=array(), $nb=count($row); $i<$nb; $i++)
{
if(!array_key_exists($i, $toSearch))
continue;
$column = $i;
if($self->getAliasMapping())
{
$column = $self->getNameByIndex($i);
}
if($self->getOption('stripSearch'))
{
$search = strip_tags($row[$column]);
}
else
{
$search = $row[$column];
}
if($caseSensitive)
{
if($self->exactWordSearch)
{
if($toSearch[$i] === $search)
$stack[$i] = true;
}
else
{
if(str_contains($search,$toSearch[$i]))
$stack[$i] = true;
}
}
else
{
if($self->getExactWordSearch())
{
if(mb_strtolower($toSearch[$i]) === mb_strtolower($search))
$stack[$i] = true;
}
else
{
if(str_contains(mb_strtolower($search),mb_strtolower($toSearch[$i])))
$stack[$i] = true;
}
}
}
if($searchType == $self::AND_CONDITION)
{
$result = array_diff_key(array_filter($toSearch), $stack);
if(empty($result))
return true;
}
else
{
if(!empty($stack))
return true;
}
});
}
private function doInternalOrder()
{
if(is_null($this->orderColumn))
return;
$column = $this->orderColumn[0];
$stripOrder = $this->options['stripOrder'];
$self = $this;
$this->workingCollection = $this->workingCollection->sortBy(function($row) use ($column,$stripOrder,$self) {
if($self->getAliasMapping())
{
$column = $self->getNameByIndex($column);
}
if($stripOrder)
{
if(is_callable($stripOrder)){
return $stripOrder($row, $column);
}else{
return strip_tags($row[$column]);
}
}
else
{
return $row[$column];
}
}, $this->options['sortFlags']);
if($this->orderDirection == BaseEngine::ORDER_DESC)
$this->workingCollection = $this->workingCollection->reverse();
}
private function compileArray($columns)
{
$self = $this;
$this->workingCollection = $this->collection->map(function($row) use ($columns, $self) {
$entry = array();
// add class and id if needed
if(!is_null($self->getRowClass()) && is_callable($self->getRowClass()))
{
$entry['DT_RowClass'] = call_user_func($self->getRowClass(),$row);
}
if(!is_null($self->getRowId()) && is_callable($self->getRowId()))
{
$entry['DT_RowId'] = call_user_func($self->getRowId(),$row);
}
if(!is_null($self->getRowData()) && is_callable($self->getRowData()))
{
$entry['DT_RowData'] = call_user_func($self->getRowData(),$row);
}
$i=0;
foreach ($columns as $col)
{
if($self->getAliasMapping())
{
$entry[$col->getName()] = $col->run($row);
}
else
{
$entry[$i] = $col->run($row);
}
$i++;
}
return $entry;
});
}
}

View File

@@ -0,0 +1,306 @@
<?php namespace Chumper\Datatable\Engines;
use Chumper\Datatable\Datatable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;
class QueryEngine extends BaseEngine {
/**
* @var Builder
*/
public $builder;
/**
* @var Builder
*/
public $originalBuilder;
/**
* @var array single column searches
*/
public $columnSearches = array();
/**
* @var Collection the returning collection
*/
private $resultCollection;
/**
* @var Collection the resulting collection
*/
private $collection = null;
/**
* @var array Different options
*/
protected $options = array(
'searchOperator' => 'LIKE',
'searchWithAlias' => false,
'orderOrder' => null,
'counter' => 0,
'noGroupByOnCount' => false,
);
function __construct($builder)
{
parent::__construct();
if($builder instanceof Relation)
{
$this->builder = $builder->getBaseQuery();
$this->originalBuilder = clone $builder->getBaseQuery();
}
else
{
$this->builder = $builder;
$this->originalBuilder = clone $builder;
}
}
public function count()
{
return $this->options['counter'];
}
public function totalCount()
{
// Store temporary copy as we may modify it, we'd be stupid to modify
// the actual "original" copy...
$originalBuilder = $this->originalBuilder;
if ($this->options['noGroupByOnCount']) {
$originalBuilder = $this->removeGroupBy($originalBuilder);
}
return $originalBuilder->count();
}
public function getArray()
{
return $this->getCollection($this->builder)->toArray();
}
public function reset()
{
$this->builder = $this->originalBuilder;
return $this;
}
public function setSearchOperator($value = "LIKE")
{
$this->options['searchOperator'] = $value;
return $this;
}
public function setSearchWithAlias()
{
$this->options['searchWithAlias'] = true;
return $this;
}
public function setNoGroupByOnCount()
{
$this->options['noGroupByOnCount'] = true;
return $this;
}
//--------PRIVATE FUNCTIONS
protected function internalMake(Collection $columns, array $searchColumns = array())
{
$builder = clone $this->builder;
$countBuilder = clone $this->builder;
$builder = $this->doInternalSearch($builder, $searchColumns);
$countBuilder = $this->doInternalSearch($countBuilder, $searchColumns);
if($this->options['searchWithAlias'])
{
$this->options['counter'] = count($countBuilder->get());
}
else
{
// Remove the GROUP BY clause for the count
if ($this->options['noGroupByOnCount']) {
$countBuilder = $this->removeGroupBy($countBuilder);
}
$this->options['counter'] = $countBuilder->count();
}
$builder = $this->doInternalOrder($builder, $columns);
$collection = $this->compile($builder, $columns);
return $collection;
}
/**
* Remove the GROUP BY clause from a builder.
*
* @param Builder|QueryBuilder $builder
* @return Builder|QueryBuilder $builder with the groups property set to null.
*/
private function removeGroupBy($builder)
{
// Handle \Illuminate\Database\Eloquent\Builder
if ($builder instanceof Builder) {
$query = $builder->getQuery();
$query->groups = null;
$builder->setQuery($query);
}
// Handle \Illuminate\Database\Query\Builder
else {
$builder->groups = null;
}
return $builder;
}
/**
* @param $builder
* @return Collection
*/
private function getCollection($builder)
{
if($this->collection == null)
{
if($this->skip > 0)
{
$builder = $builder->skip($this->skip);
}
if($this->limit > 0)
{
$builder = $builder->take($this->limit);
}
//dd($this->builder->toSql());
$this->collection = $builder->get();
if(is_array($this->collection))
$this->collection = new Collection($this->collection);
}
return $this->collection;
}
private function doInternalSearch($builder, $columns)
{
if (!empty($this->search)) {
$this->buildSearchQuery($builder, $columns);
}
if (!empty($this->columnSearches)) {
$this->buildSingleColumnSearches($builder);
}
return $builder;
}
protected function buildSearchQuery($builder, $columns)
{
$like = $this->options['searchOperator'];
$search = $this->search;
$exact = $this->exactWordSearch;
$builder = $builder->where(function($query) use ($columns, $search, $like, $exact) {
foreach ($columns as $c) {
//column to search within relationships : relatedModel::column
if(strrpos($c, '::')) {
$c = explode('::', $c);
$query->orWhereHas($c[0], function($q) use($c, $like, $exact, $search){
$q->where($c[1], $like, $exact ? $search : '%' . $search . '%');
});
}
//column to CAST following the pattern column:newType:[maxlength]
elseif(strrpos($c, ':')){
$c = explode(':', $c);
if(isset($c[2]))
$c[1] .= "($c[2])";
$query->orWhereRaw("cast($c[0] as $c[1]) ".$like." ?", array($exact ? "$search" : "%$search%"));
}
else
$query->orWhere($c, $like, $exact ? $search : '%' . $search . '%');
}
});
return $builder;
}
/**
* @param $builder
* Modified by sburkett to facilitate individual exact match searching on individual columns (rather than for all columns)
*/
private function buildSingleColumnSearches($builder)
{
foreach ($this->columnSearches as $index => $searchValue) {
if(@$this->columnSearchExact[ $this->fieldSearches[$index] ] == 1) {
$builder->where($this->fieldSearches[$index], '=', $searchValue );
} else {
$builder->where($this->fieldSearches[$index], $this->options['searchOperator'], '%' . $searchValue . '%');
}
}
}
private function compile($builder, $columns)
{
$this->resultCollection = $this->getCollection($builder);
$self = $this;
$this->resultCollection = $this->resultCollection->map(function($row) use ($columns,$self) {
$entry = array();
// add class and id if needed
if(!is_null($self->getRowClass()) && is_callable($self->getRowClass()))
{
$entry['DT_RowClass'] = call_user_func($self->getRowClass(),$row);
}
if(!is_null($self->getRowId()) && is_callable($self->getRowId()))
{
$entry['DT_RowId'] = call_user_func($self->getRowId(),$row);
}
if(!is_null($self->getRowData()) && is_callable($self->getRowData()))
{
$entry['DT_RowData'] = call_user_func($self->getRowData(),$row);
}
$i = 0;
foreach ($columns as $col)
{
if($self->getAliasMapping())
{
$entry[$col->getName()] = $col->run($row);
}
else
{
$entry[$i] = $col->run($row);
}
$i++;
}
return $entry;
});
return $this->resultCollection;
}
private function doInternalOrder($builder, $columns)
{
//var_dump($this->orderColumn);
if(!is_null($this->orderColumn))
{
$i = 0;
foreach($columns as $col)
{
if($i === (int) $this->orderColumn[0])
{
if(strrpos($this->orderColumn[1], ':')){
$c = explode(':', $this->orderColumn[1]);
if(isset($c[2]))
$c[1] .= "($c[2])";
$builder = $builder->orderByRaw("cast($c[0] as $c[1]) ".$this->orderDirection);
}
else
$builder = $builder->orderBy($col->getName(), $this->orderDirection);
return $builder;
}
$i++;
}
}
return $builder;
}
}

View File

@@ -0,0 +1,14 @@
<?php namespace Chumper\Datatable\Facades;
use Illuminate\Support\Facades\Facade;
class DatatableFacade extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'datatable'; }
}

View File

@@ -0,0 +1,441 @@
<?php namespace Chumper\Datatable;
use Exception;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Config;
/**
* Class Table
* @package Chumper\Datatable
*/
class Table {
/**
* @var array
*/
private $config = array();
/**
* @var array
*/
private $columns = array();
/**
* @var array
*/
private $options = array();
/**
* @var array
*/
private $callbacks = array();
/**
* Values to be sent to custom templates
*
* @var array
*/
private $customValues = array();
/**
* @var array
*/
private $data = array();
/**
* @var boolean Determines if the template should echo the javascript
*/
private $noScript = false;
/**
* @var String The name of the id the table will have later
*/
protected $idName;
/**
* @var String The name of the class the table will have later
*/
protected $className;
/**
* @var String The view used to render the table
*/
protected $table_view;
/**
* @var String The view used to render the javascript
*/
protected $script_view;
/**
* @var boolean indicates if the mapping was already added to the options
*/
private $createdMapping = true;
/**
* @var array name of mapped columns
*/
private $aliasColumns = array();
function __construct()
{
$this->config = Config::get('chumper.datatable.table');
$this->setId( $this->config['id'] );
$this->setClass( $this->config['class'] );
$this->setOptions( $this->config['options'] );
$this->setCallbacks( $this->config['callbacks'] );
$this->noScript = $this->config['noScript'];
$this->table_view = $this->config['table_view'];
$this->script_view = $this->config['script_view'];
}
/**
* @return $this
*/
public function addColumn()
{
foreach (func_get_args() as $title)
{
if(is_array($title))
{
foreach ($title as $mapping => $arrayTitle)
{
$this->columns[] = $arrayTitle;
$this->aliasColumns[] = $mapping;
if(is_string($mapping))
{
$this->createdMapping = false;
}
}
}
else
{
$this->columns[] = $title;
$this->aliasColumns[] = count($this->aliasColumns)+1;
}
}
return $this;
}
/**
* @return int
*/
public function countColumns()
{
return count($this->columns);
}
/**
* @return $this
*/
public function removeOption($key)
{
if(isset($this->options[$key])) unset($this->options[$key]);
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function setOptions()
{
if(func_num_args() == 2)
{
$this->options[func_get_arg(0)] =func_get_arg(1);
}
else if(func_num_args() == 1 && is_array(func_get_arg(0)))
{
foreach (func_get_arg(0) as $key => $option)
{
$this->options[$key] = $option;
}
}
else
throw new Exception('Invalid number of options provided for the method "setOptions"');
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function setOrder($order = array())
{
$_orders = array();
foreach ($order as $number => $sort)
{
$_orders[] = [$number, $sort];
}
$this->callbacks['aaSorting'] = $_orders;
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function setCallbacks()
{
if(func_num_args() == 2)
{
$this->callbacks[func_get_arg(0)] = func_get_arg(1);
}
else if(func_num_args() == 1 && is_array(func_get_arg(0)))
{
foreach (func_get_arg(0) as $key => $value)
{
$this->callbacks[$key] = $value;
}
}
else
throw new Exception('Invalid number of callbacks provided for the method "setCallbacks"');
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function setCustomValues()
{
if(func_num_args() == 2)
{
$this->customValues[func_get_arg(0)] = func_get_arg(1);
}
else if(func_num_args() == 1 && is_array(func_get_arg(0)))
{
foreach (func_get_arg(0) as $key => $value)
{
$this->customValues[$key] = $value;
}
}
else
throw new Exception('Invalid number of custom values provided for the method "setCustomValues"');
return $this;
}
/**
* @param array $data
* @return $this
*/
public function setData(array $data)
{
$this->data = $data;
return $this;
}
/**
* @param $url
* @return $this
*/
public function setUrl($url)
{
$this->options['sAjaxSource'] = $url;
$this->options['bServerSide'] = true;
return $this;
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* @return array
*/
public function getCallbacks()
{
return $this->callbacks;
}
/**
* @return array
*/
public function getCustomValues()
{
return $this->customValues;
}
/**
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* @param null $view
* @return mixed
*/
public function render($view = null)
{
if( ! is_null($view))
$this->table_view = $view;
return View::make($this->table_view, $this->getViewParameters());
}
/**
* returns an array with the parameters that will be passed to the view when it's rendered
* @return array
*/
public function getViewParameters()
{
if(!isset($this->options['sAjaxSource']))
{
$this->setUrl(Request::url());
}
// create mapping for frontend
if(!$this->createdMapping)
{
$this->createMapping();
}
return array(
'options' => $this->convertData(array_merge($this->options, $this->callbacks)),
'values' => $this->customValues,
'data' => $this->data,
'columns' => array_combine($this->aliasColumns,$this->columns),
'noScript' => $this->noScript,
'id' => $this->idName,
'class' => $this->className,
);
}
/**
* Instructs the table not to echo the javascript
*
* @return $this
*/
public function noScript()
{
$this->noScript = true;
return $this;
}
private function convertData($options) {
$is_obj = false;
$first = true;
$data = "";
foreach ($options as $k => $o) {
if ($first == true) {
if (!is_numeric($k)) {
$is_obj = true;
}
$first = false;
} else {
$data .= ",\n";
}
if (!is_numeric($k)) {
$data .= json_encode($k) . ":";
}
if (is_string($o)) {
if (@preg_match("#^\s*function\s*\([^\)]*#", $o)) {
$data .= $o;
} else {
$data .= json_encode($o);
}
} else {
if (is_array($o)) {
$data .= $this->convertData($o);
} else {
$data .= json_encode($o);
}
}
}
if ($is_obj) {
$data = "{ $data }";
} else {
$data = "[ $data ]";
}
return $data;
}
public function script($view = null)
{
if( ! is_null($view))
$this->script_view = $view;
// create mapping for frontend
if(!$this->createdMapping)
{
$this->createMapping();
}
return View::make($this->script_view,array(
'options' => $this->convertData(array_merge($this->options, $this->callbacks)),
'id' => $this->idName,
));
}
public function getId()
{
return $this->idName;
}
public function setId($id = '')
{
$this->idName = empty($id)? str_random(8) : $id;
return $this;
}
public function getClass()
{
return $this->className;
}
public function setClass($class)
{
$this->className = $class;
return $this;
}
public function setAliasMapping($value)
{
$this->createdMapping = !$value;
return $this;
}
//--------------------PRIVATE FUNCTIONS
private function createMapping()
{
// set options for better handling
// merge with existing options
if(!array_key_exists('aoColumns', $this->options))
{
$this->options['aoColumns'] = array();
}
$matching = array();
$i = 0;
foreach($this->aliasColumns as $name)
{
if(array_key_exists($i,$this->options['aoColumns']))
{
$this->options['aoColumns'][$i] = array_merge_recursive($this->options['aoColumns'][$i],array('mData' => $name));
}
else
{
$this->options['aoColumns'][$i] = array('mData' => $name);
}
$i++;
}
$this->createdMapping = true;
//dd($matching);
return $matching;
}
}

View File

View File

@@ -0,0 +1,146 @@
<?php
return array(
/*
|--------------------------------------------------------------------------
| Table specific configuration options.
|--------------------------------------------------------------------------
|
*/
'table' => array(
/*
|--------------------------------------------------------------------------
| Table class
|--------------------------------------------------------------------------
|
| Class(es) added to the table
| Supported: string
|
*/
'class' => 'table table-bordered',
/*
|--------------------------------------------------------------------------
| Table ID
|--------------------------------------------------------------------------
|
| ID given to the table. Used for connecting the table and the Datatables
| jQuery plugin. If left empty a random ID will be generated.
| Supported: string
|
*/
'id' => '',
/*
|--------------------------------------------------------------------------
| DataTable options
|--------------------------------------------------------------------------
|
| jQuery dataTable plugin options. The array will be json_encoded and
| passed through to the plugin. See https://datatables.net/usage/options
| for more information.
| Supported: array
|
*/
'options' => array(
"sPaginationType" => "full_numbers",
"bProcessing" => false
),
/*
|--------------------------------------------------------------------------
| DataTable callbacks
|--------------------------------------------------------------------------
|
| jQuery dataTable plugin callbacks. The array will be json_encoded and
| passed through to the plugin. See https://datatables.net/usage/callbacks
| for more information.
| Supported: array
|
*/
'callbacks' => array(),
/*
|--------------------------------------------------------------------------
| Skip javascript in table template
|--------------------------------------------------------------------------
|
| Determines if the template should echo the javascript
| Supported: boolean
|
*/
'noScript' => false,
/*
|--------------------------------------------------------------------------
| Table view
|--------------------------------------------------------------------------
|
| Template used to render the table
| Supported: string
|
*/
'table_view' => 'chumper.datatable::template',
/*
|--------------------------------------------------------------------------
| Script view
|--------------------------------------------------------------------------
|
| Template used to render the javascript
| Supported: string
|
*/
'script_view' => 'chumper.datatable::javascript',
),
/*
|--------------------------------------------------------------------------
| Engine specific configuration options.
|--------------------------------------------------------------------------
|
*/
'engine' => array(
/*
|--------------------------------------------------------------------------
| Search for exact words
|--------------------------------------------------------------------------
|
| If the search should be done with exact matching
| Supported: boolean
|
*/
'exactWordSearch' => false,
),
/*
|--------------------------------------------------------------------------
| Allow overrides Datatable core classes
|--------------------------------------------------------------------------
|
*/
'classmap' => array(
'CollectionEngine' => 'Chumper\Datatable\Engines\CollectionEngine',
'QueryEngine' => 'Chumper\Datatable\Engines\QueryEngine',
'Table' => 'Chumper\Datatable\Table',
)
);

View File

@@ -0,0 +1,8 @@
<script type="text/javascript">
jQuery(document).ready(function(){
// dynamic table
oTable = jQuery('#{!! $id !!}').dataTable(
{!! $options !!}
);
});
</script>

View File

@@ -0,0 +1,27 @@
<table id="{!! $id !!}" class="{!! $class !!}">
<colgroup>
@for ($i = 0; $i < count($columns); $i++)
<col class="con{!! $i !!}" />
@endfor
</colgroup>
<thead>
<tr>
@foreach($columns as $i => $c)
<th align="center" valign="middle" class="head{!! $i !!}">{!! $c !!}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach($data as $d)
<tr>
@foreach($d as $dd)
<td>{!! $dd !!}</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
@if (!$noScript)
@include(Config::get('chumper.datatable.table.script_view'), array('id' => $id, 'options' => $options))
@endif

View File

View File

@@ -0,0 +1,56 @@
<?php namespace Chumper\Datatable\Columns;
use Carbon\Carbon;
use Mockery;
class DateColumnTest extends \PHPUnit_Framework_TestCase {
public function testAll()
{
$c = Mockery::mock('Carbon\Carbon');
$column1 = new DateColumn('foo', DateColumn::DATE, 'foo');
$c->shouldReceive('toDateString')
->withNoArgs()->once()
->andReturn('fooBar');
$column2 = new DateColumn('foo', DateColumn::TIME, 'foo');
$c->shouldReceive('toTimeString')
->withNoArgs()->once()
->andReturn('fooBar');
$column3 = new DateColumn('foo', DateColumn::DATE_TIME, 'foo');
$c->shouldReceive('toDateTimeString')
->withNoArgs()->once()
->andReturn('fooBar');
$column4 = new DateColumn('foo', DateColumn::CUSTOM, 'foo');
$c->shouldReceive('format')
->with('foo')->once()
->andReturn('fooBar');
$column5 = new DateColumn('foo', DateColumn::FORMATTED_DATE, 'foo');
$c->shouldReceive('toFormattedDateString')
->withNoArgs()->once()
->andReturn('fooBar');
$column6 = new DateColumn('foo', DateColumn::DAY_DATE, 'foo');
$c->shouldReceive('toDayDateTimeString')
->withNoArgs()->once()
->andReturn('fooBar');
//now test
$this->assertEquals('fooBar', $column1->run(array('foo' => $c)));
$this->assertEquals('fooBar', $column2->run(array('foo' => $c)));
$this->assertEquals('fooBar', $column3->run(array('foo' => $c)));
$this->assertEquals('fooBar', $column4->run(array('foo' => $c)));
$this->assertEquals('fooBar', $column5->run(array('foo' => $c)));
$this->assertEquals('fooBar', $column6->run(array('foo' => $c)));
}
protected function tearDown()
{
Mockery::close();
}
}

View File

@@ -0,0 +1,31 @@
<?php
use Chumper\Datatable\Columns\FunctionColumn;
class FunctionColumnTest extends PHPUnit_Framework_TestCase {
public function testSimple()
{
$column = new FunctionColumn('foo',function($model){
return "FooBar";
});
$this->assertEquals('FooBar', $column->run(array()));
}
public function testAdvanced()
{
$column = new FunctionColumn('foo',function($model){
return $model['text'];
});
$this->assertEquals('FooBar', $column->run(array('text' => 'FooBar')));
}
public function testAdvanced2()
{
$column = new FunctionColumn('foo',function($model){
return $model['text'].'Bar';
});
$this->assertEquals('FooBar', $column->run(array('text' => 'Foo')));
}
}

View File

@@ -0,0 +1,13 @@
<?php
use Chumper\Datatable\Columns\TextColumn;
class TextColumnTest extends PHPUnit_Framework_TestCase {
public function testWorking()
{
$column = new TextColumn('foo', 'FooBar');
$this->assertEquals('FooBar', $column->run(array()));
}
}

View File

@@ -0,0 +1,61 @@
<?php
use Chumper\Datatable\Datatable;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Config;
class DatatableTest extends \Orchestra\Testbench\TestCase {
/**
* @var Datatable
*/
private $dt;
public function setUp()
{
parent::setUp();
// set up config
Config::shouldReceive('get')->zeroOrMoreTimes()->with("chumper.datatable.engine")->andReturn(
array(
'exactWordSearch' => false,
)
);
Config::shouldReceive('get')->zeroOrMoreTimes()->with("chumper.datatable.classmap.QueryEngine",NULL)->andReturn('Chumper\Datatable\Engines\QueryEngine');
Config::shouldReceive('get')->zeroOrMoreTimes()->with("chumper.datatable.classmap.CollectionEngine",NULL)->andReturn('Chumper\Datatable\Engines\CollectionEngine');
Config::shouldReceive('get')->zeroOrMoreTimes()->with("chumper.datatable.classmap.Table",NULL)->andReturn('Chumper\Datatable\Table');
Config::shouldReceive('get')->zeroOrMoreTimes()->with("chumper.datatable.table")->andReturn(
array(
'class' => 'table table-bordered',
'id' => '',
'options' => array(
"sPaginationType" => "full_numbers",
"bProcessing" => false
),
'callbacks' => array(),
'noScript' => false,
'table_view' => 'datatable::template',
'script_view' => 'datatable::javascript',
)
);
$this->dt = new Datatable;
$this->mock = Mockery::mock('Illuminate\Database\Query\Builder');
}
public function testReturnInstances()
{
$api = $this->dt->query($this->mock);
$this->assertInstanceOf('Chumper\Datatable\Engines\QueryEngine', $api);
$api = $this->dt->collection(new Collection());
$this->assertInstanceOf('Chumper\Datatable\Engines\CollectionEngine', $api);
$table = $this->dt->table();
$this->assertInstanceOf('Chumper\Datatable\Table', $table);
}
}

View File

@@ -0,0 +1,113 @@
<?php
use Chumper\Datatable\Engines\CollectionEngine;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Input;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Config;
class BaseEngineTest extends TestCase {
private $collection;
/**
* @var CollectionEngine
*/
private $engine;
public function setUp()
{
// set up config
Config::shouldReceive('get')->zeroOrMoreTimes()->with("chumper.datatable.engine")->andReturn(
array(
'exactWordSearch' => false,
)
);
$this->collection = new Collection();
$this->engine = new CollectionEngine($this->collection);
}
/**
* @expectedException Exception
*/
public function testAddColumn()
{
$this->engine->addColumn('foo', 'bar');
$this->assertInstanceOf(
'Chumper\Datatable\Columns\TextColumn',
$this->engine->getColumn('foo')
);
$this->engine->addColumn('foo2', function($model){return $model->fooBar;});
$this->assertInstanceOf(
'Chumper\Datatable\Columns\FunctionColumn',
$this->engine->getColumn('foo2')
);
$this->assertEquals(array(1 => 'foo2', 0 => 'foo'), $this->engine->getOrder());
$this->engine->addColumn();
}
public function testClearColumns()
{
$this->engine->addColumn('foo','Bar');
$this->assertInstanceOf(
'Chumper\Datatable\Columns\TextColumn',
$this->engine->getColumn('foo')
);
$this->engine->clearColumns();
$this->assertEquals(array(), $this->engine->getOrder());
}
public function testSearchColumns()
{
$this->engine->searchColumns('id');
$this->assertEquals(array('id'), $this->engine->getSearchingColumns());
$this->engine->searchColumns('name', 'email');
$this->assertEquals(array('name','email'), $this->engine->getSearchingColumns());
$this->engine->searchColumns(array('foo', 'bar'));
$this->assertEquals(array('foo', 'bar'), $this->engine->getSearchingColumns());
}
public function testOrderColumns()
{
$this->engine->orderColumns('id');
$this->assertEquals(array('id'), $this->engine->getOrderingColumns());
$this->engine->orderColumns('name', 'email');
$this->assertEquals(array('name','email'), $this->engine->getOrderingColumns());
$this->engine->orderColumns(array('foo', 'bar'));
$this->assertEquals(array('foo', 'bar'), $this->engine->getOrderingColumns());
}
public function testShowColumns()
{
$this->engine->showColumns('id');
$this->assertEquals(array('id'), $this->engine->getOrder());
$this->engine->showColumns('name', 'email');
$this->assertEquals(array('id','name','email'), $this->engine->getOrder());
$this->engine->showColumns(array('foo', 'bar'));
$this->assertEquals(array('id','name','email', 'foo', 'bar'), $this->engine->getOrder());
}
}

View File

@@ -0,0 +1,328 @@
<?php
use Chumper\Datatable\Columns\FunctionColumn;
use Chumper\Datatable\Engines\CollectionEngine;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Input;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Config;
class CollectionEngineTest extends TestCase {
/**
* @var CollectionEngine
*/
public $c;
/**
* @var \Mockery\Mock
*/
public $collection;
/**
* @var
*/
private $input;
protected function getEnvironmentSetUp($app)
{
$app['config']->set('chumper.datatable.engine', array(
'exactWordSearch' => false,
));
}
public function setUp()
{
parent::setUp();
$this->collection = Mockery::mock('Illuminate\Support\Collection');
$this->c = new CollectionEngine($this->collection);
}
public function testOrder()
{
$should = array(
array(
'id' => 'eoo'
),
array(
'id' => 'foo'
)
);
Input::replace(
array(
'iSortCol_0' => 0,
'sSortDir_0' => 'asc',
)
);
$engine = new CollectionEngine(new Collection($this->getTestArray()));
$engine->addColumn(new FunctionColumn('id', function($model){return $model['id'];}));
$engine->setAliasMapping();
$this->assertEquals($should, $engine->getArray());
Input::merge(
array(
'iSortCol_0' => 0,
'sSortDir_0' => 'desc'
)
);
$should2 = array(
array(
'id' => 'foo'
),
array(
'id' => 'eoo'
)
);
$this->assertEquals($should2, $engine->getArray());
}
public function testSearch()
{
// Facade expection
Input::replace(
array(
'sSearch' => 'eoo'
)
);
$engine = new CollectionEngine(new Collection($this->getTestArray()));
$engine->addColumn($this->getTestColumns());
$engine->searchColumns('id');
$engine->setAliasMapping();
$should = '{"aaData":[{"id":"eoo"}],"sEcho":0,"iTotalRecords":2,"iTotalDisplayRecords":1}';
$actual = $engine->make()->getContent();
$this->assertEquals($should,$actual);
//------------------TEST 2-----------------
// search in outputed data
$engine = new CollectionEngine(new Collection(array(array('foo', 'foo2', 'foo3'),array('bar', 'bar2', 'bar3'))));
$engine->addColumn(new FunctionColumn('bla', function($row){return $row[0]." - ".$row[1];}));
$engine->addColumn(new FunctionColumn('1', function($row){return $row[2];}));
$engine->addColumn(new FunctionColumn('bla3', function($row){return $row[0]." - ".$row[2];}));
$engine->searchColumns("bla",1);
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 'foo2'
)
);
$should = array(
array(
'bla' => 'foo - foo2',
'1' => 'foo3',
'bla3' => 'foo - foo3'
)
);
$response = json_decode($engine->make()->getContent());
$this->assertEquals(json_encode($should), json_encode((array)($response->aaData)));
//------------------TEST 3-----------------
// search in initial data
// TODO: Search in initial data columns?
$engine = new CollectionEngine(new Collection(array(array('foo', 'foo2', 'foo3'),array('bar', 'bar2', 'bar3'))));
$engine->addColumn(new FunctionColumn('bla3', function($row){return $row[0]." - ".$row[2];}));
$engine->addColumn(new FunctionColumn('1', function($row){return $row[1];}));
$engine->searchColumns("bla3",1);
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 'foo2'
)
);
$should = array(
array(
'bla3' => 'foo - foo3',
'1' => 'foo2'
)
);
$response = json_decode($engine->make()->getContent());
$this->assertEquals(json_encode($should), json_encode($response->aaData));
}
public function testSkip()
{
$engine = new CollectionEngine(new Collection($this->getTestArray()));
$engine->addColumn($this->getTestColumns());
$engine->setAliasMapping();
Input::replace(
array(
'iDisplayStart' => 1
)
);
$should = array(
array(
'id' => 'eoo',
)
);
$this->assertEquals($should, $engine->getArray());
}
public function testTake()
{
Input::replace(
array(
'iDisplayLength' => 1
)
);
$engine = new CollectionEngine(new Collection($this->getTestArray()));
$engine->addColumn($this->getTestColumns());
$engine->setAliasMapping();
$engine->make();
$should = array(
array(
'id' => 'foo',
)
);
$this->assertEquals($should, $engine->getArray());
}
public function testComplex()
{
$engine = new CollectionEngine(new Collection($this->getRealArray()));
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 't'
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertTrue($this->arrayHasKeyValue('foo','Nils',(array) $test));
$this->assertTrue($this->arrayHasKeyValue('foo','Taylor',(array) $test));
//Test2
$engine = new CollectionEngine(new Collection($this->getRealArray()));
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 'plasch'
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertTrue($this->arrayHasKeyValue('foo','Nils',(array) $test));
$this->assertFalse($this->arrayHasKeyValue('foo','Taylor',(array) $test));
//test3
$engine = new CollectionEngine(new Collection($this->getRealArray()));
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 'tay'
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertFalse($this->arrayHasKeyValue('foo','Nils',(array) $test));
$this->assertTrue($this->arrayHasKeyValue('foo','Taylor',(array) $test));
//test4
$engine = new CollectionEngine(new Collection($this->getRealArray()));
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 'O'
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertFalse($this->arrayHasKeyValue('foo','Nils',(array) $test));
$this->assertTrue($this->arrayHasKeyValue('foo','Taylor',(array) $test));
}
public function tearDown()
{
Mockery::close();
}
private function getTestArray()
{
return array(
array(
'id' => 'foo'
),
array(
'id' => 'eoo'
)
);
}
private function getRealArray()
{
return array(
array(
'name' => 'Nils Plaschke',
'email'=> 'github@nilsplaschke.de'
),
array(
'name' => 'Taylor Otwell',
'email'=> 'taylorotwell@gmail.com'
)
);
}
private function addRealColumns($engine)
{
$engine->addColumn(new FunctionColumn('foo', function($m){return $m['name'];}));
$engine->addColumn(new FunctionColumn('bar', function($m){return $m['email'];}));
}
private function getTestColumns()
{
return new FunctionColumn('id', function($row){return $row['id'];});
}
private function arrayHasKeyValue($key,$value,$array)
{
$array = array_pluck($array,$key);
foreach ($array as $val)
{
if(str_contains($val, $value))
return true;
}
return false;
}
}

View File

@@ -0,0 +1,251 @@
<?php
use Chumper\Datatable\Columns\FunctionColumn;
use Chumper\Datatable\Engines\BaseEngine;
use Chumper\Datatable\Engines\EngineInterface;
use Chumper\Datatable\Engines\QueryEngine;
use Illuminate\Support\Collection;
class QueryEngineTest extends PHPUnit_Framework_TestCase {
/**
* @var QueryEngine
*/
public $c;
/**
* @var \Mockery\Mock
*/
public $builder;
public function setUp()
{
Config::shouldReceive('get')->zeroOrMoreTimes()->with("chumper.datatable.engine")->andReturn(
array(
'exactWordSearch' => false,
)
);
$this->builder = Mockery::mock('Illuminate\Database\Query\Builder');
$this->c = new QueryEngine($this->builder);
}
public function testOrder()
{
$this->builder->shouldReceive('orderBy')->with('id', BaseEngine::ORDER_ASC);
Input::merge(
array(
'iSortCol_0' => 0,
'sSortDir_0' => 'asc'
)
);
//--
$this->builder->shouldReceive('orderBy')->with('id', BaseEngine::ORDER_DESC);
Input::merge(
array(
'iSortCol_0' => 0,
'sSortDir_0' => 'desc'
)
);
}
public function testSearch()
{
$this->builder->shouldReceive('where')->withAnyArgs()->andReturn($this->builder);
$this->builder->shouldReceive('get')->once()->andReturn(new Collection($this->getRealArray()));
$this->builder->shouldReceive('count')->twice()->andReturn(10);
$this->builder->shouldReceive('orderBy')->withAnyArgs()->andReturn($this->builder);
$this->c = new QueryEngine($this->builder);
$this->addRealColumns($this->c);
$this->c->searchColumns('foo');
Input::merge(
array(
'sSearch' => 'test'
)
);
$test = json_decode($this->c->make()->getContent());
$test = $test->aaData;
}
public function testSkip()
{
$this->builder->shouldReceive('skip')->once()->with(1)->andReturn($this->builder);
$this->builder->shouldReceive('get')->once()->andReturn(new Collection($this->getRealArray()));
$this->builder->shouldReceive('count')->twice()->andReturn(10);
$this->builder->shouldReceive('orderBy')->withAnyArgs()->andReturn($this->builder);
$this->c = new QueryEngine($this->builder);
$this->addRealColumns($this->c);
Input::merge(
array(
'iDisplayStart' => 1,
'sSearch' => null
)
);
$this->c->searchColumns('foo');
$test = json_decode($this->c->make()->getContent());
$test = $test->aaData;
}
public function testTake()
{
$this->builder->shouldReceive('take')->once()->with(1)->andReturn($this->builder);
$this->builder->shouldReceive('get')->once()->andReturn(new Collection($this->getRealArray()));
$this->builder->shouldReceive('count')->twice()->andReturn(10);
$this->builder->shouldReceive('orderBy')->withAnyArgs()->andReturn($this->builder);
$this->c = new QueryEngine($this->builder);
$this->addRealColumns($this->c);
Input::merge(
array(
'iDisplayLength' => 1,
'sSearch' => null,
'iDisplayStart' => null
)
);
$this->c->searchColumns('foo');
$test = json_decode($this->c->make()->getContent());
$test = $test->aaData;
}
public function testComplex()
{
$this->builder->shouldReceive('get')->andReturn(new Collection($this->getRealArray()));
$this->builder->shouldReceive('where')->withAnyArgs()->andReturn($this->builder);
$this->builder->shouldReceive('count')->times(8)->andReturn(10);
$engine = new QueryEngine($this->builder);
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 't',
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertTrue($this->arrayHasKeyValue('foo','Nils',$test));
$this->assertTrue($this->arrayHasKeyValue('foo','Taylor',$test));
//Test2
$engine = new QueryEngine($this->builder);
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 'plasch',
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertTrue($this->arrayHasKeyValue('foo','Nils',$test));
$this->assertTrue($this->arrayHasKeyValue('foo','Taylor',$test));
//test3
$engine = new QueryEngine($this->builder);
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => 'tay',
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertTrue($this->arrayHasKeyValue('foo','Nils',$test));
$this->assertTrue($this->arrayHasKeyValue('foo','Taylor',$test));
//test4
$engine = new QueryEngine($this->builder);
$this->addRealColumns($engine);
$engine->searchColumns('foo','bar');
$engine->setAliasMapping();
Input::replace(
array(
'sSearch' => '0',
)
);
$test = json_decode($engine->make()->getContent());
$test = $test->aaData;
$this->assertTrue($this->arrayHasKeyValue('foo','Nils',$test));
$this->assertTrue($this->arrayHasKeyValue('foo','Taylor',$test));
}
protected function tearDown()
{
Mockery::close();
}
private function getRealArray()
{
return array(
array(
'name' => 'Nils Plaschke',
'email'=> 'github@nilsplaschke.de'
),
array(
'name' => 'Taylor Otwell',
'email'=> 'taylorotwell@gmail.com'
)
);
}
private function addRealColumns($engine)
{
$engine->addColumn(new FunctionColumn('foo', function($m){return $m['name'];}));
$engine->addColumn(new FunctionColumn('bar', function($m){return $m['email'];}));
}
private function arrayHasKeyValue($key,$value,$array)
{
$array = array_pluck($array,$key);
foreach ($array as $val)
{
if(str_contains($val, $value))
return true;
}
return false;
}
}

View File

@@ -0,0 +1,179 @@
<?php
use Chumper\Datatable\Table;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;
use Orchestra\Testbench\TestCase;
class TableTest extends TestCase {
/**
* @var Table
*/
private $table;
protected function getEnvironmentSetUp($app)
{
$app['config']->set('chumper.datatable.table', array(
'class' => 'table table-bordered',
'id' => '',
'options' => array(
"sPaginationType" => "full_numbers",
"bProcessing" => false
),
'callbacks' => array(),
'noScript' => false,
'table_view' => 'datatable::template',
'script_view' => 'datatable::javascript',
));
}
public function setUp()
{
parent::setUp();
$this->table = new Table();
}
/**
* @expectedException Exception
*/
public function testSetOptions()
{
$this->table->setOptions('foo','bar');
$this->table->setOptions(array(
'foo2' => 'bar2',
'foo3' => 'bar3'
));
$this->table->setOptions('foo', 'bar', 'baz');
}
/**
* @expectedException Exception
*/
public function testSetCallbacks()
{
$this->table->setCallbacks('foo', 'bar');
$this->assertArrayHasKey('foo', $this->table->getCallbacks());
$this->table->setCallbacks(array(
'foo2' => 'bar2',
'foo3' => 'bar3'
));
$this->assertArrayHasKey('foo2', $this->table->getCallbacks());
$this->assertArrayHasKey('foo3', $this->table->getCallbacks());
$this->table->setCallbacks('foo', 'bar', 'baz');
$this->assertTrue(False); // should throw exception before here
}
public function testSetNamedFunctionAsCallback()
{
//set an anonymous function
$this->table->setCallbacks(['foo'=>'function(){ return foo; }']);
//set a named function
$this->table->setCallbacks(['bar'=>'myBar']);
$parameters = $this->table->getViewParameters();
//an anonymous function should be included as it is.
$this->assertThat($parameters['options'],$this->stringContains('"foo":function(){ return foo; }') );
//the callback it's a function name, it shouldn't be quoted
$this->assertThat($parameters['options'],$this->stringContains('"bar":myBar') );
}
/**
* @expectedException Exception
*/
public function testSetCustomValues()
{
$this->table->setCustomValues('foo', 'bar');
$this->assertArrayHasKey('foo', $this->table->getCustomValues());
$this->table->setCustomValues(array(
'foo2' => 'bar2',
'foo3' => 'bar3'
));
$this->assertArrayHasKey('foo2', $this->table->getCustomValues());
$this->assertArrayHasKey('foo3', $this->table->getCustomValues());
$this->table->setCustomValues('foo', 'bar', 'baz');
$this->assertTrue(False); // should throw exception before here
}
public function testAddColumn()
{
$this->table->addColumn('foo');
$this->assertEquals(1, $this->table->countColumns());
$this->table->addColumn('foo1','foo2');
$this->assertEquals(3, $this->table->countColumns());
$this->table->addColumn(array('foo3','foo4'));
$this->assertEquals(5, $this->table->countColumns());
}
public function testRender()
{
View::shouldReceive('make')->once()
->with('datatable::template', \Mockery::any())->andReturn(true);
$this->table->setUrl('fooBar');
$table1 = $this->table->addColumn('foo')->render();
$this->assertEquals(array(
'options' => '{ "sPaginationType":"full_numbers",'.PHP_EOL
. '"bProcessing":false,'.PHP_EOL
. '"sAjaxSource":"fooBar",'.PHP_EOL
. '"bServerSide":true }',
'values' => array(),
'data' => array(),
'columns' => array(1=>'foo'),
'noScript' => false,
'class' => $this->table->getClass(),
'id' => $this->table->getId(),
), $this->table->getViewParameters());
$this->assertTrue($table1);
}
public function testSetData()
{
$data = array(
array(
'foo',
'bar'
),
array(
'foo2',
'bar2'
),
);
$this->table->setData($data);
$this->assertEquals($data,$this->table->getData());
}
public function testSetUrl()
{
$this->table->setUrl('foo/url');
$this->assertArrayHasKey('bServerSide',$this->table->getOptions());
$this->assertArrayHasKey('sAjaxSource',$this->table->getOptions());
$return = $this->table->getOptions();
$this->assertEquals('foo/url',$return['sAjaxSource']);
}
public function tearDown()
{
Mockery::close();
}
}

5
vendor/chumper/zipper/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
/vendor
composer.phar
composer.lock
.DS_Store
/.idea

11
vendor/chumper/zipper/.travis.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
language: php
php:
- 5.4
- 5.5
before_script:
- curl -s http://getcomposer.org/installer | php
- php composer.phar install --dev
script: phpunit

191
vendor/chumper/zipper/LICENSE vendored Normal file
View File

@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

150
vendor/chumper/zipper/README.md vendored Normal file
View File

@@ -0,0 +1,150 @@
#Zipper
[![Build Status](https://travis-ci.org/Chumper/Zipper.png)](https://travis-ci.org/Chumper/Zipper)
This is a simple Wrapper around the ZipArchive methods with some handy functions.
##Installation
1a- To install this package for laravel 5 just require it in your
`composer.json` with `"Chumper/Zipper": "0.6.0"`
1b- To install this package for laravel 4 just require it in your
`composer.json` with `"Chumper/Zipper": "0.5.1"`
2- goto `app/config/app.php`
.add to providers
'Chumper\Zipper\ZipperServiceProvider'
.add to aliases
'Zipper' => 'Chumper\Zipper\Zipper'
You can now access Zipper with the `Zipper` alias.
##Simple example
```php
$files = glob('public/files/*');
Zipper::make('public/test.zip')->add($files);
```
- by default the package will create the `test.zip` in the project route folder but in the example above we changed it to `project_route/public/`.
####Another example
```php
$zipper = new \Chumper\Zipper\Zipper;
$zipper->make('test.zip')->folder('test')->add('composer.json');
$zipper->zip('test.zip')->folder('test')->add('composer.json','test');
$zipper->remove('composer.lock');
$zipper->folder('mySuperPackage')->add(
array(
'vendor',
'composer.json'
),
);
$zipper->getFileContent('mySuperPackage/composer.json');
$zipper->make('test.zip')->extractTo('',array('mySuperPackage/composer.json'),Zipper::WHITELIST);
```
- You can easily chain most functions, except `getFileContent`, `getStatus`, `close` and `extractTo` which must come at the end of the chaine.
The main reason i wrote this little package is the `extractTo` method since it allows you to be very flexible when extracting zips.
So you can for example implement an update method which will just override the changed files.
##Functions
**make($pathToFile)**
`Create` or `Open` a zip archive; if the file does not exists it will create a new one.
It will return the Zipper instance so you can chain easily.
**add($files/folder)**
You can add and array of Files, or a Folder which all the files in that folder will then be added, so from the first example we could instead do something like `$files = 'public/files/';`.
**addString($filename, $content)**
add a single file to the zip by specifying a name and content as strings.
**remove($file/s)**
removes a single file or an array of files from the zip.
**folder($folder)**
Specify a folder to 'add files to' or 'remove files from' from the zip, example
Zipper::make('test.zip')->folder('test')->add('composer.json');
Zipper::make('test.zip')->folder('test')->remove('composer.json');
**home()**
Resets the folder pointer.
**zip($fileName)**
Uses the ZipRepository for file handling.
**getFileContent($filePath)**
get the content of a file in the zip. This will return the content or false.
**getStatus()**
get the opening status of the zip as integer.
**close()**
closes the zip and writes all changes.
**extractTo($path)**
Extracts the content of the zip archive to the specified location, for example
Zipper::make('test.zip')->folder('test')->extractTo('foo');
This will go into the folder `test` in the zip file and extract the content of that folder only to the folder `foo`, this is equal to using the `Zipper::WHITELIST`.
This command is really nice to get just a part of the zip file, you can also pass a 2nd & 3rd param to specify a single or an array of files that will be
white listed
>**Zipper::WHITELIST**
>
Zipper::make('test.zip')->extractTo('public', array('vendor'), Zipper::WHITELIST);
Which will extract the `test.zip` into the `public` folder but **only** the folder `vendor` inside the zip will be extracted.
or black listed
>**Zipper::BLACKLIST**
>
Zipper::make('test.zip')->extractTo('public', array('vendor'), Zipper::BLACKLIST);
Which will extract the `test.zip` into the `public` folder except the folder `vendor` inside the zip will not be extracted.
##Development
May it is a goot idea to add other compress functions like rar, phar or bzip2 etc...
Everything is setup for that, if you want just fork and develop further.
If you need other functions or got errors, please leave an issue on github.

31
vendor/chumper/zipper/composer.json vendored Normal file
View File

@@ -0,0 +1,31 @@
{
"name": "chumper/zipper",
"type": "library",
"description": "This is a little neat helper for the ZipArchive methods with handy functions",
"keywords": ["laravel", "ZIP", "Archive"],
"homepage": "http://github.com/Chumper/zipper",
"license": "Apache2",
"authors": [
{
"name": "Nils Plaschke",
"email": "github@nilsplaschke.de",
"homepage": "http://nilsplaschke.de",
"role": "Developer"
}
],
"require": {
"php": ">=5.3.0",
"illuminate/support": "5.x",
"illuminate/filesystem": "5.x"
},
"require-dev": {
"phpunit/phpunit": "3.7.*",
"mockery/mockery": "dev-master"
},
"autoload": {
"psr-0": {
"Chumper\\Zipper": "src/"
}
},
"minimum-stability": "dev"
}

18
vendor/chumper/zipper/phpunit.xml vendored Normal file
View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@@ -0,0 +1,13 @@
<?php namespace Chumper\Zipper\Facades;
use Illuminate\Support\Facades\Facade;
class Zipper extends Facade{
protected static function getFacadeAccessor()
{
return 'zipper';
}
}

View File

@@ -0,0 +1,88 @@
<?php namespace Chumper\Zipper\Repositories;
/**
* RepositoryInterface that needs to be implemented by every Repository
*
* Class RepositoryInterface
* @package Chumper\Zipper\Repositories
*/
/**
* Class RepositoryInterface
* @package Chumper\Zipper\Repositories
*/
interface RepositoryInterface
{
/**
* Construct with a given path
*
* @param $filePath
* @param bool $new
* @param $archiveImplementation
*/
function __construct($filePath, $new = false, $archiveImplementation = null);
/**
* Add a file to the opened Archive
*
* @param $pathToFile
* @param $pathInArchive
* @return void
*/
public function addFile($pathToFile, $pathInArchive);
/**
* Remove a file permanently from the Archive
*
* @param $pathInArchive
* @return void
*/
public function removeFile($pathInArchive);
/**
* Get the content of a file
*
* @param $pathInArchive
* @return string
*/
public function getFileContent($pathInArchive);
/**
* Get the stream of a file
*
* @param $pathInArchive
* @return mixed
*/
public function getFileStream($pathInArchive);
/**
* Will loop over every item in the archive and will execute the callback on them
* Will provide the filename for every item
*
* @param $callback
* @return void
*/
public function each($callback);
/**
* Checks whether the file is in the archive
*
* @param $fileInArchive
* @return boolean
*/
public function fileExists($fileInArchive);
/**
* Returns the status of the archive as a string
*
* @return string
*/
public function getStatus();
/**
* Closes the archive and saves it
* @return void
*/
public function close();
}

View File

@@ -0,0 +1,141 @@
<?php namespace Chumper\Zipper\Repositories;
use Exception;
use ZipArchive;
class ZipRepository implements RepositoryInterface
{
private $archive;
/**
* Construct with a given path
*
* @param $filePath
* @param bool $create
* @param $archive
* @throws \Exception
* @return ZipRepository
*/
function __construct($filePath, $create = false, $archive = null)
{
//Check if ZipArchive is available
if (!class_exists('ZipArchive'))
throw new Exception('Error: Your PHP version is not compiled with zip support');
$this->archive = $archive ? $archive : new ZipArchive;
if ($create)
$this->archive->open($filePath, ZipArchive::CREATE);
else
$this->archive->open($filePath);
}
/**
* Add a file to the opened Archive
*
* @param $pathToFile
* @param $pathInArchive
* @return void
*/
public function addFile($pathToFile, $pathInArchive)
{
$this->archive->addFile($pathToFile, $pathInArchive);
}
/**
* Add a file to the opened Archive using its contents
*
* @param $name
* @param $content
* @return void
*/
public function addFromString($name, $content)
{
$this->archive->addFromString($name, $content);
}
/**
* Remove a file permanently from the Archive
*
* @param $pathInArchive
* @return void
*/
public function removeFile($pathInArchive)
{
$this->archive->deleteName($pathInArchive);
}
/**
* Get the content of a file
*
* @param $pathInArchive
* @return string
*/
public function getFileContent($pathInArchive)
{
return $this->archive->getFromName($pathInArchive);
}
/**
* Get the stream of a file
*
* @param $pathInArchive
* @return mixed
*/
public function getFileStream($pathInArchive)
{
return $this->archive->getStream($pathInArchive);
}
/**
* Will loop over every item in the archive and will execute the callback on them
* Will provide the filename for every item
*
* @param $callback
* @return void
*/
public function each($callback)
{
for ($i = 0; $i < $this->archive->numFiles; $i++) {
//skip if folder
$stats = $this->archive->statIndex($i);
if ($stats['size'] == 0 && $stats['crc'] == 0)
continue;
call_user_func_array($callback, array(
'file' => $this->archive->getNameIndex($i),
));
}
}
/**
* Checks whether the file is in the archive
*
* @param $fileInArchive
* @return boolean
*/
public function fileExists($fileInArchive)
{
return $this->archive->locateName($fileInArchive) !== false;
}
/**
* Returns the status of the archive as a string
*
* @return string
*/
public function getStatus()
{
return $this->archive->getStatusString();
}
/**
* Closes the archive and saves it
* @return void
*/
public function close()
{
@$this->archive->close();
}
}

View File

@@ -0,0 +1,474 @@
<?php namespace Chumper\Zipper;
use Chumper\Zipper\Repositories\RepositoryInterface;
use Exception;
use Illuminate\Filesystem\Filesystem;
/**
* This Zipper class is a wrapper around the ZipArchive methods with some handy functions
*
* Class Zipper
* @package Chumper\Zipper
*/
class Zipper
{
/**
* Constant for extracting
*/
const WHITELIST = 1;
/**
* Constant for extracting
*/
const BLACKLIST = 2;
/**
* @var string Represents the current location in the archive
*/
private $currentFolder = '';
/**
* @var Filesystem Handler to the file system
*/
private $file;
/**
* @var RepositoryInterface Handler to the archive
*/
private $repository;
/**
* @var string The path to the current zip file
*/
private $filePath;
/**
* Constructor
*
* @param Filesystem $fs
*/
function __construct(Filesystem $fs = null)
{
$this->file = $fs ? $fs : new Filesystem();
}
/**
* Create a new zip Archive if the file does not exists
* opens a zip archive if the file exists
*
* @param $pathToFile string The file to open
* @param RepositoryInterface|string $type The type of the archive, defaults to zip, possible are zip, phar
*
* @return $this Zipper instance
*/
public function make($pathToFile, $type = 'zip')
{
$new = $this->createArchiveFile($pathToFile);
$this->filePath = $pathToFile;
$name = 'Chumper\Zipper\Repositories\\' . ucwords($type) . 'Repository';
if (is_subclass_of($name, 'Chumper\Zipper\Repositories\RepositoryInterface'))
$this->repository = new $name($pathToFile, $new);
else
//TODO $type should be a class name and not a string
$this->repository = $type;
return $this;
}
/**
* Create a new zip archive or open an existing one
*
* @param $pathToFile
* @return $this
*/
public function zip($pathToFile)
{
$this->make($pathToFile);
return $this;
}
/**
* Create a new phar file or open one
*
* @param $pathToFile
* @return $this
*/
public function phar($pathToFile)
{
$this->make($pathToFile, 'phar');
return $this;
}
/**
* Extracts the opened zip archive to the specified location <br/>
* you can provide an array of files and folders and define if they should be a white list
* or a black list to extract.
*
* @param $path string The path to extract to
* @param array $files An array of files
* @param int $method The Method the files should be treated
*/
public function extractTo($path, array $files = array(), $method = Zipper::BLACKLIST)
{
$path = realpath($path);
if (!$this->file->exists($path))
$this->file->makeDirectory($path, 0755, true);
if ($method == Zipper::WHITELIST)
$this->extractWithWhiteList($path, $files);
else
$this->extractWithBlackList($path, $files);
}
/**
* Gets the content of a single file if available
*
* @param $filePath string The full path (including all folders) of the file in the zip
* @throws \Exception
* @return mixed returns the content or throws an exception
*/
public function getFileContent($filePath)
{
if ($this->repository->fileExists($filePath) === false)
throw new Exception(sprintf('The file "%s" cannot be found', $filePath));
return $this->repository->getFileContent($filePath);
}
/**
* Add one or multiple files to the zip.
*
* @param $pathToAdd array|string An array or string of files and folders to add
* @return $this Zipper instance
*/
public function add($pathToAdd)
{
if (is_array($pathToAdd)) {
foreach ($pathToAdd as $dir) {
$this->add($dir);
}
} else if ($this->file->isFile($pathToAdd)) {
$this->addFile($pathToAdd);
} else
$this->addDir($pathToAdd);
return $this;
}
/**
* Add a file to the zip using its contents
*
* @param $filename string The name of the file to create
* @param $content string The file contents
* @return $this Zipper instance
*/
public function addString($filename, $content)
{
$this->addFromString($filename, $content);
return $this;
}
/**
* Gets the status of the zip.
*
* @return integer The status of the internal zip file
*/
public function getStatus()
{
return $this->repository->getStatus();
}
/**
* Remove a file or array of files and folders from the zip archive
*
* @param $fileToRemove array|string The path/array to the files in the zip
* @return $this Zipper instance
*/
public function remove($fileToRemove)
{
if (is_array($fileToRemove)) {
$self = $this;
$this->repository->each(function ($file) use ($fileToRemove, $self) {
if (starts_with($file, $fileToRemove)) {
$self->getRepository()->removeFile($file);
}
});
} else
$this->repository->removeFile($fileToRemove);
return $this;
}
/**
* Returns the path of the current zip file if there is one.
* @return string The path to the file
*/
public function getFilePath()
{
return $this->filePath;
}
/**
* Closes the zip file and frees all handles
*/
public function close()
{
if(!is_null($this->repository))
$this->repository->close();
$this->filePath = "";
}
/**
* Sets the internal folder to the given path.<br/>
* Useful for extracting only a segment of a zip file.
* @param $path
* @return $this
*/
public function folder($path)
{
$this->currentFolder = $path;
return $this;
}
/**
* Resets the internal folder to the root of the zip file.
*
* @return $this
*/
public function home()
{
$this->currentFolder = '';
return $this;
}
/**
* Deletes the archive file
*/
public function delete()
{
if(!is_null($this->repository))
$this->repository->close();
$this->file->delete($this->filePath);
$this->filePath = "";
}
/**
* Get the type of the Archive
*
* @return string
*/
public function getArchiveType()
{
return get_class($this->repository);
}
/**
* Destructor
*/
public function __destruct()
{
if(!is_null($this->repository))
$this->repository->close();
}
/**
* Get the current internal folder pointer
*
* @return string
*/
public function getCurrentFolderPath()
{
return $this->currentFolder;
}
/**
* Checks if a file is present in the archive
*
* @param $fileInArchive
* @return bool
*/
public function contains($fileInArchive)
{
return $this->repository->fileExists($fileInArchive);
}
/**
* @return RepositoryInterface
*/
public function getRepository()
{
return $this->repository;
}
/**
* @return Filesystem
*/
public function getFileHandler()
{
return $this->file;
}
/**
* Gets the path to the internal folder
*
* @return string
*/
public function getInternalPath()
{
return empty($this->currentFolder) ? '' : $this->currentFolder . '/';
}
//---------------------PRIVATE FUNCTIONS-------------
/**
* @param $pathToZip
* @throws \Exception
* @return bool
*/
private function createArchiveFile($pathToZip)
{
if (!$this->file->exists($pathToZip)) {
if (!$this->file->exists(dirname($pathToZip)))
$this->file->makeDirectory(dirname($pathToZip), 0755, true);
if (!$this->file->isWritable(dirname($pathToZip)))
throw new Exception(sprintf('The path "%s" is not writeable', $pathToZip));
return true;
}
return false;
}
/**
* @param $pathToDir
*/
private function addDir($pathToDir)
{
// First go over the files in this directory and add them to the repository.
foreach ($this->file->files($pathToDir) as $file) {
$this->addFile($pathToDir . '/' . basename($file));
}
// Now let's visit the subdirectories and add them, too.
foreach ($this->file->directories($pathToDir) as $dir) {
$old_folder = $this->currentFolder;
$this->currentFolder = empty($this->currentFolder) ? basename($dir) : $this->currentFolder . '/' . basename($dir);
$this->addDir($pathToDir . '/' . basename($dir));
$this->currentFolder = $old_folder;
}
}
/**
* Add the file to the zip
*
* @param $pathToAdd
*/
private function addFile($pathToAdd)
{
$info = pathinfo($pathToAdd);
$file_name = isset($info['extension']) ?
$info['filename'] . '.' . $info['extension'] :
$info['filename'];
$this->repository->addFile($pathToAdd, $this->getInternalPath() . $file_name);
}
/**
* Add the file to the zip from content
*
* @param $filename
* @param $content
*/
private function addFromString($filename, $content)
{
$this->repository->addFromString($this->getInternalPath() . $filename, $content);
}
/**
* @param $path
* @param $filesArray
* @throws \Exception
*/
private function extractWithBlackList($path, $filesArray)
{
$self = $this;
$this->repository->each(function ($fileName) use ($path, $filesArray, $self) {
$oriName = $fileName;
$currentPath = $self->getCurrentFolderPath();
if (!empty($currentPath) && !starts_with($fileName, $currentPath))
return;
if (starts_with($fileName, $filesArray)) {
return;
}
$tmpPath = str_replace($self->getInternalPath(), '', $fileName);
// We need to create the directory first in case it doesn't exist
$full_path = $path . '/' . $tmpPath;
$dir = substr($full_path, 0, strrpos($full_path, '/'));
if(!is_dir($dir))
$self->getFileHandler()->makeDirectory($dir, 0777, true, true);
$self->getFileHandler()->put($path . '/' . $tmpPath, $self->getRepository()->getFileStream($oriName));
});
}
/**
* @param $path
* @param $filesArray
* @throws \Exception
*/
private function extractWithWhiteList($path, $filesArray)
{
$self = $this;
$this->repository->each(function ($fileName) use ($path, $filesArray, $self) {
$oriName = $fileName;
$currentPath = $self->getCurrentFolderPath();
if (!empty($currentPath) && !starts_with($fileName, $currentPath))
return;
if (starts_with($self->getInternalPath() . $fileName, $filesArray)) {
$tmpPath = str_replace($self->getInternalPath(), '', $fileName);
// We need to create the directory first in case it doesn't exist
$full_path = $path . '/' . $tmpPath;
$dir = substr($full_path, 0, strrpos($full_path, '/'));
if(!is_dir($dir))
$self->getFileHandler()->makeDirectory($dir, 0777, true, true);
$self->getFileHandler()->put($path . '/' . $tmpPath, $self->getRepository()->getFileStream($oriName));
}
});
}
/**
* List files that are within the archive
*
* @return array
*/
public function listFiles()
{
$filesList = array();
$this->repository->each(
function ($file) use (&$filesList) {
$filesList[] = $file;
}
);
return $filesList;
}
}

View File

@@ -0,0 +1,55 @@
<?php namespace Chumper\Zipper;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
class ZipperServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['zipper'] = $this->app->share(function($app)
{
$return = $app->make('Chumper\Zipper\Zipper');
return $return;
});
$this->app->booting(function()
{
$loader = AliasLoader::getInstance();
$loader->alias('Zipper', 'Chumper\Zipper\Facades\Zipper');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('zipper');
}
}

0
vendor/chumper/zipper/tests/.gitkeep vendored Normal file
View File

View File

@@ -0,0 +1,110 @@
<?php
use Chumper\Zipper\Repositories\RepositoryInterface;
class ArrayArchive implements RepositoryInterface
{
private $entries = array();
/**
* Construct with a given path
*
* @param $filePath
* @param bool $new
* @param $archiveImplementation
*/
function __construct($filePath, $new = false, $archiveImplementation = null)
{
}
/**
* Add a file to the opened Archive
*
* @param $pathToFile
* @param $pathInArchive
* @return void
*/
public function addFile($pathToFile, $pathInArchive)
{
$this->entries[$pathInArchive] = $pathInArchive;
}
/**
* Remove a file permanently from the Archive
*
* @param $pathInArchive
* @return void
*/
public function removeFile($pathInArchive)
{
unset($this->entries[$pathInArchive]);
}
/**
* Get the content of a file
*
* @param $pathInArchive
* @return string
*/
public function getFileContent($pathInArchive)
{
return $this->entries[$pathInArchive];
}
/**
* Get the stream of a file
*
* @param $pathInArchive
* @return mixed
*/
public function getFileStream($pathInArchive)
{
return $this->entries[$pathInArchive];
}
/**
* Will loop over every item in the archive and will execute the callback on them
* Will provide the filename for every item
*
* @param $callback
* @return void
*/
public function each($callback)
{
foreach ($this->entries as $entry) {
call_user_func_array($callback, array(
'file' => $entry,
));
}
}
/**
* Checks whether the file is in the archive
*
* @param $fileInArchive
* @return boolean
*/
public function fileExists($fileInArchive)
{
return array_key_exists($fileInArchive, $this->entries);
}
/**
* Returns the status of the archive as a string
*
* @return string
*/
public function getStatus()
{
return "OK";
}
/**
* Closes the archive and saves it
* @return void
*/
public function close()
{
}
}

View File

@@ -0,0 +1,101 @@
<?php
use Chumper\Zipper\Repositories\ZipRepository;
/**
* Created by JetBrains PhpStorm.
* User: Nils
* Date: 28.08.13
* Time: 20:57
* To change this template use File | Settings | File Templates.
*/
class ZipRepositoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var ZipRepository
*/
public $zip;
/**
* @var \Mockery\Mock
*/
public $mock;
public function setUp()
{
$this->mock = Mockery::mock(new ZipArchive);
$this->zip = new ZipRepository('foo', true, $this->mock);
}
public function testMake()
{
$zip = new ZipRepository('foo.zip', true);
$this->assertFalse($zip->fileExists('foo'));
}
public function testAddFile()
{
$this->mock->shouldReceive('addFile')->once()->with('bar', 'bar');
$this->mock->shouldReceive('addFile')->once()->with('bar', 'foo/bar');
$this->mock->shouldReceive('addFile')->once()->with('foo/bar', 'bar');
$this->zip->addFile('bar', 'bar');
$this->zip->addFile('bar', 'foo/bar');
$this->zip->addFile('foo/bar', 'bar');
}
public function testRemoveFile()
{
$this->mock->shouldReceive('deleteName')->once()->with('bar');
$this->mock->shouldReceive('deleteName')->once()->with('foo/bar');
$this->zip->removeFile('bar');
$this->zip->removeFile('foo/bar');
}
public function testGetFileContent()
{
$this->mock->shouldReceive('getFromName')->once()
->with('bar')->andReturn('foo');
$this->mock->shouldReceive('getFromName')->once()
->with('foo/bar')->andReturn('baz');
$this->assertEquals('foo', $this->zip->getFileContent('bar'));
$this->assertEquals('baz', $this->zip->getFileContent('foo/bar'));
}
public function testGetFileStream()
{
$this->mock->shouldReceive('getStream')->once()
->with('bar')->andReturn('foo');
$this->mock->shouldReceive('getStream')->once()
->with('foo/bar')->andReturn('baz');
$this->assertEquals('foo', $this->zip->getFileStream('bar'));
$this->assertEquals('baz', $this->zip->getFileStream('foo/bar'));
}
public function testFileExists()
{
$this->mock->shouldReceive('locateName')->once()
->with('bar')->andReturn(true);
$this->mock->shouldReceive('locateName')->once()
->with('foo/bar')->andReturn(false);
$this->assertTrue($this->zip->fileExists('bar'));
$this->assertFalse($this->zip->fileExists('foo/bar'));
}
public function testClose()
{
$this->zip->close();
}
protected function tearDown()
{
Mockery::close();
}
}

View File

@@ -0,0 +1,238 @@
<?php
use Chumper\Zipper\Zipper;
use Illuminate\Filesystem\Filesystem;
require_once 'ArrayArchive.php';
class ZipperTest extends PHPUnit_Framework_TestCase
{
/**
* @var \Chumper\Zipper\Zipper
*/
public $archive;
/**
* @var \Mockery\Mock
*/
public $file;
public function __construct()
{
$this->archive = new \Chumper\Zipper\Zipper(
$this->file = Mockery::mock(new Filesystem)
);
$this->archive->make('foo', new ArrayArchive('foo', true));
}
public function testMake()
{
$this->assertEquals('ArrayArchive', $this->archive->getArchiveType());
$this->assertEquals('foo', $this->archive->getFilePath());
}
public function testExtractTo()
{
}
public function testAddAndGet()
{
$this->file->shouldReceive('isFile')->with('foo.bar')
->times(3)->andReturn(true);
$this->file->shouldReceive('isFile')->with('foo')
->times(3)->andReturn(true);
/**Array**/
$this->file->shouldReceive('isFile')->with('/path/to/fooDir')
->once()->andReturn(false);
$this->file->shouldReceive('files')->with('/path/to/fooDir')
->once()->andReturn(array('foo.bar', 'bar.foo'));
$this->file->shouldReceive('directories')->with('/path/to/fooDir')
->once()->andReturn(array('fooSubdir'));
$this->file->shouldReceive('files')->with('/path/to/fooDir/fooSubdir')
->once()->andReturn(array('foo.bar'));
$this->file->shouldReceive('directories')->with('/path/to/fooDir/fooSubdir')
->once()->andReturn(array());
//test1
$this->archive->add('foo.bar');
$this->archive->add('foo');
$this->assertEquals('foo', $this->archive->getFileContent('foo'));
$this->assertEquals('foo.bar', $this->archive->getFileContent('foo.bar'));
//test2
$this->archive->add(array(
'foo.bar',
'foo'
));
$this->assertEquals('foo', $this->archive->getFileContent('foo'));
$this->assertEquals('foo.bar', $this->archive->getFileContent('foo.bar'));
/**
* test3:
* Add the local folder /path/to/fooDir as folder fooDir to the repository
* and make sure the folder structure within the repository is there.
*/
$this->archive->folder('fooDir')->add('/path/to/fooDir');
$this->assertEquals('fooDir/foo.bar', $this->archive->getFileContent('fooDir/foo.bar'));
$this->assertEquals('fooDir/bar.foo', $this->archive->getFileContent('fooDir/bar.foo'));
$this->assertEquals('fooDir/fooSubdir/foo.bar', $this->archive->getFileContent('fooDir/fooSubdir/foo.bar'));
}
/**
* @expectedException Exception
*/
public function testGetFileContent()
{
$this->archive->getFileContent('baz');
}
public function testRemove()
{
$this->file->shouldReceive('isFile')->with('foo')
->andReturn(true);
$this->archive->add('foo');
$this->assertTrue($this->archive->contains('foo'));
$this->archive->remove('foo');
$this->assertFalse($this->archive->contains('foo'));
//----
$this->file->shouldReceive('isFile')->with('foo')
->andReturn(true);
$this->file->shouldReceive('isFile')->with('fooBar')
->andReturn(true);
$this->archive->add(array('foo', 'fooBar'));
$this->assertTrue($this->archive->contains('foo'));
$this->assertTrue($this->archive->contains('fooBar'));
$this->archive->remove(array('foo', 'fooBar'));
$this->assertFalse($this->archive->contains('foo'));
$this->assertFalse($this->archive->contains('fooBar'));
}
public function testExtractWhiteList()
{
$this->file->shouldReceive('isFile')->with('foo')
->andReturn(true);
$this->archive->add('foo');
$this->file->shouldReceive('put')->with(realpath(NULL) . '/foo', 'foo');
$this->archive->extractTo('', array('foo'), Zipper::WHITELIST);
//----
$this->file->shouldReceive('isFile')->with('foo')
->andReturn(true);
$this->archive->folder('foo/bar')->add('foo');
$this->file->shouldReceive('put')->with(realpath(NULL) . '/foo', 'foo/bar/foo');
$this->archive->extractTo('', array('foo'), Zipper::WHITELIST);
}
public function testExtractBlackList()
{
$this->file->shouldReceive('isFile')->with('foo')
->andReturn(true);
$this->archive->add('foo');
$this->file->shouldReceive('put')->with(realpath(NULL) . '/foo', 'foo');
$this->archive->extractTo('', array(), Zipper::BLACKLIST);
//----
$this->file->shouldReceive('isFile')->with('foo')
->andReturn(true);
$this->archive->folder('foo/bar')->add('foo');
$this->file->shouldReceive('put')->with(realpath(NULL) . '/foo', 'foo/bar/foo');
$this->archive->extractTo('', array('foo'), Zipper::BLACKLIST);
}
public function testNavigationFolderAndHome()
{
$this->archive->folder('foo/bar');
$this->assertEquals('foo/bar', $this->archive->getCurrentFolderPath());
//----
$this->file->shouldReceive('isFile')->with('foo')
->andReturn(true);
$this->archive->add('foo');
$this->assertEquals('foo/bar/foo', $this->archive->getFileContent('foo/bar/foo'));
//----
$this->file->shouldReceive('isFile')->with('bar')
->andReturn(true);
$this->archive->home()->add('bar');
$this->assertEquals('bar', $this->archive->getFileContent('bar'));
//----
$this->file->shouldReceive('isFile')->with('baz/bar/bing')
->andReturn(true);
$this->archive->folder('test')->add('baz/bar/bing');
$this->assertEquals('test/bing', $this->archive->getFileContent('test/bing'));
}
public function testListFiles()
{
// testing empty file
$this->file->shouldReceive('isFile')->with('foo.file')->andReturn(true);
$this->file->shouldReceive('isFile')->with('bar.file')->andReturn(true);
$this->assertEquals(array(), $this->archive->listFiles());
// testing not empty file
$this->archive->add('foo.file');
$this->archive->add('bar.file');
$this->assertEquals(array('foo.file', 'bar.file'), $this->archive->listFiles());
// testing with a empty sub dir
$this->file->shouldReceive('isFile')->with('/path/to/subDirEmpty')->andReturn(false);
$this->file->shouldReceive('files')->with('/path/to/subDirEmpty')->andReturn(array());
$this->file->shouldReceive('directories')->with('/path/to/subDirEmpty')->andReturn(array());
$this->archive->folder('subDirEmpty')->add('/path/to/subDirEmpty');
$this->assertEquals(array('foo.file', 'bar.file'), $this->archive->listFiles());
// testing with a not empty sub dir
$this->file->shouldReceive('isFile')->with('/path/to/subDir')->andReturn(false);
$this->file->shouldReceive('isFile')->with('sub.file')->andReturn(true);
$this->file->shouldReceive('files')->with('/path/to/subDir')->andReturn(array('sub.file'));
$this->file->shouldReceive('directories')->with('/path/to/subDir')->andReturn(array());
$this->archive->folder('subDir')->add('/path/to/subDir');
$this->assertEquals(array('foo.file', 'bar.file', 'subDir/sub.file'), $this->archive->listFiles());
}
}