외부 코드를 Composer 기반으로 변경

This commit is contained in:
2018-01-28 19:25:31 +09:00
parent 8a181055a0
commit d422c03003
101 changed files with 12743 additions and 19 deletions
+7
View File
@@ -0,0 +1,7 @@
{
"require": {
"brandonwamboldt/utilphp": "^1.1",
"sergeytsalkov/meekrodb": "^2.3",
"league/plates": "^3.3"
}
}
Generated
+162
View File
@@ -0,0 +1,162 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"content-hash": "08d6fa0a77eca6b860aa39d42081eea9",
"packages": [
{
"name": "brandonwamboldt/utilphp",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/brandonwamboldt/utilphp.git",
"reference": "36c32efc4f0679c05163464a550f45c8d83fe683"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/brandonwamboldt/utilphp/zipball/36c32efc4f0679c05163464a550f45c8d83fe683",
"reference": "36c32efc4f0679c05163464a550f45c8d83fe683",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"satooshi/php-coveralls": "dev-master"
},
"type": "library",
"autoload": {
"psr-0": {
"utilphp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Brandon Wamboldt",
"email": "brandon.wamboldt@gmail.com"
}
],
"description": "util.php is a collection of useful functions and snippets that you need or could use every day, designed to avoid conflicts with existing projects",
"homepage": "https://github.com/brandonwamboldt/utilphp",
"keywords": [
"collection",
"helpers",
"php",
"utility"
],
"time": "2015-02-02T17:56:14+00:00"
},
{
"name": "league/plates",
"version": "3.3.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/plates.git",
"reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/plates/zipball/b1684b6f127714497a0ef927ce42c0b44b45a8af",
"reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af",
"shasum": ""
},
"require": {
"php": "^5.3 | ^7.0"
},
"require-dev": {
"mikey179/vfsstream": "^1.4",
"phpunit/phpunit": "~4.0",
"squizlabs/php_codesniffer": "~1.5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"psr-4": {
"League\\Plates\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jonathan Reinink",
"email": "jonathan@reinink.ca",
"role": "Developer"
}
],
"description": "Plates, the native PHP template system that's fast, easy to use and easy to extend.",
"homepage": "http://platesphp.com",
"keywords": [
"league",
"package",
"templates",
"templating",
"views"
],
"time": "2016-12-28T00:14:17+00:00"
},
{
"name": "sergeytsalkov/meekrodb",
"version": "v2.3",
"source": {
"type": "git",
"url": "https://github.com/SergeyTsalkov/meekrodb.git",
"reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/SergeyTsalkov/meekrodb/zipball/eb36858f1aff94ae1665900e681a1cfb78563ee1",
"reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1",
"shasum": ""
},
"require": {
"php": ">=5.2.0"
},
"type": "library",
"autoload": {
"classmap": [
"db.class.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-3.0"
],
"authors": [
{
"name": "Sergey Tsalkov",
"email": "stsalkov@gmail.com"
}
],
"description": "The Simple PHP/MySQL Library",
"homepage": "http://www.meekro.com",
"keywords": [
"database",
"mysql",
"mysqli",
"pdo"
],
"time": "2014-06-16T22:40:22+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": []
}
+1 -2
View File
@@ -1,6 +1,5 @@
<?php
require_once(__dir__.'/../e_lib/util.php');
require_once(__dir__.'/../e_lib/meekrodb.2.3.class.php.php');
require(__dir__.'/../vendor/autoload.php');
require_once(__dir__.'/../e_lib/phpmailer5/class.phpmailer.php');
require_once(__dir__.'/../e_lib/phpmailer5/class.smtp.php');
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
require_once(ROOT.W.F_FUNC.W.'class._String.php');
require_once(ROOT.W.E_LIB.W.'util.php');
require(__dir__.'/../vendor/autoload.php');
class _Validation {
public static function CheckID($id) {
$len = strlen($id);
+21 -16
View File
@@ -1,6 +1,6 @@
<?php
require(__dir__.'/../vendor/autoload.php');
require_once(__dir__.'/d_setting/conf.php');
require_once(__dir__.'/../e_lib/util.php');
require_once 'process_war.php';
require_once 'func_gamerule.php';
require_once 'func_process.php';
@@ -2320,19 +2320,26 @@ function isLock() {
return newDB()->queryFirstField("select plock from plock where no=1") != 0;
}
function lock() {
function tryLock() {
//NOTE: 게임 로직과 관련한 모든 insert, update 함수들은 lock을 거칠것을 권장함.
$db = newDB();
//테이블 락
$db->query("lock tables plock write");
// 잠금
$db->query("update plock set plock=1 where no=1");
$isUnlocked = $db->queryFirstField("select plock from plock where no=1") != 0;
if($isUnlocked){
$db->query("update plock set plock=1 where no=1");
}
//테이블 언락
$db->query("unlock tables");
return $isUnlocked;
}
function unlock() {
// 풀림
//NOTE: unlock에는 table lock이 필요없는가?
newDB()->query("update plock set plock=0 where no=1");
}
@@ -2440,23 +2447,21 @@ function checkTurn($connect) {
// 잦은 갱신 금지 현재 10초당 1회
if(!timeover($connect)) { return; }
// 현재 처리중이면 접근 불가
if(isLock()) { return; }
// 파일락 획득
//FIXME:이미 DB 테이블로 lock을 시도하는데 이게 따로 필요한가?
$fp = fopen('lock.txt', 'r');
if(!flock($fp, LOCK_EX)) {
return;
}
if(!tryLock()){
return;
}
$locklog[0] = "- checkTurn() : ".date('Y-m-d H:i:s')." : ".$_SESSION['p_id'];
pushLockLog($connect, $locklog);
// 파일락 획득
$fp = fopen('lock.txt', 'r');
if(!flock($fp, LOCK_EX)) { return; }
// 세마포어 획득(윈도우서버 불가)
//$sema = @sem_get(fileinode('stylesheet.php'));
//if(!@sem_acquire($sema)) { echo "치명적 에러! 유기체에게 문의하세요!"; exit(1); }
// 현재 처리중이면 접근 불가
if(isLock()) { return; }
// 락 걸고 처리
lock();
// 파일락 해제
if(!flock($fp, LOCK_UN)) { return; }
// 세마포어 해제
+7
View File
@@ -0,0 +1,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit67b09c83b85c3bc0027caefe5bba171a::getLoader();
+1
View File
@@ -0,0 +1 @@
service_name: travis-ci
@@ -0,0 +1,4 @@
test.php
build/*
report/*
tests/test*
+22
View File
@@ -0,0 +1,22 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- hhvm
matrix:
allow_failures:
- php: hhvm
before_script:
- pyrus install pear/PHP_CodeSniffer
- wget -nc http://getcomposer.org/composer.phar
- php composer.phar install --dev --no-interaction
- mkdir -p build/logs
- phpenv rehash
after_script:
- php vendor/bin/coveralls
+86
View File
@@ -0,0 +1,86 @@
Change Log
==========
1.1.0
-----
This release introduces a deprecation notice for `slugify()`, please update your code.
* Added a cryptographically secure random string function `secure_random_string`. Thanks to @abhimanyusharma003 via [Pull Request #53](https://github.com/brandonwamboldt/utilphp/pull/53)
* Added `limit_characters` and `limit_words` functions. Thanks to @abhimanyusharma003 via [Pull Request #55](https://github.com/brandonwamboldt/utilphp/pull/55)
* Added `rmdir` method to recursively delete a directory. Thanks to @ARACOOOL via [Pull Request #56](https://github.com/brandonwamboldt/utilphp/pull/56)
* Added `set_executable`, `set_readable`, `set_writable`, `directory_size`, `directory_contents` and `get_user_dir` functions. Thanks to @sergserg via [Pull Request #70](https://github.com/brandonwamboldt/utilphp/pull/70)
* Changed parameter ordering for `slugify`, `$css_mode` is now the third argument. For backwards compatibility, the old order will still work but it will generate an `E_USER_DEPRECATED` warning. Thanks to @abhimanyusharma003 via [Pull Request #71](https://github.com/brandonwamboldt/utilphp/pull/71)
* Added `match_string` method. Thanks to @abhimanyusharma003 via [Pull Request #72](https://github.com/brandonwamboldt/utilphp/pull/72)
* Renamed internal methods (protected ones) for PSR-2 compliance
* General performance improvements, code quality improvements, and increased unit test coverage (special thanks to @hopeseekr for getting us near 100% coverage)
1.0.7
-----
* Added `fix_broken_serialization` to fix broken serialized strings (Thanks to @hopeseekr via [Pull Request #48](https://github.com/brandonwamboldt/utilphp/pull/48))
* Fixed `get_current_url` appending port 80 or 443 when not needed (Thanks to @scottchiefbaker via [Pull Request #49](https://github.com/brandonwamboldt/utilphp/pull/49))
* `var_dump` can now handle recursive data structures without crashing
* `var_dump` code was minified and cleaned up
* `array_flatten` was optimized (thanks to @hopeseekr via [Pull Request #47](https://github.com/brandonwamboldt/utilphp/pull/47))
* `remove_accents` was completely rewritten and is now ~4x faster
1.0.6
-----
* Added `start_with` function
* Added `ends_with` function
* Added `str_contains` function
* Added `str_icontains` function
* Added `get_file_ext` function
* Fixing permissions on the files & directories
* Fixing a bug with the include path of util.php
1.0.5
-----
* [Issue #29](https://github.com/brandonwamboldt/utilphp/issues/29) Fixed error in `var_dump` if mbstring extension wasn't present
* Adding Composer support
* Updating license from GPL to MIT
* Adding Changelog to project
* Bumping minimum version to PHP 5.3.3
1.0.4
-----
* [Issue #22](https://github.com/brandonwamboldt/utilphp/issues/22) Removed all superglobal *_get functions, you can use the modified array_get now
* [Issue #22](https://github.com/brandonwamboldt/utilphp/issues/22) Modifed the behaviour of `array_get`, see documentation
* [Pull Request #21](https://github.com/brandonwamboldt/utilphp/pull/21) Added multibyte support to html* functions
* [Issue #9](https://github.com/brandonwamboldt/utilphp/issues/9) Removed the `str_to_utf8` function
* [Issue #3](https://github.com/brandonwamboldt/utilphp/issues/3) Removed the `absint` function
* Removed declare() from util.php to avoid errors
* Updated PHPUnit tests to use PHPUnit 3.6
1.0.3
-----
* [Issue #16](https://github.com/brandonwamboldt/utilphp/issues/16) Improved performance of `slugify`
* [Issue #14](https://github.com/brandonwamboldt/utilphp/issues/14) Modified the regex for `seems_utf8` to be more accurate
* [Issue #13](https://github.com/brandonwamboldt/utilphp/issues/13) Changed `validate_email` to be wrapper for `filter_var`
* Added 'ok' to the list of yes words for `str_to_bool`
* `str_to_bool` matches no followed by any number of 'o's
1.0.2
-----
* [Issue #12](https://github.com/brandonwamboldt/utilphp/issues/12) `get_current_url` now includes the port and user/password if required
* [Issue #11](https://github.com/brandonwamboldt/utilphp/issues/11) `human_time_diff` now uses the DateTime functions
* [Issue #10](https://github.com/brandonwamboldt/utilphp/issues/10) `is_https` no longer checks the port as well
1.0.1
-----
* [Issue #7](https://github.com/brandonwamboldt/utilphp/issues/7) Added the `$trust_proxy_headers` parameter to `get_client_ip`
* [Issue #6](https://github.com/brandonwamboldt/utilphp/issues/6) Removed `is_isset` as the function did not work as intended
* [Issue #6](https://github.com/brandonwamboldt/utilphp/issues/6) Removed `is_empty` as it is redundant, use ! with function calls instead
* Fixed a bug with `get_gravatar`
1.0.0
-----
* Initial release of util.php.
+48
View File
@@ -0,0 +1,48 @@
# CONTRIBUTORS
Util.php is the combined effort of many people who contributed new functions and features, bug fixes, tests, and documentation.
# Maintainer / Lead
* Brandon Wamboldt (http://brandonwamboldt.ca)
## Third-Party Projects
The following projects were fully or partially incorporated into util.php (and properly attributed).
* IntToWords (https://github.com/hemant347/IntToWords)
* LinkifyURL (https://github.com/jmrware/LinkifyURL)
* URLify.php (https://github.com/jbroadway/urlify/)
* Pure PHP http_build_url (https://github.com/jakeasmith/http_build_url)
## Methods
The following developers and/or companies helped contribute to building util.php.
* PHP Experts, Inc. (http://www.phpexperts.pro/)
- `array_flatten()`
- `fix_broken_serialization()`
- Lots of unit tests.
* Tony Ferrara (ircmaxwell, http://blog.ircmaxell.com/)
- `seemsUtf8Regex()`: http://stackoverflow.com/a/11709412/430062
* Askar ([@ARACOOOL](https://github.com/ARACOOOL))
- `rmdir()`
- `limit_characters()`
- `limit_words()`
* Anonymous (tmp1000@fastmail.fm)
- `htmlspecialentities()`: http://php.timesoft.cc/manual/en/function.htmlentities.php
- `htmlspecialchars()`
* Laravel Project (https://github.com/laravel/laravel)
- `secure_random_string()`: http://trac.allenjb.me.uk/php/browser/tagi/vendor/laravel/framework/src/Illuminate/Support/Str.php?rev=87#L127
* Abhimanyu Sharma ([@abhimanyusharma003](https://github.com/abhimanyusharma003))
- `limit_characters()`
- `limit_words()`
- `match_string()`
* Scott Baker ([@scottchiefbaker](https://github.com/scottchiefbaker))
* [@sergserg](https://github.com/sergserg)
- `set_writable()`
- `set_executable()`
- `set_readable()`
- `directory_size()`
- `directory_contents()`
- `get_user_dir()`
+24
View File
@@ -0,0 +1,24 @@
The MIT License (MIT)
=====================
The MIT License (MIT)
Copyright (c) 2013 Brandon Wamboldt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+123
View File
@@ -0,0 +1,123 @@
# Util.php [![Build Status](https://img.shields.io/travis/brandonwamboldt/utilphp.svg)](https://travis-ci.org/brandonwamboldt/utilphp) [![Coverage Status](https://img.shields.io/coveralls/brandonwamboldt/utilphp/master.svg)](https://coveralls.io/r/brandonwamboldt/utilphp)
[UtilPHP](http://brandonwamboldt.github.com/utilphp/) (Aka util.php) is a
collection of useful functions and snippets that you need or could use every
day. It's implemented as a class with static methods, to avoid conflicts with
your existing code-base. Just drop it in and start using it immediately.
Included are 55+ functions that provide you with the ability to do common
tasks much easier and more efficiently, without having to find that one comment
on php.net where you know it's been done already. Access superglobals without
checking to see if certain indexes are set first and pass default values, use a
nicely formatted var dump, validate emails, generate random strings, flatten an
array, pull a single column out of a multidimensional array and much more.
Although it's implemented as one giant class, util.php has extensive
documentation and a full suite of unit tests to avoid breaking
backwards-compatibility unintentionally.
## Release Information
This repo contains in development code for future releases as well as the
current stable branch. Development code is contained in the develop branch.
## Changelog and New Features
You can find a list of all changes for each release in the
[official documentation](http://brandonwamboldt.github.com/utilphp/#changelog)
## Installation
### Server Requirements
* PHP version 5.3.3 or higher.
### Standalone File
Simply drop `util.php` in any project and call `include 'util.php';` in your
project. You can then access the `Util` class.
### Composer
Add the following dependency to your composer.json:
```
"brandonwamboldt/utilphp": "1.0.*"
```
When used with composer, the class is namespaced (`\utilphp\util`) instead of
just `util`.
## Contributing
UtilPHP is a community driven project and accepts contributions of code and
documentation from the community. These contributions are made in the form of
Issues or [Pull Requests](http://help.github.com/send-pull-requests/) on the
[UtilityPHP repository](https://github.com/brandonwamboldt/utilphp) on GitHub.
Issues are a quick way to point out a bug. If you find a bug or documentation
error in UtilityPHP then please check a few things first:
* There is not already an open Issue
* The issue has already been fixed (check the develop branch, or look for closed Issues)
* Is it something really obvious that you fix it yourself?
Reporting issues is helpful but an even better approach is to send a Pull
Request, which is done by "Forking" the main repository and committing to your
own copy. This will require you to use the version control system called Git.
## Guidelines
Before we look into how, here are the guidelines. If your Pull Requests fail to
pass these guidelines it will be declined and you will need to re-submit when
youve made the changes. This might sound a bit tough, but it is required for
me to maintain quality of the code-base.
### PHP Style
Please ensure all new contributions match the [PSR-2](http://www.php-fig.org/psr/psr-2/)
coding style guide.
### Documentation
If you change anything that requires a change to documentation then you will
need to add it. New methods, parameters, changing default values, adding
constants, etc are all things that will require a change to documentation. The
change-log must also be updated for every change. Also PHPDoc blocks must be
maintained.
### PHP Version Compatibility
UtilityPHP is compatible with PHP 5.3.3 so all code supplied must stick to this
requirement.
Of particular note is avoiding short array notation like this:
```
$var = [];
```
Please use the old notation instead:
```
$var = array();
```
I know it's uglier, but PHP 5.3 while EOL'd, still isn't that old.
### Branching
One thing at a time: A pull request should only contain one change. That does
not mean only one commit, but one change - however many commits it took. The
reason for this is that if you change X and Y but send a pull request for both
at the same time, we might really want X but disagree with Y, meaning we cannot
merge the request. Using the Git-Flow branching model you can create new
branches for both of these features and send two requests.
## License
UtilPHP is licensed under the MIT license.
## Resources
* [Documentation](http://brandonwamboldt.github.com/utilphp/)
+24
View File
@@ -0,0 +1,24 @@
{
"name": "brandonwamboldt/utilphp",
"type": "library",
"version": "1.1.0",
"description": "util.php is a collection of useful functions and snippets that you need or could use every day, designed to avoid conflicts with existing projects",
"keywords": ["php", "utility", "collection", "helpers"],
"homepage": "https://github.com/brandonwamboldt/utilphp",
"license": "MIT",
"authors": [
{
"name": "Brandon Wamboldt",
"email": "brandon.wamboldt@gmail.com"
}
],
"autoload": {
"psr-0": { "utilphp\\": "src/" }
},
"require-dev": {
"satooshi/php-coveralls": "dev-master"
},
"require": {
"php": ">=5.3.3"
}
}
+168
View File
@@ -0,0 +1,168 @@
body {
background: #f4f4f4 url('../images/background.png');
color: #333;
font: 18px/30px "Droid Serif", "Helvetica Neue", Helvetica, Arial;
}
a {
text-decoration: none;
color: #f00;
padding: 2px;
}
a:hover {
background: #277585;
color: #fff;
border-radius: 3px;
}
h1, h2, h3, h4, h5, h6 {
padding-top: 20px;
}
h2 {
font-size: 40px;
font-weight: normal;
margin: 0 0 15px;
}
p {
margin: 20px 0;
min-width: 550px;
max-width: 900px;
}
table, tr, td {
margin: 0; padding: 0;
}
td {
padding: 2px 12px 2px 0;
}
ul {
list-style-type: circle;
padding: 0 0 0 20px;
}
li {
width: 500px;
margin-bottom: 10px;
}
code, pre, tt {
font-family: Monaco, Consolas, "Lucida Console", monospace;
font-size: 12px;
line-height: 18px;
font-style: normal;
}
tt {
padding: 0px 3px;
background: #fff;
border: 1px solid #ddd;
zoom: 1;
}
code {
margin-left: 20px;
}
pre {
font-size: 12px;
padding: 12px;
background: #fff;
margin: 0px 0 30px;
border-radius: 0 0 2px 2px;
box-shadow: inset 0 0 0 1px rgba(0,0,0,.15);
}
span.header {
font-size: 24px;
line-height: 30px;
border-left: 10px solid #ddd;
padding-left: 10px;
}
.desc-text code {
margin-left: 0;
font-size: 18px;
color: #0E04C8;
}
#sidebar {
background: #fff;
position: fixed;
top: 0; left: 0; bottom: 0;
width: 220px;
overflow-y: auto;
overflow-x: hidden;
padding: 5px 0 30px 10px;
border-right: 1px solid #bbb;
box-shadow: 0 0 20px #ccc;
-webkit-box-shadow: 0 0 20px #ccc;
-moz-box-shadow: 0 0 20px #ccc;
-webkit-overflow-scrolling: touch;
}
.toc_title, .toc_title:visited {
display: block;
color: #000;
margin-top: 15px;
}
.toc_title:hover {
background: none;
color: #f00;
}
.toc_title .version {
font-size: 12px;
font-weight: normal;
}
.toc_section {
font-size: 14px;
line-height: 24px;
margin: 5px 0 0 0;
padding-left: 10px;
list-style-type: none;
}
.toc_section li {
cursor: pointer;
margin: 0 0 3px 0;
}
.toc_section li a {
text-decoration: none;
color: black;
}
.toc_section li a:hover {
background: none;
color: #f00;
}
.container {
min-width: 550px;
max-width: 1000px;
margin: 40px 0 50px 260px;
}
#documentation section > article > p > code {
color: #999;
}
#documentation section > article > p > code > .util_class {
color: #bbb;
}
#documentation section > article > p > code > .func_name {
color: #0E04C8;
}
#documentation section > article > p > code > .param {
color: #DA72F3;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 803 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

+1234
View File
@@ -0,0 +1,1234 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
<meta name="viewport" content="width=device-width" />
<link rel="canonical" href="http://includephp.brandonwamboldt.ca/" />
<link rel="shortcut icon" href="favicon.png" type="image/png" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic" />
<link rel="stylesheet" href="css/docs.css" />
<title>util.php - The PHP programmers best friend - UtilityPHP</title>
</head>
<body>
<div id="sidebar" class="interface">
<a class="toc_title" href="#">util.php <span class="version">(1.1.0)</span></a>
<a class="toc_title" href="#debug_functions">Debugging</a>
<ul class="toc_section">
<li>- <a href="#var_dump">var_dump</a></li>
</ul>
<a class="toc_title" href="#arrays">Arrays &amp; Objects</a>
<ul class="toc_section">
<li>- <a href="#array_first">array_first</a></li>
<li>- <a href="#array_first_key">array_first_key</a></li>
<li>- <a href="#array_flatten">array_flatten</a></li>
<li>- <a href="#array_get">array_get</a></li>
<li>- <a href="#array_last">array_last</a></li>
<li>- <a href="#array_last_key">array_last_key</a></li>
<li>- <a href="#array_map_deep">array_map_deep</a></li>
<li>- <a href="#array_pluck">array_pluck</a></li>
<li>- <a href="#array_search_deep">array_search_deep</a></li>
<li>- <a href="#array_clean">array_clean</a></li>
</ul>
<a class="toc_title" href="#urls">URLs</a>
<ul class="toc_section">
<li>- <a href="#add_query_arg">add_query_arg</a></li>
<li>- <a href="#get_current_url">get_current_url</a></li>
<li>- <a href="#http_build_url">http_build_url</a></li>
<li>- <a href="#is_https">is_https</a></li>
<li>- <a href="#remove_query_arg">remove_query_arg</a></li>
<li>- <a href="#slugify">slugify</a></li>
</ul>
<a class="toc_title" href="#strings">Strings</a>
<ul class="toc_section">
<li>- <a href="#htmlentities">htmlentities</a></li>
<li>- <a href="#htmlspecialchars">htmlspecialchars</a></li>
<li>- <a href="#linkify">linkify</a></li>
<li>- <a href="#match_string">match_string</a></li>
<li>- <a href="#random_string">random_string</a></li>
<li>- <a href="#number_to_word">number_to_word</a></li>
<li>- <a href="#ordinal">ordinal</a></li>
<li>- <a href="#remove_accents">remove_accents</a></li>
<li>- <a href="#secure_random_string">secure_random_string</a></li>
<li>- <a href="#seems_utf8">seems_utf8</a></li>
<li>- <a href="#safe_truncate">safe_truncate</a></li>
<li>- <a href="#size_format">size_format</a></li>
<li>- <a href="#str_to_bool">str_to_bool</a></li>
<li>- <a href="#zero_pad">zero_pad</a></li>
<li>- <a href="#strip_space">strip_space</a></li>
<li>- <a href="#sanitize_string">sanitize_string</a></li>
</ul>
<a class="toc_title" href="#files">Files</a>
<ul class="toc_section">
<li>- <a href="#full_permissions">full_permissions</a></li>
<li>- <a href="#rmdir">rmdir</a></li>
</ul>
<a class="toc_title" href="#serialization">Serialization</a>
<ul class="toc_section">
<li>- <a href="#is_serialized">is_serialized</a></li>
<li>- <a href="#maybe_serialize">maybe_serialize</a></li>
<li>- <a href="#maybe_unserialize">maybe_unserialize</a></li>
<li>- <a href="#fix_broken_serialization">fix_broken_serialization</a></li>
</ul>
<a class="toc_title" href="#other">Other</a>
<ul class="toc_section">
<li>- <a href="#force_download">force_download</a></li>
<li>- <a href="#get_client_ip">get_client_ip</a></li>
<li>- <a href="#get_gravatar">get_gravatar</a></li>
<li>- <a href="#human_time_diff">human_time_diff</a></li>
<li>- <a href="#nocache_headers">nocache_headers</a></li>
<li>- <a href="#utf8_headers">utf8_headers</a></li>
<li>- <a href="#validate_email">validate_email</a></li>
</ul>
<a class="toc_title" href="#constants">Constants</a>
<ul class="toc_section">
<li>- <a href="#SECONDS_IN_A_MINUTE">SECONDS_IN_A_MINUTE</a></li>
<li>- <a href="#SECONDS_IN_AN_HOUR">SECONDS_IN_AN_HOUR</a></li>
<li>- <a href="#SECONDS_IN_A_DAY">SECONDS_IN_A_DAY</a></li>
<li>- <a href="#SECONDS_IN_A_WEEK">SECONDS_IN_A_WEEK</a></li>
<li>- <a href="#SECONDS_IN_A_MONTH">SECONDS_IN_A_MONTH</a></li>
<li>- <a href="#SECONDS_IN_A_YEAR">SECONDS_IN_A_YEAR</a></li>
</ul>
<a class="toc_title" href="#changelog">Change Log</a>
</div>
<div class="container">
<p id="introduction">
<img id="logo" src="images/utility_logo.png" alt="Util.php" />
</p>
<p>
<a href="http://github.com/brandonwamboldt/utilphp/">util.php</a> is a collection of useful functions and snippets
that you need or could use every day. It's implemented as a class with static methods, to avoid conflicts with your
existing code-base. Just drop it in and start using it immediately.
</p>
<p>
Included are 60+ functions that provide you with the ability to do common tasks much easier and more efficiently,
without having to find that one comment on php.net where you know its been done already. Access superglobals
without checking to see if certain indexes are set first and pass default values, use a nicely formatted var dump,
validate emails, generate random strings, flatten an array, pull a single column out of a multidimensional array
and much more.
</p>
<p>
Although it's implemented as one giant class, util.php has extensive documentation and a full suite of unit tests
to avoid breaking backwards-compatibility unintentionally.
</p>
<p>
The project is <a href="http://github.com/brandonwamboldt/utilphp/">hosted on GitHub</a>.
You can report bugs and discuss features on the
<a href="https://github.com/brandonwamboldt/utilphp/issues">issues page</a>,
or send tweets to <a href="http://twitter.com/brandonwamboldt">@brandonwamboldt</a>.
</p>
<h2>Downloads <i style="padding-left: 12px; font-size:12px;">(Right-click, and use "Save As")</i></h2>
<p>
<a href="https://github.com/brandonwamboldt/utilphp/archive/1.1.0.zip">Stable Version (1.1.0)</a><br>
<a href="https://github.com/brandonwamboldt/utilphp/zipball/master">Unstable Version (master)</a>
</p>
<h2>Installation</h2>
<span class="header">Server Requirements</span><br>
<ul>
<li>PHP 5.3.3+</li>
</ul>
<span class="header">Standalone File</span><br>
<p class="desc-text">
Simply drop <code>util.php</code> in any project and call <code>include 'util.php';</code> in your project.
You can then access the <code>Util</code> class.
</p>
<span class="header">Composer</span><br>
<p class="desc-text">
Add the following dependency to your composer.json:
<pre>"brandonwamboldt/utilphp": "1.1.*"</pre>
When used with composer, the class is namespaced (<code>\utilphp\util</code>) instead of
just <code>util</code>.
</p>
<div id="documentation">
<h2 id="debug_functions">Debugging Functions</h2>
<section>
<article id="var_dump">
<p>
<span class="header">var_dump</span>
<code>
<span class="util_class">util::</span><span class="func_name">var_dump</span>(mixed <span class="param">$var</span>[, bool <span class="param">$return</span> = FALSE])
</code>
</p>
<p>
Nicely prints out the contents of a passed variable. Booleans are properly displayed as 'true' or 'false',
null values are shown as 'NULL', variable types are displayed, and arrays and objects are displayed as a
collapsible tree powered by JavaScript.
</p>
<p><strong>Usage:</strong></p>
<pre class="usage-example">util::var_dump($var);</pre>
<img src="images/awesome_var_dump.jpg" style="border: 1px solid #ccc;" />
</article>
</section>
<h2 id="arrays">Array/Object Functions</h2>
<section>
<article id="array_first">
<p>
<span class="header">array_first</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_first</span>(array <span class="param">$array</span>)
</code>
</p>
<p>
Retrieve the first value from an array. Can be run on function callbacks, and it will not modify the pointer
of the source array unlike most other methods of doing this.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_first( ['a', 'b', 'c'] );<br />=&gt; Returns 'a'</pre>
</article>
<article id="array_first_key">
<p>
<span class="header">array_first_key</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_first_key</span>(array <span class="param">$array</span>)
</code>
</p>
<p>
Retrieve the first key from an array. Can be run on function callbacks, and it will not modify the pointer of
the source array unlike most other methods of doing this.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_first_key( $users );<br />=&gt; Returns 'brandon'</pre>
</article>
<article id="array_flatten">
<p>
<span class="header">array_flatten</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_flatten</span>(array <span class="param">$array</span>[, bool <span class="param">$preserve_keys</span> = TRUE])
</code>
</p>
<p>Flattens a multi-dimensional array into a one dimensional array</p>
<p><strong>Usage:</strong></p>
<pre>util::array_flatten( [ 'a', 'b', [ 'c', 'd', 'e', [ 'f', 'g', [ [ [ [ 'h', 'i', 'j' ] ] ] ] ] ] ] );
=&gt; Returns [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ]</pre>
</article>
<article id="array_get">
<p>
<span class="header">array_get</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_get</span>(<span class="param">$var</span>[, mixed <span class="param">$default</span> = NULL])
</code>
</p>
<p>Retrieve a value from an array, or return a given default if the index isn't set</p>
<p><strong>Usage:</strong></p>
<pre>util::array_get($_POST['action'], 'index');
=&gt; If $_POST['action'] is set, returns its value, otherwise returns 'index'
util::array_get($_POST['action']['do'], 'index');
=&gt; Returns the value of $_POST['action']['do'] or 'index'</pre>
</article>
<article id="array_last">
<p>
<span class="header">array_last</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_last</span>(array <span class="param">$array</span>)
</code>
</p>
<p>
Retrieve the last value from an array. Can be run on function callbacks, and it will not modify the pointer
of the source array unlike most other methods of doing this.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_last( [ 'a', 'b', 'c'] );
=&gt; Returns 'c'</pre>
</article>
<article id="array_last_key">
<p>
<span class="header">array_last_key</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_last_key</span>(array <span class="param">$array</span>)
</code>
</p>
<p>
Retrieve the last key from an array. Can be run on function callbacks, and it will not modify the pointer of
the source array unlike most other methods of doing this.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_last_key( $users );
=&gt; Returns 'zane'</pre>
</article>
<article id="array_map_deep">
<p>
<span class="header">array_map_deep</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_map_deep</span>(array <span class="param">$array</span>, callable <span class="param">$callback</span>[, bool <span class="param">$on_nonscalar</span> = FALSE])
</code>
</p>
<p>
Returns an array containing all the elements of $array after applying the callback function to each one recursively.
Particularly useful for avoiding errors when calling functions that only accept scalar values on an array that could
contain nested arrays, such as $_GET or $_POST.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_map_deep($_POST, 'htmlentities');
=&gt; Recursively escapes each scalar value in $_POST
util::array_map_deep($_POST, 'htmlentities', TRUE);
=&gt; Recursively escapes each value in $_POST regardless of its type</pre>
</article>
<article id="array_pluck">
<p>
<span class="header">array_pluck</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_pluck</span>(array <span class="param">$array</span>, string <span class="param">$field</span>[, bool <span class="param">$preserve_keys</span>, bool <span class="param">$remove_nomatches</span>])
</code>
</p>
<p>
Replaces each value in an array with the specified field of the array or object that used to be the value. Very
useful when you have an array of objects or arrays from a database, and you only want one specific field. For
example, you want an array of emails from an array of users.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_pluck([['val' => 1], ['val' => 2], ['val' => 3]], 'val');
=&gt; Returns [1, 2, 3]
util::array_pluck($users, 'email');
=&gt; Returns an array of email addresses for each user</pre>
</article>
<article id="array_search_deep">
<p>
<span class="header">array_search_deep</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_search_deep</span>(array <span class="param">$array</span>, mixed <span class="param">$search</span>[, string <span class="param">$field</span> = FALSE])
</code>
</p>
<p>
Allows you to search for a value in an array of arrays or an array of objects, and return the key of the value
that matches the search criteria. If $field is unspecified, the entire array/object is searched.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_search_deep($_POST, 'delete_post');
=&gt; Might return 'do' if $_POST['do']['action'] = 'delete_post'
util::array_search_deep($users, 'rogue_coder', 'username');
=&gt; Might return 5 if $users[5]->username = 'rogue_coder'</pre>
</article>
<article id="array_clean">
<p>
<span class="header">array_clean</span>
<code>
<span class="util_class">util::</span><span class="func_name">array_clean</span>(array <span class="param">$array</span>)
</code>
</p>
<p>
Remove all null/empty/false values from the given array.
</p>
<p><strong>Usage:</strong></p>
<pre>util::array_clean( array( 'a', 'b', '', null, false, 0) );<br />=&gt; Returns array('a', 'b');</pre>
</article>
</section>
<h2 id="urls">URL Functions</h2>
<section>
<article id="add_query_arg">
<p>
<span class="header">add_query_arg</span>
<code>
<span class="util_class">util::</span><span class="func_name">add_query_arg</span>()
</code>
</p>
<p>Adds one ore more query args to the query string of the current URL or a given URL</p>
<p><strong>Usage:</strong></p>
<pre>util::add_query_arg( 'user', '5', '/admin/users?action=edit' );
=&gt; Returns '/admin/users?action=edit&amp;user=5'
util::add_query_arg( [ 'user' => 5, 'action' => 'edit' ], '/admin/users' );
=&gt; Returns '/admin/users?user=5&amp;action=edit'</pre>
</article>
<article id="get_current_url">
<p>
<span class="header">get_current_url</span>
<code>
<span class="util_class">util::</span><span class="func_name">get_current_url</span>()
</code>
</p>
<p>Returns the current URL with hostname</p>
<p><strong>Usage:</strong></p>
<pre>util::get_current_url();
=&gt; Returns 'http://brandonwamboldt.ca/utilphp/'</pre>
</article>
<article id="is_https">
<p>
<span class="header">is_https</span>
<code>
<span class="util_class">util::</span><span class="func_name">is_https</span>()
</code>
</p>
<p>Returns true if the current page is being loaded over https, false if it isn't</p>
<p><strong>Usage:</strong></p>
<pre>util::is_https();
=&gt; Returns false</pre>
</article>
<article id="http_build_url">
<p>
<span class="header">http_build_url</span>
<code>
<span class="util_class">util::</span><span class="func_name">http_build_url</span>([mixed $url[, mixed $parts[, int $flags = HTTP_URL_REPLACE[, array &amo;$new_url]]]])
</code>
</p>
<p>
Pure PHP implementation/polyfill for <a href="http://php.net/http_build_url">http_build_url</a>
which requires pecl_http to be installed.
</p>
<p><strong>Usage:</strong></p>
<pre>echo util::http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
array(
"scheme" => "ftp",
"host" => "ftp.example.com",
"path" => "files/current/",
"query" => "a=c"
),
HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
);</pre>
<p>The above example will output:</p>
<pre>ftp://ftp.example.com/pub/files/current/?a=c</pre>
</article>
<article id="is_https">
<p>
<span class="header">is_https</span>
<code>
<span class="util_class">util::</span><span class="func_name">is_https</span>()
</code>
</p>
<p>Returns true if the current page is being loaded over https, false if it isn't</p>
<p><strong>Usage:</strong></p>
<pre>util::is_https();
=&gt; Returns false</pre>
</article>
<article id="remove_query_arg">
<p>
<span class="header">remove_query_arg</span>
<code>
<span class="util_class">util::</span><span class="func_name">remove_query_arg</span>( array|string <span class="param">$query_args</span>[, string <span class="param">$url</span>])
</code>
</p>
<p>Removes one ore more query args from the query string of the current URL or a given URL</p>
<p><strong>Usage:</strong></p>
<pre>util::remove_query_arg( 'action', '/admin/users?action=edit&amp;user=5' );
=&gt; Returns '/admin/users?user=5'
util::remove_query_arg( [ 'user', 'action'], '/admin/users?action=edit&amp;user=5' );
=&gt; Returns '/admin/users'</pre>
</article>
<article id="slugify">
<p>
<span class="header">slugify</span>
<code>
<span class="util_class">util::</span><span class="func_name">slugify</span>(string <span class="param">$string</span>[, string <span class="param">$separator</span> = "-", bool <span class="param">$css_mode</span> = FALSE])
</code>
</p>
<p>
Generate a string safe for use in URLs from any given string. Converts any accent characters
to their equivalent normal characters and converts any other non-alphanumeric characters to
dashes, then converts any sequence of two or more dashes to a single dash. This function
generates slugs safe for use as URLs, and if you pass TRUE as the second parameter, it will
create strings safe for use as CSS classes or IDs.
</p>
<p><strong>Usage:</strong></p>
<pre>util::slugify('This is a random --string with an Ãccent');
=&gt; Returns 'this-is-a-random-string-with-an-accent'
util::slugify('Another String', '.');
=&gt; Returns 'another.string'</pre>
</article>
</section>
<h2 id="strings">String Functions</h2>
<section>
<article id="htmlentities">
<p>
<span class="header">htmlentities</span>
<code>
<span class="util_class">util::</span><span class="func_name">htmlentities</span>(string <span class="param">$string</span>[, bool <span class="param">$preserve_encoded_entities</span> = FALSE])
</code>
</p>
<p>
Executes htmlentities with ENT_QUOTES set by default. However, if you pass TRUE as
the second parameter, it will not re-encode entities that are already encoded.
</p>
<p><strong>Usage:</strong></p>
<pre>util::htmlentities('this string &lt; this string', TRUE);
=&gt; Returns 'this string &lt; this string'</pre>
</article>
<article id="htmlspecialchars">
<p>
<span class="header">htmlspecialchars</span>
<code>
<span class="util_class">util::</span><span class="func_name">htmlspecialchars</span>(string <span class="param">$string</span>[, bool <span class="param">$preserve_encoded_entities</span> = FALSE])
</code>
</p>
<p>
Executes htmlspecialchars with ENT_QUOTES set by default. However, if you pass TRUE as
the second parameter, it will not re-encode entities that are already encoded.
</p>
<p><strong>Usage:</strong></p>
<pre>util::htmlspecialchars('this string &lt; this string', TRUE);
=&gt; Returns 'this string &lt; this string'</pre>
</article>
<article id="linkify">
<p>
<span class="header">linkify</span>
<code>
<span class="util_class">util::</span><span class="func_name">linkify</span>(string <span class="param">$text</span>)
</code>
</p>
<p>Find's any URLs in the specified text and wraps them with HTML anchor tags</p>
<p><strong>Usage:</strong></p>
<pre>util::linkify('this string has a link to www.google.com');
=&gt; Returns 'this string has a link to &lt;a href="http://wwww.google.com/"&gt;www.google.com&lt;/a&gt;'</pre>
</article>
<article id="match_string">
<p>
<span class="header">match_string</span>
<code>
<span class="util_class">util::</span><span class="func_name">match_string</span>(string <span class="param">$pattern</span>, string <span class="param">$string</span>[, bool <span class="param">$caseSensitive</span> = true])
</code>
</p>
<p>
Check if a string matches a given pattern. You can use '*' as a wildcard character.
</p>
<p><strong>Usage:</strong></p>
<pre>util::match_string("test/*", "test/my/test");
=&gt; Returns true
util::match_string("test/", "test/my/test");
=&gt; Returns false</pre>
</article>
<article id="random_string">
<p>
<span class="header">random_string</span>
<code>
<span class="util_class">util::</span><span class="func_name">random_string</span>(int <span class="param">$length</span>[, bool <span class="param">$human_friendly</span> = TRUE, bool <span class="param">$include_symbols</span> = FALSE, bool <span class="param">$no_duplicate_chars</span> = FALSE])
</code>
</p>
<p>
Generates a random string of the specified length. Human friendly mode
will exclude characters that can be confused with other characters, such
as 0 (zero) and O (capital o), 1 (one) and l (lowercase L).
</p>
<p><strong>Usage:</strong></p>
<pre>util::random_string(8);
=&gt; Returns 'a6BiF4UW'</pre>
</article>
<article id="number_to_word">
<p>
<span class="header">number_to_word</span>
<code>
<span class="util_class">util::</span><span class="func_name">number_to_word</span>(int|float <span class="param">$number</span>)
</code>
</p>
<p>Converts a number into its text equivalent. For example, 56 becomes fifty-six.</p>
<pre>util::number_to_word(512.5);
=&gt; Returns 'five hundred and twelve point five'</pre>
</article>
<article id="ordinal">
<p>
<span class="header">ordinal</span>
<code>
<span class="util_class">util::</span><span class="func_name">ordinal</span>(int <span class="param">$number</span>)
</code>
</p>
<p>Returns the ordinal version of a number (appends th, st, nd, rd)</p>
<p><strong>Usage:</strong></p>
<pre>util::ordinal(22);
=&gt; Returns '22nd'</pre>
</article>
<article id="remove_accents">
<p>
<span class="header">remove_accents</span>
<code>
<span class="util_class">util::</span><span class="func_name">remove_accents</span>(string <span class="param">$string</span>)
</code>
</p>
<p>Converts all accent characters to their ASCII equivalents</p>
<p><strong>Usage:</strong></p>
<pre>util::remove_accents('&#192;ccent');
=&gt; Returns 'Accent'</pre>
</article>
<article id="secure_random_string">
<p>
<span class="header">secure_random_string</span>
<code>
<span class="util_class">util::</span><span class="func_name">secure_random_string</span>(int <span class="param">$length</span>)
</code>
</p>
<p>Generate a random string of characters. Will attempt to use a secure source (openssl).</p>
<p><strong>Usage:</strong></p>
<pre>util::secure_random_string(16);
=&gt; Returns '5bB1RJH0cQhNjviT'</pre>
</article>
<article id="seems_utf8">
<p>
<span class="header">seems_utf8</span>
<code>
<span class="util_class">util::</span><span class="func_name">seems_utf8</span>(string <span class="param">$string</span>)
</code>
</p>
<p>Checks to see if a given string is UTF-8 encoded/safe</p>
<p><strong>Usage:</strong></p>
<pre>util::seems_utf8('This is some random string user input');
=&gt; Returns true</pre>
</article>
<article id="safe_truncate">
<p>
<span class="header">safe_truncate</span>
<code>
<span class="util_class">util::</span><span class="func_name">safe_truncate</span>(string <span class="param">$string</span>, int <span class="param">$length</span>[, string <span class="param">$append</span> = '...'])
</code>
</p>
<p>Truncate a string to a specified length without cutting a word off</p>
<p><strong>Usage:</strong></p>
<pre>util::safe_truncate('The quick brown fox jumps over the lazy dog', 24);
=&gt; Returns 'The quick brown fox...'</pre>
</article>
<article id="size_format">
<p>
<span class="header">size_format</span>
<code>
<span class="util_class">util::</span><span class="func_name">size_format</span>(int <span class="param">$bytes</span>[, int <span class="param">$decimals</span> = 0])
</code>
</p>
<p>Formats an integer as a human friendly size string, such as 4 KiB.</p>
<p><strong>Usage:</strong></p>
<pre>util::size_format( 25151251, 2 );
=&gt; Returns '23.99 MiB'</pre>
</article>
<article id="str_to_bool">
<p>
<span class="header">str_to_bool</span>
<code>
<span class="util_class">util::</span><span class="func_name">str_to_bool</span>(string <span class="param">$string</span>)
</code>
</p>
<p>Converts a string to boolean, looking for yes/no words like 'yes', 'no', 'true', 'false', 'y', 'n', etc</p>
<p><strong>Usage:</strong></p>
<pre>util::str_to_bool('yes');
=&gt; Returns true</pre>
</article>
<article id="zero_pad">
<p>
<span class="header">zero_pad</span>
<code>
<span class="util_class">util::</span><span class="func_name">zero_pad</span>(int <span class="param">$number</span>, int <span class="param">$length</span>)
</code>
</p>
<p>Pads a given number with zeroes on the left</p>
<p><strong>Usage:</strong></p>
<pre>util::zero_pad(341, 8);
=&gt; Returns '00000341'</pre>
</article>
<article id="strip_space">
<p>
<span class="header">strip_space</span>
<code>
<span class="util_class">util::</span><span class="func_name">strip_space</span>(string <span class="param">$string</span>)
</code>
</p>
<p>Strip all withspace from the given string</p>
<p><strong>Usage:</strong></p>
<pre>util::strip_space(' The quick brown fox jumps over the lazy dog ');
=&gt; Returns 'Thequickbrownfoxjumpsoverthelazydog'</pre>
</article>
<article id="sanitize_string">
<p>
<span class="header">sanitize_string</span>
<code>
<span class="util_class">util::</span><span class="func_name">sanitize_string</span>(string <span class="param">$string</span>)
</code>
</p>
<p>
Sanitize a string by performing the following operation :
<ul>
<li>Remove accents</li>
<li>Lower the string</li>
<li>Remove punctuation characters</li>
<li>Strip whitespaces</li>
</ul>
</p>
<p><strong>Usage:</strong></p>
<pre>util::sanitize_string(' Benoit! à New-York? jai perçu 1 % : Quas-tu "gagné" chez M. V. Noël? Dix francs.');
=&gt; Returns 'benoitanewyorkjaipercu1quastugagnechezmvnoeldixfrancs'</pre>
</article>
</section>
<h2 id="files">Files</h2>
<section>
<article id="full_permissions">
<p>
<span class="header">full_permissions</span>
<code>
<span class="util_class">util::</span><span class="func_name">full_permissions</span>(string <span class="param">$file</span>)
</code>
</p>
<p>Returns the file permissions as a nice string, like -rw-r--r--</p>
<p><strong>Usage:</strong></p>
<pre>util::full_permissions('/etc/passwd');
=&gt; Returns '-rw-r--r--'</pre>
</article>
<article id="rmdir">
<p>
<span class="header">rmdir</span>
<code>
<span class="util_class">util::</span><span class="func_name">rmdir</span>(string <span class="param">$dir</span>[, bool <span class="param">$traverseSymlinks</span> = false])
</code>
</p>
<p>Recursively deletes a directories (including all contents).</p>
<p><strong>Usage:</strong></p>
<pre>util::rmdir('/tmp/working/dir');
=&gt; Returns true</pre>
</article>
</section>
<h2 id="serialization">Serialization</h2>
<section>
<article id="is_serialized">
<p>
<span class="header">is_serialized</span>
<code>
<span class="util_class">util::</span><span class="func_name">is_serialized</span>(mixed <span class="param">$data</span>)
</code>
</p>
<p>Checks to see if a given variable is a seralized data structure</p>
<p><strong>Usage:</strong></p>
<pre>util::is_serialized( 'a:0:{}' );
=&gt; Returns true</pre>
</article>
<article id="maybe_serialize">
<p>
<span class="header">maybe_serialize</span>
<code>
<span class="util_class">util::</span><span class="func_name">maybe_serialize</span>(mixed <span class="param">$data</span>)
</code>
</p>
<p>Serialize data, if needed to store in plaintext (Arrays or objects)</p>
<p><strong>Usage:</strong></p>
<pre>util::maybe_serialize( 5 );
=&gt; Returns 5
util::maybe_serialize( array() );
=&gt; Returns 'a:0:{}'</pre>
</article>
<article id="maybe_unserialize">
<p>
<span class="header">maybe_unserialize</span>
<code>
<span class="util_class">util::</span><span class="func_name">maybe_unserialize</span>(mixed <span class="param">$data</span>)
</code>
</p>
<p>Unserialize data, if it's a serialized string</p>
<p><strong>Usage:</strong></p>
<pre>util::maybe_unserialize(5);
=&gt; Returns 5
util::maybe_unserialize("a:0:{}");
=&gt; Returns array()</pre>
</article>
<article id="fix_broken_serialization">
<p>
<span class="header">fix_broken_serialization</span>
<code>
<span class="util_class">util::</span><span class="func_name">fix_broken_serialization</span>(mixed <span class="param">$data</span>)
</code>
</p>
<p>
Attempt to fix a broken serialization string (e.g. where string offsets are incorrect). Can fix
errors that frequently occur with mismatched character sets or higher-than-ASCII characters.
</p>
<p><strong>Usage:</strong></p>
<pre>util::fix_broken_serialization('a:1:{s:4:"test";s:4:"abc";}');
=&gt; Returns 'a:1:{s:4:"test";s:3:"abc";}'</pre>
</article>
</section>
<h2 id="other">Other</h2>
<section>
<article id="force_download">
<p>
<span class="header">force_download</span>
<code>
<span class="util_class">util::</span><span class="func_name">force_download</span>(string <span class="param">$filename</span>, string <span class="param">$content</span> = FALSE)
</code>
</p>
<p>
Transmit headers that force a browser to display the download file dialog. Cross
browser compatible. Only fires if headers have not already been sent.
</p>
<p><strong>Usage:</strong></p>
<pre>util::force_download( 'export.csv', file_get_contents( 'securefile.csv' ) );
=&gt; The user will be prompted to download the file</pre>
</article>
<article id="get_client_ip">
<p>
<span class="header">get_client_ip</span>
<code>
<span class="util_class">util::</span><span class="func_name">get_client_ip</span>(bool <span class="param">$trust_proxy_headers</span> = FALSE)
</code>
</p>
<p>
Returns the IP address of the client. Only enable $trust_proxy_headers if your server is behind a proxy
that sets the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR headers.
</p>
<p><strong>Usage:</strong></p>
<pre>util::get_client_ip();
=&gt; Returns '12.123.12.100'</pre>
</article>
<article id="get_gravatar">
<p>
<span class="header">get_gravatar</span>
<code>
<span class="util_class">util::</span><span class="func_name">get_gravatar</span>(string <span class="param">$email</span>, int <span class="param">$size</span> = 32)
</code>
</p>
<p>Return the URL to a user's gravatar</p>
<p><strong>Usage:</strong></p>
<pre>util::get_gravatar('brandon.wamboldt@gmail.com');
=&gt; Returns 'http://www.gravatar.com/avatar/46679faeb6780ecb1ea57527fdc66eb3?s=32'</pre>
</article>
<article id="human_time_diff">
<p>
<span class="header">human_time_diff</span>
<code>
<span class="util_class">util::</span><span class="func_name">human_time_diff</span>(int <span class="param">$from</span>, int <span class="param">$to</span> = '', int <span class="param">$as_text</span> = FALSE, string <span class="param">$suffix</span> = ' ago')
</code>
</p>
<p>Converts a unix timestamp to a relative time string, such as "3 days ago" or "2 weeks ago"</p>
<p><strong>Usage:</strong></p>
<pre>util::human_time_diff(time() - 7400);
=&gt; Returns '2 hours ago'
util::human_time_diff(time() - 7400, '', TRUE);
=&gt; Returns 'two hours ago'</pre>
</article>
<article id="nocache_headers">
<p>
<span class="header">nocache_headers</span>
<code>
<span class="util_class">util::</span><span class="func_name">nocache_headers</span>(mixed <span class="param">$data</span>)
</code>
</p>
<p>Sets the headers to prevent caching for the different browsers</p>
<p>
Different browsers support different nocache headers, so several headers must be sent
so that all of them get the point that no caching should occur
</p>
<p><strong>Usage:</strong></p>
<pre>util::nocache_headers();</pre>
</article>
<article id="utf8_headers">
<p>
<span class="header">utf8_headers</span>
<code>
<span class="util_class">util::</span><span class="func_name">utf8_headers</span>(mixed <span class="param">$content_type</span> = 'text/html')
</code>
</p>
<p>Transmit UTF-8 content headers if the headers haven't already been sent</p>
<p><strong>Usage:</strong></p>
<pre>util::utf8_headers();</pre>
</article>
<article id="validate_email">
<p>
<span class="header">validate_email</span>
<code>
<span class="util_class">util::</span><span class="func_name">validate_email</span>(string <span class="param">$possible_email</span>)
</code>
</p>
<p>Validate an email address</p>
<p><strong>Usage:</strong></p>
<pre>util::validate_email( 'brandon.wamboldt@gmail.com' );
=&gt; Returns true
util::validate_email( 'not an email' );
=&gt; Returns false</pre>
</article>
</section>
<h2 id="constants">Constants</h2>
<section>
<article id="SECONDS_IN_A_MINUTE">
<p>
<span class="header">SECONDS_IN_A_MINUTE</span>
<code>
<span class="util_class">util::</span><span class="func_name">SECONDS_IN_A_MINUTE</span>
</code>
</p>
<p>The number of seconds in a minute, useful for making code more verbose</p>
</article>
<article id="SECONDS_IN_AN_HOUR">
<p>
<span class="header">SECONDS_IN_AN_HOUR</span>
<code>
<span class="util_class">util::</span><span class="func_name">SECONDS_IN_AN_HOUR</span>
</code>
</p>
<p>The number of seconds in an hour, useful for making code more verbose</p>
</article>
<article id="SECONDS_IN_A_DAY">
<p>
<span class="header">SECONDS_IN_A_DAY</span>
<code>
<span class="util_class">util::</span><span class="func_name">SECONDS_IN_A_DAY</span>
</code>
</p>
<p>The number of seconds in a day, useful for making code more verbose</p>
</article>
<article id="SECONDS_IN_A_WEEK">
<p>
<span class="header">SECONDS_IN_A_WEEK</span>
<code>
<span class="util_class">util::</span><span class="func_name">SECONDS_IN_A_WEEK</span>
</code>
</p>
<p>The number of seconds in a week (7 days), useful for making code more verbose</p>
</article>
<article id="SECONDS_IN_A_MONTH">
<p>
<span class="header">SECONDS_IN_A_MONTH</span>
<code>
<span class="util_class">util::</span><span class="func_name">SECONDS_IN_A_MONTH</span>
</code>
</p>
<p>The number of seconds in a month (30 days), useful for making code more verbose</p>
</article>
<article id="SECONDS_IN_A_YEAR">
<p>
<span class="header">SECONDS_IN_A_YEAR</span>
<code>
<span class="util_class">util::</span><span class="func_name">SECONDS_IN_A_YEAR</span>
</code>
</p>
<p>The number of seconds in a year (365 days), useful for making code more verbose</p>
</article>
</section>
<h2 id="changelog">Change Log</h2>
<!--
Find: `(.*?)`
Replace: <code>\1<\/code>
Find: \[(.*?)\]\((.*?)\)
Replace: <a href="\2">\1</a>
-->
<p class="desc-text">
<span class="header">1.1.0</span><br>
This release introduces a deprecation notice for <code>slugify()</code>, please update your code.<br><br>
- Added a cryptographically secure random string function <code>secure_random_string</code>. Thanks to @abhimanyusharma003 via <a href="https://github.com/brandonwamboldt/utilphp/pull/53">Pull Request #53</a><br>
- Added <code>limit_characters</code> and <code>limit_words</code> functions. Thanks to @abhimanyusharma003 via <a href="https://github.com/brandonwamboldt/utilphp/pull/55">Pull Request #55</a><br>
- Added <code>rmdir</code> method to recursively delete a directory. Thanks to @ARACOOOL via <a href="https://github.com/brandonwamboldt/utilphp/pull/56">Pull Request #56</a><br>
- Added <code>set_executable</code>, <code>set_readable</code>, <code>set_writable</code>, <code>directory_size</code>, <code>directory_contents</code> and <code>get_user_dir</code> functions. Thanks to @sergserg via <a href="https://github.com/brandonwamboldt/utilphp/pull/70">Pull Request #70</a><br>
- Changed parameter ordering for <code>slugify</code>, <code>$css_mode</code> is now the third argument. For backwards compatibility, the old order will still work but it will generate an <code>E_USER_DEPRECATED</code> warning. Thanks to @abhimanyusharma003 via <a href="https://github.com/brandonwamboldt/utilphp/pull/71">Pull Request #71</a><br>
- Added <code>match_string</code> method. Thanks to @abhimanyusharma003 via <a href="https://github.com/brandonwamboldt/utilphp/pull/72">Pull Request #72</a><br>
- Renamed internal methods (protected ones) for PSR-2 compliance<br>
- General performance improvements, code quality improvements, and increased unit test coverage (special thanks to @hopeseekr for getting us near 100% coverage)<br>
</p>
<p class="desc-text">
<span class="header">1.0.7</span><br>
- Added <code>fix_broken_serialization</code> to fix broken serialized strings (Thanks to @hopeseekr via <a href="https://github.com/brandonwamboldt/utilphp/pull/48">Pull Request #48</a>)<br>
- Fixed <code>get_current_url</code> appending port 80 or 443 when not needed (Thanks to @scottchiefbaker via <a href="https://github.com/brandonwamboldt/utilphp/pull/49">Pull Request #49</a>)<br>
- <code>var_dump</code> can now handle recursive data structures without crashing<br>
- <code>var_dump</code> code was minified and cleaned up<br>
- <code>array_flatten</code> was optimized (thanks to @hopeseekr via <a href="https://github.com/brandonwamboldt/utilphp/pull/47">Pull Request #47</a>)<br>
- <code>remove_accents</code> was completely rewritten and is now ~4x faster<br>
</p>
<p class="desc-text">
<span class="header">1.0.6</span><br>
- Added <code>start_with</code> function<br>
- Added <code>ends_with</code> function<br>
- Added <code>str_contains</code> function<br>
- Added <code>str_icontains</code> function<br>
- Added <code>get_file_ext</code> function<br>
- Fixing permissions on the files &amp; directories<br>
- Fixing a bug with the include path of util.php<br>
</p>
<p class="desc-text">
<span class="header">1.0.5</span><br>
- <a href="https://github.com/brandonwamboldt/utilphp/issues/29">Issue #29</a> Fixed error in <code>var_dump</code> if mbstring extension wasn't present<br>
- Adding Composer support<br>
- Updating license from GPL to MIT<br>
- Adding Changelog to project<br>
- Bumping minimum version to PHP 5.3.3<br>
</p>
<p class="desc-text">
<span class="header">1.0.4</span><br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/22">Issue #22</a> Removed all superglobal *_get functions, you can use the modified <code>array_get</code> now<br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/22">Issue #22</a> Modifed the behaviour of <code>array_get</code>, see documentation<br />
- <a href="https://github.com/brandonwamboldt/utilphp/pull/21">Pull Request #21</a> Added multibyte support to html* functions<br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/9">Issue #9</a> Removed the <code>str_to_utf8</code> function<br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/3">Issue #3</a> Removed the absint function<br />
- Removed declare() from util.php to avoid errors<br />
- Updated PHPUnit tests to use PHPUnit 3.6
</p>
<p class="desc-text">
<span class="header">1.0.3</span><br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/16">Issue #16</a> Improved performance of <code>slugify</code><br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/14">Issue #14</a> Modified the regex for <code>seems_utf8</code> to be more accurate<br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/13">Issue #13</a> Changed <code>validate_email</code> to be wrapper for <code>filter_var</code><br />
- Added 'ok' to the list of yes words for <code>str_to_bool</code><br />
- <code>str_to_bool</code> matches no followed by any number of 'o's
</p>
<p class="desc-text">
<span class="header">1.0.2</span><br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/12">Issue #12</a> <code>get_current_url</code> now includes the port and user/password if required<br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/11">Issue #11</a> <code>human_time_diff</code> now uses the DateTime functions<br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/10">Issue #10</a> <code>is_https</code> no longer checks the port as well
</p>
<p class="desc-text">
<span class="header">1.0.1</span><br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/7">Issue #7</a> Added the <code style="color:#DA72F3">$trust_proxy_headers</code> parameter to <code>get_client_ip</code><br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/6">Issue #6</a> Removed <code>is_isset</code> as the function did not work as intended<br />
- <a href="https://github.com/brandonwamboldt/utilphp/issues/6">Issue #6</a> Removed <code>is_empty</code> as it is redundant, use ! with function calls instead<br />
- Fixed a bug with <code>get_gravatar</code>
</p>
<p class="desc-text">
<span class="header">1.0.0</span><br />
Initial release of util.php.
</p>
</div>
</div>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Tests suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
File diff suppressed because one or more lines are too long
+39
View File
@@ -0,0 +1,39 @@
# UtilityPHP Unit Tests #
### Introduction
This is the testing documentation for util.php. The unit tests require PHPUnit,
and can be run in your web browser.
### Requirements
PHP Unit >= 3.5.6
#### Installation of PHPUnit
# Download the PHPUnit phar.
wget https://phar.phpunit.de/phpunit.phar
# You can just run it locally. (Preferred for Windows)
php phpunit.phar --version
# Or install it system-wide.
mv phpunit.phar phpunit
chmod +x phpunit
sudo mv phpunit /usr/local/bin
phpunit --version
## Test Suites:
util.php includes a phpunit config file, so just run `phpunit` from the working
directory to run the test suite.
```
phpunit
```
If you want code coverage reports, use the following:
```
phpunit --coverage-html ./report
```
+1183
View File
@@ -0,0 +1,1183 @@
<?php
date_default_timezone_set('UTC');
require_once dirname(__FILE__) . '/../util.php';
class VarDumpExperiment
{
public $public = 1;
protected $protected = 2;
private $private = 3;
public $data;
public function __construct()
{
$this->data = (object)array('a', 'b', 'c');
}
}
/**
* PHPUnit test case for the util.php library
*
* @author Brandon Wamboldt <brandon.wamboldt@gmail.com>
* @since 1.0.000
*/
class UtilityPHPTest extends PHPUnit_Framework_TestCase
{
/**
* Allows for the testing of private and protected methods.
*
* @param $name
* @return \ReflectionMethod
*/
protected static function getMethod($name)
{
$class = new \ReflectionClass('util');
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method;
}
public function test_array_get()
{
$_GET = array();
$_GET['abc'] = 'def';
$_GET['nested'] = array( 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' );
// Looks for $array['abc']
$this->assertEquals( 'def', util::array_get( $_GET['abc'] ) );
// Looks for $array['nested']['key2']
$this->assertEquals( 'val2', util::array_get( $_GET['nested']['key2'] ) );
// Looks for $array['doesnotexist']
$this->assertEquals( 'defaultval', util::array_get( $_GET['doesnotexist'], 'defaultval' ) );
}
public function test_slugify()
{
$this->assertEquals( 'a-simple-title', util::slugify( 'A simple title' ) );
$this->assertEquals( 'this-post-it-has-a-dash', util::slugify( 'This post -- it has a dash' ) );
$this->assertEquals( '123-1251251', util::slugify( '123----1251251' ) );
$this->assertEquals( 'one23-1251251', util::slugify( '123----1251251', '-', true ) );
$this->assertEquals( 'a-simple-title', util::slugify( 'A simple title', '-' ) );
$this->assertEquals( 'this-post-it-has-a-dash', util::slugify( 'This post -- it has a dash', '-' ) );
$this->assertEquals( '123-1251251', util::slugify( '123----1251251', '-' ) );
$this->assertEquals( 'one23-1251251', util::slugify( '123----1251251', '-', true ) );
$this->assertEquals( 'a_simple_title', util::slugify( 'A simple title', '_' ) );
$this->assertEquals( 'this_post_it_has_a_dash', util::slugify( 'This post -- it has a dash', '_' ) );
$this->assertEquals( '123_1251251', util::slugify( '123----1251251', '_' ) );
$this->assertEquals( 'one23_1251251', util::slugify( '123----1251251', '_', true ) );
// Blank seperator test
$this->assertEquals( 'asimpletitle', util::slugify( 'A simple title', '' ) );
$this->assertEquals( 'thispostithasadash', util::slugify( 'This post -- it has a dash', '' ) );
$this->assertEquals( '1231251251', util::slugify( '123----1251251', '' ) );
$this->assertEquals( 'one231251251', util::slugify( '123----1251251', '', true ) );
// Test old parameter ordering for backwards compatability
error_reporting(E_ALL ^ E_USER_DEPRECATED);
$this->assertEquals( 'one23-1251251', util::slugify( '123----1251251', true ) );
$this->assertEquals( '123-1251251', util::slugify( '123----1251251', false ) );
}
public function test_seems_utf8()
{
// Test a valid UTF-8 sequence: "ÜTF-8 Fµñ".
$validUTF8 = "\xC3\x9CTF-8 F\xC2\xB5\xC3\xB1";
$this->assertTrue( util::seems_utf8( $validUTF8 ) );
$this->assertTrue( util::seems_utf8( "\xEF\xBF\xBD this has \xEF\xBF\xBD\xEF\xBF\xBD some invalid utf8 \xEF\xBF\xBD" ) );
// Test invalid UTF-8 sequences
$invalidUTF8 = "\xc3 this has \xe6\x9d some invalid utf8 \xe6";
$this->assertFalse( util::seems_utf8( $invalidUTF8 ) );
// And test some plain ASCII
$this->assertTrue( util::seems_utf8( 'The quick brown fox jumps over the lazy dog' ) );
// Test an invalid non-UTF-8 string.
if (function_exists('mb_convert_encoding')) {
mb_internal_encoding('UTF-8');
// Converts the 'ç' UTF-8 character to UCS-2LE
$utf8Char = pack('n', 50087);
$ucsChar = mb_convert_encoding($utf8Char, 'UCS-2LE', 'UTF-8');
// Ensure that PHP's internal encoding system isn't malconfigured.
$this->assertEquals( $utf8Char, 'ç', 'This PHP system\'s internal character set is not properly set as UTF-8.' );
$this->assertEquals( $utf8Char, pack('n', 50087), 'Something is wrong with your ICU unicode library.' );
// Test for not UTF-8.
$this->assertFalse( util::seems_utf8( $ucsChar) );
// Test the worker method.
$method = self::getMethod('seemsUtf8Regex');
$this->assertFalse($method->invoke(null, $invalidUTF8), 'util::seemsUtf8Regex did not properly detect invalid UTF-8.');
$this->assertTrue($method->invoke(null, $validUTF8), 'util::seemsUtf8Regex did not properly detect valid UTF-8.');
}
}
public function test_size_format()
{
$size = util::size_format( 512, 0 );
$this->assertEquals( '512 B', $size );
$size = util::size_format( 2048, 1 );
$this->assertEquals( '2.0 KiB', $size );
$size = util::size_format( 25151251, 2 );
$this->assertEquals( '23.99 MiB', $size );
$size = util::size_format( 19971597926, 2 );
$this->assertEquals( '18.60 GiB', $size );
$size = util::size_format( 2748779069440, 1 );
$this->assertEquals( '2.5 TiB', $size );
$size = util::size_format( 2.81475e15, 1 );
$this->assertEquals( '2.5 PiB', $size );
$size = util::size_format( 2.81475e19, 1 );
$this->assertEquals( '25000.0 PiB', $size );
}
public function test_maybe_serialize()
{
$obj = new stdClass();
$obj->prop1 = 'Hello';
$obj->prop2 = 'World';
$this->assertEquals( 'This is a string', util::maybe_serialize( 'This is a string' ) );
$this->assertEquals( 5.81, util::maybe_serialize( 5.81 ) );
$this->assertEquals( 'a:0:{}', util::maybe_serialize( array() ) );
$this->assertEquals( 'O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}', util::maybe_serialize( $obj ) );
$this->assertEquals( 'a:4:{i:0;s:4:"test";i:1;s:4:"blah";s:5:"hello";s:5:"world";s:5:"array";O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}}', util::maybe_serialize( array( 'test', 'blah', 'hello' => 'world', 'array' => $obj ) ) );
}
public function test_maybe_unserialize()
{
$obj = new stdClass();
$obj->prop1 = 'Hello';
$obj->prop2 = 'World';
$this->assertNull(util::maybe_unserialize(serialize(null)));
$this->assertFalse(util::maybe_unserialize(serialize(false)));
$this->assertEquals( 'This is a string', util::maybe_unserialize( 'This is a string' ) );
$this->assertEquals( 5.81, util::maybe_unserialize( 5.81 ) );
$this->assertEquals( array(), util::maybe_unserialize( 'a:0:{}' ) );
$this->assertEquals( $obj, util::maybe_unserialize( 'O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}' ) );
$this->assertEquals( array( 'test', 'blah', 'hello' => 'world', 'array' => $obj ), util::maybe_unserialize( 'a:4:{i:0;s:4:"test";i:1;s:4:"blah";s:5:"hello";s:5:"world";s:5:"array";O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}}' ) );
// Test a broken serialization.
$expectedData = array(
'Normal',
'High-value Char: '.chr(231).'a-va?', // High-value Char: ça-va? [in ISO-8859-1]
);
$brokenSerialization = 'a:2:{i:0;s:6:"Normal";i:1;s:23:"High-value Char: ▒a-va?";}';
$unserializedData = util::maybe_unserialize($brokenSerialization);
$this->assertEquals($expectedData[0], $unserializedData[0], 'Did not properly fix the broken serialized data.');
$this->assertEquals(substr($expectedData[1], 0, 10), substr($unserializedData[1], 0, 10), 'Did not properly fix the broken serialized data.');
// Test unfixable serialization.
$unfixableSerialization = 'a:2:{i:0;s:6:"Normal";}';
$this->assertEquals($unfixableSerialization, util::maybe_unserialize($unfixableSerialization), 'Somehow the [previously?] impossible happened and utilphp thinks it has unserialized an unfixable serialization.');
}
public function test_is_serialized()
{
$this->assertFalse( util::is_serialized(1) );
$this->assertFalse( util::is_serialized(null) );
$this->assertFalse( util::is_serialized( 's:4:"test;' ) );
$this->assertFalse( util::is_serialized( 'a:0:{}!' ) );
$this->assertFalse( util::is_serialized( 'a:0' ) );
$this->assertFalse( util::is_serialized( 'This is a string' ) );
$this->assertFalse( util::is_serialized( 'a string' ) );
$this->assertFalse( util::is_serialized( 'z:0;' ) );
$this->assertTrue( util::is_serialized( 'N;' ) );
$this->assertTrue( util::is_serialized( 'b:1;' ) );
$this->assertTrue( util::is_serialized( 'a:0:{}' ) );
$this->assertTrue( util::is_serialized( 'O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}' ) );
}
public function test_fix_broken_serialization()
{
$expectedData = array(
'Normal',
'High-value Char: '.chr(231).'a-va?', // High-value Char: ça-va? [in ISO-8859-1]
);
$brokenSerialization = 'a:2:{i:0;s:6:"Normal";i:1;s:23:"High-value Char: ▒a-va?";}';
// Temporarily override error handling to ensure that this is, in fact, [still] a broken serialization.
{
$expectedError = array(
'errno' => 8,
'errstr' => 'unserialize(): Error at offset 55 of 60 bytes'
);
$reportedError = array();
set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) use (&$reportedError) {
$reportedError = compact('errno', 'errstr');
});
unserialize($brokenSerialization);
$this->assertEquals($expectedError['errno'], $reportedError['errno']);
// Because HHVM's unserialize() error message does not contain enough info to properly test.
if (!defined('HHVM_VERSION')) {
$this->assertEquals($expectedError['errstr'], $reportedError['errstr']);
}
restore_error_handler();
}
$fixedSerialization = util::fix_broken_serialization($brokenSerialization);
$unserializedData = unserialize($fixedSerialization);
$this->assertEquals($expectedData[0], $unserializedData[0], 'Did not properly fix the broken serialized data.');
$this->assertEquals(substr($expectedData[1], 0, 10), substr($unserializedData[1], 0, 10), 'Did not properly fix the broken serialized data.');
}
public function test_is_https()
{
$_SERVER['HTTPS'] = null;
$this->assertFalse( util::is_https() );
$_SERVER['HTTPS'] = 'on';
$this->assertTrue( util::is_https() );
}
public function test_add_query_arg()
{
// Regular tests
$this->assertEquals( '/app/admin/users?user=5', util::add_query_arg( 'user', 5, '/app/admin/users' ) );
$this->assertEquals( '/app/admin/users?user=5', util::add_query_arg( array( 'user' => 5 ), '/app/admin/users' ) );
$this->assertEquals( '/app/admin/users?user=5', util::add_query_arg( array( 'user' => 5 ), null, '/app/admin/users' ) );
$this->assertEquals( '/app/admin/users?action=edit&user=5', util::add_query_arg( 'user', 5, '/app/admin/users?action=edit' ) );
$this->assertEquals( '/app/admin/users?action=edit&user=5', util::add_query_arg( array( 'user' => 5 ), '/app/admin/users?action=edit' ) );
$this->assertEquals( '/app/admin/users?action=edit&tab=personal&user=5', util::add_query_arg( 'user', 5, '/app/admin/users?action=edit&tab=personal' ) );
$this->assertEquals( '/app/admin/users?action=edit&tab=personal&user=5', util::add_query_arg( array( 'user' => 5 ), '/app/admin/users?action=edit&tab=personal' ) );
// Ensure strips false.
$this->assertEquals('/index.php', util::add_query_arg('debug', false, '/index.php'));
// With a URL fragment
$this->assertEquals( '/app/admin/users?user=5#test', util::add_query_arg( 'user', 5, '/app/admin/users#test' ) );
// Full URL
$this->assertEquals( 'http://example.com/?a=b', util::add_query_arg( 'a', 'b', 'http://example.com' ) );
// Only the query string
$this->assertEquals( '?a=b&c=d', util::add_query_arg( 'c', 'd', '?a=b' ) );
$this->assertEquals( 'a=b&c=d', util::add_query_arg( 'c', 'd', 'a=b' ) );
// Url encoding test
$this->assertEquals( '/app/admin/users?param=containsa%26sym', util::add_query_arg( 'param', 'containsa&sym', '/app/admin/users' ) );
// If not provided, grab the URI from the server.
$_SERVER['REQUEST_URI'] = '/app/admin/users';
$this->assertEquals( '/app/admin/users?user=6', util::add_query_arg( array( 'user' => 6 ) ) );
$this->assertEquals( '/app/admin/users?user=7', util::add_query_arg( 'user', 7 ) );
}
public function test_remove_query_arg()
{
$this->assertEquals( '/app/admin/users', util::remove_query_arg( 'user', '/app/admin/users?user=5' ) );
$this->assertEquals( '/app/admin/users?action=edit', util::remove_query_arg( 'user', '/app/admin/users?action=edit&user=5' ) );
$this->assertEquals( '/app/admin/users?user=5', util::remove_query_arg( array( 'tab', 'action' ), '/app/admin/users?action=edit&tab=personal&user=5' ) );
}
public function test_http_build_url()
{
$url = 'http://user:pass@example.com:8080/path/?query#fragment';
$expected = 'http://example.com/';
$actual = util::http_build_url($url, array(), util::HTTP_URL_STRIP_ALL);
$this->assertEquals($expected, $actual);
$expected = 'http://example.com:8080/path/?query#fragment';
$actual = util::http_build_url($url, array(), util::HTTP_URL_STRIP_AUTH);
$this->assertEquals($expected, $actual);
$this->assertEquals('https://dev.example.com/', util::http_build_url('http://example.com/', array('scheme' => 'https', 'host' => 'dev.example.com')));
$this->assertEquals('http://example.com/#hi', util::http_build_url('http://example.com/', array('fragment' => 'hi'), util::HTTP_URL_REPLACE));
$this->assertEquals('http://example.com/page', util::http_build_url('http://example.com/', array('path' => 'page'), util::HTTP_URL_JOIN_PATH));
$this->assertEquals('http://example.com/page', util::http_build_url('http://example.com', array('path' => 'page'), util::HTTP_URL_JOIN_PATH));
$this->assertEquals('http://example.com/?hi=Bro', util::http_build_url('http://example.com/', array('query' => 'hi=Bro'), util::HTTP_URL_JOIN_QUERY));
$this->assertEquals('http://example.com/?show=1&hi=Bro', util::http_build_url('http://example.com/?show=1', array('query' => 'hi=Bro'), util::HTTP_URL_JOIN_QUERY));
$this->assertEquals('http://admin@example.com/', util::http_build_url('http://example.com/', array('user' => 'admin')));
$this->assertEquals('http://admin:1@example.com/', util::http_build_url('http://example.com/', array('user' => 'admin', 'pass' => '1')));
}
public function test_str_to_bool()
{
$this->assertTrue( util::str_to_bool( 'true' ) );
$this->assertTrue( util::str_to_bool( 'yes' ) );
$this->assertTrue( util::str_to_bool( 'y' ) );
$this->assertTrue( util::str_to_bool( 'oui' ) );
$this->assertTrue( util::str_to_bool( 'vrai' ) );
$this->assertFalse( util::str_to_bool( 'false' ) );
$this->assertFalse( util::str_to_bool( 'no' ) );
$this->assertFalse( util::str_to_bool( 'n' ) );
$this->assertFalse( util::str_to_bool( 'non' ) );
$this->assertFalse( util::str_to_bool( 'faux' ) );
$this->assertFalse( util::str_to_bool( 'test' , false) );
}
public function test_array_pluck()
{
$array = array(
array(
'name' => 'Bob',
'age' => 37
),
array(
'name' => 'Fred',
'age' => 37
),
array(
'name' => 'Jane',
'age' => 29
),
array(
'name' => 'Brandon',
'age' => 20
),
array(
'age' => 41
)
);
$obj_array = array(
'bob' => (object) array(
'name' => 'Bob',
'age' => 37
),
'fred' => (object) array(
'name' => 'Fred',
'age' => 37
),
'jane' => (object) array(
'name' => 'Jane',
'age' => 29
),
'brandon' => (object) array(
'name' => 'Brandon',
'age' => 20
),
'invalid' => (object) array(
'age' => 41
)
);
$obj_array_expect = array(
'bob' => 'Bob',
'fred' => 'Fred',
'jane' => 'Jane',
'brandon' => 'Brandon'
);
$this->assertEquals( array( 'Bob', 'Fred', 'Jane', 'Brandon' ), util::array_pluck( $array, 'name' ) );
$this->assertEquals( array( 'Bob', 'Fred', 'Jane', 'Brandon', array( 'age' => 41 ) ), util::array_pluck( $array, 'name', TRUE, FALSE ) );
$this->assertEquals( $obj_array_expect, util::array_pluck( $obj_array, 'name' ) );
$this->assertEquals( array( 'Bob', 'Fred', 'Jane', 'Brandon' ), util::array_pluck( $obj_array, 'name', FALSE ) );
$expected = array('Bob', 'Fred', 'Jane', 'Brandon', 'invalid' => (object)array('age' => 41));
$this->assertEquals($expected, util::array_pluck($obj_array, 'name', FALSE, FALSE));
$expected = array('Bob', 'Fred', 'Jane', 'Brandon', array('age' => 41));
$this->assertEquals($expected, util::array_pluck($array, 'name', false, false));
}
public function test_htmlentities()
{
$this->assertEquals( 'One &amp; Two', util::htmlentities( 'One & Two' ) );
$this->assertEquals( 'One &amp; Two', util::htmlentities( 'One &amp; Two', TRUE ) );
}
public function test_htmlspecialchars()
{
$this->assertEquals( 'One &amp; Two', util::htmlspecialchars( 'One & Two' ) );
$this->assertEquals( 'One &amp; Two', util::htmlspecialchars( 'One &amp; Two', TRUE ) );
}
public function test_remove_accents()
{
$this->assertEquals( 'A', util::remove_accents( "\xC3\x81" ) );
$this->assertEquals( 'e', util::remove_accents( "\xC4\x97" ) );
$this->assertEquals( 'U', util::remove_accents( "\xC3\x9C" ) );
$this->assertEquals( 'Ae', util::remove_accents( "Ä", 'de' ) );
$this->assertEquals( 'OEoeAEDHTHssaedhth', util::remove_accents(chr(140) . chr(156) . chr(198) . chr(208) . chr(222) . chr(223) . chr(230) . chr(240) . chr(254)));
}
public function test_zero_pad()
{
$this->assertEquals( '00000341', util::zero_pad( 341, 8 ) );
$this->assertEquals( '341', util::zero_pad( 341, 1 ) );
}
public function test_human_time_diff()
{
$this->assertEquals( '1 second ago', util::human_time_diff( time() - 1 ) );
$this->assertEquals( '30 seconds ago', util::human_time_diff( time() - 30 ) );
$this->assertEquals( '1 minute ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MINUTE * 1.4 ) ) );
$this->assertEquals( '5 minutes ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MINUTE * 5 ) ) );
$this->assertEquals( '1 hour ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR ) ) );
$this->assertEquals( '2 hours ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 2 ) ) );
$this->assertEquals( '1 day ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 ) ) );
$this->assertEquals( '5 days ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 * 5 ) ) );
$this->assertEquals( '1 week ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 * 7 ) ) );
$this->assertEquals( '2 weeks ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 * 14 ) ) );
$this->assertEquals( '1 month ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_WEEK * 5 ) ) );
$this->assertEquals( '2 months ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_WEEK * 10 ) ) );
$this->assertEquals( '1 year ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MONTH * 15 ) ) );
$this->assertEquals( '2 years ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MONTH * 36 ) ) );
$this->assertEquals( '11 years ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MONTH * 140 ) ) );
$this->assertEquals( 'fifteen minutes ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MINUTE * 15 ), '', TRUE ) );
}
public function test_number_to_word()
{
try {
util::number_to_word('junk data');
$this->fail('Accepted junk data');
} catch(\LogicException $e) {
$this->assertEquals('Not a number', $e->getMessage());
}
// Partially numeric.
$this->assertEquals('', util::number_to_word('1a'));
// Decimals
$this->assertEquals( 'five point zero five', util::number_to_word('5.05') );
$this->assertEquals( 'zero point eight', util::number_to_word( 0.8 ) );
// Integers
$this->assertEquals( 'positive one', util::number_to_word( '+1' ) );
$this->assertEquals( 'negative twelve', util::number_to_word( -12 ) );
$this->assertEquals( 'one', util::number_to_word( 1 ) );
$this->assertEquals( 'five', util::number_to_word( 5 ) );
$this->assertEquals( 'fifteen', util::number_to_word( 15 ) );
$this->assertEquals( 'twenty-one', util::number_to_word( 21 ) );
$this->assertEquals( 'thirty-two', util::number_to_word( 32 ) );
$this->assertEquals( 'forty-three', util::number_to_word( 43 ) );
$this->assertEquals( 'fifty-four', util::number_to_word( 54 ) );
$this->assertEquals( 'sixty-six', util::number_to_word( 66 ) );
$this->assertEquals( 'seventy-seven', util::number_to_word( 77 ) );
$this->assertEquals( 'eighty-eight', util::number_to_word( 88 ) );
$this->assertEquals( 'ninety-nine', util::number_to_word( 99 ) );
$this->assertEquals( 'one hundred and thirty-six', util::number_to_word( 136 ) );
$this->assertEquals( 'ten', util::number_to_word( 10 ) );
$this->assertEquals( 'twenty', util::number_to_word( 20 ) );
$this->assertEquals( 'thirty', util::number_to_word( 30 ) );
$this->assertEquals( 'forty', util::number_to_word( 40 ) );
$this->assertEquals( 'fifty', util::number_to_word( 50 ) );
$this->assertEquals( 'sixty', util::number_to_word( 60 ) );
$this->assertEquals( 'seventy', util::number_to_word( 70 ) );
$this->assertEquals( 'eighty', util::number_to_word( 80 ) );
$this->assertEquals( 'ninety', util::number_to_word( 90 ) );
$this->assertEquals( 'eleven', util::number_to_word( 11 ) );
$this->assertEquals( 'thirteen', util::number_to_word( 13 ) );
$this->assertEquals( 'fourteen', util::number_to_word( 14 ) );
$this->assertEquals( 'fifteen', util::number_to_word( 15 ) );
$this->assertEquals( 'sixteen', util::number_to_word( 16 ) );
$this->assertEquals( 'seventeen', util::number_to_word( 17 ) );
$this->assertEquals( 'eighteen', util::number_to_word( 18 ) );
$this->assertEquals( 'nineteen', util::number_to_word( 19 ) );
$this->assertEquals( 'one thousand', util::number_to_word( 1000 ) );
$this->assertEquals( 'one million', util::number_to_word( 1000000 ) );
$this->assertEquals( 'one billion', util::number_to_word( 1000000000 ) );
$this->assertEquals( 'one trillion', util::number_to_word( 1000000000000 ) );
$this->assertEquals( 'one quadrillion', util::number_to_word( '1000000000000000' ) );
$this->assertEquals( 'one quintrillion', util::number_to_word( '1000000000000000000' ) );
$this->assertEquals( 'one sextillion', util::number_to_word( '1000000000000000000000' ) );
$this->assertEquals( 'one septillion', util::number_to_word( '1000000000000000000000000' ) );
$this->assertEquals( 'one octillion', util::number_to_word( '1000000000000000000000000000' ) );
$this->assertEquals( 'one nonillion', util::number_to_word( '1000000000000000000000000000000' ) );
$this->assertEquals( 'one decillion', util::number_to_word( '1000000000000000000000000000000000' ) );
$this->assertEquals( 'one', util::number_to_word( '1000000000000000000000000000000000000000000' ) );
}
public function test_array_search_deep()
{
$users = array(
1 => (object) array( 'username' => 'brandon', 'age' => 20 ),
2 => (object) array( 'username' => 'matt', 'age' => 27 ),
3 => (object) array( 'username' => 'jane', 'age' => 53 ),
4 => (object) array( 'username' => 'john', 'age' => 41 ),
5 => (object) array( 'username' => 'steve', 'age' => 11 ),
6 => (object) array( 'username' => 'fred', 'age' => 42 ),
7 => (object) array( 'username' => 'rasmus', 'age' => 21 ),
8 => (object) array( 'username' => 'don', 'age' => 15 ),
9 => array( 'username' => 'darcy', 'age' => 33 ),
);
$test = array(
1 => 'brandon',
2 => 'devon',
3 => array( 'troy' ),
4 => 'annie'
);
$this->assertFalse( util::array_search_deep( $test, 'bob' ) );
$this->assertEquals( 3, util::array_search_deep( $test, 'troy' ) );
$this->assertEquals( 4, util::array_search_deep( $test, 'annie' ) );
$this->assertEquals( 2, util::array_search_deep( $test, 'devon', 'devon' ) );
$this->assertEquals( 7, util::array_search_deep( $users, 'rasmus', 'username' ) );
$this->assertEquals( 9, util::array_search_deep( $users, 'darcy', 'username' ) );
$this->assertEquals( 1, util::array_search_deep( $users, 'brandon' ) );
}
public function test_array_map_deep()
{
$input = array(
'<',
'abc',
'>',
'def',
array( '&', 'test', '123' ),
(object) array( 'hey', '<>' )
);
$expect = array(
'&lt;',
'abc',
'&gt;',
'def',
array( '&amp;', 'test', '123' ),
(object) array( 'hey', '<>' )
);
$this->assertEquals( $expect, util::array_map_deep( $input, 'htmlentities' ) );
}
public function test_random_string()
{
// Make sure the generated string contains only human friendly characters and is 30 characters long
$str = util::random_string( 30 );
$this->assertTrue( (bool) preg_match( '/^([ABCDEFGHJKLMNPQRSTUVWXYZabcdefhjkmnprstuvwxyz23456789]{30})$/', $str ) );
// Make sure the generated string is 30 characters long
$str = util::random_string( 30, false, true );
$this->assertTrue( strlen( $str ) === 30, 'random_string produced an invalid length string' );
// Make sure the generated string is 120 characters long
$str = util::random_string( 120 );
$this->assertTrue(strlen( $str ) === 120, 'random_string produced an invalid length string');
// Make sure the string doesn't contain duplicate letters
$str = util::random_string( 53, true, false, true );
$this->assertTrue(strlen($str) === 53, 'random_string produced an invalid length string');
$this->assertTrue(count(array_unique(str_split($str))) === strlen($str), 'random_string produced a string with duplicate characters');
// Longer length than characters available
try {
$str = util::random_string( 55, true, false, true );
$this->assertTrue( false );
} catch (Exception $e) {
$this->assertTrue( true );
}
// Test secure variant
$str = util::secure_random_string(16);
$this->assertTrue(strlen($str) === 16);
// Longer length than characters available
try {
$str = util::secure_random_string(0);
$this->assertTrue(false);
} catch (Exception $e) {
$this->assertTrue(true);
}
}
public function test_match_string()
{
$this->assertTrue( util::match_string('a', 'a') );
$this->assertFalse( util::match_string('a', ' a') );
$this->assertFalse( util::match_string('/', '/something') );
$this->assertTrue( util::match_string('test/*', 'test/first/second') );
$this->assertTrue( util::match_string('*/test', 'first/second/test') );
$this->assertFalse( util::match_string('first/', 'first/second/test') );
$this->assertFalse( util::match_string('test', 'TEST') );
$this->assertTrue( util::match_string('test', 'TEST', false) );
}
public function test_validate_email()
{
$this->assertTrue( util::validate_email( 'john.smith@gmail.com' ) );
$this->assertTrue( util::validate_email( 'john.smith+label@gmail.com' ) );
$this->assertTrue( util::validate_email( 'john.smith@gmail.co.uk' ) );
}
public function test_safe_truncate()
{
$this->assertEquals( 'The quick brown fox...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 24 ) );
$this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 55 ) );
$this->assertEquals( 'Th...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 2 ) );
$this->assertEquals( 'The...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 3 ) );
$this->assertEquals( 'The...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 7 ) );
}
public function test_limit_characters()
{
$this->assertEquals( 'The quick brown fox jump...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 24 ) );
$this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 55 ) );
$this->assertEquals( 'Th...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 2 ) );
$this->assertEquals( 'The...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 3 ) );
$this->assertEquals( 'The qui...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 7 ) );
$this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 150 ) );
}
public function test_limit_words()
{
$this->assertEquals( 'The quick brown...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 3 ) );
$this->assertEquals( 'The quick brown fox jumps...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 5 ) );
$this->assertEquals( 'The...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 1 ) );
$this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::limit_words( 'The quick brown fox jumps over the lazy dog', 90 ) );
$this->assertEquals( 'The quick brown fox jumps over the...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 7 ) );
}
public function test_ordinal()
{
$this->assertEquals( '1st', util::ordinal( 1 ) );
$this->assertEquals( '2nd', util::ordinal( 2 ) );
$this->assertEquals( '3rd', util::ordinal( 3 ) );
$this->assertEquals( '4th', util::ordinal( 4 ) );
$this->assertEquals( '5th', util::ordinal( 5 ) );
$this->assertEquals( '6th', util::ordinal( 6 ) );
$this->assertEquals( '7th', util::ordinal( 7 ) );
$this->assertEquals( '8th', util::ordinal( 8 ) );
$this->assertEquals( '9th', util::ordinal( 9 ) );
$this->assertEquals( '22nd', util::ordinal( 22 ) );
$this->assertEquals( '23rd', util::ordinal( 23 ) );
$this->assertEquals( '143rd', util::ordinal( 143 ) );
}
public function test_array_first()
{
$test = array( 'a' => array( 'a', 'b', 'c' ) );
$this->assertEquals( 'a', util::array_first( util::array_get( $test['a'] ) ) );
}
public function test_array_first_key()
{
$test = array( 'a' => array( 'a' => 'b', 'c' => 'd' ) );
$this->assertEquals( 'a', util::array_first_key( util::array_get( $test['a'] ) ) );
}
public function test_array_last()
{
$test = array( 'a' => array( 'a', 'b', 'c' ) );
$this->assertEquals( 'c', util::array_last( util::array_get( $test['a'] ) ) );
}
public function test_array_last_key()
{
$test = array( 'a' => array( 'a' => 'b', 'c' => 'd' ) );
$this->assertEquals( 'c', util::array_last_key( util::array_get( $test['a'] ) ) );
}
public function test_array_flatten()
{
$input = array( 'a', 'b', 'c', 'd', array( 'first' => 'e', 'f', 'second' => 'g', array( 'h', 'third' => 'i', array( array( array( array( 'j', 'k', 'l' ) ) ) ) ) ) );
$expectNoKeys = range( 'a', 'l' );
$expectWithKeys = array(
'a', 'b', 'c', 'd',
'first' => 'e',
'f',
'second' => 'g',
'h',
'third' => 'i',
'j', 'k', 'l'
);
$this->assertEquals( $expectWithKeys, util::array_flatten( $input ) );
$this->assertEquals( $expectNoKeys, util::array_flatten( $input, false ) );
$this->assertEquals( $expectWithKeys, util::array_flatten( $input, true ) );
}
public function test_strip_space()
{
$input = ' The quick brown fox jumps over the lazy dog ';
$expect = 'Thequickbrownfoxjumpsoverthelazydog';
$this->assertEquals($expect, Util::strip_space($input));
}
public function test_sanitize_string()
{
$input = ' Benoit! à New-York? jai perçu 1 % : Quas-tu "gagné" chez M. V. Noël? Dix francs.';
$expect = 'benoitanewyorkjaipercu1quastugagnechezmvnoeldixfrancs';
$this->assertEquals($expect, Util::sanitize_string($input));
}
public function test_get_gravatar()
{
$_SERVER['HTTPS'] = 'on';
$this->assertEquals('https://secure.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=32', util::get_gravatar('john.doe@example.org'));
$this->assertEquals('https://secure.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=128', util::get_gravatar('john.doe@example.org', 128));
$_SERVER['HTTPS'] = 'off';
$this->assertEquals('http://www.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=32', util::get_gravatar('john.doe@example.org'));
$this->assertEquals('http://www.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=128', util::get_gravatar('john.doe@example.org', 128));
}
public function test_get_client_ip()
{
$_SERVER['REMOTE_ADDR'] = '192.168.30.152';
$_SERVER['HTTP_CLIENT_IP'] = '192.168.30.153';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.30.154';
$this->assertEquals('192.168.30.152', util::get_client_ip());
$this->assertEquals('192.168.30.153', util::get_client_ip(true));
unset($_SERVER['HTTP_CLIENT_IP']);
$this->assertEquals('192.168.30.154', util::get_client_ip(true));
unset($_SERVER['HTTP_X_FORWARDED_FOR']);
$this->assertEquals('192.168.30.152', util::get_client_ip(true));
}
public function test_full_permissions()
{
// Text a non-existant file.
$this->assertFalse(util::full_permissions('faker-123.blah'), 'Gave a permission value for a non-existant file.');
// Test an existing file.
$expected = '-rw-rw-rw-';
$tempFile = tempnam(sys_get_temp_dir(), 'foo');
$this->assertTrue(chmod($tempFile, 0666), 'Oops. Could not change temp file\'s permissions to 0666.');
$this->assertEquals($expected, util::full_permissions($tempFile), 'Could not properly obtain permissions of an existing file.');
unlink($tempFile);
$this->assertEquals('lr--r--r--', util::full_permissions('fake-file-222', octdec('120444')));
$this->assertEquals('ur--r--r--', util::full_permissions('fake-file-222', octdec('000444')));
$this->assertEquals('srwxr-xr-x', util::full_permissions('fake-file-222', octdec('140755')));
$this->assertEquals('drwxr-xr-x', util::full_permissions('fake-file-222', octdec('40755')));
$this->assertEquals('brw-rw----', util::full_permissions('fake-file-222', octdec('60660')));
$this->assertEquals('crw-rw----', util::full_permissions('fake-file-222', octdec('20660')));
$this->assertEquals('prw-rw----', util::full_permissions('fake-file-222', octdec('10660')));
$this->assertEquals('---x------', util::full_permissions('fake-file-222', octdec('100100')));
$this->assertEquals('--w-------', util::full_permissions('fake-file-222', octdec('100200')));
$this->assertEquals('--wx------', util::full_permissions('fake-file-222', octdec('100300')));
$this->assertEquals('-r--------', util::full_permissions('fake-file-222', octdec('100400')));
$this->assertEquals('-r-x------', util::full_permissions('fake-file-222', octdec('100500')));
$this->assertEquals('-rw-------', util::full_permissions('fake-file-222', octdec('100600')));
$this->assertEquals('-rwx------', util::full_permissions('fake-file-222', octdec('100700')));
// Windows does not have the concept of /.
if (!defined('PHP_WINDOWS_VERSION_MAJOR')) {
$this->assertEquals('drwxr-xr-x', util::full_permissions('/'));
}
}
public function test_array_clean()
{
$input = array( 'a', 'b', '', null, false, 0);
$expect = array('a', 'b');
$this->assertEquals($expect, Util::array_clean($input));
}
public function test_var_dump_plain()
{
$input = 'var';
$expect = '<span style="color:#588bff;">string</span><span style="color:#999;">(</span>3<span style="color:#999;">)</span> <strong>"var"</strong>';
$this->assertEquals($expect, Util::var_dump_plain($input, true));
$input = true;
$expect = '<span style="color:#588bff;">bool</span><span style="color:#999;">(</span><strong>true</strong><span style="color:#999;">)</span>';
$this->assertEquals($expect, Util::var_dump_plain($input, true));
$input = 1;
$expect = '<span style="color:#588bff;">int</span><span style="color:#999;">(</span><strong>1</strong><span style="color:#999;">)</span>';
$this->assertEquals($expect, Util::var_dump_plain($input, true));
$input = 1.5;
$expect = '<span style="color:#588bff;">float</span><span style="color:#999;">(</span><strong>1.5</strong><span style="color:#999;">)</span>';
$this->assertEquals($expect, Util::var_dump_plain($input, true));
$input = null;
$expect = '<strong>NULL</strong>';
$this->assertEquals($expect, Util::var_dump_plain($input, true));
$input = fopen('php://memory', 'r');
$expect = '<span style="color:#588bff;">resource</span>("stream") <strong>"' . $input . '"</strong>';
$this->assertEquals($expect, Util::var_dump_plain($input, -1));
fclose($input);
// Test complex arrays.
$input = array(1, 2, 4, 6, 10 => 20, 100 => 200);
$actual = util::var_dump_plain($input, true);
$this->assertContains('<img id="include-php-', $actual);
$this->assertContains('<br /> 100 => <span', $actual);
$this->assertContains('(</span><strong>200</strong><span style="color:#999;">)', $actual);
// Test complex objects.
$experiment = new VarDumpExperiment();
$actual = util::var_dump_plain($experiment, true);
$this->assertContains('1 => <span style="color:#588bff;">string</span><span style="color:#999;">(</span>1<span style="color:#999;">', $actual);
}
public function test_var_dump()
{
$input = 'var';
$expect = '<pre style="margin-bottom: 18px;background: #f7f7f9;border: 1px solid #e1e1e8;padding: 8px;border-radius: 4px;-moz-border-radius: 4px;-webkit-border radius: 4px;display: block;font-size: 12.05px;white-space: pre-wrap;word-wrap: break-word;color: #333;font-family: Menlo,Monaco,Consolas,\'Courier New\',monospace;"><span style="color:#588bff;">string</span><span style="color:#999;">(</span>3<span style="color:#999;">)</span> <strong>"var"</strong></pre>';
// Ensure the proper output is returned
$this->assertEquals($expect, Util::var_dump($input, true));
// Ensure the proper output is actually outputted
$this->expectOutputString($expect);
util::var_dump($input);
// Ensure we avoid infinite recursion on recursive arrays
$a = array('a' => 'value a', 'b' => 'value b');
$b = array('test' => &$a);
$c = array('a' => &$a, 'b' => &$b);
$a['c'] = &$c;
$b['c'] = &$c;
$this->assertContains('*RECURSION DETECTED*', Util::var_dump($c, true));
// Ensure we avoid infinite recursion on recursive objects
$a = (object) array('a' => 'value a', 'b' => 'value b');
$b = (object) array('test' => &$a);
$c = (object) array('a' => &$a, 'b' => &$b);
$a->c = &$c;
$b->c = &$c;
$this->assertContains('*RECURSION DETECTED*', Util::var_dump($c, true));
// Test class scoping.
$experiment = new VarDumpExperiment();
$actual = util::var_dump($experiment, true);
$snippet = substr($actual, strrpos($actual, 'display:inline'));
$this->assertContains('"public"', $snippet);
$this->assertContains('"protected:protected"', $snippet);
$this->assertContains('"private:VarDumpExperiment:private"', $actual);
}
public function test_linkify()
{
$input = 'great websites: http://www.google.com?param=test and http://yahoo.com/a/nested/folder';
$expect = 'great websites: <a href="http://www.google.com?param=test">http://www.google.com?param=test</a> and <a href="http://yahoo.com/a/nested/folder">http://yahoo.com/a/nested/folder</a>';
$this->assertEquals($expect, Util::linkify($input));
$this->assertEquals($expect, util::linkify($expect), 'linkify() tried to double linkify an href.');
}
public function test_start_with()
{
$this->assertTrue(Util::starts_with('start a string', 'start a'));
$this->assertFalse(Util::starts_with('start a string', 'string'));
}
public function test_end_with()
{
$this->assertTrue(Util::ends_with('start a string', 'a string'));
$this->assertFalse(Util::ends_with('start a string', 'start'));
}
public function test_contains()
{
$this->assertTrue(Util::str_contains('start a string', 'a string'));
$this->assertFalse(Util::str_contains('start a string', 'Start'));
}
public function test_iContains()
{
$this->assertTrue(Util::str_icontains('start a string', 'a string'));
$this->assertTrue(Util::str_icontains('start a string', 'Start'));
}
public function test_get_file_ext()
{
$input = 'a_pdf_fil.pdf';
$expect = 'pdf';
$this->assertEquals($expect, Util::get_file_ext($input));
}
public function test_rmdir()
{
$dirname = dirname(__FILE__);
// Test deleting a non-existant directory
$this->assertFalse(file_exists($dirname . '/test1'));
$this->assertTrue(util::rmdir($dirname . '/test1'));
// Test deleting an empty directory
$dir = $dirname . '/test2';
mkdir($dir);
$this->assertTrue(is_dir($dir));
if (is_dir($dir)) {
util::rmdir($dir);
$this->assertFalse(is_dir($dir));
}
// Test deleting a non-empty directory
$dir = $dirname . '/test3';
$file = $dirname . '/test3/test.txt';
mkdir($dir);
touch($file);
$this->assertTrue(is_dir($dir));
$this->assertTrue(is_file($file));
if (is_dir($dir)) {
util::rmdir($dir);
$this->assertFalse(is_dir($dir));
$this->assertFalse(is_file($file));
}
// Test deleting a non-directory path
$file = $dirname . '/test4.txt';
touch($file);
try {
$str = util::rmdir($file);
$this->assertTrue(false);
} catch (\Exception $e) {
$this->assertTrue(true);
}
unlink($file);
// Test deleting a nested directory
$dir1 = $dirname . '/test5';
$dir2 = $dirname . '/test5/nested_dir';
$file1 = $dir1 . '/file1.txt';
$file2 = $dir2 . '/file2.txt';
mkdir($dir1);
mkdir($dir2);
touch($file1);
touch($file2);
$this->assertTrue(is_dir($dir1));
$this->assertTrue(is_dir($dir2));
$this->assertTrue(is_file($file1));
$this->assertTrue(is_file($file2));
if (is_dir($dir1)) {
util::rmdir($dir1);
$this->assertFalse(is_dir($dir1));
$this->assertFalse(is_dir($dir2));
$this->assertFalse(is_file($file1));
$this->assertFalse(is_file($file2));
}
// Test symlink traversal.
$dir = $dirname . '/test6';
$nestedDir = "$dir/nested";
$symlink = "$dir/nested-symlink";
mkdir($dir);
mkdir($nestedDir);
$symlinkStatus = symlink($nestedDir, $symlink);
$this->assertTrue($symlinkStatus, 'The test system does not support making symlinks.');
if (!$symlink) {
return;
}
$this->assertTrue(util::rmdir($symlink, true), 'Could not delete a symlinked directory.');
$this->assertFalse(file_exists($symlink), 'Could not delete a symlinked directory.');
util::rmdir($dir, true);
$this->assertFalse(is_dir($dir), 'Could not delete a directory with a symlinked directory inside of it.');
}
public function test_get_current_url()
{
$expected = 'http://test.dev/test.php?foo=bar';
$expectedAuth = 'http://admin:123@test.dev/test.php?foo=bar';
$expectedPort = 'http://test.dev:443/test.php?foo=bar';
$expectedPort2 = 'https://test.dev:80/test.php?foo=bar';
$expectedSSL = 'https://test.dev/test.php?foo=bar';
$_SERVER['HTTP_HOST'] = 'test.dev';
$_SERVER['SERVER_PORT'] = 80;
$_SERVER['REQUEST_URI'] = '/test.php?foo=bar';
$_SERVER['QUERY_STRING'] = 'foo=bar';
$_SERVER['PHP_SELF'] = '/test.php';
// Test regular.
$this->assertEquals($expected, util::get_current_url());
// Test server auth.
$_SERVER['PHP_AUTH_USER'] = 'admin';
$_SERVER['PHP_AUTH_PW'] = '123';
$this->assertEquals($expectedAuth, util::get_current_url());
unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']);
// Test port.
$_SERVER['SERVER_PORT'] = 443;
$this->assertEquals($expectedPort, util::get_current_url());
// Test SSL.
$_SERVER['HTTPS'] = 'on';
$this->assertEquals($expectedSSL, util::get_current_url());
$_SERVER['SERVER_PORT'] = 80;
$this->assertEquals($expectedPort2, util::get_current_url());
unset($_SERVER['HTTPS']);
// Test no $_SERVER['REQUEST_URI'] (e.g., MS IIS).
unset($_SERVER['REQUEST_URI']);
$this->assertEquals($expected, util::get_current_url());
}
public function test_set_writable()
{
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
$this->markTestSkipped('This functionality is not working on Windows.');
}
if (posix_geteuid() === 0) {
$this->markTestSkipped('These tests don\'t work when run as root');
}
$this->assertFalse(util::set_writable('/no/such/file'));
// Create a file to test with
$dirname = dirname(__FILE__);
$file = $dirname . '/test7';
touch($file);
chmod($file, 0644);
// The file is owned by us so it should be writable
$this->assertTrue(is_writable($file));
$this->assertEquals('-rw-r--r--', util::full_permissions($file));
// Toggle writable bit off for us
util::set_writable($file, false);
clearstatcache();
$this->assertFalse(is_writable($file));
$this->assertEquals('-r--r--r--', util::full_permissions($file));
// Toggle writable bit back on for us
util::set_writable($file, true);
clearstatcache();
$this->assertTrue(is_writable($file));
$this->assertEquals('-rw-r--r--', util::full_permissions($file));
unlink($file);
}
public function test_set_readable()
{
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
$this->markTestSkipped('This functionality is not working on Windows.');
}
if (posix_geteuid() === 0) {
$this->markTestSkipped('These tests don\'t work when run as root');
}
$this->assertFalse(util::set_readable('/no/such/file'));
$dirname = dirname(__FILE__);
$file = $dirname . '/test8';
touch($file);
$this->assertTrue(is_readable($file));
util::set_readable($file, false);
clearstatcache();
$this->assertFalse(is_readable($file));
util::set_readable($file, true);
clearstatcache();
$this->assertTrue(is_readable($file));
unlink($file);
}
public function test_set_executable()
{
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
$this->markTestSkipped('This functionality is not working on Windows.');
}
if (posix_geteuid() === 0) {
$this->markTestSkipped('These tests don\'t work when run as root');
}
$this->assertFalse(util::set_executable('/no/such/file'));
$dirname = dirname(__FILE__);
$file = $dirname . '/test9';
touch($file);
$this->assertFalse(is_executable($file));
util::set_executable($file, true);
clearstatcache();
$this->assertTrue(is_executable($file));
util::set_executable($file, false);
clearstatcache();
$this->assertFalse(is_executable($file));
unlink($file);
}
public function test_directory_size() {
$dirname = dirname(__FILE__);
$dir = $dirname .'/dir1';
mkdir($dir);
$file1 = $dir .'/file1';
file_put_contents($file1, '1234567890');
$file2 = $dir .'/file2';
file_put_contents($file2, range('a', 'z'));
$this->assertEquals(10 + 26, util::directory_size($dir));
util::rmdir($dir);
}
public function test_get_user_directory() {
// Test for OS Default.
$this->assertTrue(is_writable(util::get_user_directory()));
$oldServer = $_SERVER;
unset($_SERVER);
// Test for UNIX.
$_SERVER['HOME'] = '/home/unknown';
$this->assertEquals($_SERVER['HOME'], util::get_user_directory(), 'Could not get the user\'s home directory in UNIX.');
unset($_SERVER);
// Test for Windows.
$expected = 'X:\Users\ThisUser';
$_SERVER['HOMEDRIVE'] = 'X:';
$_SERVER['HOMEPATH'] = '\Users\ThisUser';
$this->assertEquals($expected, util::get_user_directory(), 'Could not get the user\'s home directory in Windows.');
// In case the tests are not being run in isolation.
$_SERVER = $oldServer;
}
public function test_directory_contents() {
$dirname = dirname(__FILE__);
$dir = $dirname . DIRECTORY_SEPARATOR .'dir1';
mkdir($dir);
$file1 = $dir . DIRECTORY_SEPARATOR .'file1';
touch($file1);
$this->assertEquals(array($file1), util::directory_contents($dir));
util::rmdir($dir);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
require __DIR__ . '/src/utilphp/util.php';
/**
* Globally namespaced version of the class.
*
* @author Brandon Wamboldt <brandon.wamboldt@gmail.com>
*/
class util extends \utilphp\util { }
+445
View File
@@ -0,0 +1,445 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath.'\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+16
View File
@@ -0,0 +1,16 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'DB' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php',
'DBHelper' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php',
'DBTransaction' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php',
'MeekroDB' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php',
'MeekroDBEval' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php',
'MeekroDBException' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php',
'WhereClause' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php',
);
+10
View File
@@ -0,0 +1,10 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'utilphp\\' => array($vendorDir . '/brandonwamboldt/utilphp/src'),
);
+10
View File
@@ -0,0 +1,10 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'League\\Plates\\' => array($vendorDir . '/league/plates/src'),
);
+52
View File
@@ -0,0 +1,52 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit67b09c83b85c3bc0027caefe5bba171a
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit67b09c83b85c3bc0027caefe5bba171a', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit67b09c83b85c3bc0027caefe5bba171a', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
return $loader;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a
{
public static $prefixLengthsPsr4 = array (
'L' =>
array (
'League\\Plates\\' => 14,
),
);
public static $prefixDirsPsr4 = array (
'League\\Plates\\' =>
array (
0 => __DIR__ . '/..' . '/league/plates/src',
),
);
public static $prefixesPsr0 = array (
'u' =>
array (
'utilphp\\' =>
array (
0 => __DIR__ . '/..' . '/brandonwamboldt/utilphp/src',
),
),
);
public static $classMap = array (
'DB' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php',
'DBHelper' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php',
'DBTransaction' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php',
'MeekroDB' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php',
'MeekroDBEval' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php',
'MeekroDBException' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php',
'WhereClause' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$prefixesPsr0;
$loader->classMap = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$classMap;
}, null, ClassLoader::class);
}
}
+152
View File
@@ -0,0 +1,152 @@
[
{
"name": "brandonwamboldt/utilphp",
"version": "1.1.0",
"version_normalized": "1.1.0.0",
"source": {
"type": "git",
"url": "https://github.com/brandonwamboldt/utilphp.git",
"reference": "36c32efc4f0679c05163464a550f45c8d83fe683"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/brandonwamboldt/utilphp/zipball/36c32efc4f0679c05163464a550f45c8d83fe683",
"reference": "36c32efc4f0679c05163464a550f45c8d83fe683",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"satooshi/php-coveralls": "dev-master"
},
"time": "2015-02-02T17:56:14+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"utilphp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Brandon Wamboldt",
"email": "brandon.wamboldt@gmail.com"
}
],
"description": "util.php is a collection of useful functions and snippets that you need or could use every day, designed to avoid conflicts with existing projects",
"homepage": "https://github.com/brandonwamboldt/utilphp",
"keywords": [
"collection",
"helpers",
"php",
"utility"
]
},
{
"name": "league/plates",
"version": "3.3.0",
"version_normalized": "3.3.0.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/plates.git",
"reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/plates/zipball/b1684b6f127714497a0ef927ce42c0b44b45a8af",
"reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af",
"shasum": ""
},
"require": {
"php": "^5.3 | ^7.0"
},
"require-dev": {
"mikey179/vfsstream": "^1.4",
"phpunit/phpunit": "~4.0",
"squizlabs/php_codesniffer": "~1.5"
},
"time": "2016-12-28T00:14:17+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"League\\Plates\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jonathan Reinink",
"email": "jonathan@reinink.ca",
"role": "Developer"
}
],
"description": "Plates, the native PHP template system that's fast, easy to use and easy to extend.",
"homepage": "http://platesphp.com",
"keywords": [
"league",
"package",
"templates",
"templating",
"views"
]
},
{
"name": "sergeytsalkov/meekrodb",
"version": "v2.3",
"version_normalized": "2.3.0.0",
"source": {
"type": "git",
"url": "https://github.com/SergeyTsalkov/meekrodb.git",
"reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/SergeyTsalkov/meekrodb/zipball/eb36858f1aff94ae1665900e681a1cfb78563ee1",
"reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1",
"shasum": ""
},
"require": {
"php": ">=5.2.0"
},
"time": "2014-06-16T22:40:22+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"classmap": [
"db.class.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-3.0"
],
"authors": [
{
"name": "Sergey Tsalkov",
"email": "stsalkov@gmail.com"
}
],
"description": "The Simple PHP/MySQL Library",
"homepage": "http://www.meekro.com",
"keywords": [
"database",
"mysql",
"mysqli",
"pdo"
]
}
]
+22
View File
@@ -0,0 +1,22 @@
# Contributing
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/plates).
## Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow semver. Randomly breaking public APIs is not an option.
- **Create topic branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting.
## Running Tests
``` bash
$ phpunit
```
**Happy coding**!
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013 The League of Extraordinary Packages
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+63
View File
@@ -0,0 +1,63 @@
Plates
======
[![Author](http://img.shields.io/badge/author-@reinink-blue.svg?style=flat-square)](https://twitter.com/reinink)
[![Source Code](http://img.shields.io/badge/source-league/plates-blue.svg?style=flat-square)](https://github.com/thephpleague/plates)
[![Latest Version](https://img.shields.io/github/release/thephpleague/plates.svg?style=flat-square)](https://github.com/thephpleague/plates/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)
[![Build Status](https://img.shields.io/travis/thephpleague/plates/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/plates)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates)
[![Total Downloads](https://img.shields.io/packagist/dt/league/plates.svg?style=flat-square)](https://packagist.org/packages/league/plates)
Plates is a native PHP template system that's fast, easy to use and easy to extend. It's inspired by the excellent [Twig](http://twig.sensiolabs.org/) template engine and strives to bring modern template language functionality to native PHP templates. Plates is designed for developers who prefer to use native PHP templates over compiled template languages, such as Twig or Smarty.
### Highlights
- Native PHP templates, no new [syntax](http://platesphp.com/templates/syntax/) to learn
- Plates is a template system, not a template language
- Plates encourages the use of existing PHP functions
- Increase code reuse with template [layouts](http://platesphp.com/templates/layouts/) and [inheritance](http://platesphp.com/templates/inheritance/)
- Template [folders](http://platesphp.com/engine/folders/) for grouping templates into namespaces
- [Data](http://platesphp.com/templates/data/#preassigned-and-shared-data) sharing across templates
- Preassign [data](http://platesphp.com/templates/data/#preassigned-and-shared-data) to specific templates
- Built-in [escaping](http://platesphp.com/templates/escaping/) helpers
- Easy to extend using [functions](http://platesphp.com/engine/functions/) and [extensions](http://platesphp.com/engine/extensions/)
- Framework-agnostic, will work with any project
- Decoupled design makes templates easy to test
- Composer ready and PSR-2 compliant
## Installation
Plates is available via Composer:
```
composer require league/plates
```
## Documentation
Full documentation can be found at [platesphp.com](http://platesphp.com/).
## Testing
```bash
phpunit
```
## Contributing
Please see [CONTRIBUTING](https://github.com/thephpleague/plates/blob/master/CONTRIBUTING.md) for details.
## Security
If you discover any security related issues, please email jonathan@reinink.ca instead of using the issue tracker.
## Credits
- [Jonathan Reinink](https://github.com/reinink)
- [All Contributors](https://github.com/thephpleague/plates/contributors)
## License
The MIT License (MIT). Please see [License File](https://github.com/thephpleague/plates/blob/master/LICENSE) for more information.
+41
View File
@@ -0,0 +1,41 @@
{
"name": "league/plates",
"description": "Plates, the native PHP template system that's fast, easy to use and easy to extend.",
"keywords": [
"league",
"package",
"templating",
"templates",
"views"
],
"homepage": "http://platesphp.com",
"license": "MIT",
"authors" : [
{
"name": "Jonathan Reinink",
"email": "jonathan@reinink.ca",
"role": "Developer"
}
],
"require" : {
"php": "^5.3 | ^7.0"
},
"require-dev": {
"mikey179/vfsStream": "^1.4",
"phpunit/phpunit": "~4.0",
"squizlabs/php_codesniffer": "~1.5"
},
"autoload": {
"psr-4": {
"League\\Plates\\": "src"
}
},
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"scripts": {
"test": "phpunit"
}
}
+1
View File
@@ -0,0 +1 @@
platesphp.com
+8
View File
@@ -0,0 +1,8 @@
# Path to project specific favicon.ico, leave blank to use default
favicon: /favicon.ico
# Path to project specific apple-touch-icon-precomposed.png, leave blank to use default
apple_touch: /apple-touch-icon-precomposed.png
# Path to project logo
logo: /logo.png
+24
View File
@@ -0,0 +1,24 @@
Getting Started:
Introduction: '/'
Simple example: '/simple-example/'
Installation: '/installation/'
Changelog: '/changelog/'
The Engine:
Overview: '/engine/'
File extensions: '/engine/file-extensions/'
Folders: '/engine/folders/'
Functions: '/engine/functions/'
Extensions: '/engine/extensions/'
Templates:
Overview: '/templates/'
Data: '/templates/data/'
Functions: '/templates/functions/'
Nesting: '/templates/nesting/'
Layouts: '/templates/layouts/'
Sections: '/templates/sections/'
Inheritance: '/templates/inheritance/'
Escaping: '/templates/escaping/'
Syntax: '/templates/syntax/'
Extensions:
Asset: '/extensions/asset/'
URI: '/extensions/uri/'
+4
View File
@@ -0,0 +1,4 @@
title: Plates
tagline: Native PHP Templates
description: 'Plates is a Twig inspired, native PHP template system that brings modern template language functionality to native PHP templates.'
google_analytics_tracking_id: UA-46050814-2
+107
View File
@@ -0,0 +1,107 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% if page.url == '/' %}
<title>{{ site.data.project.title }} - {{ site.data.project.tagline }}</title>
{% else %}
<title>{{ page.title }} - {{ site.data.project.title }}</title>
{% endif %}
{% if site.data.project.description %}
<meta name="description" content="{{ site.data.project.description }}">
{% endif %}
{% if site.github.url %}
<base href="{{ site.github.url }}">
{% endif %}
{% if site.data.images.favicon %}
<link rel="icon" type="image/x-icon" href="{{ site.data.images.favicon }}" />
{% else %}
<link rel="icon" type="image/x-icon" href="http://theme.thephpleague.com/img/favicon.ico" />
{% endif %}
{% if site.data.images.apple_touch %}
<link rel="apple-touch-icon-precomposed" href="{{ site.data.images.apple_touch }}">
{% else %}
<link rel="apple-touch-icon-precomposed" href="http://theme.thephpleague.com/img/apple-touch-icon-precomposed.png">
{% endif %}
<link rel="stylesheet" href="http://theme.thephpleague.com/css/all.css">
<link rel="stylesheet" href="/css/custom.css">
</head>
<body>
<a href="https://github.com/thephpleague/plates" class="github">
<img src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png">
</a>
<section class="all_packages">
<a href="http://thephpleague.com/">
<img src="http://theme.thephpleague.com/img/loep_logo.png" width="195" height="200" alt="The League of Extraordinary Packages">
</a>
<h2>Our Packages:</h2>
<ul>
<!-- Loaded via JavaScript -->
</ul>
</section>
<header>
<a class="logo" href="/">
{% if site.data.images.logo %}
<span class="icon">
<img src="{{ site.data.images.logo }}" width="50" height="40" alt="{{ site.data.project.title }} - {{ site.data.project.tagline }}">
</span>
{% endif %}
<span class="name">{{ site.data.project.title }}</span>
<span class="tagline">{{ site.data.project.tagline }}</span>
</a>
<a href="http://thephpleague.com/" class="league">
Presented by The League of Extraordinary Packages
</a>
</header>
<input type="checkbox" id="menu">
<label for="menu" onclick>
<div class="closed">&#9776; Menu</div>
<div class="open">&#9776; Hide Menu</div>
</label>
<main>
<menu>
{% for section in site.data.menu %}
<h2>{{ section[0] }}</h2>
<ul>
{% for link in section[1] %}
<li {% if page.url == link[1] %}class="selected"{% endif %}>
<a href="{{ link[1] }}">{{ link[0] }}</a>
</li>
{% endfor %}
</ul>
{% endfor %}
</menu>
<article>
{{ content }}
</article>
</main>
<footer>
<span>&copy; Copyright <a href="http://thephpleague.com">The League of Extraordinary Packages</a>.</span>
<span>Site design by <a href="http://reinink.ca">Jonathan Reinink</a>.</span>
</footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://theme.thephpleague.com/js/scripts.js"></script>
<script src="http://theme.thephpleague.com/js/prism.js"></script>
{% if site.data.project.google_analytics_tracking_id %}
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','{{ site.data.project.google_analytics_tracking_id }}');ga('send','pageview');
</script>
{% endif %}
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

+15
View File
@@ -0,0 +1,15 @@
---
layout: default
permalink: changelog/
title: Changelog
---
Changelog
=========
All notable changes to this project will be documented in this file.
{% for release in site.github.releases %}
## [{{ release.name }}]({{ release.html_url }}) - {{ release.published_at | date: "%Y-%m-%d" }}
{{ release.body | markdownify }}
{% endfor %}
+16
View File
@@ -0,0 +1,16 @@
---
---
.github {
position: absolute;
top: 0;
right: 0;
border: 0;
z-index: 1000;
}
@media screen and (max-width: 1065px) {
.github {
display: none;
}
}
+120
View File
@@ -0,0 +1,120 @@
---
layout: default
permalink: engine/extensions/
title: Extensions
---
Extensions
==========
Creating extensions couldn't be easier, and can really make Plates sing for your specific project. Start by creating a class that implements `\League\Plates\Extension\ExtensionInterface`. Next, register your template [functions](/engine/functions/) within a `register()` method.
## Simple extensions example
~~~ php
use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;
class ChangeCase implements ExtensionInterface
{
public function register(Engine $engine)
{
$engine->registerFunction('uppercase', [$this, 'uppercaseString']);
$engine->registerFunction('lowercase', [$this, 'lowercaseString']);
}
public function uppercaseString($var)
{
return strtoupper($var);
}
public function lowercaseString($var)
{
return strtolower($var);
}
}
~~~
To use this extension in your template, simply call your new functions:
~~~ php
<p>Hello, <?=$this->e($this->uppercase($name))?></p>
~~~
They can also be used in a [batch](/templates/functions/#batch-function-calls) compatible function:
~~~ php
<h1>Hello <?=$this->e($name, 'uppercase')</h1>
~~~
## Single method extensions
Alternatively, you may choose to expose the entire extension object to the template using a single function. This can make your templates more legible and also reduce the chance of conflicts with other extensions.
~~~ php
use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;
class ChangeCase implements ExtensionInterface
{
public function register(Engine $engine)
{
$engine->registerFunction('case', [$this, 'getObject']);
}
public function getObject()
{
return $this;
}
public function upper($var)
{
return strtoupper($var);
}
public function lower($var)
{
return strtolower($var);
}
}
~~~
To use this extension in your template, first call the primary function, then the secondary functions:
~~~ php
<p>Hello, <?=$this->e($this->case()->upper($name))?></p>
~~~
## Loading extensions
To enable an extension, load it into the [engine](/engine/) object using the `loadExtension()` method.
~~~ php
$engine->loadExtension(new ChangeCase());
~~~
## Accessing the engine and template
It may be desirable to access the `engine` or `template` objects from within your extension. Plates makes both of these objects available to you. The engine is automatically passed to the `register()` method, and the template is assigned as a parameter on each function call.
~~~ php
use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;
class MyExtension implements ExtensionInterface
{
protected $engine;
public $template; // must be public
public function register(Engine $engine)
{
$this->engine = $engine;
// Access template data:
$data = $this->template->data();
// Register functions
// ...
}
}
~~~
+36
View File
@@ -0,0 +1,36 @@
---
layout: default
permalink: engine/file-extensions/
title: File extensions
---
File extensions
===============
Plates does not enforce a specific template file extension. By default it assumes `.php`. This file extension is automatically appended to your template names when rendered. You are welcome to change the default extension using one of the following methods.
## Constructor method
~~~ php
// Create new engine and set the default file extension to ".tpl"
$template = new League\Plates\Engine('/path/to/templates', 'tpl');
~~~
## Setter method
~~~ php
// Sets the default file extension to ".tpl" after engine instantiation
$template->setFileExtension('tpl');
~~~
## Manually assign
If you prefer to manually set the file extension, simply set the default file extension to `null`.
~~~ php
// Disable automatic file extensions
$template->setFileExtension(null);
// Render template
echo $templates->render('home.php');
~~~
+50
View File
@@ -0,0 +1,50 @@
---
layout: default
permalink: engine/folders/
title: Folders
---
Folders
=======
Folders make it really easy to organize and access your templates. Folders allow you to group your templates under different namespaces, each of which having their own file system path.
## Creating folders
To create folders, use the `addFolder()` method:
~~~ php
// Create new Plates instance
$templates = new League\Plates\Engine();
// Add folders
$templates->addFolder('admin', '/path/to/admin/templates');
$templates->addFolder('emails', '/path/to/email/templates');
~~~
## Using folders
To use the folders you created within your project simply append the folder name with two colons before the template name. For example, to render a welcome email:
~~~ php
$email = $templates->render('emails::welcome');
~~~
This works with template functions as well, such as layouts or nested templates. For example:
~~~ php
<?php $this->layout('shared::template') ?>
~~~
## Folder fallbacks
When enabled, if a folder template is missing, Plates will automatically fallback and look for a template with the **same** name in the default folder. This can be helpful when using folders to manage themes. To enable fallbacks, simply pass `true` as the third parameter in the `addFolders()` method.
~~~ php
// Create new Plates engine
$templates = new \League\Plates\Engine('/path/to/default/theme');
// Add themes
$templates->addFolder('theme1', '/path/to/theme/1', true);
$templates->addFolder('theme2', '/path/to/theme/2', true);
~~~
+34
View File
@@ -0,0 +1,34 @@
---
layout: default
permalink: engine/functions/
title: Functions
---
Functions
=========
While [extensions](/engine/extensions/) are awesome for adding additional reusable functionality to Plates, sometimes it's easier to just create a one-off function for a specific use case. Plates makes this easy to do.
## Registering functions
~~~ php
// Create new Plates engine
$templates = new \League\Plates\Engine('/path/to/templates');
// Register a one-off function
$templates->registerFunction('uppercase', function ($string) {
return strtoupper($string);
});
~~~
To use this function in a template, simply call it like any other function:
~~~ php
<h1>Hello <?=$this->e($this->uppercase($name))</h1>
~~~
It can also be used in a [batch](/templates/functions/#batch-function-calls) compatible function:
~~~ php
<h1>Hello <?=$this->e($name, 'uppercase')</h1>
~~~
+56
View File
@@ -0,0 +1,56 @@
---
layout: default
permalink: engine/
title: The Engine
---
The Engine
==========
Plates uses a central object called the `Engine`, which is used to store the environment configuration, functions and extensions. It helps decouple your templates from the file system and other dependencies. For example, if you want to change the folder where your templates are stored, you can do so by simply changing the path in one location.
## Basic usage
~~~ php
// Create new Plates engine
$templates = new League\Plates\Engine('/path/to/templates');
// Add any any additional folders
$templates->addFolder('emails', '/path/to/emails');
// Load any additional extensions
$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public'));
// Create a new template
$template = $templates->make('emails::welcome');
~~~
## Dependency Injection
Plates is designed to be easily passed around your application and easily injected in your controllers or other application objects. Simply pass an instance of the `Engine` to any consuming objects, and then use either the `make()` method to create a new template, or the `render()` method to render it immediately. For example:
~~~ php
class Controller
{
private $templates;
public function __construct(League\Plates\Engine $templates)
{
$this->templates = $templates;
}
// Create a template object
public function getIndex()
{
$template = $this->templates->make('home');
return $template->render();
}
// Render a template directly
public function getIndex()
{
return $this->templates->render('home');
}
}
~~~
+59
View File
@@ -0,0 +1,59 @@
---
layout: default
permalink: extensions/asset/
title: Asset extension
---
Asset
=====
The asset extension can be used to quickly create "cache busted" asset URLs in your templates. This is particularly helpful for aggressively cached files that can potentially change in the future, such as CSS files, JavaScript files and images. It works by appending the timestamp of the file's last update to its URL. For example, `/css/all.css` becomes `/css/all.1373577602.css`. As long as the file does not change, the timestamp remains the same and caching occurs. However, if the file is changed, a new URL is automatically generated with a new timestamp, and visitors receive the new file.
## Installing the asset extension
The asset extension comes packaged with Plates but is not enabled by default, as it requires extra parameters passed to it at instantiation.
~~~ php
// Load asset extension
$engine->loadExtension(new League\Plates\Extension\Asset('/path/to/public/assets/', true));
~~~
The first constructor parameter is the file system path of the assets directory. The second is an optional `boolean` parameter that if set to true uses the filename caching method (ie. `file.1373577602.css`) instead of the default query string method (ie. `file.css?v=1373577602`).
## Filename caching
To make filename caching work, some URL rewriting is required:
### Apache example
~~~ php
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
</IfModule>
~~~
### Nginx example
~~~ php
location ~* (.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$ {
try_files $uri $1.$2;
}
~~~
## Using the asset extension
~~~ php
<html>
<head>
<title>Asset Extension Example</title>
<link rel="stylesheet" href="<?=$this->asset('/css/all.css')?>" />
</head>
<body>
<img src="<?=$this->asset('/img/logo.png')?>">
</body>
</html>
~~~
+83
View File
@@ -0,0 +1,83 @@
---
layout: default
permalink: extensions/uri/
title: URI extension
---
URI
===
The URI extension is designed to make URI checks within templates easier. The most common use is marking the current page in a menu as "selected". It only has one function, `uri()`, but can do a number of helpful tasks depending on the parameters passed to it.
## Installing the URI extension
The URI extension comes packaged with Plates but is not enabled by default, as it requires an extra parameter passed to it at instantiation.
~~~ php
// Load URI extension using global variable
$engine->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO']));
// Load URI extension using a HttpFoundation's request object
$engine->loadExtension(new League\Plates\Extension\URI($request->getPathInfo()));
~~~
## URI example
~~~ php
<ul>
<li <?=$this->uri('/', 'class="selected"')?>><a href="/">Home</a></li>
<li <?=$this->uri('/about', 'class="selected"')?>><a href="/about">About</a></li>
<li <?=$this->uri('/products', 'class="selected"')?>><a href="/products">Products</a></li>
<li <?=$this->uri('/contact', 'class="selected"')?>><a href="/contact">Contact</a></li>
</ul>
~~~
## Using the URI extension
Get the whole URI.
~~~ php
<?=$this->uri()?>
~~~
Get a specified segment of the URI.
~~~ php
<?=$this->uri(1)?>
~~~
Check if a specific segment of the URI (first parameter) equals a given string (second parameter). Returns `true` on success or `false` on failure.
~~~ php
<?php if ($this->uri(1, 'home')): ?>
~~~
Check if a specific segment of the URI (first parameter) equals a given string (second parameter). Returns string (third parameter) on success or `false` on failure.
~~~ php
<?=$this->uri(1, 'home', 'success')?>
~~~
Check if a specific segment of the URI (first parameter) equals a given string (second parameter). Returns string (third parameter) on success or string (fourth parameter) on failure.
~~~ php
<?=$this->uri(1, 'home', 'success', 'fail')?>
~~~
Check if a regular expression string matches the current URI. Returns `true` on success or `false` on failure.
~~~ php
<?php if($this->uri('/home')): ?>
~~~
Check if a regular expression string (first parameter) matches the current URI. Returns string (second parameter) on success or `false` on failure.
~~~ php
<?=$this->uri('/home', 'success')?>
~~~
Check if a regular expression string (first parameter) matches the current URI. Returns string (second parameter) on success or string (third parameter) on failure.
~~~ php
<?=$this->uri('/home', 'success', 'fail')?>
~~~
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

+40
View File
@@ -0,0 +1,40 @@
---
layout: default
permalink: /
title: Introduction
---
Introduction
============
[![Author](http://img.shields.io/badge/author-@reinink-blue.svg?style=flat-square)](https://twitter.com/reinink)
[![Source Code](http://img.shields.io/badge/source-league/plates-blue.svg?style=flat-square)](https://github.com/thephpleague/plates)
[![Latest Version](https://img.shields.io/github/release/thephpleague/plates.svg?style=flat-square)](https://github.com/thephpleague/plates/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/thephpleague/plates/blob/master/LICENSE)<br />
[![Build Status](https://img.shields.io/travis/thephpleague/plates/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/plates)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates)
[![Total Downloads](https://img.shields.io/packagist/dt/league/plates.svg?style=flat-square)](https://packagist.org/packages/league/plates)
## About
Plates is a native PHP template system that's fast, easy to use and easy to extend. It's inspired by the excellent [Twig](http://twig.sensiolabs.org/) template engine and strives to bring modern template language functionality to native PHP templates. Plates is designed for developers who prefer to use native PHP templates over compiled template languages, such as Twig or Smarty.
## Highlights
- Native PHP templates, no new [syntax](/templates/syntax/) to learn
- Plates is a template system, not a template language
- Plates encourages the use of existing PHP functions
- Increase code reuse with template [layouts](/templates/layouts/) and [inheritance](/templates/inheritance/)
- Template [folders](/engine/folders/) for grouping templates into namespaces
- [Data](/templates/data/#preassigned-and-shared-data) sharing across templates
- Preassign [data](/templates/data/#preassigned-and-shared-data) to specific templates
- Built-in [escaping](/templates/escaping/) helpers
- Easy to extend using [functions](/engine/functions/) and [extensions](/engine/extensions/)
- Framework-agnostic, will work with any project
- Decoupled design makes templates easy to test
- Composer ready and PSR-2 compliant
## Questions?
Plates was created by [Jonathan Reinink](https://twitter.com/reinink). Submit issues to [Github](https://github.com/thephpleague/plates/issues).
+35
View File
@@ -0,0 +1,35 @@
---
layout: default
permalink: installation/
title: Installation
---
Installation
============
## Using Composer
Plates is available on [Packagist](https://packagist.org/packages/league/plates) and can be installed using [Composer](https://getcomposer.org/). This can be done by running the following command or by updating your `composer.json` file.
~~~ bash
composer require league/plates
~~~
<div class="filename">composer.json</div>
~~~ javascript
{
"require": {
"league/plates": "3.*"
}
}
~~~
Be sure to also include your Composer autoload file in your project:
~~~ php
require 'vendor/autoload.php';
~~~
## Downloading .zip file
This project is also available for download as a `.zip` file on GitHub. Visit the [releases page](https://github.com/thephpleague/plates/releases), select the version you want, and click the "Source code (zip)" download button.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

+54
View File
@@ -0,0 +1,54 @@
---
layout: default
permalink: simple-example/
title: Simple example
---
Simple example
==============
Here is a simple example of how to use Plates. We will assume the following directory stucture:
~~~
`-- path
`-- to
`-- templates
|-- template.php
|-- profile.php
~~~
## Within your controller
~~~ php
// Create new Plates instance
$templates = new League\Plates\Engine('/path/to/templates');
// Render a template
echo $templates->render('profile', ['name' => 'Jonathan']);
~~~
## The page template
<div class="filename">profile.php</div>
~~~ php
<?php $this->layout('template', ['title' => 'User Profile']) ?>
<h1>User Profile</h1>
<p>Hello, <?=$this->e($name)?></p>
~~~
## The layout template
<div class="filename">template.php</div>
~~~ php
<html>
<head>
<title><?=$this->e($title)?></title>
</head>
<body>
<?=$this->section('content')?>
</body>
</html>
~~~
+61
View File
@@ -0,0 +1,61 @@
---
layout: default
permalink: templates/data/
title: Data
---
Data
====
It's very common to share application data (variables) with a template. Data can be whatever you want: strings, arrays, objects, etc. Plates allows you set both template specific data as well as shared template data.
## Assign data
Assigning data is done from within your application code, such as a controller. There are a number of ways to assign the data, depending on how you structure your objects.
~~~ php
// Create new Plates instance
$templates = new League\Plates\Engine('/path/to/templates');
// Assign via the engine's render method
echo $templates->render('profile', ['name' => 'Jonathan']);
// Assign via the engine's make method
$template = $templates->make('profile', ['name' => 'Jonathan']);
// Assign directly to a template object
$template = $templates->make('profile');
$template->data(['name' => 'Jonathan']);
~~~
## Accessing data
Template data is available as locally scoped variables at the time of rendering. Continuing with the example above, here is how you would [escape](/templates/escaping/) and output the "name" value in a template:
~~~ php
<p>Hello <?=$this->e($name)?></p>
~~~
<p class="message-notice">Prior to Plates 3.0, variables were accessed using the <code>$this</code> pseudo-variable. This is no longer possible. Use the locally scoped variables instead.</p>
## Preassigned and shared data
If you have data that you want assigned to a specific template each time that template is rendered throughout your application, the `addData()` function can help organize that code in one place.
~~~ php
$templates->addData(['name' => 'Jonathan'], 'emails::welcome');
~~~
You can pressaign data to more than one template by passing an array of templates:
~~~ php
$templates->addData(['name' => 'Jonathan'], ['login', 'template']);
~~~
To assign data to ALL templates, simply omit the second parameter:
~~~ php
$templates->addData(['name' => 'Jonathan']);
~~~
Keep in mind that shared data is assigned to a template when it's first created, meaning any conflicting data assigned that's afterwards to a specific template will overwrite the shared data. This is generally desired behavior.
+50
View File
@@ -0,0 +1,50 @@
---
layout: default
permalink: templates/escaping/
title: Escaping
---
Escaping
========
Escaping is a form of [data filtering](http://www.phptherightway.com/#data_filtering) which sanitizes unsafe, user supplied input prior to outputting it as HTML. Plates provides two shortcuts to the `htmlspecialchars()` function.
## Escaping example
~~~ php
<h1>Hello, <?=$this->escape($name)?></h1>
<!-- Using the alternative, shorthand function -->
<h1>Hello, <?=$this->e($name)?></h1>
~~~
## Batch function calls
The escape functions also support [batch](/templates/functions/#batch-function-calls) function calls, which allow you to apply multiple functions, including native PHP functions, to a variable at one time.
~~~ php
<p>Welcome <?=$this->e($name, 'strip_tags|strtoupper')?></p>
~~~
## Escaping HTML attributes
<p class="message-notice">It's VERY important to always double quote HTML attributes that contain escaped variables, otherwise your template will still be open to injection attacks.</p>
Some [libraries](http://framework.zend.com/manual/2.1/en/modules/zend.escaper.escaping-html-attributes.html) go as far as having a special function for escaping HTML attributes. However, this is somewhat redundant considering that if a developer forgets to properly quote an HTML attribute, they will likely also forget to use this special function. Here is how you properly escape HTML attributes:
~~~ php
<!-- Good -->
<img src="portrait.jpg" alt="<?=$this->e($name)?>">
<!-- BAD -->
<img src="portrait.jpg" alt='<?=$this->e($name)?>'>
<!-- BAD -->
<img src="portrait.jpg" alt=<?=$this->e($name)?>>
~~~
## Automatic escaping
Probably the biggest drawbacks to native PHP templates is the inability to auto-escape variables properly. Template languages like Twig and Smarty can identify "echoed" variables during a parsing stage and automatically escape them. This cannot be done in native PHP as the language does not offer overloading functionality for it's output functions (ie. `print` and `echo`).
Don't worry, escaping can still be done safely, it just means you are responsible for manually escaping each variable on output. Consider creating a snippet for one of the above, built-in escaping functions to make this process easier.
+47
View File
@@ -0,0 +1,47 @@
---
layout: default
permalink: templates/functions/
title: Functions
---
Functions
=========
Template functions in Plates are accessed using the `$this` pseudo-variable.
~~~ php
<p>Hello, <?=$this->escape($name)?></p>
~~~
## Custom fuctions
In addition to the functions included with Plates, it's also possible to add [one-off functions](/engine/functions/), or even groups of functions, known as [extensions](/engine/extensions/).
## Batch function calls
Sometimes you need to apply more than function to a variable in your templates. This can become somewhat illegible. The `batch()` function helps by allowing you to apply multiple functions, including native PHP functions, to a variable at one time.
~~~ php
<!-- Example without using batch -->
<p>Welcome <?=$this->escape(strtoupper(strip_tags($name)))?></p>
<!-- Example using batch -->
<p>Welcome <?=$this->batch($name, 'strip_tags|strtoupper|escape')?></p>
~~~
The [escape](/templates/escaping/) functions also support batch function calls.
~~~ php
<p>Welcome <?=$this->e($name, 'strip_tags|strtoupper')?></p>
~~~
The batch functions works well for "piped" functions that accept one parameter, modify it, and then return it. It's important to note that they execute functions left to right and will favour extension functions over native PHP functions if there are conflicts.
~~~ php
<!-- Will output: JONATHAN -->
<?=$this->batch('Jonathan', 'escape|strtolower|strtoupper')?>
<!-- Will output: jonathan -->
<?=$this->batch('Jonathan', 'escape|strtoupper|strtolower')?>
~~~
+73
View File
@@ -0,0 +1,73 @@
---
layout: default
permalink: templates/
title: Templates
---
Templates
=========
Plates templates are very simple PHP objects. Generally you'll want to create these using the two factory methods, `make()` and `render()`, in the [engine](/engine/). For example:
~~~ php
// Create new Plates instance
$templates = new League\Plates\Engine('/path/to/templates');
// Render a template in a subdirectory
echo $templates->render('partials/header');
// Render a template
echo $templates->render('profile', ['name' => 'Jonathan']);
~~~
For more information about how Plates is designed to be easily added to your application, see the section on [dependency injection](/engine/#dependency-injection).
## Manually creating templates
It's also possible to create templates manually. The only dependency they require is an instance of the [engine](/engine/) object. For example:
~~~ php
// Create new Plates instance
$templates = new League\Plates\Engine('/path/to/templates');
// Create a new template
$template = new League\Plates\Template\Template($templates, 'profile');
// Render the template
echo $template->render(['name' => 'Jonathan']);
// You can also render the template using the toString() magic method
echo $template;
~~~
## Check if a template exists
When dynamically loading templates, you may need to check if they exist. This can be done using the engine's `exists()` method:
~~~ php
if ($templates->exists('articles::beginners_guide')) {
// It exists!
}
~~~
You can also run this check on an existing template:
~~~ php
if ($template->exists()) {
// It exists!
}
~~~
## Get a template path
To get a template path from its name, use the engine's `path()` method:
~~~ php
$path = $templates->path('articles::beginners_guide');
~~~
You can also get the path from an existing template:
~~~ php
$path = $template->path();
~~~
+63
View File
@@ -0,0 +1,63 @@
---
layout: default
permalink: templates/inheritance/
title: Inheritance
---
Inheritance
===========
By combining [layouts](/templates/layouts/) and [sections](/templates/sections/), Plates allows you to "build up" your pages using predefined sections. This is best understand using an example:
## Inheritance example
The following example illustrates a pretty standard website. Start by creating a site template, which includes your header and footer as well as any predefined content [sections](/templates/sections/). Notice how Plates makes it possible to even set default section content, in the event that a page doesn't define it.
<div class="filename">template.php</div>
~~~ php
<html>
<head>
<title><?=$this->e($title)?></title>
</head>
<body>
<img src="logo.png">
<div id="page">
<?=$this->section('page')?>
</div>
<div id="sidebar">
<?php if ($this->section('sidebar')): ?>
<?=$this->section('sidebar')?>
<?php else: ?>
<?=$this->fetch('default-sidebar')?>
<?php endif ?>
</div>
</body>
</html>
~~~
With the template defined, any page can now "implement" this [layout](/templates/layouts/). Notice how each section of content is defined between the `start()` and `end()` functions.
<div class="filename">profile.php</div>
~~~ php
<?php $this->layout('template', ['title' => 'User Profile']) ?>
<?php $this->start('page') ?>
<h1>Welcome!</h1>
<p>Hello <?=$this->e($name)?></p>
<?php $this->stop() ?>
<?php $this->start('sidebar') ?>
<ul>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
</ul>
<?php $this->stop() ?>
~~~
+102
View File
@@ -0,0 +1,102 @@
---
layout: default
permalink: templates/layouts/
title: Layouts
---
Layouts
=======
The `layout()` function allows you to define a layout template that a template will implement. It's like having separate header and footer templates in one file.
## Define a layout
The `layout()` function can be called anywhere in a template, since the layout template is actually rendered second. Typically it's placed at the top of the file.
~~~ php
<?php $this->layout('template') ?>
<h1>User Profile</h1>
<p>Hello, <?=$this->e($name)?></p>
~~~
This function also works with [folders](/engine/folders/):
~~~ php
<?php $this->layout('shared::template') ?>
~~~
## Assign data
To assign data (variables) to a layout template, pass them as an array to the `layout()` function. This data will then be available as locally scoped variables within the layout template.
~~~ php
<?php $this->layout('template', ['title' => 'User Profile']) ?>
~~~
## Accessing the content
To access the rendered template content within the layout, use the `section()` function, passing `'content'` as the section name. This will return all outputted content from the template that hasn't been defined in a [section](/templates/sections/).
~~~ php
<html>
<head>
<title><?=$this->e($title)?></title>
</head>
<body>
<?=$this->section('content')?>
</body>
</html>
~~~
## Stacked layouts
Plates allows stacking of layouts, allowing even further simplification and organization of templates. Instead of just using one main layout, it's possible to break templates into more specific layouts, which themselves implement a main layout. Consider this example:
### The main site layout
<div class="filename">template.php</div>
~~~ php
<html>
<head>
<title><?=$this->e($title)?></title>
</head>
<body>
<?=$this->section('content')?>
</body>
</html>
~~~
### The blog layout
<div class="filename">blog.php</div>
~~~ php
<?php $this->layout('template') ?>
<h1>The Blog</h1>
<section>
<article>
<?=$this->section('content')?>
</article>
<aside>
<?=$this->insert('blog/sidebar')?>
</aside>
</section>
~~~
### A blog article
<div class="filename">blog-article.php</div>
~~~ php
<?php $this->layout('blog', ['title' => $article->title]) ?>
<h2><?=$this->e($article->title)?></h2>
<article>
<?=$this->e($article->content)?>
</article>
~~~
+44
View File
@@ -0,0 +1,44 @@
---
layout: default
permalink: templates/nesting/
title: Nesting
---
Nesting
=======
Including another template into the current template is done using the `insert()` function:
~~~ php
<?php $this->insert('partials/header') ?>
<p>Your content.</p>
<?php $this->insert('partials/footer') ?>
~~~
The `insert()` function also works with [folders](/engine/folders/):
~~~ php
<?php $this->insert('partials::header') ?>
~~~
## Alternative syntax
The `insert()` function automatically outputs the rendered template. If you prefer to manually output the response, use the `fetch()` function instead:
~~~ php
<?=$this->fetch('partials/header')?>
~~~
## Assign data
To assign data (variables) to a nested template, pass them as an array to the `insert()` or `fetch()` functions. This data will then be available as locally scoped variables within the nested template.
~~~ php
<?php $this->insert('partials/header', ['name' => 'Jonathan']) ?>
<p>Your content.</p>
<?php $this->insert('partials/footer') ?>
~~~
+80
View File
@@ -0,0 +1,80 @@
---
layout: default
permalink: templates/sections/
title: Sections
---
Sections
========
The `start()` and `stop` functions allow you to build sections (or blocks) of content within your template, and instead of them being rendered directly, they are saved for use elsewhere. For example, in your [layout](/templates/layouts/) template.
## Creating sections
You define the name of the section with the `start()` function. To end a section call the `stop()` function.
~~~ php
<?php $this->start('welcome') ?>
<h1>Welcome!</h1>
<p>Hello <?=$this->e($name)?></p>
<?php $this->stop() ?>
~~~
## Stacking section content
By default, when you render a section its content will overwrite any existing content for that section. However, it's possible to append (or stack) the content instead using the `push()` method. This can be useful for specifying any JavaScript libraries required by your child views.
~~~ php
<?php $this->push('scripts') ?>
<script src="example.js"></script>
<?php $this->end() ?>
~~~
<p class="message-notice">The <code>end()</code> function is simply an alias of <code>stop()</code>. These functions can be used interchangeably.</p>
## Accessing section content
Access rendered section content using the name you assigned in the `start()` method. This variable can be accessed from the current template and layout templates using the `section()` function.
~~~ php
<?=$this->section('welcome')?>
~~~
<p class="message-notice">Prior to Plates 3.0, accessing template content was done using either the <code>content()</code> or <code>child()</code> functions. For consistency with sections, this is no longer possible.</p>
## Default section content
In situations where a page doesn't implement a particular section, it's helpful to assign default content. There are a couple ways to do this:
### Defining it inline
If the default content can be defined in a single line of code, it's best to simply pass it as the second parameter of the `content()` function.
~~~ php
<div id="sidebar">
<?=$this->section('sidebar', $this->fetch('default-sidebar')?>
</div>
~~~
### Use an if statement
If the default content requires more than a single line of code, it's best to use a simple if statement to check if a section exists, and otherwise display the default.
~~~ php
<div id="sidebar">
<?php if ($this->section('sidebar')): ?>
<?=$this->section('sidebar')?>
<?php else: ?>
<ul>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
<li><a href="/link">Example Link</a></li>
</ul>
<?php endif ?>
</div>
~~~
+50
View File
@@ -0,0 +1,50 @@
---
layout: default
permalink: templates/syntax/
title: Syntax
---
Syntax
======
While the actual syntax you use in your templates is entirely your choice (it's just PHP after all), we suggest the following syntax guidelines to help keep templates clean and legible.
## Guidelines
- Always use HTML with inline PHP. Never use blocks of PHP.
- Always escape potentially dangerous variables prior to outputting using the built-in escape functions. More on escaping [here](/templates/escaping/).
- Always use the short echo syntax (`<?=`) when outputting variables. For all other inline PHP code, use full the `<?php` tag. Do not use [short tags](http://us3.php.net/manual/en/ini.core.php#ini.short-open-tag).
- Always use the [alternative syntax for control structures](http://php.net/manual/en/control-structures.alternative-syntax.php), which are designed to make templates more legible.
- Never use PHP curly brackets.
- Only ever have one statement in each PHP tag.
- Avoid using semicolons. They are not needed when there is only one statement per PHP tag.
- Never use the `use` operator. Templates should not be interacting with classes in this way.
- Never use the `for`, `while` or `switch` control structures. Instead use `if` and `foreach`.
- Avoid variable assignment.
## Syntax example
Here is an example of a template that complies with the above syntax rules.
~~~ php
<?php $this->layout('template', ['title' => 'User Profile']) ?>
<h1>Welcome!</h1>
<p>Hello <?=$this->e($name)?></p>
<h2>Friends</h2>
<ul>
<?php foreach($friends as $friend): ?>
<li>
<a href="/profile/<?=$this->e($friend->id)?>">
<?=$this->e($friend->name)?>
</a>
</li>
<?php endforeach ?>
</ul>
<?php if ($invitations): ?>
<h2>Invitations</h2>
<p>You have some friend invites!</p>
<?php endif ?>
~~~
+12
View File
@@ -0,0 +1,12 @@
<?php
include '../vendor/autoload.php';
// Create new Plates instance
$templates = new League\Plates\Engine('templates');
// Preassign data to the layout
$templates->addData(['company' => 'The Company Name'], 'layout');
// Render a template
echo $templates->render('profile', ['name' => 'Jonathan']);
+12
View File
@@ -0,0 +1,12 @@
<html>
<head>
<title><?=$this->e($title)?> | <?=$this->e($company)?></title>
</head>
<body>
<?=$this->section('content')?>
<?=$this->section('scripts')?>
</body>
</html>
+12
View File
@@ -0,0 +1,12 @@
<?php $this->layout('layout', ['title' => 'User Profile']) ?>
<h1>User Profile</h1>
<p>Hello, <?=$this->e($name)?>!</p>
<?php $this->insert('sidebar') ?>
<?php $this->push('scripts') ?>
<script>
// Some JavaScript
</script>
<?php $this->end() ?>
+6
View File
@@ -0,0 +1,6 @@
<ul>
<li><a href="#link">Example sidebar link</a></li>
<li><a href="#link">Example sidebar link</a></li>
<li><a href="#link">Example sidebar link</a></li>
<li><a href="#link">Example sidebar link</a></li>
</ul>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="all">
<directory suffix="Test.php">tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<logging>
<log type="tap" target="build/report.tap"/>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage" charset="UTF-8" yui="true" highlight="true"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
+279
View File
@@ -0,0 +1,279 @@
<?php
namespace League\Plates;
use League\Plates\Extension\ExtensionInterface;
use League\Plates\Template\Data;
use League\Plates\Template\Directory;
use League\Plates\Template\FileExtension;
use League\Plates\Template\Folders;
use League\Plates\Template\Func;
use League\Plates\Template\Functions;
use League\Plates\Template\Name;
use League\Plates\Template\Template;
/**
* Template API and environment settings storage.
*/
class Engine
{
/**
* Default template directory.
* @var Directory
*/
protected $directory;
/**
* Template file extension.
* @var FileExtension
*/
protected $fileExtension;
/**
* Collection of template folders.
* @var Folders
*/
protected $folders;
/**
* Collection of template functions.
* @var Functions
*/
protected $functions;
/**
* Collection of preassigned template data.
* @var Data
*/
protected $data;
/**
* Create new Engine instance.
* @param string $directory
* @param string $fileExtension
*/
public function __construct($directory = null, $fileExtension = 'php')
{
$this->directory = new Directory($directory);
$this->fileExtension = new FileExtension($fileExtension);
$this->folders = new Folders();
$this->functions = new Functions();
$this->data = new Data();
}
/**
* Set path to templates directory.
* @param string|null $directory Pass null to disable the default directory.
* @return Engine
*/
public function setDirectory($directory)
{
$this->directory->set($directory);
return $this;
}
/**
* Get path to templates directory.
* @return string
*/
public function getDirectory()
{
return $this->directory->get();
}
/**
* Set the template file extension.
* @param string|null $fileExtension Pass null to manually set it.
* @return Engine
*/
public function setFileExtension($fileExtension)
{
$this->fileExtension->set($fileExtension);
return $this;
}
/**
* Get the template file extension.
* @return string
*/
public function getFileExtension()
{
return $this->fileExtension->get();
}
/**
* Add a new template folder for grouping templates under different namespaces.
* @param string $name
* @param string $directory
* @param boolean $fallback
* @return Engine
*/
public function addFolder($name, $directory, $fallback = false)
{
$this->folders->add($name, $directory, $fallback);
return $this;
}
/**
* Remove a template folder.
* @param string $name
* @return Engine
*/
public function removeFolder($name)
{
$this->folders->remove($name);
return $this;
}
/**
* Get collection of all template folders.
* @return Folders
*/
public function getFolders()
{
return $this->folders;
}
/**
* Add preassigned template data.
* @param array $data;
* @param null|string|array $templates;
* @return Engine
*/
public function addData(array $data, $templates = null)
{
$this->data->add($data, $templates);
return $this;
}
/**
* Get all preassigned template data.
* @param null|string $template;
* @return array
*/
public function getData($template = null)
{
return $this->data->get($template);
}
/**
* Register a new template function.
* @param string $name;
* @param callback $callback;
* @return Engine
*/
public function registerFunction($name, $callback)
{
$this->functions->add($name, $callback);
return $this;
}
/**
* Remove a template function.
* @param string $name;
* @return Engine
*/
public function dropFunction($name)
{
$this->functions->remove($name);
return $this;
}
/**
* Get a template function.
* @param string $name
* @return Func
*/
public function getFunction($name)
{
return $this->functions->get($name);
}
/**
* Check if a template function exists.
* @param string $name
* @return boolean
*/
public function doesFunctionExist($name)
{
return $this->functions->exists($name);
}
/**
* Load an extension.
* @param ExtensionInterface $extension
* @return Engine
*/
public function loadExtension(ExtensionInterface $extension)
{
$extension->register($this);
return $this;
}
/**
* Load multiple extensions.
* @param array $extensions
* @return Engine
*/
public function loadExtensions(array $extensions = array())
{
foreach ($extensions as $extension) {
$this->loadExtension($extension);
}
return $this;
}
/**
* Get a template path.
* @param string $name
* @return string
*/
public function path($name)
{
$name = new Name($this, $name);
return $name->getPath();
}
/**
* Check if a template exists.
* @param string $name
* @return boolean
*/
public function exists($name)
{
$name = new Name($this, $name);
return $name->doesPathExist();
}
/**
* Create a new template.
* @param string $name
* @return Template
*/
public function make($name)
{
return new Template($this, $name);
}
/**
* Create a new template and render it.
* @param string $name
* @param array $data
* @return string
*/
public function render($name, array $data = array())
{
return $this->make($name)->render($data);
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace League\Plates\Extension;
use League\Plates\Engine;
use League\Plates\Template\Template;
use LogicException;
/**
* Extension that adds the ability to create "cache busted" asset URLs.
*/
class Asset implements ExtensionInterface
{
/**
* Instance of the current template.
* @var Template
*/
public $template;
/**
* Path to asset directory.
* @var string
*/
public $path;
/**
* Enables the filename method.
* @var boolean
*/
public $filenameMethod;
/**
* Create new Asset instance.
* @param string $path
* @param boolean $filenameMethod
*/
public function __construct($path, $filenameMethod = false)
{
$this->path = rtrim($path, '/');
$this->filenameMethod = $filenameMethod;
}
/**
* Register extension function.
* @param Engine $engine
* @return null
*/
public function register(Engine $engine)
{
$engine->registerFunction('asset', array($this, 'cachedAssetUrl'));
}
/**
* Create "cache busted" asset URL.
* @param string $url
* @return string
*/
public function cachedAssetUrl($url)
{
$filePath = $this->path . '/' . ltrim($url, '/');
if (!file_exists($filePath)) {
throw new LogicException(
'Unable to locate the asset "' . $url . '" in the "' . $this->path . '" directory.'
);
}
$lastUpdated = filemtime($filePath);
$pathInfo = pathinfo($url);
if ($pathInfo['dirname'] === '.') {
$directory = '';
} elseif ($pathInfo['dirname'] === '/') {
$directory = '/';
} else {
$directory = $pathInfo['dirname'] . '/';
}
if ($this->filenameMethod) {
return $directory . $pathInfo['filename'] . '.' . $lastUpdated . '.' . $pathInfo['extension'];
}
return $directory . $pathInfo['filename'] . '.' . $pathInfo['extension'] . '?v=' . $lastUpdated;
}
}
@@ -0,0 +1,13 @@
<?php
namespace League\Plates\Extension;
use League\Plates\Engine;
/**
* A common interface for extensions.
*/
interface ExtensionInterface
{
public function register(Engine $engine);
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace League\Plates\Extension;
use League\Plates\Engine;
use League\Plates\Template\Template;
use LogicException;
/**
* Extension that adds a number of URI checks.
*/
class URI implements ExtensionInterface
{
/**
* Instance of the current template.
* @var Template
*/
public $template;
/**
* The request URI.
* @var string
*/
protected $uri;
/**
* The request URI as an array.
* @var array
*/
protected $parts;
/**
* Create new URI instance.
* @param string $uri
*/
public function __construct($uri)
{
$this->uri = $uri;
$this->parts = explode('/', $this->uri);
}
/**
* Register extension functions.
* @param Engine $engine
* @return null
*/
public function register(Engine $engine)
{
$engine->registerFunction('uri', array($this, 'runUri'));
}
/**
* Perform URI check.
* @param null|integer|string $var1
* @param mixed $var2
* @param mixed $var3
* @param mixed $var4
* @return mixed
*/
public function runUri($var1 = null, $var2 = null, $var3 = null, $var4 = null)
{
if (is_null($var1)) {
return $this->uri;
}
if (is_numeric($var1) and is_null($var2)) {
return array_key_exists($var1, $this->parts) ? $this->parts[$var1] : null;
}
if (is_numeric($var1) and is_string($var2)) {
return $this->checkUriSegmentMatch($var1, $var2, $var3, $var4);
}
if (is_string($var1)) {
return $this->checkUriRegexMatch($var1, $var2, $var3);
}
throw new LogicException('Invalid use of the uri function.');
}
/**
* Perform a URI segment match.
* @param integer $key
* @param string $string
* @param mixed $returnOnTrue
* @param mixed $returnOnFalse
* @return mixed
*/
protected function checkUriSegmentMatch($key, $string, $returnOnTrue = null, $returnOnFalse = null)
{
if (array_key_exists($key, $this->parts) && $this->parts[$key] === $string) {
return is_null($returnOnTrue) ? true : $returnOnTrue;
}
return is_null($returnOnFalse) ? false : $returnOnFalse;
}
/**
* Perform a regular express match.
* @param string $regex
* @param mixed $returnOnTrue
* @param mixed $returnOnFalse
* @return mixed
*/
protected function checkUriRegexMatch($regex, $returnOnTrue = null, $returnOnFalse = null)
{
if (preg_match('#^' . $regex . '$#', $this->uri) === 1) {
return is_null($returnOnTrue) ? true : $returnOnTrue;
}
return is_null($returnOnFalse) ? false : $returnOnFalse;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace League\Plates\Template;
use LogicException;
/**
* Preassigned template data.
*/
class Data
{
/**
* Variables shared by all templates.
* @var array
*/
protected $sharedVariables = array();
/**
* Specific template variables.
* @var array
*/
protected $templateVariables = array();
/**
* Add template data.
* @param array $data;
* @param null|string|array $templates;
* @return Data
*/
public function add(array $data, $templates = null)
{
if (is_null($templates)) {
return $this->shareWithAll($data);
}
if (is_array($templates)) {
return $this->shareWithSome($data, $templates);
}
if (is_string($templates)) {
return $this->shareWithSome($data, array($templates));
}
throw new LogicException(
'The templates variable must be null, an array or a string, ' . gettype($templates) . ' given.'
);
}
/**
* Add data shared with all templates.
* @param array $data;
* @return Data
*/
public function shareWithAll($data)
{
$this->sharedVariables = array_merge($this->sharedVariables, $data);
return $this;
}
/**
* Add data shared with some templates.
* @param array $data;
* @param array $templates;
* @return Data
*/
public function shareWithSome($data, array $templates)
{
foreach ($templates as $template) {
if (isset($this->templateVariables[$template])) {
$this->templateVariables[$template] = array_merge($this->templateVariables[$template], $data);
} else {
$this->templateVariables[$template] = $data;
}
}
return $this;
}
/**
* Get template data.
* @param null|string $template;
* @return array
*/
public function get($template = null)
{
if (isset($template, $this->templateVariables[$template])) {
return array_merge($this->sharedVariables, $this->templateVariables[$template]);
}
return $this->sharedVariables;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace League\Plates\Template;
use LogicException;
/**
* Default template directory.
*/
class Directory
{
/**
* Template directory path.
* @var string
*/
protected $path;
/**
* Create new Directory instance.
* @param string $path
*/
public function __construct($path = null)
{
$this->set($path);
}
/**
* Set path to templates directory.
* @param string|null $path Pass null to disable the default directory.
* @return Directory
*/
public function set($path)
{
if (!is_null($path) and !is_dir($path)) {
throw new LogicException(
'The specified path "' . $path . '" does not exist.'
);
}
$this->path = $path;
return $this;
}
/**
* Get path to templates directory.
* @return string
*/
public function get()
{
return $this->path;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace League\Plates\Template;
/**
* Template file extension.
*/
class FileExtension
{
/**
* Template file extension.
* @var string
*/
protected $fileExtension;
/**
* Create new FileExtension instance.
* @param null|string $fileExtension
*/
public function __construct($fileExtension = 'php')
{
$this->set($fileExtension);
}
/**
* Set the template file extension.
* @param null|string $fileExtension
* @return FileExtension
*/
public function set($fileExtension)
{
$this->fileExtension = $fileExtension;
return $this;
}
/**
* Get the template file extension.
* @return string
*/
public function get()
{
return $this->fileExtension;
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace League\Plates\Template;
use LogicException;
/**
* A template folder.
*/
class Folder
{
/**
* The folder name.
* @var string
*/
protected $name;
/**
* The folder path.
* @var string
*/
protected $path;
/**
* The folder fallback status.
* @var boolean
*/
protected $fallback;
/**
* Create a new Folder instance.
* @param string $name
* @param string $path
* @param boolean $fallback
*/
public function __construct($name, $path, $fallback = false)
{
$this->setName($name);
$this->setPath($path);
$this->setFallback($fallback);
}
/**
* Set the folder name.
* @param string $name
* @return Folder
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get the folder name.
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set the folder path.
* @param string $path
* @return Folder
*/
public function setPath($path)
{
if (!is_dir($path)) {
throw new LogicException('The specified directory path "' . $path . '" does not exist.');
}
$this->path = $path;
return $this;
}
/**
* Get the folder path.
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set the folder fallback status.
* @param boolean $fallback
* @return Folder
*/
public function setFallback($fallback)
{
$this->fallback = $fallback;
return $this;
}
/**
* Get the folder fallback status.
* @return boolean
*/
public function getFallback()
{
return $this->fallback;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace League\Plates\Template;
use LogicException;
/**
* A collection of template folders.
*/
class Folders
{
/**
* Array of template folders.
* @var array
*/
protected $folders = array();
/**
* Add a template folder.
* @param string $name
* @param string $path
* @param boolean $fallback
* @return Folders
*/
public function add($name, $path, $fallback = false)
{
if ($this->exists($name)) {
throw new LogicException('The template folder "' . $name . '" is already being used.');
}
$this->folders[$name] = new Folder($name, $path, $fallback);
return $this;
}
/**
* Remove a template folder.
* @param string $name
* @return Folders
*/
public function remove($name)
{
if (!$this->exists($name)) {
throw new LogicException('The template folder "' . $name . '" was not found.');
}
unset($this->folders[$name]);
return $this;
}
/**
* Get a template folder.
* @param string $name
* @return Folder
*/
public function get($name)
{
if (!$this->exists($name)) {
throw new LogicException('The template folder "' . $name . '" was not found.');
}
return $this->folders[$name];
}
/**
* Check if a template folder exists.
* @param string $name
* @return boolean
*/
public function exists($name)
{
return isset($this->folders[$name]);
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace League\Plates\Template;
use League\Plates\Extension\ExtensionInterface;
use LogicException;
/**
* A template function.
*/
class Func
{
/**
* The function name.
* @var string
*/
protected $name;
/**
* The function callback.
* @var callable
*/
protected $callback;
/**
* Create new Func instance.
* @param string $name
* @param callable $callback
*/
public function __construct($name, $callback)
{
$this->setName($name);
$this->setCallback($callback);
}
/**
* Set the function name.
* @param string $name
* @return Func
*/
public function setName($name)
{
if (preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $name) !== 1) {
throw new LogicException(
'Not a valid function name.'
);
}
$this->name = $name;
return $this;
}
/**
* Get the function name.
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set the function callback
* @param callable $callback
* @return Func
*/
public function setCallback($callback)
{
if (!is_callable($callback, true)) {
throw new LogicException(
'Not a valid function callback.'
);
}
$this->callback = $callback;
return $this;
}
/**
* Get the function callback.
* @return callable
*/
public function getCallback()
{
return $this->callback;
}
/**
* Call the function.
* @param Template $template
* @param array $arguments
* @return mixed
*/
public function call(Template $template = null, $arguments = array())
{
if (is_array($this->callback) and
isset($this->callback[0]) and
$this->callback[0] instanceof ExtensionInterface
) {
$this->callback[0]->template = $template;
}
return call_user_func_array($this->callback, $arguments);
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace League\Plates\Template;
use LogicException;
/**
* A collection of template functions.
*/
class Functions
{
/**
* Array of template functions.
* @var array
*/
protected $functions = array();
/**
* Add a new template function.
* @param string $name;
* @param callback $callback;
* @return Functions
*/
public function add($name, $callback)
{
if ($this->exists($name)) {
throw new LogicException(
'The template function name "' . $name . '" is already registered.'
);
}
$this->functions[$name] = new Func($name, $callback);
return $this;
}
/**
* Remove a template function.
* @param string $name;
* @return Functions
*/
public function remove($name)
{
if (!$this->exists($name)) {
throw new LogicException(
'The template function "' . $name . '" was not found.'
);
}
unset($this->functions[$name]);
return $this;
}
/**
* Get a template function.
* @param string $name
* @return Func
*/
public function get($name)
{
if (!$this->exists($name)) {
throw new LogicException('The template function "' . $name . '" was not found.');
}
return $this->functions[$name];
}
/**
* Check if a template function exists.
* @param string $name
* @return boolean
*/
public function exists($name)
{
return isset($this->functions[$name]);
}
}
+202
View File
@@ -0,0 +1,202 @@
<?php
namespace League\Plates\Template;
use League\Plates\Engine;
use LogicException;
/**
* A template name.
*/
class Name
{
/**
* Instance of the template engine.
* @var Engine
*/
protected $engine;
/**
* The original name.
* @var string
*/
protected $name;
/**
* The parsed template folder.
* @var Folder
*/
protected $folder;
/**
* The parsed template filename.
* @var string
*/
protected $file;
/**
* Create a new Name instance.
* @param Engine $engine
* @param string $name
*/
public function __construct(Engine $engine, $name)
{
$this->setEngine($engine);
$this->setName($name);
}
/**
* Set the engine.
* @param Engine $engine
* @return Name
*/
public function setEngine(Engine $engine)
{
$this->engine = $engine;
return $this;
}
/**
* Get the engine.
* @return Engine
*/
public function getEngine()
{
return $this->engine;
}
/**
* Set the original name and parse it.
* @param string $name
* @return Name
*/
public function setName($name)
{
$this->name = $name;
$parts = explode('::', $this->name);
if (count($parts) === 1) {
$this->setFile($parts[0]);
} elseif (count($parts) === 2) {
$this->setFolder($parts[0]);
$this->setFile($parts[1]);
} else {
throw new LogicException(
'The template name "' . $this->name . '" is not valid. ' .
'Do not use the folder namespace separator "::" more than once.'
);
}
return $this;
}
/**
* Get the original name.
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set the parsed template folder.
* @param string $folder
* @return Name
*/
public function setFolder($folder)
{
$this->folder = $this->engine->getFolders()->get($folder);
return $this;
}
/**
* Get the parsed template folder.
* @return string
*/
public function getFolder()
{
return $this->folder;
}
/**
* Set the parsed template file.
* @param string $file
* @return Name
*/
public function setFile($file)
{
if ($file === '') {
throw new LogicException(
'The template name "' . $this->name . '" is not valid. ' .
'The template name cannot be empty.'
);
}
$this->file = $file;
if (!is_null($this->engine->getFileExtension())) {
$this->file .= '.' . $this->engine->getFileExtension();
}
return $this;
}
/**
* Get the parsed template file.
* @return string
*/
public function getFile()
{
return $this->file;
}
/**
* Resolve template path.
* @return string
*/
public function getPath()
{
if (is_null($this->folder)) {
return $this->getDefaultDirectory() . DIRECTORY_SEPARATOR . $this->file;
}
$path = $this->folder->getPath() . DIRECTORY_SEPARATOR . $this->file;
if (!is_file($path) and $this->folder->getFallback() and is_file($this->getDefaultDirectory() . DIRECTORY_SEPARATOR . $this->file)) {
$path = $this->getDefaultDirectory() . DIRECTORY_SEPARATOR . $this->file;
}
return $path;
}
/**
* Check if template path exists.
* @return boolean
*/
public function doesPathExist()
{
return is_file($this->getPath());
}
/**
* Get the default templates directory.
* @return string
*/
protected function getDefaultDirectory()
{
$directory = $this->engine->getDirectory();
if (is_null($directory)) {
throw new LogicException(
'The template name "' . $this->name . '" is not valid. '.
'The default directory has not been defined.'
);
}
return $directory;
}
}
+346
View File
@@ -0,0 +1,346 @@
<?php
namespace League\Plates\Template;
use Exception;
use League\Plates\Engine;
use LogicException;
use Throwable;
/**
* Container which holds template data and provides access to template functions.
*/
class Template
{
/**
* Instance of the template engine.
* @var Engine
*/
protected $engine;
/**
* The name of the template.
* @var Name
*/
protected $name;
/**
* The data assigned to the template.
* @var array
*/
protected $data = array();
/**
* An array of section content.
* @var array
*/
protected $sections = array();
/**
* The name of the section currently being rendered.
* @var string
*/
protected $sectionName;
/**
* Whether the section should be appended or not.
* @var boolean
*/
protected $appendSection;
/**
* The name of the template layout.
* @var string
*/
protected $layoutName;
/**
* The data assigned to the template layout.
* @var array
*/
protected $layoutData;
/**
* Create new Template instance.
* @param Engine $engine
* @param string $name
*/
public function __construct(Engine $engine, $name)
{
$this->engine = $engine;
$this->name = new Name($engine, $name);
$this->data($this->engine->getData($name));
}
/**
* Magic method used to call extension functions.
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
return $this->engine->getFunction($name)->call($this, $arguments);
}
/**
* Alias for render() method.
* @throws \Throwable
* @throws \Exception
* @return string
*/
public function __toString()
{
return $this->render();
}
/**
* Assign or get template data.
* @param array $data
* @return mixed
*/
public function data(array $data = null)
{
if (is_null($data)) {
return $this->data;
}
$this->data = array_merge($this->data, $data);
}
/**
* Check if the template exists.
* @return boolean
*/
public function exists()
{
return $this->name->doesPathExist();
}
/**
* Get the template path.
* @return string
*/
public function path()
{
return $this->name->getPath();
}
/**
* Render the template and layout.
* @param array $data
* @throws \Throwable
* @throws \Exception
* @return string
*/
public function render(array $data = array())
{
$this->data($data);
unset($data);
extract($this->data);
if (!$this->exists()) {
throw new LogicException(
'The template "' . $this->name->getName() . '" could not be found at "' . $this->path() . '".'
);
}
try {
$level = ob_get_level();
ob_start();
include $this->path();
$content = ob_get_clean();
if (isset($this->layoutName)) {
$layout = $this->engine->make($this->layoutName);
$layout->sections = array_merge($this->sections, array('content' => $content));
$content = $layout->render($this->layoutData);
}
return $content;
} catch (Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
} catch (Exception $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
}
}
/**
* Set the template's layout.
* @param string $name
* @param array $data
* @return null
*/
public function layout($name, array $data = array())
{
$this->layoutName = $name;
$this->layoutData = $data;
}
/**
* Start a new section block.
* @param string $name
* @return null
*/
public function start($name)
{
if ($name === 'content') {
throw new LogicException(
'The section name "content" is reserved.'
);
}
if ($this->sectionName) {
throw new LogicException('You cannot nest sections within other sections.');
}
$this->sectionName = $name;
ob_start();
}
/**
* Start a new append section block.
* @param string $name
* @return null
*/
public function push($name)
{
$this->appendSection = true;
$this->start($name);
}
/**
* Stop the current section block.
* @return null
*/
public function stop()
{
if (is_null($this->sectionName)) {
throw new LogicException(
'You must start a section before you can stop it.'
);
}
if (!isset($this->sections[$this->sectionName])) {
$this->sections[$this->sectionName] = '';
}
$this->sections[$this->sectionName] = $this->appendSection ? $this->sections[$this->sectionName] . ob_get_clean() : ob_get_clean();
$this->sectionName = null;
$this->appendSection = false;
}
/**
* Alias of stop().
* @return null
*/
public function end()
{
$this->stop();
}
/**
* Returns the content for a section block.
* @param string $name Section name
* @param string $default Default section content
* @return string|null
*/
public function section($name, $default = null)
{
if (!isset($this->sections[$name])) {
return $default;
}
return $this->sections[$name];
}
/**
* Fetch a rendered template.
* @param string $name
* @param array $data
* @return string
*/
public function fetch($name, array $data = array())
{
return $this->engine->render($name, $data);
}
/**
* Output a rendered template.
* @param string $name
* @param array $data
* @return null
*/
public function insert($name, array $data = array())
{
echo $this->engine->render($name, $data);
}
/**
* Apply multiple functions to variable.
* @param mixed $var
* @param string $functions
* @return mixed
*/
public function batch($var, $functions)
{
foreach (explode('|', $functions) as $function) {
if ($this->engine->doesFunctionExist($function)) {
$var = call_user_func(array($this, $function), $var);
} elseif (is_callable($function)) {
$var = call_user_func($function, $var);
} else {
throw new LogicException(
'The batch function could not find the "' . $function . '" function.'
);
}
}
return $var;
}
/**
* Escape string.
* @param string $string
* @param null|string $functions
* @return string
*/
public function escape($string, $functions = null)
{
static $flags;
if (!isset($flags)) {
$flags = ENT_QUOTES | (defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0);
}
if ($functions) {
$string = $this->batch($string, $functions);
}
return htmlspecialchars($string, $flags, 'UTF-8');
}
/**
* Alias to escape function.
* @param string $string
* @param null|string $functions
* @return string
*/
public function e($string, $functions = null)
{
return $this->escape($string, $functions);
}
}
+1
View File
@@ -0,0 +1 @@
simpletest/test_setup.php
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+139
View File
@@ -0,0 +1,139 @@
MeekroDB -- The Simple PHP MySQL Library
========
Learn more: http://www.meekro.com
MeekroDB is:
* A PHP MySQL library that lets you **get more done with fewer lines of code**, and **makes SQL injection 100% impossible**.
* Google's #1 search result for "php mysql library" for over 2 years, with **thousands of deployments worldwide**.
* A library with a **perfect security track record**. No bugs relating to security or SQL injection have ever been discovered.
Installation
========
When you're ready to get started, see the [Quick Start Guide](http://www.meekro.com/quickstart.php) on our website.
### Manual Setup
Include the `db.class.php` file into your project and set it up like this:
require_once 'db.class.php';
DB::$user = 'my_database_user';
DB::$password = 'my_database_password';
DB::$dbName = 'my_database_name';
### Composer
Add this to your `composer.json`
{
"require": {
"sergeytsalkov/meekrodb": "*"
}
}
Code Examples
========
### Grab some rows from the database and print out a field from each row.
$accounts = DB::query("SELECT * FROM accounts WHERE type = %s AND age > %i", $type, 15);
foreach ($accounts as $account) {
echo $account['username'] . "\n";
}
### Insert a new row.
DB::insert('mytable', array(
'name' => $name,
'rank' => $rank,
'location' => $location,
'age' => $age,
'intelligence' => $intelligence
));
### Grab one row or field
$account = DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe');
$number_accounts = DB::queryFirstField("SELECT COUNT(*) FROM accounts");
### Use a list in a query
DB::query("SELECT * FROM tbl WHERE name IN %ls AND age NOT IN %li", array('John', 'Bob'), array(12, 15));
### Nested Transactions
DB::$nested_transactions = true;
DB::startTransaction(); // outer transaction
// .. some queries..
$depth = DB::startTransaction(); // inner transaction
echo $depth . 'transactions are currently active'; // 2
// .. some queries..
DB::commit(); // commit inner transaction
// .. some queries..
DB::commit(); // commit outer transaction
### Lots More - See: http://www.meekro.com/docs.php
How is MeekroDB better than PDO?
========
### Optional Static Class Mode
Most web apps will only ever talk to one database. This means that
passing $db objects to every function of your code just adds unnecessary clutter.
The simplest approach is to use static methods such as DB::query(), and that's how
MeekroDB works. Still, if you need database objects, MeekroDB can do that too.
### Do more with fewer lines of code
The code below escapes your parameters for safety, runs the query, and grabs
the first row of results. Try doing that in one line with PDO.
$account = DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe');
### Work with list parameters easily
Using MySQL's IN keyword should not be hard. MeekroDB smooths out the syntax for you,
PDO does not.
$accounts = DB::query("SELECT * FROM accounts WHERE username IN %ls", array('Joe', 'Frank'));
### Simple inserts
Using MySQL's INSERT should not be more complicated than passing in an
associative array. MeekroDB also simplifies many related commands, including
the useful and bizarre INSERT .. ON DUPLICATE UPDATE command. PDO does none of this.
DB::insert('accounts', array('username' => 'John', 'password' => 'whatever'));
### Focus on the goal, not the task
Want to do INSERT yourself rather than relying on DB::insert()?
It's dead simple. I don't even want to think about how many lines
you'd need to pull this off in PDO.
// Insert 2 rows at once
DB::query("INSERT INTO %b %lb VALUES %?", 'accounts',
array('username', 'password', 'last_login_timestamp'),
array(
array('Joe', 'joes_password', new DateTime('yesterday')),
array('Frank', 'franks_password', new DateTime('last Monday'))
)
);
### Nested transactions
MySQL's SAVEPOINT commands lets you create nested transactions, but only
if you keep track of SAVEPOINT ids yourself. MeekroDB does this for you,
so you can have nested transactions with no complexity or learning curve.
DB::$nested_transactions = true;
DB::startTransaction(); // outer transaction
// .. some queries..
$depth = DB::startTransaction(); // inner transaction
echo $depth . 'transactions are currently active'; // 2
// .. some queries..
DB::commit(); // commit inner transaction
// .. some queries..
DB::commit(); // commit outer transaction
### Flexible error and success handlers
Set your own custom function run on errors, or on every query that succeeds.
You can easily have separate error handling behavior for the dev and live
versions of your application. Want to count up all your queries and their
runtime? Just add a new success handler.
### More about MeekroDB's design philosophy: http://www.meekro.com/beliefs.php
+29
View File
@@ -0,0 +1,29 @@
{
"name": "SergeyTsalkov/meekrodb",
"description": "The Simple PHP/MySQL Library",
"homepage": "http://www.meekro.com",
"support": {
"email": "support@meekro.com"
},
"keywords": [
"mysql",
"database",
"mysqli",
"pdo"
],
"license": "LGPL-3.0",
"authors": [
{
"name": "Sergey Tsalkov",
"email": "stsalkov@gmail.com"
}
],
"require": {
"php": ">=5.2.0"
},
"autoload": {
"classmap": [
"db.class.php"
]
}
}
+956
View File
@@ -0,0 +1,956 @@
<?php
/*
Copyright (C) 2008-2012 Sergey Tsalkov (stsalkov@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class DB {
// initial connection
public static $dbName = '';
public static $user = '';
public static $password = '';
public static $host = 'localhost';
public static $port = null;
public static $encoding = 'latin1';
// configure workings
public static $param_char = '%';
public static $named_param_seperator = '_';
public static $success_handler = false;
public static $error_handler = true;
public static $throw_exception_on_error = false;
public static $nonsql_error_handler = null;
public static $throw_exception_on_nonsql_error = false;
public static $nested_transactions = false;
public static $usenull = true;
public static $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => '');
public static $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30);
// internal
protected static $mdb = null;
public static function getMDB() {
$mdb = DB::$mdb;
if ($mdb === null) {
$mdb = DB::$mdb = new MeekroDB();
}
static $variables_to_sync = array('param_char', 'named_param_seperator', 'success_handler', 'error_handler', 'throw_exception_on_error',
'nonsql_error_handler', 'throw_exception_on_nonsql_error', 'nested_transactions', 'usenull', 'ssl', 'connect_options');
$db_class_vars = get_class_vars('DB'); // the DB::$$var syntax only works in 5.3+
foreach ($variables_to_sync as $variable) {
if ($mdb->$variable !== $db_class_vars[$variable]) {
$mdb->$variable = $db_class_vars[$variable];
}
}
return $mdb;
}
// yes, this is ugly. __callStatic() only works in 5.3+
public static function get() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'get'), $args); }
public static function disconnect() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'disconnect'), $args); }
public static function query() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'query'), $args); }
public static function queryFirstRow() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstRow'), $args); }
public static function queryOneRow() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneRow'), $args); }
public static function queryAllLists() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryAllLists'), $args); }
public static function queryFullColumns() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFullColumns'), $args); }
public static function queryFirstList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstList'), $args); }
public static function queryOneList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneList'), $args); }
public static function queryFirstColumn() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstColumn'), $args); }
public static function queryOneColumn() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneColumn'), $args); }
public static function queryFirstField() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstField'), $args); }
public static function queryOneField() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneField'), $args); }
public static function queryRaw() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryRaw'), $args); }
public static function queryRawUnbuf() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryRawUnbuf'), $args); }
public static function insert() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insert'), $args); }
public static function insertIgnore() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertIgnore'), $args); }
public static function insertUpdate() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertUpdate'), $args); }
public static function replace() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'replace'), $args); }
public static function update() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'update'), $args); }
public static function delete() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'delete'), $args); }
public static function insertId() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertId'), $args); }
public static function count() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'count'), $args); }
public static function affectedRows() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'affectedRows'), $args); }
public static function useDB() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'useDB'), $args); }
public static function startTransaction() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'startTransaction'), $args); }
public static function commit() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'commit'), $args); }
public static function rollback() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'rollback'), $args); }
public static function tableList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'tableList'), $args); }
public static function columnList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'columnList'), $args); }
public static function sqlEval() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'sqlEval'), $args); }
public static function nonSQLError() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'nonSQLError'), $args); }
public static function serverVersion() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'serverVersion'), $args); }
public static function transactionDepth() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'transactionDepth'), $args); }
public static function debugMode($handler = true) {
DB::$success_handler = $handler;
}
}
class MeekroDB {
// initial connection
public $dbName = '';
public $user = '';
public $password = '';
public $host = 'localhost';
public $port = null;
public $encoding = 'latin1';
// configure workings
public $param_char = '%';
public $named_param_seperator = '_';
public $success_handler = false;
public $error_handler = true;
public $throw_exception_on_error = false;
public $nonsql_error_handler = null;
public $throw_exception_on_nonsql_error = false;
public $nested_transactions = false;
public $usenull = true;
public $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => '');
public $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30);
// internal
public $internal_mysql = null;
public $server_info = null;
public $insert_id = 0;
public $num_rows = 0;
public $affected_rows = 0;
public $current_db = null;
public $nested_transactions_count = 0;
public function __construct($host=null, $user=null, $password=null, $dbName=null, $port=null, $encoding=null) {
if ($host === null) $host = DB::$host;
if ($user === null) $user = DB::$user;
if ($password === null) $password = DB::$password;
if ($dbName === null) $dbName = DB::$dbName;
if ($port === null) $port = DB::$port;
if ($encoding === null) $encoding = DB::$encoding;
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->dbName = $dbName;
$this->port = $port;
$this->encoding = $encoding;
}
public function get() {
$mysql = $this->internal_mysql;
if (!($mysql instanceof MySQLi)) {
if (! $this->port) $this->port = ini_get('mysqli.default_port');
$this->current_db = $this->dbName;
$mysql = new mysqli();
$connect_flags = 0;
if ($this->ssl['key']) {
$mysql->ssl_set($this->ssl['key'], $this->ssl['cert'], $this->ssl['ca_cert'], $this->ssl['ca_path'], $this->ssl['cipher']);
$connect_flags |= MYSQLI_CLIENT_SSL;
}
foreach ($this->connect_options as $key => $value) {
$mysql->options($key, $value);
}
// suppress warnings, since we will check connect_error anyway
@$mysql->real_connect($this->host, $this->user, $this->password, $this->dbName, $this->port, null, $connect_flags);
if ($mysql->connect_error) {
$this->nonSQLError('Unable to connect to MySQL server! Error: ' . $mysql->connect_error);
}
$mysql->set_charset($this->encoding);
$this->internal_mysql = $mysql;
$this->server_info = $mysql->server_info;
}
return $mysql;
}
public function disconnect() {
$mysqli = $this->internal_mysql;
if ($mysqli instanceof MySQLi) {
if ($thread_id = $mysqli->thread_id) $mysqli->kill($thread_id);
$mysqli->close();
}
$this->internal_mysql = null;
}
public function nonSQLError($message) {
if ($this->throw_exception_on_nonsql_error) {
$e = new MeekroDBException($message);
throw $e;
}
$error_handler = is_callable($this->nonsql_error_handler) ? $this->nonsql_error_handler : 'meekrodb_error_handler';
call_user_func($error_handler, array(
'type' => 'nonsql',
'error' => $message
));
}
public function debugMode($handler = true) {
$this->success_handler = $handler;
}
public function serverVersion() { $this->get(); return $this->server_info; }
public function transactionDepth() { return $this->nested_transactions_count; }
public function insertId() { return $this->insert_id; }
public function affectedRows() { return $this->affected_rows; }
public function count() { $args = func_get_args(); return call_user_func_array(array($this, 'numRows'), $args); }
public function numRows() { return $this->num_rows; }
public function useDB() { $args = func_get_args(); return call_user_func_array(array($this, 'setDB'), $args); }
public function setDB($dbName) {
$db = $this->get();
if (! $db->select_db($dbName)) $this->nonSQLError("Unable to set database to $dbName");
$this->current_db = $dbName;
}
public function startTransaction() {
if ($this->nested_transactions && $this->serverVersion() < '5.5') {
return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion());
}
if (!$this->nested_transactions || $this->nested_transactions_count == 0) {
$this->query('START TRANSACTION');
$this->nested_transactions_count = 1;
} else {
$this->query("SAVEPOINT LEVEL{$this->nested_transactions_count}");
$this->nested_transactions_count++;
}
return $this->nested_transactions_count;
}
public function commit($all=false) {
if ($this->nested_transactions && $this->serverVersion() < '5.5') {
return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion());
}
if ($this->nested_transactions && $this->nested_transactions_count > 0)
$this->nested_transactions_count--;
if (!$this->nested_transactions || $all || $this->nested_transactions_count == 0) {
$this->nested_transactions_count = 0;
$this->query('COMMIT');
} else {
$this->query("RELEASE SAVEPOINT LEVEL{$this->nested_transactions_count}");
}
return $this->nested_transactions_count;
}
public function rollback($all=false) {
if ($this->nested_transactions && $this->serverVersion() < '5.5') {
return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion());
}
if ($this->nested_transactions && $this->nested_transactions_count > 0)
$this->nested_transactions_count--;
if (!$this->nested_transactions || $all || $this->nested_transactions_count == 0) {
$this->nested_transactions_count = 0;
$this->query('ROLLBACK');
} else {
$this->query("ROLLBACK TO SAVEPOINT LEVEL{$this->nested_transactions_count}");
}
return $this->nested_transactions_count;
}
protected function formatTableName($table) {
$table = trim($table, '`');
if (strpos($table, '.')) return implode('.', array_map(array($this, 'formatTableName'), explode('.', $table)));
else return '`' . str_replace('`', '``', $table) . '`';
}
public function update() {
$args = func_get_args();
$table = array_shift($args);
$params = array_shift($args);
$where = array_shift($args);
$query = str_replace('%', $this->param_char, "UPDATE %b SET %? WHERE ") . $where;
array_unshift($args, $params);
array_unshift($args, $table);
array_unshift($args, $query);
return call_user_func_array(array($this, 'query'), $args);
}
public function insertOrReplace($which, $table, $datas, $options=array()) {
$datas = unserialize(serialize($datas)); // break references within array
$keys = $values = array();
if (isset($datas[0]) && is_array($datas[0])) {
foreach ($datas as $datum) {
ksort($datum);
if (! $keys) $keys = array_keys($datum);
$values[] = array_values($datum);
}
} else {
$keys = array_keys($datas);
$values = array_values($datas);
}
if (isset($options['ignore']) && $options['ignore']) $which = 'INSERT IGNORE';
if (isset($options['update']) && is_array($options['update']) && $options['update'] && strtolower($which) == 'insert') {
if (array_values($options['update']) !== $options['update']) {
return $this->query(
str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE %?"),
$table, $keys, $values, $options['update']);
} else {
$update_str = array_shift($options['update']);
$query_param = array(
str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE ") . $update_str,
$table, $keys, $values);
$query_param = array_merge($query_param, $options['update']);
return call_user_func_array(array($this, 'query'), $query_param);
}
}
return $this->query(
str_replace('%', $this->param_char, "%l INTO %b %lb VALUES %?"),
$which, $table, $keys, $values);
}
public function insert($table, $data) { return $this->insertOrReplace('INSERT', $table, $data); }
public function insertIgnore($table, $data) { return $this->insertOrReplace('INSERT', $table, $data, array('ignore' => true)); }
public function replace($table, $data) { return $this->insertOrReplace('REPLACE', $table, $data); }
public function insertUpdate() {
$args = func_get_args();
$table = array_shift($args);
$data = array_shift($args);
if (! isset($args[0])) { // update will have all the data of the insert
if (isset($data[0]) && is_array($data[0])) { //multiple insert rows specified -- failing!
$this->nonSQLError("Badly formatted insertUpdate() query -- you didn't specify the update component!");
}
$args[0] = $data;
}
if (is_array($args[0])) $update = $args[0];
else $update = $args;
return $this->insertOrReplace('INSERT', $table, $data, array('update' => $update));
}
public function delete() {
$args = func_get_args();
$table = $this->formatTableName(array_shift($args));
$where = array_shift($args);
$buildquery = "DELETE FROM $table WHERE $where";
array_unshift($args, $buildquery);
return call_user_func_array(array($this, 'query'), $args);
}
public function sqleval() {
$args = func_get_args();
$text = call_user_func_array(array($this, 'parseQueryParams'), $args);
return new MeekroDBEval($text);
}
public function columnList($table) {
return $this->queryOneColumn('Field', "SHOW COLUMNS FROM %b", $table);
}
public function tableList($db = null) {
if ($db) {
$olddb = $this->current_db;
$this->useDB($db);
}
$result = $this->queryFirstColumn('SHOW TABLES');
if (isset($olddb)) $this->useDB($olddb);
return $result;
}
protected function preparseQueryParams() {
$args = func_get_args();
$sql = trim(strval(array_shift($args)));
$args_all = $args;
if (count($args_all) == 0) return array($sql);
$param_char_length = strlen($this->param_char);
$named_seperator_length = strlen($this->named_param_seperator);
$types = array(
$this->param_char . 'll', // list of literals
$this->param_char . 'ls', // list of strings
$this->param_char . 'l', // literal
$this->param_char . 'li', // list of integers
$this->param_char . 'ld', // list of decimals
$this->param_char . 'lb', // list of backticks
$this->param_char . 'lt', // list of timestamps
$this->param_char . 's', // string
$this->param_char . 'i', // integer
$this->param_char . 'd', // double / decimal
$this->param_char . 'b', // backtick
$this->param_char . 't', // timestamp
$this->param_char . '?', // infer type
$this->param_char . 'ss' // search string (like string, surrounded with %'s)
);
// generate list of all MeekroDB variables in our query, and their position
// in the form "offset => variable", sorted by offsets
$posList = array();
foreach ($types as $type) {
$lastPos = 0;
while (($pos = strpos($sql, $type, $lastPos)) !== false) {
$lastPos = $pos + 1;
if (isset($posList[$pos]) && strlen($posList[$pos]) > strlen($type)) continue;
$posList[$pos] = $type;
}
}
ksort($posList);
// for each MeekroDB variable, substitute it with array(type: i, value: 53) or whatever
$chunkyQuery = array(); // preparsed query
$pos_adj = 0; // how much we've added or removed from the original sql string
foreach ($posList as $pos => $type) {
$type = substr($type, $param_char_length); // variable, without % in front of it
$length_type = strlen($type) + $param_char_length; // length of variable w/o %
$new_pos = $pos + $pos_adj; // position of start of variable
$new_pos_back = $new_pos + $length_type; // position of end of variable
$arg_number_length = 0; // length of any named or numbered parameter addition
// handle numbered parameters
if ($arg_number_length = strspn($sql, '0123456789', $new_pos_back)) {
$arg_number = substr($sql, $new_pos_back, $arg_number_length);
if (! array_key_exists($arg_number, $args_all)) $this->nonSQLError("Non existent argument reference (arg $arg_number): $sql");
$arg = $args_all[$arg_number];
// handle named parameters
} else if (substr($sql, $new_pos_back, $named_seperator_length) == $this->named_param_seperator) {
$arg_number_length = strspn($sql, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_',
$new_pos_back + $named_seperator_length) + $named_seperator_length;
$arg_number = substr($sql, $new_pos_back + $named_seperator_length, $arg_number_length - $named_seperator_length);
if (count($args_all) != 1 || !is_array($args_all[0])) $this->nonSQLError("If you use named parameters, the second argument must be an array of parameters");
if (! array_key_exists($arg_number, $args_all[0])) $this->nonSQLError("Non existent argument reference (arg $arg_number): $sql");
$arg = $args_all[0][$arg_number];
} else {
$arg_number = 0;
$arg = array_shift($args);
}
if ($new_pos > 0) $chunkyQuery[] = substr($sql, 0, $new_pos);
if (is_object($arg) && ($arg instanceof WhereClause)) {
list($clause_sql, $clause_args) = $arg->textAndArgs();
array_unshift($clause_args, $clause_sql);
$preparsed_sql = call_user_func_array(array($this, 'preparseQueryParams'), $clause_args);
$chunkyQuery = array_merge($chunkyQuery, $preparsed_sql);
} else {
$chunkyQuery[] = array('type' => $type, 'value' => $arg);
}
$sql = substr($sql, $new_pos_back + $arg_number_length);
$pos_adj -= $new_pos_back + $arg_number_length;
}
if (strlen($sql) > 0) $chunkyQuery[] = $sql;
return $chunkyQuery;
}
protected function escape($str) { return "'" . $this->get()->real_escape_string(strval($str)) . "'"; }
protected function sanitize($value) {
if (is_object($value)) {
if ($value instanceof MeekroDBEval) return $value->text;
else if ($value instanceof DateTime) return $this->escape($value->format('Y-m-d H:i:s'));
else return '';
}
if (is_null($value)) return $this->usenull ? 'NULL' : "''";
else if (is_bool($value)) return ($value ? 1 : 0);
else if (is_int($value)) return $value;
else if (is_float($value)) return $value;
else if (is_array($value)) {
// non-assoc array?
if (array_values($value) === $value) {
if (is_array($value[0])) return implode(', ', array_map(array($this, 'sanitize'), $value));
else return '(' . implode(', ', array_map(array($this, 'sanitize'), $value)) . ')';
}
$pairs = array();
foreach ($value as $k => $v) {
$pairs[] = $this->formatTableName($k) . '=' . $this->sanitize($v);
}
return implode(', ', $pairs);
}
else return $this->escape($value);
}
protected function parseTS($ts) {
if (is_string($ts)) return date('Y-m-d H:i:s', strtotime($ts));
else if (is_object($ts) && ($ts instanceof DateTime)) return $ts->format('Y-m-d H:i:s');
}
protected function intval($var) {
if (PHP_INT_SIZE == 8) return intval($var);
return floor(doubleval($var));
}
protected function parseQueryParams() {
$args = func_get_args();
$chunkyQuery = call_user_func_array(array($this, 'preparseQueryParams'), $args);
$query = '';
$array_types = array('ls', 'li', 'ld', 'lb', 'll', 'lt');
foreach ($chunkyQuery as $chunk) {
if (is_string($chunk)) {
$query .= $chunk;
continue;
}
$type = $chunk['type'];
$arg = $chunk['value'];
$result = '';
if ($type != '?') {
$is_array_type = in_array($type, $array_types, true);
if ($is_array_type && !is_array($arg)) $this->nonSQLError("Badly formatted SQL query: Expected array, got scalar instead!");
else if (!$is_array_type && is_array($arg)) $this->nonSQLError("Badly formatted SQL query: Expected scalar, got array instead!");
}
if ($type == 's') $result = $this->escape($arg);
else if ($type == 'i') $result = $this->intval($arg);
else if ($type == 'd') $result = doubleval($arg);
else if ($type == 'b') $result = $this->formatTableName($arg);
else if ($type == 'l') $result = $arg;
else if ($type == 'ss') $result = $this->escape("%" . str_replace(array('%', '_'), array('\%', '\_'), $arg) . "%");
else if ($type == 't') $result = $this->escape($this->parseTS($arg));
else if ($type == 'ls') $result = array_map(array($this, 'escape'), $arg);
else if ($type == 'li') $result = array_map(array($this, 'intval'), $arg);
else if ($type == 'ld') $result = array_map('doubleval', $arg);
else if ($type == 'lb') $result = array_map(array($this, 'formatTableName'), $arg);
else if ($type == 'll') $result = $arg;
else if ($type == 'lt') $result = array_map(array($this, 'escape'), array_map(array($this, 'parseTS'), $arg));
else if ($type == '?') $result = $this->sanitize($arg);
else $this->nonSQLError("Badly formatted SQL query: Invalid MeekroDB param $type");
if (is_array($result)) $result = '(' . implode(',', $result) . ')';
$query .= $result;
}
return $query;
}
protected function prependCall($function, $args, $prepend) { array_unshift($args, $prepend); return call_user_func_array($function, $args); }
public function query() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'assoc'); }
public function queryAllLists() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'list'); }
public function queryFullColumns() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'full'); }
public function queryRaw() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'raw_buf'); }
public function queryRawUnbuf() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'raw_unbuf'); }
protected function queryHelper() {
$args = func_get_args();
$type = array_shift($args);
$db = $this->get();
$is_buffered = true;
$row_type = 'assoc'; // assoc, list, raw
$full_names = false;
switch ($type) {
case 'assoc':
break;
case 'list':
$row_type = 'list';
break;
case 'full':
$row_type = 'list';
$full_names = true;
break;
case 'raw_buf':
$row_type = 'raw';
break;
case 'raw_unbuf':
$is_buffered = false;
$row_type = 'raw';
break;
default:
$this->nonSQLError('Error -- invalid argument to queryHelper!');
}
$sql = call_user_func_array(array($this, 'parseQueryParams'), $args);
if ($this->success_handler) $starttime = microtime(true);
$result = $db->query($sql, $is_buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
if ($this->success_handler) $runtime = microtime(true) - $starttime;
else $runtime = 0;
// ----- BEGIN ERROR HANDLING
if (!$sql || $db->error) {
if ($this->error_handler) {
$error_handler = is_callable($this->error_handler) ? $this->error_handler : 'meekrodb_error_handler';
call_user_func($error_handler, array(
'type' => 'sql',
'query' => $sql,
'error' => $db->error,
'code' => $db->errno
));
}
if ($this->throw_exception_on_error) {
$e = new MeekroDBException($db->error, $sql, $db->errno);
throw $e;
}
} else if ($this->success_handler) {
$runtime = sprintf('%f', $runtime * 1000);
$success_handler = is_callable($this->success_handler) ? $this->success_handler : 'meekrodb_debugmode_handler';
call_user_func($success_handler, array(
'query' => $sql,
'runtime' => $runtime,
'affected' => $db->affected_rows
));
}
// ----- END ERROR HANDLING
$this->insert_id = $db->insert_id;
$this->affected_rows = $db->affected_rows;
// mysqli_result->num_rows won't initially show correct results for unbuffered data
if ($is_buffered && ($result instanceof MySQLi_Result)) $this->num_rows = $result->num_rows;
else $this->num_rows = null;
if ($row_type == 'raw' || !($result instanceof MySQLi_Result)) return $result;
$return = array();
if ($full_names) {
$infos = array();
foreach ($result->fetch_fields() as $info) {
if (strlen($info->table)) $infos[] = $info->table . '.' . $info->name;
else $infos[] = $info->name;
}
}
while ($row = ($row_type == 'assoc' ? $result->fetch_assoc() : $result->fetch_row())) {
if ($full_names) $row = array_combine($infos, $row);
$return[] = $row;
}
// free results
$result->free();
while ($db->more_results()) {
$db->next_result();
if ($result = $db->use_result()) $result->free();
}
return $return;
}
public function queryOneRow() { $args = func_get_args(); return call_user_func_array(array($this, 'queryFirstRow'), $args); }
public function queryFirstRow() {
$args = func_get_args();
$result = call_user_func_array(array($this, 'query'), $args);
if (!$result || !is_array($result)) return null;
return reset($result);
}
public function queryOneList() { $args = func_get_args(); return call_user_func_array(array($this, 'queryFirstList'), $args); }
public function queryFirstList() {
$args = func_get_args();
$result = call_user_func_array(array($this, 'queryAllLists'), $args);
if (!$result || !is_array($result)) return null;
return reset($result);
}
public function queryFirstColumn() {
$args = func_get_args();
$results = call_user_func_array(array($this, 'queryAllLists'), $args);
$ret = array();
if (!count($results) || !count($results[0])) return $ret;
foreach ($results as $row) {
$ret[] = $row[0];
}
return $ret;
}
public function queryOneColumn() {
$args = func_get_args();
$column = array_shift($args);
$results = call_user_func_array(array($this, 'query'), $args);
$ret = array();
if (!count($results) || !count($results[0])) return $ret;
if ($column === null) {
$keys = array_keys($results[0]);
$column = $keys[0];
}
foreach ($results as $row) {
$ret[] = $row[$column];
}
return $ret;
}
public function queryFirstField() {
$args = func_get_args();
$row = call_user_func_array(array($this, 'queryFirstList'), $args);
if ($row == null) return null;
return $row[0];
}
public function queryOneField() {
$args = func_get_args();
$column = array_shift($args);
$row = call_user_func_array(array($this, 'queryOneRow'), $args);
if ($row == null) {
return null;
} else if ($column === null) {
$keys = array_keys($row);
$column = $keys[0];
}
return $row[$column];
}
}
class WhereClause {
public $type = 'and'; //AND or OR
public $negate = false;
public $clauses = array();
function __construct($type) {
$type = strtolower($type);
if ($type !== 'or' && $type !== 'and') DB::nonSQLError('you must use either WhereClause(and) or WhereClause(or)');
$this->type = $type;
}
function add() {
$args = func_get_args();
$sql = array_shift($args);
if ($sql instanceof WhereClause) {
$this->clauses[] = $sql;
} else {
$this->clauses[] = array('sql' => $sql, 'args' => $args);
}
}
function negateLast() {
$i = count($this->clauses) - 1;
if (!isset($this->clauses[$i])) return;
if ($this->clauses[$i] instanceof WhereClause) {
$this->clauses[$i]->negate();
} else {
$this->clauses[$i]['sql'] = 'NOT (' . $this->clauses[$i]['sql'] . ')';
}
}
function negate() {
$this->negate = ! $this->negate;
}
function addClause($type) {
$r = new WhereClause($type);
$this->add($r);
return $r;
}
function count() {
return count($this->clauses);
}
function textAndArgs() {
$sql = array();
$args = array();
if (count($this->clauses) == 0) return array('(1)', $args);
foreach ($this->clauses as $clause) {
if ($clause instanceof WhereClause) {
list($clause_sql, $clause_args) = $clause->textAndArgs();
} else {
$clause_sql = $clause['sql'];
$clause_args = $clause['args'];
}
$sql[] = "($clause_sql)";
$args = array_merge($args, $clause_args);
}
if ($this->type == 'and') $sql = implode(' AND ', $sql);
else $sql = implode(' OR ', $sql);
if ($this->negate) $sql = '(NOT ' . $sql . ')';
return array($sql, $args);
}
// backwards compatability
// we now return full WhereClause object here and evaluate it in preparseQueryParams
function text() { return $this; }
}
class DBTransaction {
private $committed = false;
function __construct() {
DB::startTransaction();
}
function __destruct() {
if (! $this->committed) DB::rollback();
}
function commit() {
DB::commit();
$this->committed = true;
}
}
class MeekroDBException extends Exception {
protected $query = '';
function __construct($message='', $query='', $code = 0) {
parent::__construct($message);
$this->query = $query;
$this->code = $code;
}
public function getQuery() { return $this->query; }
}
class DBHelper {
/*
verticalSlice
1. For an array of assoc rays, return an array of values for a particular key
2. if $keyfield is given, same as above but use that hash key as the key in new array
*/
public static function verticalSlice($array, $field, $keyfield = null) {
$array = (array) $array;
$R = array();
foreach ($array as $obj) {
if (! array_key_exists($field, $obj)) die("verticalSlice: array doesn't have requested field\n");
if ($keyfield) {
if (! array_key_exists($keyfield, $obj)) die("verticalSlice: array doesn't have requested field\n");
$R[$obj[$keyfield]] = $obj[$field];
} else {
$R[] = $obj[$field];
}
}
return $R;
}
/*
reIndex
For an array of assoc rays, return a new array of assoc rays using a certain field for keys
*/
public static function reIndex() {
$fields = func_get_args();
$array = array_shift($fields);
$array = (array) $array;
$R = array();
foreach ($array as $obj) {
$target =& $R;
foreach ($fields as $field) {
if (! array_key_exists($field, $obj)) die("reIndex: array doesn't have requested field\n");
$nextkey = $obj[$field];
$target =& $target[$nextkey];
}
$target = $obj;
}
return $R;
}
}
function meekrodb_error_handler($params) {
if (isset($params['query'])) $out[] = "QUERY: " . $params['query'];
if (isset($params['error'])) $out[] = "ERROR: " . $params['error'];
$out[] = "";
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
echo implode("\n", $out);
} else {
echo implode("<br>\n", $out);
}
die;
}
function meekrodb_debugmode_handler($params) {
echo "QUERY: " . $params['query'] . " [" . $params['runtime'] . " ms]";
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
echo "\n";
} else {
echo "<br>\n";
}
}
class MeekroDBEval {
public $text = '';
function __construct($text) {
$this->text = $text;
}
}
?>
+420
View File
@@ -0,0 +1,420 @@
<?php
class BasicTest extends SimpleTest {
function __construct() {
foreach (DB::tableList() as $table) {
DB::query("DROP TABLE %b", $table);
}
}
function test_1_create_table() {
DB::query("CREATE TABLE `accounts` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`profile_id` INT NOT NULL,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NULL ,
`age` INT NOT NULL DEFAULT '10',
`height` DOUBLE NOT NULL DEFAULT '10.0',
`favorite_word` VARCHAR( 255 ) NULL DEFAULT 'hi',
`birthday` TIMESTAMP NOT NULL
) ENGINE = InnoDB");
DB::query("CREATE TABLE `profile` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`signature` VARCHAR( 255 ) NULL DEFAULT 'donewriting'
) ENGINE = InnoDB");
$mysqli = DB::get();
DB::disconnect();
@$this->assert($mysqli->server_info === null);
}
function test_1_5_empty_table() {
$counter = DB::queryFirstField("SELECT COUNT(*) FROM accounts");
$this->assert($counter === strval(0));
$row = DB::queryFirstRow("SELECT * FROM accounts");
$this->assert($row === null);
$field = DB::queryFirstField("SELECT * FROM accounts");
$this->assert($field === null);
$field = DB::queryOneField('nothere', "SELECT * FROM accounts");
$this->assert($field === null);
$column = DB::queryFirstColumn("SELECT * FROM accounts");
$this->assert(is_array($column) && count($column) === 0);
$column = DB::queryOneColumn('nothere', "SELECT * FROM accounts"); //TODO: is this what we want?
$this->assert(is_array($column) && count($column) === 0);
}
function test_2_insert_row() {
$true = DB::insert('accounts', array(
'username' => 'Abe',
'password' => 'hello'
));
$this->assert($true === true);
$this->assert(DB::affectedRows() === 1);
$counter = DB::queryFirstField("SELECT COUNT(*) FROM accounts");
$this->assert($counter === strval(1));
}
function test_3_more_inserts() {
DB::insert('`accounts`', array(
'username' => 'Bart',
'password' => 'hello',
'age' => 15,
'height' => 10.371
));
$dbname = DB::$dbName;
DB::insert("`$dbname`.`accounts`", array(
'username' => 'Charlie\'s Friend',
'password' => 'goodbye',
'age' => 30,
'height' => 155.23,
'favorite_word' => null,
));
$this->assert(DB::insertId() === 3);
$counter = DB::queryFirstField("SELECT COUNT(*) FROM accounts");
$this->assert($counter === strval(3));
DB::insert('`accounts`', array(
'username' => 'Deer',
'password' => '',
'age' => 15,
'height' => 10.371
));
$username = DB::queryFirstField("SELECT username FROM accounts WHERE password=%s0", null);
$this->assert($username === 'Deer');
$password = DB::queryFirstField("SELECT password FROM accounts WHERE favorite_word IS NULL");
$this->assert($password === 'goodbye');
DB::$usenull = false;
DB::insertUpdate('accounts', array(
'id' => 3,
'favorite_word' => null,
));
$password = DB::queryFirstField("SELECT password FROM accounts WHERE favorite_word=%s AND favorite_word=%s", null, '');
$this->assert($password === 'goodbye');
DB::$usenull = true;
DB::insertUpdate('accounts', array(
'id' => 3,
'favorite_word' => null,
));
DB::$param_char = '###';
$bart = DB::queryFirstRow("SELECT * FROM accounts WHERE age IN ###li AND height IN ###ld AND username IN ###ls",
array(15, 25), array(10.371, 150.123), array('Bart', 'Barts'));
$this->assert($bart['username'] === 'Bart');
DB::insert('accounts', array('username' => 'f_u'));
DB::query("DELETE FROM accounts WHERE username=###s", 'f_u');
DB::$param_char = '%';
$charlie_password = DB::queryFirstField("SELECT password FROM accounts WHERE username IN %ls AND username = %s",
array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend');
$this->assert($charlie_password === 'goodbye');
$charlie_password = DB::queryOneField('password', "SELECT * FROM accounts WHERE username IN %ls AND username = %s",
array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend');
$this->assert($charlie_password === 'goodbye');
$passwords = DB::queryFirstColumn("SELECT password FROM accounts WHERE username=%s", 'Bart');
$this->assert(count($passwords) === 1);
$this->assert($passwords[0] === 'hello');
$username = $password = $age = null;
list($age, $username, $password) = DB::queryOneList("SELECT age,username,password FROM accounts WHERE username=%s", 'Bart');
$this->assert($username === 'Bart');
$this->assert($password === 'hello');
$this->assert($age == 15);
$mysqli_result = DB::queryRaw("SELECT * FROM accounts WHERE favorite_word IS NULL");
$this->assert($mysqli_result instanceof MySQLi_Result);
$row = $mysqli_result->fetch_assoc();
$this->assert($row['password'] === 'goodbye');
$this->assert($mysqli_result->fetch_assoc() === null);
}
function test_4_query() {
DB::update('accounts', array(
'birthday' => new DateTime('10 September 2000 13:13:13')
), 'username=%s', 'Charlie\'s Friend');
$results = DB::query("SELECT * FROM accounts WHERE username=%s AND birthday IN %lt", 'Charlie\'s Friend', array('September 10 2000 13:13:13'));
$this->assert(count($results) === 1);
$this->assert($results[0]['age'] === '30' && $results[0]['password'] === 'goodbye');
$this->assert($results[0]['birthday'] == '2000-09-10 13:13:13');
$results = DB::query("SELECT * FROM accounts WHERE username!=%s", "Charlie's Friend");
$this->assert(count($results) === 3);
$columnlist = DB::columnList('accounts');
$this->assert(count($columnlist) === 8);
$this->assert($columnlist[0] === 'id');
$this->assert($columnlist[5] === 'height');
$tablelist = DB::tableList();
$this->assert(count($tablelist) === 2);
$this->assert($tablelist[0] === 'accounts');
$tablelist = null;
$tablelist = DB::tableList(DB::$dbName);
$this->assert(count($tablelist) === 2);
$this->assert($tablelist[0] === 'accounts');
}
function test_4_1_query() {
DB::insert('accounts', array(
'username' => 'newguy',
'password' => DB::sqleval("REPEAT('blah', %i)", '3'),
'age' => DB::sqleval('171+1'),
'height' => 111.15
));
$row = DB::queryOneRow("SELECT * FROM accounts WHERE password=%s", 'blahblahblah');
$this->assert($row['username'] === 'newguy');
$this->assert($row['age'] === '172');
$true = DB::update('accounts', array(
'password' => DB::sqleval("REPEAT('blah', %i)", 4),
'favorite_word' => null,
), 'username=%s', 'newguy');
$row = null;
$row = DB::queryOneRow("SELECT * FROM accounts WHERE username=%s", 'newguy');
$this->assert($true === true);
$this->assert($row['password'] === 'blahblahblahblah');
$this->assert($row['favorite_word'] === null);
$row = DB::query("SELECT * FROM accounts WHERE password=%s_mypass AND (password=%s_mypass) AND username=%s_myuser",
array('myuser' => 'newguy', 'mypass' => 'blahblahblahblah')
);
$this->assert(count($row) === 1);
$this->assert($row[0]['username'] === 'newguy');
$this->assert($row[0]['age'] === '172');
$true = DB::query("DELETE FROM accounts WHERE password=%s", 'blahblahblahblah');
$this->assert($true === true);
$this->assert(DB::affectedRows() === 1);
}
function test_4_2_delete() {
DB::insert('accounts', array(
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
));
$ct = DB::queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', 199.194);
$this->assert(intval($ct) === 1);
$ct = DB::queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s1 AND height=%d0 AND height=%d", 199.194, 'gonesoon');
$this->assert(intval($ct) === 1);
DB::delete('accounts', 'username=%s AND age=%i AND height=%d', 'gonesoon', '61', '199.194');
$this->assert(DB::affectedRows() === 1);
$ct = DB::queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', '199.194');
$this->assert(intval($ct) === 0);
}
function test_4_3_insertmany() {
$ins[] = array(
'username' => '1ofmany',
'password' => 'something',
'age' => 23,
'height' => 190.194
);
$ins[] = array(
'password' => 'somethingelse',
'username' => '2ofmany',
'age' => 25,
'height' => 190.194
);
$ins[] = array(
'password' => NULL,
'username' => '3ofmany',
'age' => 15,
'height' => 111.951
);
DB::insert('accounts', $ins);
$this->assert(DB::affectedRows() === 3);
$rows = DB::query("SELECT * FROM accounts WHERE height=%d ORDER BY age ASC", 190.194);
$this->assert(count($rows) === 2);
$this->assert($rows[0]['username'] === '1ofmany');
$this->assert($rows[0]['age'] === '23');
$this->assert($rows[1]['age'] === '25');
$this->assert($rows[1]['password'] === 'somethingelse');
$this->assert($rows[1]['username'] === '2ofmany');
$nullrow = DB::queryOneRow("SELECT * FROM accounts WHERE username LIKE %ss", '3ofman');
$this->assert($nullrow['password'] === NULL);
$this->assert($nullrow['age'] === '15');
}
function test_5_insert_blobs() {
DB::query("CREATE TABLE `store data` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`picture` BLOB
) ENGINE = InnoDB");
$columns = DB::columnList('store data');
$this->assert(count($columns) === 2);
$this->assert($columns[1] === 'picture');
$smile = file_get_contents('smile1.jpg');
DB::insert('store data', array(
'picture' => $smile,
));
DB::queryOneRow("INSERT INTO %b (picture) VALUES (%s)", 'store data', $smile);
$getsmile = DB::queryFirstField("SELECT picture FROM %b WHERE id=1", 'store data');
$getsmile2 = DB::queryFirstField("SELECT picture FROM %b WHERE id=2", 'store data');
$this->assert($smile === $getsmile);
$this->assert($smile === $getsmile2);
}
function test_6_insert_ignore() {
DB::insertIgnore('accounts', array(
'id' => 1, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
));
}
function test_7_insert_update() {
$true = DB::insertUpdate('accounts', array(
'id' => 2, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
), 'age = age + %i', 1);
$this->assert($true === true);
$this->assert(DB::affectedRows() === 2); // a quirk of MySQL, even though only 1 row was updated
$result = DB::query("SELECT * FROM accounts WHERE age = %i", 16);
$this->assert(count($result) === 1);
$this->assert($result[0]['height'] === '10.371');
DB::insertUpdate('accounts', array(
'id' => 2, //duplicate primary key
'username' => 'blahblahdude',
'age' => 233,
'height' => 199.194
));
$result = DB::query("SELECT * FROM accounts WHERE age = %i", 233);
$this->assert(count($result) === 1);
$this->assert($result[0]['height'] === '199.194');
$this->assert($result[0]['username'] === 'blahblahdude');
DB::insertUpdate('accounts', array(
'id' => 2, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
), array(
'age' => 74,
));
$result = DB::query("SELECT * FROM accounts WHERE age = %i", 74);
$this->assert(count($result) === 1);
$this->assert($result[0]['height'] === '199.194');
$this->assert($result[0]['username'] === 'blahblahdude');
$multiples[] = array(
'id' => 3, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
);
$multiples[] = array(
'id' => 1, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
);
DB::insertUpdate('accounts', $multiples, array('age' => 914));
$this->assert(DB::affectedRows() === 4);
$result = DB::query("SELECT * FROM accounts WHERE age=914 ORDER BY id ASC");
$this->assert(count($result) === 2);
$this->assert($result[0]['username'] === 'Abe');
$this->assert($result[1]['username'] === 'Charlie\'s Friend');
$true = DB::query("UPDATE accounts SET age=15, username='Bart' WHERE age=%i", 74);
$this->assert($true === true);
$this->assert(DB::affectedRows() === 1);
}
function test_8_lb() {
$data = array(
'username' => 'vookoo',
'password' => 'dookoo',
);
$true = DB::query("INSERT into accounts %lb VALUES %ls", array_keys($data), array_values($data));
$result = DB::query("SELECT * FROM accounts WHERE username=%s", 'vookoo');
$this->assert($true === true);
$this->assert(count($result) === 1);
$this->assert($result[0]['password'] === 'dookoo');
}
function test_9_fullcolumns() {
$true = DB::insert('profile', array(
'id' => 1,
'signature' => 'u_suck'
));
DB::query("UPDATE accounts SET profile_id=1 WHERE id=2");
$r = DB::queryFullColumns("SELECT accounts.*, profile.*, 1+1 FROM accounts
INNER JOIN profile ON accounts.profile_id=profile.id");
$this->assert($true === true);
$this->assert(count($r) === 1);
$this->assert($r[0]['accounts.id'] === '2');
$this->assert($r[0]['profile.id'] === '1');
$this->assert($r[0]['profile.signature'] === 'u_suck');
$this->assert($r[0]['1+1'] === '2');
}
function test_901_updatewithspecialchar() {
$data = 'www.mysite.com/product?s=t-%s-%%3d%%3d%i&RCAID=24322';
DB::update('profile', array('signature' => $data), 'id=%i', 1);
$signature = DB::queryFirstField("SELECT signature FROM profile WHERE id=%i", 1);
$this->assert($signature === $data);
DB::update('profile',array('signature'=> "%li "),"id = %d",1);
$signature = DB::queryFirstField("SELECT signature FROM profile WHERE id=%i", 1);
$this->assert($signature === "%li ");
}
}
?>
+17
View File
@@ -0,0 +1,17 @@
<?php
class CallTest extends SimpleTest {
function test_1_create_procedure() {
DB::query("DROP PROCEDURE IF EXISTS myProc");
DB::query("CREATE PROCEDURE myProc()
BEGIN
SELECT * FROM accounts;
END");
}
function test_2_run_procedure() {
$r = DB::query("CALL myProc()");
$this->assert($r[0]['username'] === 'Abe');
$this->assert($r[2]['age'] === '914');
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
function new_error_callback($params) {
global $error_callback_worked;
if (substr_count($params['error'], 'You have an error in your SQL syntax')) $error_callback_worked = 1;
}
function my_debug_handler($params) {
global $debug_callback_worked;
if (substr_count($params['query'], 'SELECT')) $debug_callback_worked = 1;
}
class ErrorTest extends SimpleTest {
function test_1_error_handler() {
global $error_callback_worked, $static_error_callback_worked, $nonstatic_error_callback_worked;
DB::$error_handler = 'new_error_callback';
DB::query("SELET * FROM accounts");
$this->assert($error_callback_worked === 1);
DB::$error_handler = array('ErrorTest', 'static_error_callback');
DB::query("SELET * FROM accounts");
$this->assert($static_error_callback_worked === 1);
DB::$error_handler = array($this, 'nonstatic_error_callback');
DB::query("SELET * FROM accounts");
$this->assert($nonstatic_error_callback_worked === 1);
}
public static function static_error_callback($params) {
global $static_error_callback_worked;
if (substr_count($params['error'], 'You have an error in your SQL syntax')) $static_error_callback_worked = 1;
}
public function nonstatic_error_callback($params) {
global $nonstatic_error_callback_worked;
if (substr_count($params['error'], 'You have an error in your SQL syntax')) $nonstatic_error_callback_worked = 1;
}
function test_2_exception_catch() {
$dbname = DB::$dbName;
DB::$error_handler = '';
DB::$throw_exception_on_error = true;
try {
DB::query("SELET * FROM accounts");
} catch(MeekroDBException $e) {
$this->assert(substr_count($e->getMessage(), 'You have an error in your SQL syntax'));
$this->assert($e->getQuery() === 'SELET * FROM accounts');
$exception_was_caught = 1;
}
$this->assert($exception_was_caught === 1);
try {
DB::insert("`$dbname`.`accounts`", array(
'id' => 2,
'username' => 'Another Dude\'s \'Mom"',
'password' => 'asdfsdse',
'age' => 35,
'height' => 555.23
));
} catch(MeekroDBException $e) {
$this->assert(substr_count($e->getMessage(), 'Duplicate entry'));
$exception_was_caught = 2;
}
$this->assert($exception_was_caught === 2);
}
function test_3_debugmode_handler() {
global $debug_callback_worked;
DB::debugMode('my_debug_handler');
DB::query("SELECT * FROM accounts WHERE username!=%s", "Charlie's Friend");
$this->assert($debug_callback_worked === 1);
DB::debugMode(false);
}
}
?>
@@ -0,0 +1,19 @@
<?php
class ErrorTest_53 extends SimpleTest {
function test_1_error_handler() {
global $anonymous_error_callback_worked;
DB::$throw_exception_on_error = false;
DB::$error_handler = function($params) {
global $anonymous_error_callback_worked;
if (substr_count($params['error'], 'You have an error in your SQL syntax')) $anonymous_error_callback_worked = 1;
};
DB::query("SELET * FROM accounts");
$this->assert($anonymous_error_callback_worked === 1);
}
}
?>
+51
View File
@@ -0,0 +1,51 @@
<?php
class HelperTest extends SimpleTest {
function test_1_verticalslice() {
$all = DB::query("SELECT * FROM accounts ORDER BY id ASC");
$names = DBHelper::verticalSlice($all, 'username');
$this->assert(count($names) === 5);
$this->assert($names[0] === 'Abe');
$ages = DBHelper::verticalSlice($all, 'age', 'username');
$this->assert(count($ages) === 5);
$this->assert($ages['Abe'] === '700');
}
function test_2_reindex() {
$all = DB::query("SELECT * FROM accounts ORDER BY id ASC");
$names = DBHelper::reIndex($all, 'username');
$this->assert(count($names) === 5);
$this->assert($names['Bart']['username'] === 'Bart');
$this->assert($names['Bart']['age'] === '15');
$names = DBHelper::reIndex($all, 'username', 'age');
$this->assert($names['Bart']['15']['username'] === 'Bart');
$this->assert($names['Bart']['15']['age'] === '15');
}
function test_3_empty() {
$none = DB::query("SELECT * FROM accounts WHERE username=%s", 'doesnotexist');
$this->assert(is_array($none) && count($none) === 0);
$names = DBHelper::verticalSlice($none, 'username', 'age');
$this->assert(is_array($names) && count($names) === 0);
$names_other = DBHelper::reIndex($none, 'username', 'age');
$this->assert(is_array($names_other) && count($names_other) === 0);
}
function test_4_null() {
DB::query("UPDATE accounts SET password = NULL WHERE username=%s", 'Bart');
$all = DB::query("SELECT * FROM accounts ORDER BY id ASC");
$ages = DBHelper::verticalSlice($all, 'age', 'password');
$this->assert(count($ages) === 5);
$this->assert($ages[''] === '15');
$passwords = DBHelper::reIndex($all, 'password');
$this->assert(count($passwords) === 5);
$this->assert($passwords['']['username'] === 'Bart');
$this->assert($passwords['']['password'] === NULL);
}
}
?>
+312
View File
@@ -0,0 +1,312 @@
<?php
class ObjectTest extends SimpleTest {
public $mdb;
function __construct() {
$this->mdb = new MeekroDB();
foreach ($this->mdb->tableList() as $table) {
$this->mdb->query("DROP TABLE %b", $table);
}
}
function test_1_create_table() {
$this->mdb->query("CREATE TABLE `accounts` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NULL ,
`age` INT NOT NULL DEFAULT '10',
`height` DOUBLE NOT NULL DEFAULT '10.0',
`favorite_word` VARCHAR( 255 ) NULL DEFAULT 'hi'
) ENGINE = InnoDB");
}
function test_1_5_empty_table() {
$counter = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts");
$this->assert($counter === strval(0));
$row = $this->mdb->queryFirstRow("SELECT * FROM accounts");
$this->assert($row === null);
$field = $this->mdb->queryFirstField("SELECT * FROM accounts");
$this->assert($field === null);
$field = $this->mdb->queryOneField('nothere', "SELECT * FROM accounts");
$this->assert($field === null);
$column = $this->mdb->queryFirstColumn("SELECT * FROM accounts");
$this->assert(is_array($column) && count($column) === 0);
$column = $this->mdb->queryOneColumn('nothere', "SELECT * FROM accounts"); //TODO: is this what we want?
$this->assert(is_array($column) && count($column) === 0);
}
function test_2_insert_row() {
$this->mdb->insert('accounts', array(
'username' => 'Abe',
'password' => 'hello'
));
$this->assert($this->mdb->affectedRows() === 1);
$counter = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts");
$this->assert($counter === strval(1));
}
function test_3_more_inserts() {
$this->mdb->insert('`accounts`', array(
'username' => 'Bart',
'password' => 'hello',
'age' => 15,
'height' => 10.371
));
$dbname = $this->mdb->dbName;
$this->mdb->insert("`$dbname`.`accounts`", array(
'username' => 'Charlie\'s Friend',
'password' => 'goodbye',
'age' => 30,
'height' => 155.23,
'favorite_word' => null,
));
$this->assert($this->mdb->insertId() === 3);
$counter = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts");
$this->assert($counter === strval(3));
$password = $this->mdb->queryFirstField("SELECT password FROM accounts WHERE favorite_word IS NULL");
$this->assert($password === 'goodbye');
$this->mdb->param_char = '###';
$bart = $this->mdb->queryFirstRow("SELECT * FROM accounts WHERE age IN ###li AND height IN ###ld AND username IN ###ls",
array(15, 25), array(10.371, 150.123), array('Bart', 'Barts'));
$this->assert($bart['username'] === 'Bart');
$this->mdb->param_char = '%';
$charlie_password = $this->mdb->queryFirstField("SELECT password FROM accounts WHERE username IN %ls AND username = %s",
array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend');
$this->assert($charlie_password === 'goodbye');
$charlie_password = $this->mdb->queryOneField('password', "SELECT * FROM accounts WHERE username IN %ls AND username = %s",
array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend');
$this->assert($charlie_password === 'goodbye');
$passwords = $this->mdb->queryFirstColumn("SELECT password FROM accounts WHERE username=%s", 'Bart');
$this->assert(count($passwords) === 1);
$this->assert($passwords[0] === 'hello');
$username = $password = $age = null;
list($age, $username, $password) = $this->mdb->queryOneList("SELECT age,username,password FROM accounts WHERE username=%s", 'Bart');
$this->assert($username === 'Bart');
$this->assert($password === 'hello');
$this->assert($age == 15);
$mysqli_result = $this->mdb->queryRaw("SELECT * FROM accounts WHERE favorite_word IS NULL");
$this->assert($mysqli_result instanceof MySQLi_Result);
$row = $mysqli_result->fetch_assoc();
$this->assert($row['password'] === 'goodbye');
$this->assert($mysqli_result->fetch_assoc() === null);
}
function test_4_query() {
$results = $this->mdb->query("SELECT * FROM accounts WHERE username=%s", 'Charlie\'s Friend');
$this->assert(count($results) === 1);
$this->assert($results[0]['age'] == 30 && $results[0]['password'] == 'goodbye');
$results = $this->mdb->query("SELECT * FROM accounts WHERE username!=%s", "Charlie's Friend");
$this->assert(count($results) === 2);
$columnlist = $this->mdb->columnList('accounts');
$this->assert(count($columnlist) === 6);
$this->assert($columnlist[0] === 'id');
$this->assert($columnlist[4] === 'height');
$tablelist = $this->mdb->tableList();
$this->assert(count($tablelist) === 1);
$this->assert($tablelist[0] === 'accounts');
$tablelist = null;
$tablelist = $this->mdb->tableList($this->mdb->dbName);
$this->assert(count($tablelist) === 1);
$this->assert($tablelist[0] === 'accounts');
}
function test_4_1_query() {
$this->mdb->insert('accounts', array(
'username' => 'newguy',
'password' => $this->mdb->sqleval("REPEAT('blah', %i)", '3'),
'age' => $this->mdb->sqleval('171+1'),
'height' => 111.15
));
$row = $this->mdb->queryOneRow("SELECT * FROM accounts WHERE password=%s", 'blahblahblah');
$this->assert($row['username'] === 'newguy');
$this->assert($row['age'] === '172');
$this->mdb->update('accounts', array(
'password' => $this->mdb->sqleval("REPEAT('blah', %i)", 4),
'favorite_word' => null,
), 'username=%s', 'newguy');
$row = null;
$row = $this->mdb->queryOneRow("SELECT * FROM accounts WHERE username=%s", 'newguy');
$this->assert($row['password'] === 'blahblahblahblah');
$this->assert($row['favorite_word'] === null);
$this->mdb->query("DELETE FROM accounts WHERE password=%s", 'blahblahblahblah');
$this->assert($this->mdb->affectedRows() === 1);
}
function test_4_2_delete() {
$this->mdb->insert('accounts', array(
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
));
$ct = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', 199.194);
$this->assert(intval($ct) === 1);
$ct = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s1 AND height=%d0 AND height=%d", 199.194, 'gonesoon');
$this->assert(intval($ct) === 1);
$this->mdb->delete('accounts', 'username=%s AND age=%i AND height=%d', 'gonesoon', '61', '199.194');
$this->assert($this->mdb->affectedRows() === 1);
$ct = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', '199.194');
$this->assert(intval($ct) === 0);
}
function test_4_3_insertmany() {
$ins[] = array(
'username' => '1ofmany',
'password' => 'something',
'age' => 23,
'height' => 190.194
);
$ins[] = array(
'password' => 'somethingelse',
'username' => '2ofmany',
'age' => 25,
'height' => 190.194
);
$this->mdb->insert('accounts', $ins);
$this->assert($this->mdb->affectedRows() === 2);
$rows = $this->mdb->query("SELECT * FROM accounts WHERE height=%d ORDER BY age ASC", 190.194);
$this->assert(count($rows) === 2);
$this->assert($rows[0]['username'] === '1ofmany');
$this->assert($rows[0]['age'] === '23');
$this->assert($rows[1]['age'] === '25');
$this->assert($rows[1]['password'] === 'somethingelse');
$this->assert($rows[1]['username'] === '2ofmany');
}
function test_5_insert_blobs() {
$this->mdb->query("CREATE TABLE `storedata` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`picture` BLOB
) ENGINE = InnoDB");
$smile = file_get_contents('smile1.jpg');
$this->mdb->insert('storedata', array(
'picture' => $smile,
));
$this->mdb->query("INSERT INTO storedata (picture) VALUES (%s)", $smile);
$getsmile = $this->mdb->queryFirstField("SELECT picture FROM storedata WHERE id=1");
$getsmile2 = $this->mdb->queryFirstField("SELECT picture FROM storedata WHERE id=2");
$this->assert($smile === $getsmile);
$this->assert($smile === $getsmile2);
}
function test_6_insert_ignore() {
$this->mdb->insertIgnore('accounts', array(
'id' => 1, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
));
}
function test_7_insert_update() {
$this->mdb->insertUpdate('accounts', array(
'id' => 2, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
), 'age = age + %i', 1);
$this->assert($this->mdb->affectedRows() === 2); // a quirk of MySQL, even though only 1 row was updated
$result = $this->mdb->query("SELECT * FROM accounts WHERE age = %i", 16);
$this->assert(count($result) === 1);
$this->assert($result[0]['height'] === '10.371');
$this->mdb->insertUpdate('accounts', array(
'id' => 2, //duplicate primary key
'username' => 'blahblahdude',
'age' => 233,
'height' => 199.194
));
$result = $this->mdb->query("SELECT * FROM accounts WHERE age = %i", 233);
$this->assert(count($result) === 1);
$this->assert($result[0]['height'] === '199.194');
$this->assert($result[0]['username'] === 'blahblahdude');
$this->mdb->insertUpdate('accounts', array(
'id' => 2, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
), array(
'age' => 74,
));
$result = $this->mdb->query("SELECT * FROM accounts WHERE age = %i", 74);
$this->assert(count($result) === 1);
$this->assert($result[0]['height'] === '199.194');
$this->assert($result[0]['username'] === 'blahblahdude');
$multiples[] = array(
'id' => 3, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
);
$multiples[] = array(
'id' => 1, //duplicate primary key
'username' => 'gonesoon',
'password' => 'something',
'age' => 61,
'height' => 199.194
);
$this->mdb->insertUpdate('accounts', $multiples, array('age' => 914));
$this->assert($this->mdb->affectedRows() === 4);
$result = $this->mdb->query("SELECT * FROM accounts WHERE age=914 ORDER BY id ASC");
$this->assert(count($result) === 2);
$this->assert($result[0]['username'] === 'Abe');
$this->assert($result[1]['username'] === 'Charlie\'s Friend');
$this->mdb->query("UPDATE accounts SET age=15, username='Bart' WHERE age=%i", 74);
$this->assert($this->mdb->affectedRows() === 1);
}
}
?>
@@ -0,0 +1,30 @@
<?php
class TransactionTest extends SimpleTest {
function test_1_transactions() {
DB::$nested_transactions = false;
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 600, 'Abe');
$depth = DB::startTransaction();
$this->assert($depth === 1);
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 700, 'Abe');
$depth = DB::startTransaction();
$this->assert($depth === 1);
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 800, 'Abe');
$depth = DB::rollback();
$this->assert($depth === 0);
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 700);
$depth = DB::rollback();
$this->assert($depth === 0);
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 700);
}
}
?>
@@ -0,0 +1,85 @@
<?php
class TransactionTest_55 extends SimpleTest {
function test_1_transactions() {
DB::$nested_transactions = true;
$depth = DB::startTransaction();
$this->assert($depth === 1);
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 700, 'Abe');
$depth = DB::startTransaction();
$this->assert($depth === 2);
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 800, 'Abe');
$depth = DB::startTransaction();
$this->assert($depth === 3);
$this->assert(DB::transactionDepth() === 3);
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 500, 'Abe');
$depth = DB::commit();
$this->assert($depth === 2);
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 500);
$depth = DB::rollback();
$this->assert($depth === 1);
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 700);
$depth = DB::commit();
$this->assert($depth === 0);
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 700);
DB::$nested_transactions = false;
}
function test_2_transactions() {
DB::$nested_transactions = true;
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 600, 'Abe');
DB::startTransaction();
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 700, 'Abe');
DB::startTransaction();
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 800, 'Abe');
DB::rollback();
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 700);
DB::rollback();
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 600);
DB::$nested_transactions = false;
}
function test_3_transaction_rollback_all() {
DB::$nested_transactions = true;
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 200, 'Abe');
$depth = DB::startTransaction();
$this->assert($depth === 1);
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 300, 'Abe');
$depth = DB::startTransaction();
$this->assert($depth === 2);
DB::query("UPDATE accounts SET age=%i WHERE username=%s", 400, 'Abe');
$depth = DB::rollback(true);
$this->assert($depth === 0);
$age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe');
$this->assert($age == 200);
DB::$nested_transactions = false;
}
}
?>
@@ -0,0 +1,73 @@
<?php
class WhereClauseTest extends SimpleTest {
function test_1_basic_where() {
$where = new WhereClause('and');
$where->add('username=%s', 'Bart');
$where->add('password=%s', 'hello');
$result = DB::query("SELECT * FROM accounts WHERE %l", $where->text());
$this->assert(count($result) === 1);
$this->assert($result[0]['age'] === '15');
}
function test_2_simple_grouping() {
$where = new WhereClause('and');
$where->add('password=%s', 'hello');
$subclause = $where->addClause('or');
$subclause->add('age=%i', 15);
$subclause->add('age=%i', 14);
$result = DB::query("SELECT * FROM accounts WHERE %l", $where->text());
$this->assert(count($result) === 1);
$this->assert($result[0]['age'] === '15');
}
function test_3_negate_last() {
$where = new WhereClause('and');
$where->add('password=%s', 'hello');
$subclause = $where->addClause('or');
$subclause->add('username!=%s', 'Bart');
$subclause->negateLast();
$result = DB::query("SELECT * FROM accounts WHERE %l", $where->text());
$this->assert(count($result) === 1);
$this->assert($result[0]['age'] === '15');
}
function test_4_negate_last_query() {
$where = new WhereClause('and');
$where->add('password=%s', 'hello');
$subclause = $where->addClause('or');
$subclause->add('username!=%s', 'Bart');
$where->negateLast();
$result = DB::query("SELECT * FROM accounts WHERE %l", $where);
$this->assert(count($result) === 1);
$this->assert($result[0]['age'] === '15');
}
function test_5_negate() {
$where = new WhereClause('and');
$where->add('password=%s', 'hello');
$subclause = $where->addClause('or');
$subclause->add('username!=%s', 'Bart');
$subclause->negate();
$result = DB::query("SELECT * FROM accounts WHERE %l", $where);
$this->assert(count($result) === 1);
$this->assert($result[0]['age'] === '15');
}
function test_6_or() {
$where = new WhereClause('or');
$where->add('username=%s', 'Bart');
$where->add('username=%s', 'Abe');
$result = DB::query("SELECT * FROM accounts WHERE %l", $where);
$this->assert(count($result) === 2);
}
}
?>
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Some files were not shown because too many files have changed in this diff Show More