Version 5.1 - All the GraphQL #32

Closed
timw4mail wants to merge 1160 commits from develop into master
205 changed files with 8285 additions and 7514 deletions
Showing only changes of commit 0644c40b1c - Show all commits

5
.gitignore vendored
View File

@ -23,4 +23,7 @@ build/**
!build/*.php !build/*.php
app/config/*.toml app/config/*.toml
!app/config/*.toml.example !app/config/*.toml.example
phinx.yml phinx.yml
.idea/
Caddyfile
build/humbuglog.txt

37
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,37 @@
# Composer stores all downloaded packages in the vendor/ directory.
# Do not use the following if the vendor/ directory is commited to
# your git repository.
cache:
paths:
- vendor/
services:
- redis:latest
test:7:
before_script:
- bash build/docker_install.sh > /dev/null
- curl -sS https://getcomposer.org/installer | php
- php composer.phar install --no-dev
image: php:7
script:
- phpunit -c build
test:7.1:
before_script:
- bash build/docker_install.sh > /dev/null
- curl -sS https://getcomposer.org/installer | php
- php composer.phar install --no-dev
image: php:7.1
script:
- phpunit -c build
test:hhvm:
before_script:
- /usr/local/bin/composer self-update
- curl -Lo /usr/local/bin/phpunit https://phar.phpunit.de/phpunit.phar
- chmod +x /usr/local/bin/phpunit
- composer install --no-dev
image: 51systems/docker-gitlab-ci-runner-hhvm
script:
- hhvm -d hhvm.php7.all=true vendor/bin/phpunit -c build

View File

@ -1 +0,0 @@
extension = "redis.so"

View File

@ -4,20 +4,14 @@ install:
- composer install - composer install
php: php:
- 5.5
- 5.6
- 7 - 7
- hhvm - hhvm
- nightly - nightly
before_script:
- phpenv config-add .travis.ini
script: script:
- mkdir -p build/logs - mkdir -p build/logs
- phpunit -c build - vendor/bin/phpunit -c build
services: services:
- redis - redis

330
RoboFile.php Normal file
View File

@ -0,0 +1,330 @@
<?php
if ( ! function_exists('glob_recursive'))
{
// Does not support flag GLOB_BRACE
function glob_recursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
{
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
}
/**
* This is project's console commands configuration for Robo task runner.
*
* @see http://robo.li/
*/
class RoboFile extends \Robo\Tasks {
/**
* Directories used by analysis tools
*
* @var array
*/
protected $taskDirs = [
'build/logs',
'build/pdepend',
'build/phpdox',
];
/**
* Directories to remove with the clean task
*
* @var array
*/
protected $cleanDirs = [
'coverage',
'docs',
'phpdoc',
'build/logs',
'build/phpdox',
'build/pdepend'
];
/**
* Do static analysis tasks
*/
public function analyze()
{
$this->prepare();
$this->lint();
$this->phploc(TRUE);
$this->phpcs(TRUE);
$this->dependencyReport();
$this->phpcpdReport();
}
/**
* Run all tests, generate coverage, generate docs, generate code statistics
*/
public function build()
{
$this->analyze();
$this->coverage();
$this->docs();
}
/**
* Cleanup temporary files
*/
public function clean()
{
$cleanFiles = [
'build/humbug.json',
'build/humbug-log.txt',
];
array_map(function ($file) {
@unlink($file);
}, $cleanFiles);
// So the task doesn't complain,
// make any 'missing' dirs to cleanup
array_map(function ($dir) {
if ( ! is_dir($dir))
{
`mkdir -p {$dir}`;
}
}, $this->cleanDirs);
$this->_cleanDir($this->cleanDirs);
$this->_deleteDir($this->cleanDirs);
}
/**
* Run unit tests and generate coverage reports
*/
public function coverage()
{
$this->taskPhpUnit()
->configFile('build/phpunit.xml')
->printed(true)
->run();
}
/**
* Generate documentation with phpdox
*/
public function docs()
{
$cmd_parts = [
'cd build',
'../vendor/bin/phpdox',
'cd ..'
];
$this->_run($cmd_parts, ' && ');
}
/**
* Verify that source files are valid
*/
public function lint()
{
$files = $this->getAllSourceFiles();
$chunks = array_chunk($files, 6);
foreach($chunks as $chunk)
{
$this->parallelLint($chunk);
}
}
/**
* Run mutation tests with humbug
*
* @param bool $stats - if true, generates stats rather than running mutation tests
*/
public function mutate($stats = FALSE)
{
$test_parts = [
'vendor/bin/humbug'
];
$stat_parts = [
'vendor/bin/humbug',
'--skip-killed=yes',
'-v',
'./build/humbug.json'
];
$cmd_parts = ($stats) ? $stat_parts : $test_parts;
$this->_run($cmd_parts);
}
/**
* Run the phpcs tool
*
* @param bool $report - if true, generates reports instead of direct output
*/
public function phpcs($report = FALSE)
{
$report_cmd_parts = [
'vendor/bin/phpcs',
'--standard=./build/phpcs.xml',
'--report-checkstyle=./build/logs/phpcs.xml',
];
$normal_cmd_parts = [
'vendor/bin/phpcs',
'--standard=./build/phpcs.xml',
];
$cmd_parts = ($report) ? $report_cmd_parts : $normal_cmd_parts;
$this->_run($cmd_parts);
}
/**
* Run the phploc tool
*
* @param bool $report - if true, generates reports instead of direct output
*/
public function phploc($report = FALSE)
{
// Command for generating reports
$report_cmd_parts = [
'vendor/bin/phploc',
'--count-tests',
'--log-csv=build/logs/phploc.csv',
'--log-xml=build/logs/phploc.xml',
'src',
'tests'
];
// Command for generating direct output
$normal_cmd_parts = [
'vendor/bin/phploc',
'--count-tests',
'src',
'tests'
];
$cmd_parts = ($report) ? $report_cmd_parts : $normal_cmd_parts;
$this->_run($cmd_parts);
}
/**
* Create temporary directories
*/
public function prepare()
{
array_map([$this, '_mkdir'], $this->taskDirs);
}
/**
* Lint php files and run unit tests
*/
public function test()
{
$this->lint();
$this->taskPHPUnit()
->configFile('phpunit.xml')
->printed(true)
->run();
}
/**
* Watches for file updates, and automatically runs appropriate actions
*/
public function watch()
{
$this->taskWatch()
->monitor('composer.json', function() {
$this->taskComposerUpdate()->run();
})
->monitor('src', function () {
$this->taskExec('test')->run();
})
->monitor('tests', function () {
$this->taskExec('test')->run();
})
->run();
}
/**
* Create pdepend reports
*/
protected function dependencyReport()
{
$cmd_parts = [
'vendor/bin/pdepend',
'--jdepend-xml=build/logs/jdepend.xml',
'--jdepend-chart=build/pdepend/dependencies.svg',
'--overview-pyramid=build/pdepend/overview-pyramid.svg',
'src'
];
$this->_run($cmd_parts);
}
/**
* Get the total list of source files, including tests
*
* @return array
*/
protected function getAllSourceFiles()
{
$files = array_merge(
glob_recursive('build/*.php'),
glob_recursive('src/*.php'),
glob_recursive('tests/*.php'),
glob('*.php')
);
sort($files);
return $files;
}
/**
* Run php's linter in one parallel task for the passed chunk
*
* @param array $chunk
*/
protected function parallelLint(array $chunk)
{
$task = $this->taskParallelExec()
->timeout(5)
->printed(FALSE);
foreach($chunk as $file)
{
$task = $task->process("php -l {$file}");
}
$task->run();
}
/**
* Generate copy paste detector report
*/
protected function phpcpdReport()
{
$cmd_parts = [
'vendor/bin/phpcpd',
'--log-pmd build/logs/pmd-cpd.xml',
'src'
];
$this->_run($cmd_parts);
}
/**
* Shortcut for joining an array of command arguments
* and then running it
*
* @param array $cmd_parts - command arguments
* @param string $join_on - what to join the command arguments with
*/
protected function _run(array $cmd_parts, $join_on = ' ')
{
$this->taskExec(implode($join_on, $cmd_parts))->run();
}
}

View File

@ -1,22 +1,34 @@
<?php <?php declare(strict_types=1);
/** /**
* Bootstrap / Dependency Injection * Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/ */
namespace Aviat\AnimeClient; namespace Aviat\AnimeClient;
use Aura\Html\HelperLocatorFactory; use Aura\Html\HelperLocatorFactory;
use Aura\Router\RouterContainer; use Aura\Router\RouterContainer;
use Aura\Session\SessionFactory; use Aura\Session\SessionFactory;
use Monolog\Logger; use Aviat\AnimeClient\API\Kitsu\Auth as KitsuAuth;
use Monolog\Handler\RotatingFileHandler; use Aviat\AnimeClient\API\Kitsu\ListItem as KitsuListItem;
use Zend\Diactoros\ServerRequestFactory; use Aviat\AnimeClient\API\Kitsu\KitsuModel;
use Zend\Diactoros\Response;
use Aviat\Ion\Di\Container;
use Aviat\Ion\Cache\CacheManager;
use Aviat\AnimeClient\Auth\HummingbirdAuth;
use Aviat\AnimeClient\Model; use Aviat\AnimeClient\Model;
use Aviat\Banker\Pool;
use Aviat\Ion\Config;
use Aviat\Ion\Di\Container;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Zend\Diactoros\{Response, ServerRequestFactory};
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Setup DI container // Setup DI container
@ -30,65 +42,104 @@ return function(array $config_array = []) {
$app_logger = new Logger('animeclient'); $app_logger = new Logger('animeclient');
$app_logger->pushHandler(new RotatingFileHandler(__DIR__ . '/logs/app.log', Logger::NOTICE)); $app_logger->pushHandler(new RotatingFileHandler(__DIR__ . '/logs/app.log', Logger::NOTICE));
$request_logger = new Logger('request');
$request_logger->pushHandler(new RotatingFileHandler(__DIR__ . '/logs/request.log', Logger::NOTICE));
$container->setLogger($app_logger, 'default'); $container->setLogger($app_logger, 'default');
$container->setLogger($request_logger, 'request');
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Injected Objects // Injected Objects
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Create Config Object // Create Config Object
$config = new Config($config_array); $container->set('config', function() {
$container->set('config', $config); return new Config();
});
$container->setInstance('config', new Config($config_array));
// Create Cache Object // Create Cache Object
$container->set('cache', new CacheManager($container)); $container->set('cache', function($container) {
$logger = $container->getLogger();
$config = $container->get('config')->get('cache');
return new Pool($config, $logger);
});
// Create Aura Router Object // Create Aura Router Object
$container->set('aura-router', new RouterContainer); $container->set('aura-router', function() {
return new RouterContainer;
});
// Create Html helper Object // Create Html helper Object
$html_helper = (new HelperLocatorFactory)->newInstance(); $container->set('html-helper', function($container) {
$html_helper->set('menu', function() use ($container) { $html_helper = (new HelperLocatorFactory)->newInstance();
$menu_helper = new Helper\Menu(); $html_helper->set('menu', function() use ($container) {
$menu_helper->setContainer($container); $menu_helper = new Helper\Menu();
return $menu_helper; $menu_helper->setContainer($container);
return $menu_helper;
});
return $html_helper;
}); });
$container->set('html-helper', $html_helper);
// Create Request/Response Objects // Create Request/Response Objects
$request = ServerRequestFactory::fromGlobals( $container->set('request', function() {
$_SERVER, return ServerRequestFactory::fromGlobals(
$_GET, $_SERVER,
$_POST, $_GET,
$_COOKIE, $_POST,
$_FILES $_COOKIE,
); $_FILES
$container->set('request', $request); );
$container->set('response', new Response()); });
$container->set('response', function() {
return new Response;
});
// Create session Object // Create session Object
$session = (new SessionFactory())->newInstance($_COOKIE); $container->set('session', function() {
$container->set('session', $session); return (new SessionFactory())->newInstance($_COOKIE);
});
// Miscellaneous helper methods // Miscellaneous helper methods
$anime_client = new AnimeClient(); $container->set('util', function($container) {
$anime_client->setContainer($container); return new Util($container);
$container->set('anime-client', $anime_client); });
// Models // Models
$container->set('api-model', new Model\API($container)); $container->set('kitsu-model', function($container) {
$container->set('anime-model', new Model\Anime($container)); $listItem = new KitsuListItem();
$container->set('manga-model', new Model\Manga($container)); $listItem->setContainer($container);
$container->set('anime-collection-model', new Model\AnimeCollection($container)); $model = new KitsuModel($listItem);
$model->setContainer($container);
return $model;
});
$container->set('api-model', function($container) {
return new Model\API($container);
});
$container->set('anime-model', function($container) {
return new Model\Anime($container);
});
$container->set('manga-model', function($container) {
return new Model\Manga($container);
});
$container->set('anime-collection-model', function($container) {
return new Model\AnimeCollection($container);
});
// Miscellaneous Classes // Miscellaneous Classes
$container->set('auth', new HummingbirdAuth($container)); $container->set('auth', function($container) {
$container->set('url-generator', new UrlGenerator($container)); return new KitsuAuth($container);
});
$container->set('url-generator', function($container) {
return new UrlGenerator($container);
});
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Dispatcher // Dispatcher
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
$container->set('dispatcher', new Dispatcher($container)); $container->set('dispatcher', function($container) {
return new Dispatcher($container);
});
return $container; return $container;
}; };

View File

@ -4,11 +4,14 @@
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* PHP version 5.6
*
* @package HummingbirdAnimeClient * @package HummingbirdAnimeClient
* @author Timothy J. Warren * @author Timothy J. Warren <tim@timshomepage.net>
* @copyright Copyright (c) 2015 - 2016 * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @link https://github.com/timw4mail/HummingBirdAnimeClient
* @license MIT
*/ */
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------

View File

@ -0,0 +1,20 @@
################################################################################
# Cache Setup #
################################################################################
driver = "redis"
[connection]
# Host or socket to connect to
host = "127.0.0.1"
# Connection port
#port = 6379
# Connection password
#password = ""
# Database number
database = 2
[options]

View File

@ -10,4 +10,14 @@ pass = ""
port = "" port = ""
name = "default" name = "default"
database = "" database = ""
file = "/../../anime_collection.sqlite" file = "anime_collection.sqlite"
[cache]
type = "sqlite"
host = ""
user = ""
pass = ""
port = ""
name = "default"
database = ""
file = "anime_collection.sqlite"

View File

@ -4,11 +4,14 @@
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* PHP version 5.6
*
* @package HummingbirdAnimeClient * @package HummingbirdAnimeClient
* @author Timothy J. Warren * @author Timothy J. Warren <tim@timshomepage.net>
* @copyright Copyright (c) 2015 - 2016 * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @link https://github.com/timw4mail/HummingBirdAnimeClient
* @license MIT
*/ */
return [ return [
@ -20,7 +23,7 @@ return [
'on_hold' => '/on_hold', 'on_hold' => '/on_hold',
'dropped' => '/dropped', 'dropped' => '/dropped',
'completed' => '/completed', 'completed' => '/completed',
'all' => '/all' //'all' => '/all'
] ]
], ],
'manga_list' => [ 'manga_list' => [
@ -31,7 +34,7 @@ return [
'on_hold' => '/on_hold', 'on_hold' => '/on_hold',
'dropped' => '/dropped', 'dropped' => '/dropped',
'completed' => '/completed', 'completed' => '/completed',
'all' => '/all' //'all' => '/all'
] ]
] ]
]; ];

View File

@ -4,11 +4,14 @@
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* @package HummingbirdAnimeClient * PHP version 5.6
* @author Timothy J. Warren *
* @copyright Copyright (c) 2015 - 2016 * @package HummingbirdAnimeClient
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @author Timothy J. Warren <tim@timshomepage.net>
* @license MIT * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------

View File

@ -4,11 +4,14 @@
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* PHP version 5.6
*
* @package HummingbirdAnimeClient * @package HummingbirdAnimeClient
* @author Timothy J. Warren * @author Timothy J. Warren <tim@timshomepage.net>
* @copyright Copyright (c) 2015 - 2016 * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @link https://github.com/timw4mail/HummingBirdAnimeClient
* @license MIT
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -30,7 +33,6 @@ return [
), ),
*/ */
'base' => [ 'base' => [
'marx.css',
'base.css' 'base.css'
] ]
]; ];

View File

@ -4,11 +4,14 @@
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* PHP version 5.6
*
* @package HummingbirdAnimeClient * @package HummingbirdAnimeClient
* @author Timothy J. Warren * @author Timothy J. Warren <tim@timshomepage.net>
* @copyright Copyright (c) 2015 - 2016 * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @link https://github.com/timw4mail/HummingBirdAnimeClient
* @license MIT
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
@ -28,7 +31,7 @@ return [
'base/sort_tables.js', 'base/sort_tables.js',
], ],
'table_edit' => [ 'table_edit' => [
'sort_tables.js', 'base/sort_tables.js',
'anime_edit.js', 'anime_edit.js',
'manga_edit.js', 'manga_edit.js',
], ],

View File

@ -3,6 +3,7 @@
################################################################################ ################################################################################
# Host or socket to connect to # Host or socket to connect to
# Socket must be prefixed with 'unix:'
host = "127.0.0.1" host = "127.0.0.1"
# Connection port # Connection port

View File

@ -4,11 +4,14 @@
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* PHP version 5.6
*
* @package HummingbirdAnimeClient * @package HummingbirdAnimeClient
* @author Timothy J. Warren * @author Timothy J. Warren <tim@timshomepage.net>
* @copyright Copyright (c) 2015 - 2016 * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @link https://github.com/timw4mail/HummingBirdAnimeClient
* @license MIT
*/ */
use Aviat\AnimeClient\AnimeClient; use Aviat\AnimeClient\AnimeClient;
@ -144,7 +147,7 @@ return [
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
'cache_purge' => [ 'cache_purge' => [
'path' => '/cache_purge', 'path' => '/cache_purge',
'action' => 'clear_cache', 'action' => 'clearCache',
'controller' => AnimeClient::DEFAULT_CONTROLLER_NAMESPACE, 'controller' => AnimeClient::DEFAULT_CONTROLLER_NAMESPACE,
'verb' => 'get', 'verb' => 'get',
], ],
@ -156,7 +159,7 @@ return [
], ],
'login.post' => [ 'login.post' => [
'path' => '/login', 'path' => '/login',
'action' => 'login_action', 'action' => 'loginAction',
'controller' => AnimeClient::DEFAULT_CONTROLLER_NAMESPACE, 'controller' => AnimeClient::DEFAULT_CONTROLLER_NAMESPACE,
'verb' => 'post', 'verb' => 'post',
], ],
@ -200,7 +203,7 @@ return [
'index_redirect' => [ 'index_redirect' => [
'path' => '/', 'path' => '/',
'controller' => AnimeClient::DEFAULT_CONTROLLER_NAMESPACE, 'controller' => AnimeClient::DEFAULT_CONTROLLER_NAMESPACE,
'action' => 'redirect_to_default', 'action' => 'redirectToDefaultRoute',
], ],
], ],
]; ];

View File

@ -28,6 +28,7 @@
<tr> <tr>
<td>&nbsp;</td> <td>&nbsp;</td>
<td> <td>
<input type="hidden" name="type" value="anime" />
<button type="submit">Save</button> <button type="submit">Save</button>
</td> </td>
</tr> </tr>

View File

@ -11,15 +11,17 @@
<section class="media-wrap"> <section class="media-wrap">
<?php foreach($items as $item): ?> <?php foreach($items as $item): ?>
<?php if ($item['private'] && ! $auth->is_authenticated()) continue; ?> <?php if ($item['private'] && ! $auth->is_authenticated()) continue; ?>
<article class="media" id="<?= $item['anime']['slug'] ?>"> <article class="media" id="<?= $item['id'] ?>">
<?php if ($auth->is_authenticated()): ?> <?php if ($auth->is_authenticated()): ?>
<button title="Increment episode count" class="plus_one" hidden>+1 Episode</button> <button title="Increment episode count" class="plus_one" hidden>+1 Episode</button>
<?php endif ?> <?php endif ?>
<?= $helper->img($item['anime']['image']); ?> <?= $helper->img($item['anime']['image']); ?>
<div class="name"> <div class="name">
<a href="<?= $url->generate('anime.details', ['id' => $item['anime']['slug']]); ?>"> <a href="<?= $url->generate('anime.details', ['id' => $item['anime']['slug']]); ?>">
<?= $escape->html($item['anime']['title']) ?> <?= array_shift($item['anime']['titles']) ?>
<?= ($item['anime']['alternate_title'] != "") ? "<br />({$item['anime']['alternate_title']})" : ""; ?> <?php foreach ($item['anime']['titles'] as $title): ?>
<br /><small><?= $title ?></small>
<?php endforeach ?>
</a> </a>
</div> </div>
<div class="table"> <div class="table">
@ -66,4 +68,4 @@
</main> </main>
<?php if ($auth->is_authenticated()): ?> <?php if ($auth->is_authenticated()): ?>
<script src="<?= $urlGenerator->asset_url('js.php/g/edit') ?>"></script> <script src="<?= $urlGenerator->asset_url('js.php/g/edit') ?>"></script>
<?php endif ?> <?php endif ?>

View File

@ -23,26 +23,21 @@
</tr> </tr>
<tr> <tr>
<td>Age Rating</td> <td>Age Rating</td>
<td><?= $data['age_rating'] ?></td> <td><abbr title="<?= $data['age_rating_guide'] ?>"><?= $data['age_rating'] ?></abbr></td>
</tr> </tr>
<tr> <tr>
<td>Genres</td> <td>Genres</td>
<td> <td>
<?php <?= implode(', ', $data['genres']) ?>
$genres = [];
foreach($data['genres'] as $g) $genres[] = $g['name'];
?>
<?= implode(', ', $genres); ?>
</td> </td>
</tr> </tr>
</table> </table>
</div> </div>
<div> <div>
<h2><a rel="external" href="<?= $data['url'] ?>"><?= $data['title'] ?></a></h2> <h2><a rel="external" href="<?= $data['url'] ?>"><?= array_shift($data['titles']) ?></a></h2>
<?php if( ! empty($data['alternate_title'])): ?> <?php foreach ($data['titles'] as $title): ?>
<h3><?= $data['alternate_title'] ?></h3> <h3><?= $title ?></h3>
<?php endif ?> <?php endforeach ?>
<br /> <br />
<p><?= nl2br($data['synopsis']) ?></p> <p><?= nl2br($data['synopsis']) ?></p>
</div> </div>

View File

@ -6,10 +6,10 @@
<thead> <thead>
<tr> <tr>
<th> <th>
<h3><?= $escape->html($item['anime']['title']) ?></h3> <h3><?= $escape->html(array_shift($item['anime']['titles'])) ?></h3>
<?php if($item['anime']['alternate_title'] != ""): ?> <?php foreach($item['anime']['titles'] as $title): ?>
<h4><?= $escape->html($item['anime']['alternate_title']) ?></h4> <h4><?= $escape->html($title) ?></h4>
<?php endif ?> <?php endforeach ?>
</th> </th>
<th> <th>
<article class="media"> <article class="media">
@ -76,7 +76,7 @@
<tr> <tr>
<td>&nbsp;</td> <td>&nbsp;</td>
<td> <td>
<input type="hidden" value="<?= $item['anime']['slug'] ?>" name="id" /> <input type="hidden" value="<?= $item['id'] ?>" name="id" />
<input type="hidden" value="true" name="edit" /> <input type="hidden" value="true" name="edit" />
<button type="submit">Submit</button> <button type="submit">Submit</button>
</td> </td>
@ -92,7 +92,7 @@
<tr> <tr>
<td>&nbsp;</td> <td>&nbsp;</td>
<td> <td>
<input type="hidden" value="<?= $item['anime']['slug'] ?>" name="id" /> <input type="hidden" value="<?= $item['id'] ?>" name="id" />
<button type="submit" class="danger">Delete Entry</button> <button type="submit" class="danger">Delete Entry</button>
</td> </td>
</tr> </tr>

View File

@ -35,36 +35,38 @@
<?php endif ?> <?php endif ?>
<td class="justify"> <td class="justify">
<a href="<?= $url->generate('anime.details', ['id' => $item['anime']['slug']]) ?>"> <a href="<?= $url->generate('anime.details', ['id' => $item['anime']['slug']]) ?>">
<?= $item['anime']['title'] ?> <?= array_shift($item['anime']['titles']) ?>
</a> </a>
<?= ( ! empty($item['anime']['alternate_title'])) ? " <br /> " . $item['anime']['alternate_title'] : "" ?> <?php foreach($item['anime']['titles'] as $title): ?>
<br /><?= $title ?>
<?php endforeach ?>
</td> </td>
<td class="align_left"><?= $item['airing']['status'] ?></td> <td><?= $item['airing']['status'] ?></td>
<td><?= $item['user_rating'] ?> / 10 </td> <td><?= $item['user_rating'] ?> / 10 </td>
<td><?= $item['anime']['type'] ?></td> <td><?= $item['anime']['type'] ?></td>
<td class="align_left" id="<?= $item['anime']['slug'] ?>"> <td id="<?= $item['anime']['slug'] ?>">
Episodes: <br /> Episodes: <br />
<span class="completed_number"><?= $item['episodes']['watched'] ?></span>&nbsp;/&nbsp;<span class="total_number"><?= $item['episodes']['total'] ?></span> <span class="completed_number"><?= $item['episodes']['watched'] ?></span>&nbsp;/&nbsp;<span class="total_number"><?= $item['episodes']['total'] ?></span>
</td> </td>
<td><?= $item['anime']['age_rating'] ?></td> <td><?= $item['anime']['age_rating'] ?></td>
<td> <td>
<ul>
<?php if ($item['rewatched'] > 0): ?> <?php if ($item['rewatched'] > 0): ?>
Rewatched <?= $item['rewatched'] ?> time(s)<br /> <li>Rewatched <?= $item['rewatched'] ?> time(s)</li>
<?php endif ?> <?php endif ?>
<?php $attr_list = []; ?>
<?php foreach(['private','rewatching'] as $attr): ?> <?php foreach(['private','rewatching'] as $attr): ?>
<?php if($item[$attr]): ?> <?php if($item[$attr]): ?>
<?php $attr_list[] = ucfirst($attr); ?> <li><?= ucfirst($attr); ?></li>
<?php endif ?> <?php endif ?>
<?php endforeach ?> <?php endforeach ?>
<?= implode(', ', $attr_list); ?> </ul>
</td> </td>
<td> <td>
<p><?= $escape->html($item['notes']) ?></p> <p><?= $escape->html($item['notes']) ?></p>
</td> </td>
<td class="align_left"> <td class="align_left">
<?php sort($item['anime']['genres']) ?> <?php sort($item['anime']['genres']) ?>
<?= join(', ', $item['anime']['genres']) ?> <?= implode(', ', $item['anime']['genres']) ?>
</td> </td>
</tr> </tr>
<?php endforeach ?> <?php endforeach ?>
@ -74,4 +76,4 @@
<?php endif ?> <?php endif ?>
</main> </main>
<?php $group = ($auth->is_authenticated()) ? 'table_edit' : 'table' ?> <?php $group = ($auth->is_authenticated()) ? 'table_edit' : 'table' ?>
<script src="<?= $urlGenerator->asset_url("js.php/g/{$group}") ?>"></script> <script src="<?= $urlGenerator->asset_url("js.php/g/{$group}") ?>"></script>

View File

@ -1,4 +1,3 @@
<?php namespace Aviat\AnimeClient ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
@ -7,54 +6,12 @@
<meta http-equiv="cache-control" content="no-store" /> <meta http-equiv="cache-control" content="no-store" />
<meta http-equiv="Content-Security-Policy" content="script-src 'self'" /> <meta http-equiv="Content-Security-Policy" content="script-src 'self'" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0" />
<link rel="stylesheet" href="<?= $urlGenerator->asset_url('css.php/g/base/debug') ?>" /> <link rel="stylesheet" href="<?= $urlGenerator->asset_url('css.php/g/base') ?>" />
<script src="<?= $urlGenerator->asset_url('js.php/g/base') ?>"></script> <script src="<?= $urlGenerator->asset_url('js.php/g/base') ?>"></script>
</head> </head>
<body class="<?= $escape->attr($url_type) ?> list"> <body class="<?= $escape->attr($url_type) ?> list">
<header> <header>
<h1 class="flex flex-align-end flex-wrap"> <?php include 'main-menu.php' ?>
<span class="flex-no-wrap grow-1">
<?php if(strpos($route_path, 'collection') === FALSE): ?>
<a href="<?= $escape->attr($urlGenerator->default_url($url_type)) ?>">
<?= $config->get('whose_list') ?>'s <?= ucfirst($url_type) ?> List
</a>
<?php if($config->get("show_{$url_type}_collection")): ?>
[<a href="<?= $urlGenerator->url('collection/view') ?>"><?= ucfirst($url_type) ?> Collection</a>]
<?php endif ?>
[<a href="<?= $urlGenerator->default_url($other_type) ?>"><?= ucfirst($other_type) ?> List</a>]
<?php else: ?>
<a href="<?= $urlGenerator->url('collection/view') ?>">
<?= $config->get('whose_list') ?>'s <?= ucfirst($url_type) ?> Collection
</a>
[<a href="<?= $urlGenerator->default_url('anime') ?>">Anime List</a>]
[<a href="<?= $urlGenerator->default_url('manga') ?>">Manga List</a>]
<?php endif ?>
</span>
<?php if ($auth->is_authenticated()): ?>
<span class="flex-no-wrap">&nbsp;</span>
<span class="flex-no-wrap small-font">
<button type="button" class="js-clear-cache user-btn">Clear API Cache</button>
</span>
<span class="flex-no-wrap">&nbsp;</span>
<?php endif ?>
<span class="flex-no-wrap small-font">
<?php if ($auth->is_authenticated()): ?>
<a class="bracketed" href="<?= $url->generate('logout') ?>">Logout</a>
<?php else: ?>
[<a href="<?= $url->generate('login'); ?>"><?= $config->get('whose_list') ?>'s Login</a>]
<?php endif ?>
</span>
</h1>
<nav>
<?php if ($container->get('anime-client')->is_view_page()): ?>
<?= $helper->menu($menu_name) ?>
<br />
<ul>
<li class="<?= AnimeClient::is_not_selected('list', $urlGenerator->last_segment()) ?>"><a href="<?= $urlGenerator->url($route_path) ?>">Cover View</a></li>
<li class="<?= AnimeClient::is_selected('list', $urlGenerator->last_segment()) ?>"><a href="<?= $urlGenerator->url("{$route_path}/list") ?>">List View</a></li>
</ul>
<?php endif ?>
</nav>
<?php if(isset($message) && is_array($message)): <?php if(isset($message) && is_array($message)):
extract($message); extract($message);
include 'message.php'; include 'message.php';

44
app/views/main-menu.php Normal file
View File

@ -0,0 +1,44 @@
<?php declare(strict_types=1); namespace Aviat\AnimeClient; ?>
<h1 class="flex flex-align-end flex-wrap">
<span class="flex-no-wrap grow-1">
<?php if(strpos($route_path, 'collection') === FALSE): ?>
<a href="<?= $escape->attr($urlGenerator->default_url($url_type)) ?>">
<?= $config->get('whose_list') ?>'s <?= ucfirst($url_type) ?> List
</a>
<?php if($config->get("show_{$url_type}_collection")): ?>
[<a href="<?= $urlGenerator->url('collection/view') ?>"><?= ucfirst($url_type) ?> Collection</a>]
<?php endif ?>
[<a href="<?= $urlGenerator->default_url($other_type) ?>"><?= ucfirst($other_type) ?> List</a>]
<?php else: ?>
<a href="<?= $urlGenerator->url('collection/view') ?>">
<?= $config->get('whose_list') ?>'s <?= ucfirst($url_type) ?> Collection
</a>
[<a href="<?= $urlGenerator->default_url('anime') ?>">Anime List</a>]
[<a href="<?= $urlGenerator->default_url('manga') ?>">Manga List</a>]
<?php endif ?>
</span>
<?php /* if ($auth->is_authenticated()): ?>
<span class="flex-no-wrap">&nbsp;</span>
<span class="flex-no-wrap small-font">
<button type="button" class="js-clear-cache user-btn">Clear API Cache</button>
</span>
<span class="flex-no-wrap">&nbsp;</span>
<?php endif */ ?>
<span class="flex-no-wrap small-font">
<?php if ($auth->is_authenticated()): ?>
<a class="bracketed" href="<?= $url->generate('logout') ?>">Logout</a>
<?php else: ?>
[<a href="<?= $url->generate('login'); ?>"><?= $config->get('whose_list') ?>'s Login</a>]
<?php endif ?>
</span>
</h1>
<nav>
<?php if ($container->get('util')->is_view_page()): ?>
<?= $helper->menu($menu_name) ?>
<br />
<ul>
<li class="<?= Util::is_not_selected('list', $urlGenerator->last_segment()) ?>"><a href="<?= $urlGenerator->url($route_path) ?>">Cover View</a></li>
<li class="<?= Util::is_selected('list', $urlGenerator->last_segment()) ?>"><a href="<?= $urlGenerator->url("{$route_path}/list") ?>">List View</a></li>
</ul>
<?php endif ?>
</nav>

View File

@ -28,6 +28,7 @@
<tr> <tr>
<td>&nbsp;</td> <td>&nbsp;</td>
<td> <td>
<input type="hidden" name="type" value="manga" />
<button type="submit">Save</button> <button type="submit">Save</button>
</td> </td>
</tr> </tr>

View File

@ -14,14 +14,15 @@
<?php if ($auth->is_authenticated()): ?> <?php if ($auth->is_authenticated()): ?>
<div class="edit_buttons" hidden> <div class="edit_buttons" hidden>
<button class="plus_one_chapter">+1 Chapter</button> <button class="plus_one_chapter">+1 Chapter</button>
<button class="plus_one_volume">+1 Volume</button>
</div> </div>
<?php endif ?> <?php endif ?>
<img src="<?= $escape->attr($item['manga']['image']) ?>" /> <img src="<?= $escape->attr($item['manga']['image']) ?>" />
<div class="name"> <div class="name">
<a href="<?= $url->generate('manga.details', ['id' => $item['manga']['slug']]) ?>"> <a href="<?= $url->generate('manga.details', ['id' => $item['manga']['slug']]) ?>">
<?= $escape->html($item['manga']['title']) ?> <?= $escape->html(array_shift($item['manga']['titles'])) ?>
<?= (isset($item['manga']['alternate_title'])) ? "<br />({$item['manga']['alternate_title']})" : ""; ?> <?php foreach($item['manga']['titles'] as $title): ?>
<br /><small><?= $title ?></small>
<?php endforeach ?>
</a> </a>
</div> </div>
<div class="table"> <div class="table">
@ -43,8 +44,7 @@
</div> </div>
<div class="row"> <div class="row">
<div class="volume_completion"> <div class="volume_completion">
Volumes: <span class="volumes_read"><?= $item['volumes']['read'] ?></span> / Volumes: <span class="volume_count"><?= $item['volumes']['total'] ?></span>
<span class="volume_count"><?= $item['volumes']['total'] ?></span>
</div> </div>
</div> </div>
</div> </div>
@ -57,4 +57,4 @@
</main> </main>
<?php if ($auth->is_authenticated()): ?> <?php if ($auth->is_authenticated()): ?>
<script src="<?= $urlGenerator->asset_url('js.php/g/edit') ?>"></script> <script src="<?= $urlGenerator->asset_url('js.php/g/edit') ?>"></script>
<?php endif ?> <?php endif ?>

View File

@ -1,7 +1,7 @@
<main class="details"> <main class="details">
<section class="flex flex-no-wrap"> <section class="flex flex-no-wrap">
<div> <div>
<img class="cover" src="<?= $data['poster_image'] ?>" alt="<?= $data['title'] ?> cover image" /> <img class="cover" src="<?= $data['cover_image'] ?>" alt="<?= $data['title'] ?> cover image" />
<br /> <br />
<br /> <br />
<table> <table>
@ -26,9 +26,9 @@
</table> </table>
</div> </div>
<div> <div>
<h2><a rel="external" href="https://hummingbird.me/manga/<?= $data['id'] ?>"><?= $data['romaji_title'] ?></a></h2> <h2><a rel="external" href="<?= $data['url'] ?>"><?= $data['title'] ?></a></h2>
<?php if( ! empty($data['english_title'])): ?> <?php if( ! empty($data['en_title'])): ?>
<h3><?= $data['english_title'] ?></h3> <h3><?= $data['en_title'] ?></h3>
<?php endif ?> <?php endif ?>
<br /> <br />

View File

@ -1,19 +1,18 @@
<?php if ($auth->is_authenticated()): ?> <?php if ($auth->is_authenticated()): ?>
<main> <main>
<h1> <h1>
Edit <?= $item['manga']['title'] ?> Edit <?= $item['manga']['titles'][0] ?>
<?= ($item['manga']['alternate_title'] != "") ? "({$item['manga']['alternate_title']})" : ""; ?>
</h1> </h1>
<form action="<?= $action ?>" method="post"> <form action="<?= $action ?>" method="post">
<table class="form"> <table class="form">
<thead> <thead>
<tr> <tr>
<th> <th>
<h3><?= $escape->html($item['manga']['title']) ?></h3> <h3><?= $escape->html(array_shift($item['manga']['titles'])) ?></h3>
<?php if($item['manga']['alternate_title'] != ""): ?> <?php foreach($item['manga']['titles'] as $title): ?>
<h4><?= $escape->html($item['manga']['alternate_title']) ?></h4> <h4><?= $escape->html($title) ?></h4>
<?php endif ?> <?php endforeach ?>
</th> </th>
<th> <th>
<article class="media"> <article class="media">
<?= $helper->img($item['manga']['image']); ?> <?= $helper->img($item['manga']['image']); ?>
@ -26,9 +25,9 @@
<td><label for="status">Reading Status</label></td> <td><label for="status">Reading Status</label></td>
<td> <td>
<select name="status" id="status"> <select name="status" id="status">
<?php foreach($status_list as $status): ?> <?php foreach($status_list as $val => $status): ?>
<option <?php if($item['reading_status'] === $status): ?>selected="selected"<?php endif ?> <option <?php if($item['reading_status'] === $val): ?>selected="selected"<?php endif ?>
value="<?= $status ?>"><?= $status ?></option> value="<?= $val ?>"><?= $status ?></option>
<?php endforeach ?> <?php endforeach ?>
</select> </select>
</td> </td>
@ -45,12 +44,12 @@
<input type="number" min="0" name="chapters_read" id="chapters_read" value="<?= $item['chapters']['read'] ?>" /> / <?= $item['chapters']['total'] ?> <input type="number" min="0" name="chapters_read" id="chapters_read" value="<?= $item['chapters']['read'] ?>" /> / <?= $item['chapters']['total'] ?>
</td> </td>
</tr> </tr>
<tr> <? /*<tr>
<td><label for="volumes_read">Volumes Read</label></td> <td><label for="volumes_read">Volumes Read</label></td>
<td> <td>
<input type="number" min="0" name="volumes_read" id="volumes_read" value="<?= $item['volumes']['read'] ?>" /> / <?= $item['volumes']['total'] ?> <input type="number" min="0" name="volumes_read" id="volumes_read" value="<?= $item['volumes']['read'] ?>" /> / <?= $item['volumes']['total'] ?>
</td> </td>
</tr> </tr> */ ?>
<tr> <tr>
<td><label for="rereading_flag">Rereading?</label></td> <td><label for="rereading_flag">Rereading?</label></td>
<td> <td>

View File

@ -1,7 +1,7 @@
<main> <main>
<?php if ($auth->is_authenticated()): ?> <?php /*if ($auth->is_authenticated()): ?>
<a class="bracketed" href="<?= $urlGenerator->url('manga/add') ?>">Add Item</a> <a class="bracketed" href="<?= $urlGenerator->url('manga/add') ?>">Add Item</a>
<?php endif ?> <?php endif*/ ?>
<?php if (empty($sections)): ?> <?php if (empty($sections)): ?>
<h3>There's nothing here!</h3> <h3>There's nothing here!</h3>
<?php else: ?> <?php else: ?>
@ -15,8 +15,8 @@
<?php endif ?> <?php endif ?>
<th>Title</th> <th>Title</th>
<th>Rating</th> <th>Rating</th>
<th>Chapters</th> <th>Completed Chapters</th>
<th>Volumes</th> <th># of Volumes</th>
<th>Type</th> <th>Type</th>
</tr> </tr>
</thead> </thead>
@ -30,13 +30,15 @@
<?php endif ?> <?php endif ?>
<td class="align_left"> <td class="align_left">
<a href="<?= $url->generate('manga.details', ['id' => $item['manga']['slug']]) ?>"> <a href="<?= $url->generate('manga.details', ['id' => $item['manga']['slug']]) ?>">
<?= $item['manga']['title'] ?> <?= array_shift($item['manga']['titles']) ?>
</a> </a>
<?= ( ! is_null($item['manga']['alternate_title'])) ? " &middot; " . $item['manga']['alternate_title'] : "" ?> <?php foreach($item['manga']['titles'] as $title): ?>
<br /><?= $title ?>
<?php endforeach ?>
</td> </td>
<td><?= $item['user_rating'] ?> / 10</td> <td><?= $item['user_rating'] ?> / 10</td>
<td><?= $item['chapters']['read'] ?> / <?= $item['chapters']['total'] ?></td> <td><?= $item['chapters']['read'] ?> / <?= $item['chapters']['total'] ?></td>
<td><?= $item['volumes']['read'] ?> / <?= $item['volumes']['total'] ?></td> <td><?= $item['volumes']['total'] ?></td>
<td><?= $item['manga']['type'] ?></td> <td><?= $item['manga']['type'] ?></td>
</tr> </tr>
<?php endforeach ?> <?php endforeach ?>

168
build.xml
View File

@ -1,168 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project default="full-build" name="animeclient" basedir=".">
<!-- By default, we assume all tools to be on the $PATH -->
<property name="pdepend" value="pdepend" />
<property name="phpcpd" value="phpcpd" />
<property name="phpdox" value="phpdox" />
<property name="phploc" value="phploc" />
<property name="phpmd" value="phpmd" />
<property name="phpunit" value="phpunit" />
<property name="sonar" value="sonar-runner" />
<target name="full-build"
depends="prepare,static-analysis,phpunit,phpdox,sonar"
description="Performs static analysis, runs the tests, and generates project documentation"
/>
<target name="quick-build"
depends="prepare,lint,phpunit-no-coverage"
description="Performs a lint check and runs the tests (without generating code coverage reports)"
/>
<target name="static-analysis"
depends="lint,phploc-ci,pdepend,phpcpd-ci"
description="Performs static analysis"
/>
<target name="clean" unless="clean.done" description="Cleanup build artifacts">
<delete dir="build/api" />
<delete dir="build/coverage" />
<delete dir="build/logs" />
<delete dir="build/pdepend" />
<delete dir="build/phpdox" />
<property name="clean.done" value="true" />
</target>
<target name="prepare" depends="clean" unless="prepare.done" description="Prepare for build">
<mkdir dir="build/api" />
<mkdir dir="build/coverage" />
<mkdir dir="build/logs" />
<mkdir dir="build/pdepend" />
<mkdir dir="build/phpdox" />
<property name="prepare.done" value="true" />
</target>
<target name="lint" unless="lint.done" description="Perform syntax check of sourcecode files">
<parallel threadcount="6">
<apply executable="php" passthru="true" taskname="lint">
<arg value="-l" />
<fileset dir=".">
<include name="src/Aviat/AnimeClient/**/*.php" />
</fileset>
</apply>
<apply executable="php" passthru="true" taskname="lint">
<arg value="-l" />
<fileset dir=".">
<include name="src/Aviat/Ion/**/*.php" />
</fileset>
</apply>
<apply executable="php" passthru="true" taskname="lint">
<arg value="-l" />
<fileset dir=".">
<include name="tests/AnimeClient/**/*.php" />
</fileset>
</apply>
<apply executable="php" passthru="true" taskname="lint">
<arg value="-l" />
<fileset dir=".">
<include name="tests/Ion/**/*.php" />
</fileset>
</apply>
</parallel>
<property name="lint.done" value="true" />
</target>
<target name="phploc" unless="phploc.done" description="Measure project size using PHPLOC and print human readable output. Intended for usage on the command line.">
<exec executable="${phploc}" passthru="true" taskname="phploc">
<arg value="--count-tests" />
<arg path="src" />
<arg path="tests" />
</exec>
<property name="phploc.done" value="true" />
</target>
<target name="phploc-ci" depends="prepare" unless="phploc.done" description="Measure project size using PHPLOC and log result in CSV and XML format. Intended for usage within a continuous integration environment.">
<parallel threadcount="2">
<phploc countTests="true" reportType="csv" reportDirectory="build/logs" reportName="phploc" taskname="csv report">
<fileset dir=".">
<include name="src/**/*.php" />
<include name="tests/**/*.php" />
</fileset>
</phploc>
<phploc countTests="true" reportType="xml" reportDirectory="build/logs" reportName="phploc" taskname="xml report">
<fileset dir=".">
<include name="src/**/*.php" />
<include name="tests/**/*.php" />
</fileset>
</phploc>
</parallel>
<property name="phploc.done" value="true" />
</target>
<target name="pdepend" depends="prepare" unless="pdepend.done" description="Calculate software metrics using PHP_Depend and log result in XML format. Intended for usage within a continuous integration environment.">
<phpdepend>
<fileset dir=".">
<include name="src/**/*.php" />
</fileset>
<logger type="jdepend-xml" outfile="build/logs/jdepend.xml" />
<logger type="jdepend-chart" outfile="build/pdepend/dependencies.svg" />
<logger type="overview-pyramid" outfile="build/pdepend/overview-pyramid.svg" />
</phpdepend>
<property name="pdepend.done" value="true" />
</target>
<target name="phpcpd" unless="phpcpd.done" description="Find duplicate code using PHPCPD and print human readable output. Intended for usage on the command line before committing.">
<phpcpd>
<formatter type="default" usefile="false" />
<fileset dir=".">
<include name="src/**/*.php" />
</fileset>
</phpcpd>
<property name="phpcpd.done" value="true" />
</target>
<target name="phpcpd-ci" depends="prepare" unless="phpcpd.done" description="Find duplicate code using PHPCPD and log result in XML format. Intended for usage within a continuous integration environment.">
<phpcpd>
<formatter type="pmd" outfile="build/logs/pmd-cpd.xml" />
<fileset dir=".">
<include name="src/**/*.php" />
</fileset>
</phpcpd>
<property name="phpcpd.done" value="true" />
</target>
<target name="phpunit" unless="phpunit.done" depends="prepare" description="Run unit tests with PHPUnit">
<exec executable="${phpunit}" logoutput="true" passthru="true" checkreturn="true" taskname="phpunit">
<arg value="--configuration" />
<arg path="build/phpunit.xml" />
</exec>
<property name="phpunit.done" value="true" />
</target>
<target name="phpunit-no-coverage" depends="prepare" unless="phpunit.done" description="Run unit tests with PHPUnit (without generating code coverage reports)">
<exec executable="${phpunit}" passthru="true" taskname="phpunit">
<arg value="--configuration" />
<arg path="build/phpunit.xml" />
<arg value="--no-coverage" />
</exec>
<property name="phpunit.done" value="true" />
</target>
<target name="phpdox" depends="phploc-ci,phpunit" unless="phpdox.done" description="Generate project documentation using phpDox">
<exec dir="build" executable="${phpdox}" passthru="true" taskname="phpdox" />
<property name="phpdox.done" value="true" />
</target>
<target name="sonar" depends="phpunit" unless="sonar.done" description="Generate code analysis with sonarqube">
<exec executable="${sonar}" passthru="true" taskname="sonar" />
<property name="sonar.done" value="true" />
</target>
</project>

View File

@ -0,0 +1,28 @@
<documentation title="Closing comments instead of PHP closing tag">
<standard>
<![CDATA[
The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag, and instead use a comment block to mark the end of file and it's location relative to the application root. This allows you to still identify a file as being complete and not truncated.
]]>
</standard>
<code_comparison>
<code title="Examples of valid closing comments">
<![CDATA[
<?php
echo "Here's my code!";
/* End of file myfile.php */
/* Location: ./system/modules/mymodule/myfile.php */
]]>
</code>
<code title="Examples of invalid closing comments">
<![CDATA[
<?php
echo "Here's my code!";
?>
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,7 @@
<documentation title="Unicode (UTF-8) encoding without BOM">
<standard>
<![CDATA[
Files should be saved with Unicode (UTF-8) encoding. The BOM should not be used. Unlike UTF-16 and UTF-32, there's no byte order to indicate in a UTF-8 encoded file, and the BOM can have a negative side effect in PHP of sending output, preventing the application from being able to set its own headers. Unix line endings should be used (LF).
]]>
</standard>
</documentation>

View File

@ -0,0 +1,31 @@
<documentation title="Constructor Names">
<standard>
<![CDATA[
Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased. All other class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names.
]]>
</standard>
<code_comparison>
<code title="Examples of valid constructor name">
<![CDATA[
class Super_class
{
function Super_class()
{
echo 'Some code here !';
}
}
]]>
</code>
<code title="Examples of invalid constructor name">
<![CDATA[
class Super_class
{
function __constructor()
{
echo 'Some code here !';
}
}
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,21 @@
<documentation title="Class names">
<standard>
<![CDATA[
Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased. All other class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names.
]]>
</standard>
<code_comparison>
<code title="Examples of valid class names">
<![CDATA[
class Super_class
]]>
</code>
<code title="Examples of invalid class names">
<![CDATA[
class SuperClass // words not separated with underscores and words next to the first one start with an upper case
class superclass // words not separated with underscores
class Super_Class // words next to the first one start with an upper case
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,21 @@
<documentation title="File names">
<standard>
<![CDATA[
To be able to find which class is contained in a file, file names should be case-insensitively equal to class names. Some operating systems and tools are case-insensitive, though other are. So, file names should be in lower case to avoid any trouble.
]]>
</standard>
<code_comparison>
<code title="Examples of valid file names">
<![CDATA[
super_class.php
]]>
</code>
<code title="Examples of invalid file names">
<![CDATA[
superclass.php // words not separated with underscores
SuperClass.php // not in lower case and words not separated with underscores
Super_class.php // not in lower case
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,27 @@
<documentation title="Function and Method Names">
<standard>
<![CDATA[
Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased. All other class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names.
Methods and variables that are only accessed internally by your class, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.
]]>
</standard>
<code_comparison>
<code title="Examples of valid method names">
<![CDATA[
function get_file_properties() // descriptive, underscore separator, and all lowercase letters
private function _get_file_properties()
]]>
</code>
<code title="Examples of invalid method names">
<![CDATA[
function fileproperties() // not descriptive and needs underscore separator
function fileProperties() // not descriptive and uses CamelCase
function getfileproperties() // Better! But still missing underscore separator
function getFileProperties() // uses CamelCase
function get_the_file_properties_from_the_file() // wordy
private function get_the_file_properties() // not prefixed with an underscor, though private
function _get_the_file_properties() // prefixed with an underscor, though public
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,31 @@
<documentation title="Variable names">
<standard>
<![CDATA[
Namely, variables should contain only lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very short, non-word variables should only be used as iterators in for() loops.
Methods and variables that are only accessed internally by your class, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.
]]>
</standard>
<code_comparison>
<code title="Examples of valid variable names">
<![CDATA[
for ($j = 0; $j < 10; $j++)
$str
$buffer
$group_id
$last_city
private $_internal_data;
]]>
</code>
<code title="Examples of invalid variable names">
<![CDATA[
$j = 'foo'; // single letter variables should only be used in for() loops
$Str // contains uppercase letters
$bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning
$groupid // multiple words, needs underscore separator
$name_of_last_city_used // too long
private $internal_data; // not prefixed with an underscor, though private
$_public_attribute; // prefixed with an underscor, though public
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,40 @@
<documentation title="Strict comparison operators">
<standard>
<![CDATA[
Some PHP functions return FALSE on failure, but may also have a valid return value of "" or 0, which would evaluate to FALSE in loose comparisons. Be explicit by comparing the variable type when using these return values in conditionals to ensure the return value is indeed what you expect, and not a value that has an equivalent loose-type evaluation.
Use the same stringency in returning and checking your own variables. Use === and !== as necessary.
]]>
</standard>
<code_comparison>
<code title="Valid strict comparison">
<![CDATA[
if (strpos($str, 'foo') === FALSE) {
echo 'Do something.';
}
function build_string($str = "")
{
if ($str === "") {
echo 'Buid string.';
}
}
]]>
</code>
<code title="Invalid loose comparison">
<![CDATA[
// If 'foo' is at the beginning of the string, strpos will return a 0,
// resulting in this conditional evaluating as TRUE
if (strpos($str, 'foo') == FALSE) {
echo 'Do something.';
}
function build_string($str = "")
{
if ($str == "") { // uh-oh! What if FALSE or the integer 0 is passed as an argument?
echo 'Buid string.';
}
}
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,28 @@
<documentation title="Double-quoted strings">
<standard>
<![CDATA[
Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters.
]]>
</standard>
<code_comparison>
<code title="Examples of invalid double-quoted strings">
<![CDATA[
"My String" // no variable parsing, so no use for double quotes
"My string $foo" // needs braces
'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly
'\r\n' // it isn't wrong, but it won't be interpreted as a new line feed
]]>
</code>
<code title="Examples of valid double-quoted strings">
<![CDATA[
'My String'
"My string {$foo}" // variables in strings may be enclosed with braces in 2 ways
"My string ${foo}"
"My string {$foo['bar']}" // variables in strings may be an array entry
"My string {$foo->bar}" // variables in strings may be an object attribute
"SELECT foo FROM bar WHERE baz = 'bag'"
"\n" // not specified in Code Igniter coding standard, but it should be allowed
]]>
</code>
</code_comparison>
</documentation>

View File

@ -0,0 +1,187 @@
<?php
/**
* CodeIgniter_Sniffs_Commenting_InlineCommentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Commenting_InlineCommentSniff.
*
* Ensure the use of single line comments within code (i.e //)
* and blank lines between large comment blocks and code.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Commenting;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class InlineCommentSniff implements Sniff
{
/**
* @var int Limit defining long comments.
* Long comments count $longCommentLimit or more lines.
*/
public $longCommentLimit = 5;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_COMMENT
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// keep testing only if it's about the first comment of the block
$previousCommentPtr = $phpcsFile->findPrevious($tokens[$stackPtr]['code'], $stackPtr - 1);
if ($tokens[$previousCommentPtr]['line'] !== $tokens[$stackPtr]['line'] - 1) {
if (TRUE !== $this->_checkCommentStyle($phpcsFile, $stackPtr)) {
return;
}
$commentLines = $this->_getCommentBlock($phpcsFile, $stackPtr);
if (count($commentLines) >= $this->longCommentLimit) {
$this->_checkBlankLinesAroundLongComment($phpcsFile, $commentLines);
}
}
}//end process()
/**
* Add error to $phpcsFile, if comment pointed by $stackPtr doesn't start
* with '//'.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* that has to be a comment.
*
* @return bool TRUE if the content of the token pointed by $stackPtr starts
* with //, FALSE if an error was added to $phpcsFile.
*/
private function _checkCommentStyle(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['content']{0} === '#') {
$error = 'Perl-style comments are not allowed; use "// Comment" or DocBlock comments instead';
$phpcsFile->addError($error, $stackPtr, 'WrongStyle');
return FALSE;
} else if (substr($tokens[$stackPtr]['content'], 0, 2) === '/*'
|| $tokens[$stackPtr]['content']{0} === '*'
) {
$error = 'Multi lines comments are not allowed; use "// Comment" DocBlock comments instead';
$phpcsFile->addError($error, $stackPtr, 'WrongStyle');
return FALSE;
} else if (substr($tokens[$stackPtr]['content'], 0, 2) !== '//') {
$error = 'Use single line or DocBlock comments within code';
$phpcsFile->addError($error, $stackPtr, 'WrongStyle');
return FALSE;
}
return TRUE;
}//_checkCommentStyle()
/**
* Gather into an array all comment lines to which $stackPtr belongs.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr Pointer to the first comment line.
*
* @return type array Pointers to tokens making up the comment block.
*/
private function _getCommentBlock(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$commentLines = array($stackPtr);
$nextComment = $stackPtr;
$lastLine = $tokens[$stackPtr]['line'];
while (($nextComment = $phpcsFile->findNext($tokens[$stackPtr]['code'], ($nextComment + 1), null, false)) !== false) {
if (($tokens[$nextComment]['line'] - 1) !== $lastLine) {
// Not part of the block.
break;
}
$lastLine = $tokens[$nextComment]['line'];
$commentLines[] = $nextComment;
}
return $commentLines;
}//_getCommentBlock()
/**
* Add errors to $phpcsFile, if $commentLines isn't enclosed with blank lines.
*
* @param File $phpcsFile The current file being scanned.
* @param array $commentLines Lines of the comment block being checked.
*
* @return bool TRUE if $commentLines is enclosed with at least a blank line
* before and after, FALSE otherwise.
*/
private function _checkBlankLinesAroundLongComment(File $phpcsFile, array $commentLines)
{
$hasBlankLinesAround = TRUE;
$tokens = $phpcsFile->getTokens();
// check blank line before the long comment
$firstCommentPtr = reset($commentLines);
$firstPreviousSpacePtr = $firstCommentPtr - 1;
while (T_WHITESPACE === $tokens[$firstPreviousSpacePtr]['code'] && $firstPreviousSpacePtr > 0) {
$firstPreviousSpacePtr--;
}
if ($tokens[$firstPreviousSpacePtr]['line'] >= $tokens[$firstCommentPtr]['line'] - 1) {
$error = "Please add a blank line before comments counting more than {$this->longCommentLimit} lines.";
$phpcsFile->addError($error, $firstCommentPtr, 'LongCommentWithoutSpacing');
$hasBlankLinesAround = FALSE;
}
// check blank line after the long comment
$lastCommentPtr = end($commentLines);
$lastNextSpacePtr = $lastCommentPtr + 1;
while (T_WHITESPACE === $tokens[$lastNextSpacePtr]['code'] && $lastNextSpacePtr < count($tokens)) {
$lastNextSpacePtr++;
}
if ($tokens[$lastNextSpacePtr]['line'] <= $tokens[$lastCommentPtr]['line'] + 1) {
$error = "Please add a blank line after comments counting more than {$this->longCommentLimit} lines.";
$phpcsFile->addError($error, $lastCommentPtr, 'LongCommentWithoutSpacing');
$hasBlankLinesAround = FALSE;
}
return $hasBlankLinesAround;
}//end _checkBlanksAroundLongComment()
}//end class
?>

View File

@ -0,0 +1,98 @@
<?php
/**
* CodeIgniter_Sniffs_Files_ByteOrderMarkSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Files_ByteOrderMarkSniff.
*
* Ensures that no BOM appears at the beginning of file.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Files;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class ByteOrderMarkSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array( T_OPEN_TAG );
}//end register()
/**
* List of supported BOM definitions.
*
* Use encoding names as keys and hex BOM representations as values.
*
* @return array
*/
protected function getBomDefinitions()
{
return array(
'UTF-8' => 'efbbbf',
'UTF-16 (BE)' => 'feff',
'UTF-16 (LE)' => 'fffe',
'UTF-32 (BE)' => '0000feff',
'UTF-32 (LE)' => 'fffe0000'
);
}//end getBomDefinitions()
/**
* Process tokens.
*
* Actually, only proceed when we're at index 0, this should be the only case
* that will contain BOM. Then check if BOM definition matches what
* we've found as file's inline HTML. Inline HTML could be longer than just BOM
* so make sure you test as much as needed.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr )
{
// We are only interested if this is the first open tag.
if ($stackPtr !== 0) {
if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) {
return;
}
}
$tokens = $phpcsFile->getTokens();
$fileStartString = $tokens[0]['content'];
foreach ($this->getBomDefinitions() as $bomName => $expectedBomHex) {
$bomByteLength = strlen($expectedBomHex) / 2;
$fileStartHex = bin2hex(substr($fileStartString, 0, $bomByteLength));
if ($fileStartHex === $expectedBomHex) {
$error = "File contains a $bomName byte order mark (BOM).";
$phpcsFile->addError($error, $stackPtr);
break;
}
}
}//end process()
}

View File

@ -0,0 +1,222 @@
<?php
/**
* CodeIgniter_Sniffs_Files_Utf8EncodingSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Files_Utf8EncodingSniff.
*
* Ensures that PHP files are encoded with Unicode (UTF-8) encoding.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Files;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class Utf8EncodingSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_OPEN_TAG
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
// We are only interested if this is the first open tag.
if ($stackPtr !== 0) {
if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) {
return;
}
}
$file_path = $phpcsFile->getFilename();
$file_name = basename($file_path);
$file_content = file_get_contents($file_path);
if (false === mb_check_encoding($file_content, 'UTF-8')) {
$error = 'File "' . $file_name . '" should be saved with Unicode (UTF-8) encoding.';
$phpcsFile->addError($error, 0);
}
if ( ! self::_checkUtf8W3c($file_content)) {
$error = 'File "' . $file_name . '" should be saved with Unicode (UTF-8) encoding, but it did not successfully pass the W3C test.';
$phpcsFile->addError($error, 0);
}
if ( ! self::_checkUtf8Rfc3629($file_content)) {
$error = 'File "' . $file_name . '" should be saved with Unicode (UTF-8) encoding, but it did not meet RFC3629 requirements.';
$phpcsFile->addError($error, 0);
}
}//end process()
/**
* Checks that the string $content contains only valid UTF-8 chars
* using W3C's method.
* Returns true if $content contains only UTF-8 chars, false otherwise.
*
* @param string $content String to check.
*
* @return bool true if $content contains only UTF-8 chars, false otherwise.
*
* @see http://w3.org/International/questions/qa-forms-utf-8.html
*/
private static function _checkUtf8W3c($content)
{
$content_chunks=self::mb_chunk_split($content, 4096, '');
foreach($content_chunks as $content_chunk)
{
$preg_result= preg_match(
'%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs',
$content_chunk
);
if($preg_result!==1)
{
return false;
}
}
return true;
}//end _checkUtf8W3c()
/**
* Checks that the string $content contains only valid UTF-8 chars
* using the method described in RFC 3629.
* Returns true if $content contains only UTF-8 chars, false otherwise.
*
* @param string $content String to check.
*
* @return bool true if $content contains only UTF-8 chars, false otherwise.
*
* @see http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
*/
private static function _checkUtf8Rfc3629($content)
{
$len = strlen($content);
for ($i = 0; $i < $len; $i++) {
$c = ord($content[$i]);
if ($c > 128) {
if (($c >= 254)) {
return false;
} elseif ($c >= 252) {
$bits=6;
} elseif ($c >= 248) {
$bits=5;
} elseif ($c >= 240) {
$bytes = 4;
} elseif ($c >= 224) {
$bytes = 3;
} elseif ($c >= 192) {
$bytes = 2;
} else {
return false;
} if (($i + $bytes) > $len) {
return false;
} while ($bytes > 1) {
$i++;
$b = ord($content[$i]);
if ($b < 128 || $b > 191) {
return false;
}
$bytes--;
}
}
}
return true;
}//_checkUtf8Rfc3629()
/**
* Splits a string to chunks of given size
* This helps to avoid segmentation fault errors when large text is given
* Returns array of strings after splitting
*
* @param string $str String to split.
* @param int $len number of characters per chunk
*
* @return array string array after splitting
*
* @see http://php.net/manual/en/function.chunk-split.php
*/
private static function mb_chunk_split($str, $len, $glue)
{
if (empty($str)) return false;
$array = self::mbStringToArray ($str);
$n = -1;
$new = Array();
foreach ($array as $char) {
$n++;
if ($n < $len) $new []= $char;
elseif ($n == $len) {
$new []= $glue . $char;
$n = 0;
}
}
return $new;
}//mb_chunk_split
/**
* Supporting function for mb_chunk_split
*
* @param string $str
*
* @return array
*
* @see http://php.net/manual/en/function.chunk-split.php
*/
private static function mbStringToArray ($str)
{
if (empty($str)) return false;
$len = mb_strlen($str);
$array = array();
for ($i = 0; $i < $len; $i++) {
$array[] = mb_substr($str, $i, 1);
}
return $array;
}
}//end class
?>

View File

@ -0,0 +1,81 @@
<?php
/**
* CodeIgniter_Sniffs_Operators_LogicalOperatorAndSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Operators_LogicalOperatorAndSniff.
*
* Ensures that the logical operator 'AND' is in upper case and suggest the use of its symbolic equivalent.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Operators;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class LogicalOperatorAndSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for: symbolic and literal operators and.
*
* @return array
*/
public function register()
{
return array(
T_LOGICAL_AND,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$operator_token = $tokens[$stackPtr];
$operator_string = $operator_token['content'];
$operator_code = $operator_token['code'];
if ($operator_string !== strtoupper($operator_string)) {
$error_message = 'Logical operator should be in upper case;'
. ' use "' . strtoupper($operator_string)
. '" instead of "' . $operator_string . '"';
$phpcsFile->addError($error_message, $stackPtr, 'LowercaseLogicalOperator');
}
$warning_message = 'The symbolic form "&&" is preferred over the literal form "AND"';
$phpcsFile->addWarning($warning_message, $stackPtr, 'UseOfLiteralAndOperator');
}//end process()
}//end class
?>

View File

@ -0,0 +1,81 @@
<?php
/**
* CodeIgniter_Sniffs_Operators_StrictComparisonOperatorSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Operators_StrictComparisonOperatorSniff.
*
* Ensures that only strict comparison operators are used instead of
* equal and not equal operators.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Operators;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class StrictComparisonOperatorSniff implements Sniff
{
private static $_replacements = array(
T_IS_EQUAL => '===',
T_IS_NOT_EQUAL => '!==',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_IS_EQUAL,
T_IS_NOT_EQUAL,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$operator_token = $tokens[$stackPtr];
$operator_string = $operator_token['content'];
$operator_code = $operator_token['code'];
$error_message = '"==" and "!=" are prohibited; use "'
. self::$_replacements[$operator_code] . '" instead of "'
. $operator_string . '".';
$phpcsFile->addError($error_message, $stackPtr, 'NonStrictComparisonUsed');
}//end process()
}//end class
?>

View File

@ -0,0 +1,84 @@
<?php
/**
* CodeIgniter_Sniffs_Operators_UppercaseLogicalOperatorOrSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Operators_UppercaseLogicalOperatorOrSniff.
*
* Ensures that the logical operator 'OR' is in upper cases and its symbolic equivalent.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Operators;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class UppercaseLogicalOperatorOrSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for: literal and symbolic operators or.
*
* @return array
*/
public function register()
{
return array(
T_BOOLEAN_OR,
T_LOGICAL_OR,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$operator_token = $tokens[$stackPtr];
$operator_string = $operator_token['content'];
$operator_code = $operator_token['code'];
if ($operator_code == T_BOOLEAN_OR) {
$error_message = 'Logical operator "' . $operator_string
. '" is prohibited; use "OR" instead';
$phpcsFile->addError($error_message, $stackPtr, 'UseOf||InsteadOfOR');
}
// it is literal, if it is not symbolic
else if ($operator_string !== strtoupper($operator_string)) {
$error_message = 'Logical operator should be in upper case;'
. ' use "' . strtoupper($operator_string)
. '" instead of "' . $operator_string . '"';
$phpcsFile->addError($error_message, $stackPtr, 'UseOfLowercaseOr');
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,464 @@
<?php
/**
* CodeIgniter_Sniffs_Strings_DoubleQuoteUsageSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Strings;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* CodeIgniter_Sniffs_Strings_DoubleQuoteUsageSniff.
*
* Ensures that double-quoted strings are used only to parse variables,
* to avoid escape characters before single quotes or for chars that need
* to be interpreted like \r, \n or \t.
* If a double-quoted string contain both single and double quotes
* but no variable, then a warning is raised to encourage the use of
* single-quoted strings.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class VariableUsageSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
/*
return array(
T_DOUBLE_QUOTED_STRING,
T_CONSTANT_ENCAPSED_STRING,
);
*/
return array();
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$string = $tokens[$stackPtr]['content'];
// makes sure that it is about a double quote string,
// since variables are not parsed out of double quoted string
$openDblQtStr = substr($string, 0, 1);
if (0 === strcmp($openDblQtStr, '"')) {
$this->processDoubleQuotedString($phpcsFile, $stackPtr, $string);
} else if (0 === strcmp($openDblQtStr, "'")) {
$this->processSingleQuotedString($phpcsFile, $stackPtr, $string);
}
}//end process()
/**
* Processes this test, when the token encountered is a double-quoted string.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $dblQtString The double-quoted string content,
* i.e. without quotes.
*
* @return void
*/
protected function processDoubleQuotedString (File $phpcsFile, $stackPtr, $dblQtString)
{
$variableFound = FALSE;
$strTokens = token_get_all('<?php '.$dblQtString);
$strPtr = 1; // skip php opening tag added by ourselves
$requireDblQuotes = FALSE;
while ($strPtr < count($strTokens)) {
$strToken = $strTokens[$strPtr];
if (is_array($strToken)) {
if (in_array($strToken[0], array(T_DOLLAR_OPEN_CURLY_BRACES, T_CURLY_OPEN))) {
$strPtr++;
try {
$this->_parseVariable($strTokens, $strPtr);
} catch (Exception $err) {
$error = 'There is no variable, object nor array between curly braces. Please use the escape char for $ or {.';
$phpcsFile->addError($error, $stackPtr);
}
$variableFound = TRUE;
if ('}' !== $strTokens[$strPtr]) {
$error = 'There is no matching closing curly brace.';
$phpcsFile->addError($error, $stackPtr);
}
// don't move forward, since it will be done in the main loop
// $strPtr++;
} else if (T_VARIABLE === $strToken[0]) {
$variableFound = TRUE;
$error = "Variable {$strToken[1]} in double-quoted strings should be enclosed with curly braces. Please consider {{$strToken[1]}}";
$phpcsFile->addError($error, $stackPtr);
}
}
$strPtr++;
}
return $variableFound;
}//end processDoubleQuotedString()
/**
* Processes this test, when the token encountered is a single-quoted string.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $sglQtString The single-quoted string content,
* i.e. without quotes.
*
* @return void
*/
protected function processSingleQuotedString (File $phpcsFile, $stackPtr, $sglQtString)
{
$variableFound = FALSE;
$strTokens = token_get_all('<?php '.$sglQtString);
$strPtr = 1; // skip php opening tag added by ourselves
while ($strPtr < count($strTokens)) {
$strToken = $strTokens[$strPtr];
if (is_array($strToken)) {
if (T_VARIABLE === $strToken[0]) {
$error = "Variables like {$strToken[1]} should be in double-quoted strings only.";
$phpcsFile->addError($error, $stackPtr);
}
}
$strPtr++;
}
return $variableFound;
}//end processSingleQuotedString()
/**
* Grammar rule to parse the use of a variable. Please notice that it
* doesn't manage the leading $.
*
* _parseVariable ::= <variable>
* | <variable>_parseObjectAttribute()
* | <variable>_parseArrayIndexes()
*
* @exception Exception raised if $strTokens starting from $strPtr
* doesn't matched the rule.
*
* @param array $strTokens Tokens to parse.
* @param int $strPtr Pointer to the token where parsing starts.
*
* @return array The attribute name associated to index 'var', an array with
* indexes 'obj' and 'attr' or an array with indexes 'arr' and 'idx'.
*/
private function _parseVariable ($strTokens, &$strPtr)
{
if ( ! in_array($strTokens[$strPtr][0], array(T_VARIABLE, T_STRING_VARNAME))) {
throw new Exception ('Expected variable name.');
}
$var = $strTokens[$strPtr][1];
$strPtr++;
$startStrPtr = $strPtr;
try {
$attr = $this->_parseObjectAttribute($strTokens, $strPtr);
return array ('obj' => $var, 'attr' => $attr);
} catch (Exception $err) {
if ($strPtr !== $startStrPtr) {
throw $err;
}
}
try {
$idx = $this->_parseArrayIndexes($strTokens, $strPtr);
return array ('arr' => $var, 'idx' => $idx);
} catch (Exception $err) {
if ($strPtr !== $startStrPtr) {
throw $err;
}
}
return array ('var' => $var);
}//end _parseVariable()
/**
* Grammar rule to parse the use of an object attribute.
*
* _parseObjectAttribute ::= -><attribute>
* | -><attribute>_parseObjectAttribute()
* | -><attribute>_parseArrayIndexes()
*
* @exception Exception raised if $strTokens starting from $strPtr
* doesn't matched the rule.
*
* @param array $strTokens Tokens to parse.
* @param int $strPtr Pointer to the token where parsing starts.
*
* @return mixed The attribute name as a string, an array with indexes
* 'obj' and 'attr' or an array with indexes 'arr' and 'idx'.
*/
private function _parseObjectAttribute ($strTokens, &$strPtr)
{
if (T_OBJECT_OPERATOR !== $strTokens[$strPtr][0]) {
throw new Exception ('Expected ->.');
}
$strPtr++;
if (T_STRING !== $strTokens[$strPtr][0]) {
throw new Exception ('Expected an object attribute.');
}
$attr = $strTokens[$strPtr][1];
$strPtr++;
$startStrPtr = $strPtr;
try {
$sub_attr = $this->_parseObjectAttribute($strTokens, $strPtr);
return array ('obj' => $attr, 'attr' => $sub_attr);
} catch (Exception $err) {
if ($strPtr !== $startStrPtr) {
throw $err;
}
}
try {
$idx = $this->_parseArrayIndexes($strTokens, $strPtr);
return array ('arr' => $attr, 'idx' => $idx);
} catch (Exception $err) {
if ($strPtr !== $startStrPtr) {
throw $err;
}
}
return $attr;
}//end _parseObjectAttribute()
/**
* Grammar rule to parse the use of one or more array indexes.
*
* _parseArrayIndexes ::= _parseArrayIndex()+
*
* @exception Exception raised if $strTokens starting from $strPtr
* doesn't matched the rule.
*
* @param array $strTokens Tokens to parse.
* @param int $strPtr Pointer to the token where parsing starts.
*
* @return array Indexes in the same order as in the string.
*/
private function _parseArrayIndexes ($strTokens, &$strPtr)
{
$indexes = array($this->_parseArrayIndex($strTokens, $strPtr));
try {
while (1) {
$startStrPtr = $strPtr;
$indexes [] = $this->_parseArrayIndex($strTokens, $strPtr);
}
} catch (Exception $err) {
if (0 !== ($strPtr - $startStrPtr)) {
throw $err;
}
return $indexes;
}
}//end _parseArrayIndexes()
/**
* Grammar rule to parse the use of array index.
*
* _parseArrayIndex ::= [<index>]
*
* @exception Exception raised if $strTokens starting from $strPtr
* doesn't matched the rule.
*
* @param array $strTokens Tokens to parse.
* @param int $strPtr Pointer to the token where parsing starts.
*
* @return string Index between the 2 square brackets
*/
private function _parseArrayIndex ($strTokens, &$strPtr)
{
if ('[' !== $strTokens[$strPtr]) {
throw new Exception ('Expected [.');
}
$strPtr++;
if (! in_array($strTokens[$strPtr][0], array(T_CONSTANT_ENCAPSED_STRING, T_LNUMBER))) {
throw new Exception ('Expected an array index.');
}
$index = $strTokens[$strPtr][1];
$strPtr++;
if (']' !== $strTokens[$strPtr]) {
throw new Exception ('Expected ].');
}
$strPtr++;
return $index;
}//end _parseArrayIndex()
}//end class
/**
* CodeIgniter_Sniffs_Strings_VariableUsageSniff.
*
* Ensures that variables parsed in double-quoted strings are enclosed with
* braces to prevent greedy token parsing.
* Single-quoted strings don't parse variables, so there is no risk of greedy
* token parsing.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class DoubleQuoteUsageSniff extends VariableUsageSniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_DOUBLE_QUOTED_STRING,
T_CONSTANT_ENCAPSED_STRING,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
// no variable are in the string from here
$tokens = $phpcsFile->getTokens();
$qtString = $tokens[$stackPtr]['content'];
// makes sure that it is about a double quote string,
// since variables are not parsed out of double quoted string
$open_qt_str = substr($qtString, 0, 1);
// clean the enclosing quotes
$qtString = substr($qtString, 1, strlen($qtString) - 1 - 1);
if (0 === strcmp($open_qt_str, '"')) {
$this->processDoubleQuotedString($phpcsFile, $stackPtr, $qtString);
} else if (0 === strcmp($open_qt_str, "'")) {
$this->processSingleQuotedString($phpcsFile, $stackPtr, $qtString);
}
}//end process()
/**
* Processes this test, when the token encountered is a double-quoted string.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $qtString The double-quoted string content,
* i.e. without quotes.
*
* @return void
*/
protected function processDoubleQuotedString (File $phpcsFile, $stackPtr, $qtString)
{
// so there should be at least a single quote or a special char
// if there are the 2 kinds of quote and no special char, then add a warning
$has_variable = parent::processDoubleQuotedString($phpcsFile, $stackPtr, '"'.$qtString.'"');
$has_specific_sequence = $this->_hasSpecificSequence($qtString);
$dbl_qt_at = strpos($qtString, '"');
$smpl_qt_at = strpos($qtString, "'");
if (false === $has_variable && false === $has_specific_sequence
&& false === $smpl_qt_at
) {
$error = 'Single-quoted strings should be used unless it contains variables, special chars like \n or single quotes.';
$phpcsFile->addError($error, $stackPtr);
} else if (false !== $smpl_qt_at && false !== $dbl_qt_at
&& false === $has_variable && false === $has_specific_sequence
) {
$warning = 'It is encouraged to use a single-quoted string, since it doesn\'t contain any variable nor special char though it mixes single and double quotes.';
$phpcsFile->addWarning($warning, $stackPtr);
}
}//end processDoubleQuotedString()
/**
* Processes this test, when the token encountered is a single-quoted string.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $qtString The single-quoted string content,
* i.e. without quotes.
*
* @return void
*/
protected function processSingleQuotedString (File $phpcsFile, $stackPtr, $qtString)
{
// if there is single quotes without additional double quotes,
// then user is allowed to use double quote to avoid having to
// escape single quotes. Don't add the warning, if an error was
// already added, because a variable was found in a single-quoted
// string.
$has_variable = parent::processSingleQuotedString($phpcsFile, $stackPtr, "'".$qtString."'");
$dbl_qt_at = strpos($qtString, '"');
$smpl_qt_at = strpos($qtString, "'");
if (false === $has_variable && false !== $smpl_qt_at && false === $dbl_qt_at) {
$warning = 'You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters.';
$phpcsFile->addWarning($warning, $stackPtr);
}
}//end processSingleQuotedString()
/**
* Return TRUE, if a sequence of chars that is parsed in a specific way
* in double-quoted strings is found, FALSE otherwise.
*
* @param string $string String in which sequence of special chars will
* be researched.
*
* @return TRUE, if a sequence of chars that is parsed in a specific way
* in double-quoted strings is found, FALSE otherwise.
*
* @link http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
*/
private function _hasSpecificSequence($string)
{
$hasSpecificSequence = FALSE;
$specialMeaningStrs = array('\n', '\r', '\t', '\v', '\f');
foreach ($specialMeaningStrs as $splStr) {
if (FALSE !== strpos($string, $splStr)) {
$hasSpecificSequence = TRUE;
}
}
$specialMeaningPtrns = array('\[0-7]{1,3}', '\x[0-9A-Fa-f]{1,2}');
foreach ($specialMeaningPtrns as $splPtrn) {
if (1 === preg_match("/{$splPtrn}/", $string)) {
$hasSpecificSequence = TRUE;
}
}
return $hasSpecificSequence;
}//end _hasSpecificSequence()
}//end class
?>

View File

@ -0,0 +1,87 @@
<?php
/**
* CodeIgniter_Sniffs_WhiteSpace_DisallowSpaceIndentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@gmail.com>
* @copyright 2011 Thomas ERNEST
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_WhiteSpace_DisallowSpaceIndentSniff.
*
* Ensures the use of tabs for indentation.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@gmail.com>
* @copyright 2011 Thomas ERNEST
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\WhiteSpace;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class DisallowSpaceIndentSniff implements Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
'CSS',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_WHITESPACE);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile All the tokens found in the document.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Make sure this is whitespace used for indentation.
$line = $tokens[$stackPtr]['line'];
if ($stackPtr > 0 && $tokens[($stackPtr - 1)]['line'] === $line) {
return;
}
if (strpos($tokens[$stackPtr]['content'], " ") !== false) {
$error = 'Tabs must be used to indent lines; spaces are not allowed for code indentation';
$phpcsFile->addError($error, $stackPtr, 'SpacesUsedForIndentation');
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,95 @@
<?php
/**
* CodeIgniter_Sniffs_WhiteSpace_DisallowWitheSpaceAroundPhpTagsSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_WhiteSpace_DisallowWitheSpaceAroundPhpTagsSniff.
*
* Ensures that no whitespace precedes the opening PHP tag
* or follows the closing PHP tag.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\WhiteSpace;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class DisallowWitheSpaceAroundPhpTagsSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_OPEN_TAG,
T_CLOSE_TAG
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$php_tag_token = $tokens[$stackPtr];
$php_tag_code = $php_tag_token['code'];
if (T_OPEN_TAG === $php_tag_code) {
// opening php tag should be the first token.
// any whitespace beofre an opening php tag is tokenized
// as T_INLINE_HTML, so no need to check the content of the token.
$isFirst = 0 === $stackPtr;
if ( ! $isFirst) {
$error = 'Any char before the opening PHP tag is prohibited. Please remove newline or indentation before the opening PHP tag.';
$phpcsFile->addError($error, $stackPtr);
}
} else {
// if (T_CLOSE_TAG === $php_tag_code)
// closing php tag should be the last token
// and it must not contain any whitespace.
$php_tag_string = $php_tag_token['content'];
$isLast = count($tokens) - 1 === $stackPtr;
// both of the two closing php tags contains 2 chars exactly.
$containsEndTagOnly = strlen($php_tag_string) > 2;
if ( ! $isLast || ! $containsEndTagOnly ) {
$error = 'Any char after the closing PHP tag is prohibited. Please removes newline or spaces after the closing PHP tag.';
$phpcsFile->addError($error, $stackPtr);
}
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,82 @@
<?php
/**
* CodeIgniter_Sniffs_WhiteSpace_ElseOnNewLineSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_WhiteSpace_ElseOnNewLineSniff.
*
* Ensures that control structures else and elseif stand on new lines.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\WhiteSpace;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class ElseOnNewLineSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_ELSE,
T_ELSEIF,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$else_token = $tokens[$stackPtr];
$previous_non_blank_token_ptr = $phpcsFile->findPrevious(array(T_WHITESPACE), $stackPtr - 1, null, true);
if (false === $previous_non_blank_token_ptr) {
// else is no preceded with any symbol, but it is not the responsibility of this sniff.
return;
}
$previous_non_blank_token = $tokens[$previous_non_blank_token_ptr];
if ($previous_non_blank_token['line'] === $else_token['line']) {
$error = '"' . $else_token['content'] . '" should be on a new line.';
$phpcsFile->addError($error, $stackPtr);
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,75 @@
<?php
/**
* CodeIgniter_Sniffs_WhiteSpace_LogicalNotSpacingSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_WhiteSpace_LogicalNotSpacingSniff.
*
* Ensures that at exactly a space precedes and follows the logical operator !.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\WhiteSpace;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class LogicalNotSpacingSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_BOOLEAN_NOT,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$operator_token = $tokens[$stackPtr];
$previous_token = $tokens[$stackPtr - 1];
$next_token = $tokens[$stackPtr + 1];
if (T_WHITESPACE !== $previous_token['code'] || T_WHITESPACE !== $next_token['code']) {
$error = 'Logical operator ! should always be preceded and followed with a whitespace.';
$phpcsFile->addError($error, $stackPtr);
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,104 @@
<?php
/**
* CodeIgniter_Sniffs_Files_AbstractClosingCommentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Files_AbstractClosingCommentSniff.
*
* Defines some methods used by
* CodeIgniter_Sniffs_Files_ClosingFileCommentSniff
* and CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Files;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class AbstractClosingCommentSniff implements Sniff
{
/**
* As an abstract class, this sniff is not associated to any token.
*/
public function register()
{
return array();
}
/**
* As an abstract class, this sniff is not dedicated to process a token.
*/
public function process(File $phpcsFile, $stackPtr)
{
$error = __CLASS__.'::'.__METHOD__.' is abstract. Please develop this method in a child class.';
throw new PHP_CodeSniffer_Exception($error);
}
/**
* Returns the comment without its delimiter(s) as well as leading
* and traling whitespaces.
*
* It removes the first #, the two first / (i.e. //) or the first /*
* and last \*\/. If a comment starts with /**, then the last * will remain
* as well as whitespaces between this star and the comment content.
*
* @param string $comment Comment containing either comment delimiter(s) and
* trailing or leading whitspaces to clean.
*
* @return string Comment without comment delimiter(s) and whitespaces.
*/
protected static function _getCommentContent ($comment)
{
if (self::_stringStartsWith($comment, '#')) {
$comment = substr($comment, 1);
} else if (self::_stringStartsWith($comment, '//')) {
$comment = substr($comment, 2);
} else if (self::_stringStartsWith($comment, '/*')) {
$comment = substr($comment, 2, strlen($comment) - 2 - 2);
}
$comment = trim($comment);
return $comment;
}//_getCommentContent()
/**
* Binary safe string comparison between $needle and
* the beginning of $haystack. Returns true if $haystack starts with
* $needle, false otherwise.
*
* @param string $haystack The string to search in.
* @param string $needle The string to search for.
*
* @return bool true if $haystack starts with $needle, false otherwise.
*/
protected static function _stringStartsWith ($haystack, $needle)
{
$startsWith = false;
if (strlen($needle) <= strlen($haystack)) {
$haystackBeginning = substr($haystack, 0, strlen($needle));
if (0 === strcmp($haystackBeginning, $needle)) {
$startsWith = true;
}
}
return $startsWith;
}//_stringStartsWith()
}//end class
?>

View File

@ -0,0 +1,109 @@
<?php
/**
* CodeIgniter_Sniffs_Files_ClosingFileCommentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Files_ClosingFileCommentSniff.
*
* Ensures that a comment containing the file name is available at the end of file.
* Only other comments and whitespaces are allowed to follow this specific comment.
*
* It may be all kind of comment like multi-line and inline C-style comments as
* well as PERL-style comments. Any number of white may separate comment delimiters
* from comment content. However, content has to be equal to template
* "End of file <file_name>". Comparison between content and template is
* case-sensitive.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Files;
use PHP_CodeSniffer\Files\File;
class ClosingFileCommentSniff extends AbstractClosingCommentSniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_OPEN_TAG,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
// We are only interested if this is the first open tag.
if ($stackPtr !== 0) {
if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) {
return;
}
}
$fullFilename = $phpcsFile->getFilename();
$filename = basename($fullFilename);
$commentTemplate = "End of file $filename";
$tokens = $phpcsFile->getTokens();
$currentToken = count($tokens) - 1;
$hasClosingFileComment = false;
$isNotAWhitespaceOrAComment = false;
while ($currentToken >= 0
&& ! $isNotAWhitespaceOrAComment
&& ! $hasClosingFileComment
) {
$token = $tokens[$currentToken];
$tokenCode = $token['code'];
if (T_COMMENT === $tokenCode) {
$commentString = self::_getCommentContent($token['content']);
if (0 === strcmp($commentString, $commentTemplate)) {
$hasClosingFileComment = true;
}
} else if (T_WHITESPACE === $tokenCode) {
// Whitespaces are allowed between the closing file comment,
// other comments and end of file
} else {
$isNotAWhitespaceOrAComment = true;
}
$currentToken--;
}
if ( ! $hasClosingFileComment) {
$error = 'No comment block marks the end of file instead of the closing PHP tag. Please add a comment block containing only "' . $commentTemplate . '".';
$phpcsFile->addError($error, $currentToken);
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,182 @@
<?php
/**
* CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff.
*
* Ensures that a comment containing the file location exists at the end of file.
* Only other comments and whitespaces are allowed between this comment and
* the end of file.
*
* It may be all kind of comment like multi-line and inline C-style comments as
* well as PERL-style comments. Any number of white may separate comment delimiters
* from comment content. However, content has to be equal to template
* "Location: <file_path_relative_to_application_root>".
* Comparison between content and template is case-sensitive.
*
* There are several ways to configure the application root. In order of priority :
* - Configuration variable ci_application_root.
* - Rule property applicationRoot.
* - Default value '/application/'
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2006 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\Files;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Common;
class ClosingLocationCommentSniff extends AbstractClosingCommentSniff
{
public $applicationRoot = '/application/';
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_OPEN_TAG
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
// We are only interested if this is the first open tag.
if ($stackPtr !== 0) {
if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) {
return;
}
}
$filePath = $phpcsFile->getFilename();
$tokens = $phpcsFile->getTokens();
// removes the application root from the beginning of the file path
$locationPath = self::_getLocationPath($filePath, $this->_getAppRoot());
// add an error, if application root doesn't exist in current file path
if (false === $locationPath) {
$error = 'Unable to find "' . $this->_getAppRoot() . '" in file path "' . $filePath . '". Please set your project\'s application root.';
$phpcsFile->addError($error, count($tokens) - 1);
return;
}
// generates the expected comment
$commentTemplate = "Location: $locationPath";
$currentToken = count($tokens) - 1;
$hasClosingLocationComment = false;
$isNotAWhitespaceOrAComment = false;
while ($currentToken >= 0
&& ! $isNotAWhitespaceOrAComment
&& ! $hasClosingLocationComment
) {
$token = $tokens[$currentToken];
$tokenCode = $token['code'];
if (T_COMMENT === $tokenCode) {
$commentString = self::_getCommentContent($token['content']);
if (0 === strcmp($commentString, $commentTemplate)) {
$hasClosingLocationComment = true;
}
} else if (T_WHITESPACE === $tokenCode) {
// Whitespaces are allowed between the closing file comment,
//other comments and end of file
} else {
$isNotAWhitespaceOrAComment = true;
}
$currentToken--;
}
if ( ! $hasClosingLocationComment) {
$error = 'No comment block marks the end of file instead of the closing PHP tag. Please add a comment block containing only "' . $commentTemplate . '".';
$phpcsFile->addError($error, $currentToken);
}
}//end process()
/**
* Returns the relative path from $appRoot to $filePath, or false if
* $appRoot cannot be found in $filePath, because $appRoot is not a parent
* of $filePath.
*
* @param string $filePath Full path to the file being proceed.
* @param string $appRoot Partial or full path to the CodeIgniter
* application root of the file being proceed. It must not contain the
* full path to the application root, but at least the name of the
* application root. Parent directory of the application root are allowed
* but not mandatory.
*
* @return string|bool The relative path from $appRoot to $filePath, or
* false if $appRoot cannot be found in $filePath.
*/
private static function _getLocationPath ($filePath, $appRoot)
{
// removes the path to application root
// from the beginning of the file path
$appRootAt = strpos($filePath, $appRoot);
if (false === $appRootAt) {
return false;
}
$localPath = substr($filePath, $appRootAt + strlen($appRoot));
// ensures the location path to be a relative path starting with "./".
if ( ! self::_stringStartsWith($localPath, './')) {
$localPath = './' . $localPath;
} else if ( ! self::_stringStartsWith($localPath, '.')
&& self::_stringStartsWith($localPath, '/')
) {
$localPath = '.' . $localPath;
}
return $localPath;
}//end _getLocationPath()
/**
* Returns the application root that should be used first.
*
* There are several ways to configure the application root.
* In order of priority :
* - Configuration variable ci_application_root.
* - Rule property applicationRoot.
* - Default value '/application/'
*
* @return string Path to your project application root.
*/
private function _getAppRoot()
{
$appRoot = Common::getConfigData('ci_application_root');
if (null === $appRoot) {
$appRoot = $this->applicationRoot;
}
return $appRoot;
}//end _getAppRoot()
}//end class
?>

View File

@ -0,0 +1,142 @@
<?php
/**
* CodeIgniter_Sniffs_NamingConventions_ConstructorNameSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@gmail.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\NamingConventions;
use PHP_CodeSniffer\Sniffs\AbstractScopeSniff;
use PHP_CodeSniffer\Files\File;
/**
* CodeIgniter_Sniffs_NamingConventions_ConstructorNameSniff.
*
* Favor PHP 4 constructor syntax, which uses "function ClassName()".
* Avoid PHP 5 constructor syntax, which uses "function __construct()".
*
* @todo Try to avoid overly long and verbose names.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@gmail.com>
* @copyright 2010 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class ConstructorNameSniff extends AbstractScopeSniff
{
public $php5Constructors = '1';
/**
* Constructs the test with the tokens it wishes to listen for.
*
* @return void
*/
public function __construct()
{
parent::__construct(array(T_CLASS, T_INTERFACE), array(T_FUNCTION), true);
}//end __construct()
/**
* Processes this test when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param int $currScope A pointer to the start of the scope.
*
* @return void
*/
protected function processTokenWithinScope(
File $phpcsFile,
$stackPtr,
$currScope
) {
$methodName = $phpcsFile->getDeclarationName($stackPtr);
$className = $phpcsFile->getDeclarationName($currScope);
$isPhp4Constructor = strcasecmp($methodName, $className) === 0;
$isPhp5Constructor = strcasecmp($methodName, '__construct') === 0;
if ($this->php5Constructors != '0') {
if ($isPhp4Constructor) {
$error = "PHP4 style constructors are not allowed; use \"__construct\" instead";
$phpcsFile->addError($error, $stackPtr);
}
} else {
if ($isPhp5Constructor) {
$error = "PHP5 style constructors are not allowed; use \"$className\" instead";
$phpcsFile->addError($error, $stackPtr);
}
}
if ( ! $isPhp4Constructor && ! $isPhp5Constructor ) {
return;
}
$tokens = $phpcsFile->getTokens();
$parentClassName = $phpcsFile->findExtendedClassName($currScope);
$wrongConstructor = '';
// prepares the error message and wrong constructor
if ($this->php5Constructors != '0') {
$error = 'PHP4 style calls to parent constructors are not allowed.';
$error = "$error Please use \"parent::__construct\" instead.";
if (false !== $parentClassName) {
$wrongConstructor = $parentClassName;
}
// Else $wrongConstructor will be empty
// and the test expression will always be false.
// It doesn't check that no parent method should be called
// when no parent class is defined.
} else {
$error = 'PHP5 style calls to parent constructors are not allowed.';
if (false !== $parentClassName) {
$error = "$error Please use \"parent::$parentClassName\" instead.";
}
$wrongConstructor = '__construct';
}
// looks for the use of a wrong constructor.
$endFunctionIndex = $tokens[$stackPtr]['scope_closer'];
$doubleColonIndex = $phpcsFile->findNext(
array(T_DOUBLE_COLON),
$stackPtr,
$endFunctionIndex
);
while ($doubleColonIndex) {
if ($tokens[($doubleColonIndex + 1)]['code'] === T_STRING
&& $tokens[($doubleColonIndex + 1)]['content'] === $wrongConstructor
) {
$phpcsFile->addError($error, ($doubleColonIndex + 1));
}
$doubleColonIndex = $phpcsFile->findNext(
array(T_DOUBLE_COLON),
$doubleColonIndex + 1,
$endFunctionIndex
);
}
}//end processTokenWithinScope()
protected function processTokenOutsideScope(File $phpcsFile, $stackPtr)
{
// TODO: Implement processTokenOutsideScope() method.
}
}//end class
?>

View File

@ -0,0 +1,84 @@
<?php
/**
* CodeIgniter_Sniffs_NamingConventions_ValidClassNameSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baoabz.com>
* @copyright 2010 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_NamingConventions_ValidClassNameSniff.
*
* Ensures that class and interface names have their first letter uppercase
* and that words are separated with an underscore, and not CamelCased.
*
* @todo Try to avoid overly long and verbose names in using property rule and
* configuration variable to set limits. Have a look at
* CodeIgniter_Sniffs_NamingConventions_ValidMethodNameSniff.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baoabz.com>
* @copyright 2010 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\NamingConventions;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class ValidClassNameSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_CLASS,
T_INTERFACE,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The current file being processed.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
// get the class name
$className = trim($phpcsFile->getDeclarationName($stackPtr));
// compute the expected class name
// [^_] means "something different from _", but not "nothing or something different from _"
$lcClassNameChunk = preg_replace('/([^_])([A-Z])/', '${1}_${2}', $className);
$expectedClassName
= strtoupper($className[0]) . strtolower(substr($lcClassNameChunk,1));
// ensures that the current class name
// and the expected class name are identical
if (0 !== strcmp($className, $expectedClassName)) {
$error = 'Class names should always have their first letter uppercase. Multiple words should be separated with an underscore, and not CamelCased. Please consider ' . $expectedClassName . ' instead of ' . $className . '.';
$phpcsFile->addError($error, $stackPtr);
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,84 @@
<?php
/**
* CodeIgniter_Sniffs_NamingConventions_ValidFileNameSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_NamingConventions_ValidFileNameSniff.
*
* Tests that the file name matchs the name of the class that it contains in lower case.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baobaz.com>
* @copyright 2011 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\NamingConventions;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class ValidFileNameSniff implements Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_CLASS,
T_INTERFACE,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// computes the expected filename based on the name of the class or interface that it contains.
$decNamePtr = $phpcsFile->findNext(T_STRING, $stackPtr);
$decName = $tokens[$decNamePtr]['content'];
$expectedFileName = strtolower($decName);
// extracts filename without extension from its path.
$fullPath = $phpcsFile->getFilename();
$fileNameAndExt = basename($fullPath);
$fileName = substr($fileNameAndExt, 0, strrpos($fileNameAndExt, '.'));
if ($expectedFileName !== $fileName) {
$errorTemplate = 'Filename "%s" doesn\'t match the name of the %s that it contains "%s" in lower case. "%s" was expected.';
$errorMessage = sprintf(
$errorTemplate,
$fileName,
strtolower($tokens[$stackPtr]['content']), // class or interface
$decName,
$expectedFileName
);
$phpcsFile->addError($errorMessage, 0);
}
}//end process()
}//end class
?>

View File

@ -0,0 +1,161 @@
<?php
/**
* CodeIgniter_Sniffs_NamingConventions_ValidMethodNameSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baoabz.com>
* @copyright 2010 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_NamingConventions_ValidMethodNameSniff.
*
* Ensures that class methods and functions areentirely lowercased and that
* words are separated with an underscore, and not CamelCased.
* Ensures that private class methods are prefixed with an underscore and that
* all other methods are not prefixed with an underscored.
* Ensures that names longer than 50 chars are prohibited. Likewise names longer
* than 35 chars raise a warning.
*
* @todo Use a rule property or a configuration variable to allow users to set
* their own maximum lengths for function and method names. Have a look at
* CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff and application root.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baoabz.com>
* @copyright 2010 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\NamingConventions;
use PHP_CodeSniffer\Sniffs\AbstactScopeSniff;
use PHP_CodeSniffer\Files\File;
class ValidMethodNameSniff extends AbstractScopeSniff
{
/**
* A list of all PHP magic methods.
*
* @var array
*/
protected static $magicMethods = array(
'construct',
'destruct',
'call',
'callStatic',
'get',
'set',
'isset',
'unset',
'sleep',
'wakeup',
'toString',
'set_state',
'clone',
);
/**
* Defines which token(s) in which scope(s) will be proceed.
*/
public function __construct()
{
parent::__construct(array(T_CLASS, T_INTERFACE), array(T_FUNCTION), true);
}//end __construct()
/**
* Processes the tokens within the scope.
*
* @param File $phpcsFile The file being processed.
* @param int $stackPtr The position where this token was
* found.
* @param int $currScope The position of the current scope.
*
* @return void
*/
protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope)
{
$methodName = $phpcsFile->getDeclarationName($stackPtr);
if ($methodName === null) {
// Ignore closures.
return;
}
$className = $phpcsFile->getDeclarationName($currScope);
// Is this a magic method i.e. is prefixed with "__".
if (0 === strcmp(substr($methodName, 0, 2), '__')) {
$magicPart = substr($methodName, 2);
if (in_array($magicPart, self::$magicMethods) === false) {
$error = "Method name \"$className::$methodName\" is invalid; only PHP magic methods should be prefixed with a double underscore";
$phpcsFile->addError($error, $stackPtr);
}
return;
}
// PHP4 constructors are allowed to break our rules.
if ($methodName === $className) {
return;
}
// PHP4 destructors are allowed to break our rules.
if ($methodName === '_'.$className) {
return;
}
if (0 !== strcmp($methodName, strtolower($methodName))) {
$uscrdMethodName = preg_replace('/([A-Z])/', '_${1}', $methodName);
$expectedMethodName = strtolower($uscrdMethodName);
$error = "Class methods should be entirely lowercased. Please consider \"$expectedMethodName\" instead of \"$methodName\".";
$phpcsFile->addError($error, $stackPtr);
return;
}
$methodProps = $phpcsFile->getMethodProperties($stackPtr);
$scope = $methodProps['scope'];
$scopeSpecified = $methodProps['scope_specified'];
// If it's a private method, it must have an underscore on the front.
if ($scope === 'private' && $methodName{0} !== '_') {
$error = "Private method name \"$className::$methodName\" must be prefixed with an underscore";
$phpcsFile->addError($error, $stackPtr);
return;
}
// If it's not a private method, it must not have an underscore on the front.
if ($scope !== 'private' && $methodName{0} === '_') {
if (true === $scopeSpecified) {
$error = "Public method name \"$className::$methodName\" must not be prefixed with an underscore";
} else {
$error = ucfirst($scope)." method name \"$className::$methodName\" must not be prefixed with an underscore";
}
$phpcsFile->addError($error, $stackPtr);
return;
}
// If name is too verbose,
// then either an error or a warning is displayed.
$error_limit = 50;
$warning_limit = 35;
if (strlen($methodName) > $error_limit) {
$error = "Overly long and verbose names are prohibited. Please find a name shorter than $error_limit chars.";
$phpcsFile->addError($error, $stackPtr);
return;
} else if (strlen($methodName) > $warning_limit) {
$warning = "Try to avoid overly long and verbose names in finding a name shorter than $warning_limit chars.";
$phpcsFile->addWarning($warning, $stackPtr);
}
}//end processTokenWithinScope()
}//end class
?>

View File

@ -0,0 +1,562 @@
<?php
/**
* CodeIgniter_Sniffs_NamingConventions_ValidVariableNameSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baoabz.com>
* @copyright 2010 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* CodeIgniter_Sniffs_NamingConventions_ValidVariableNameSniff.
*
* Ensures that variable names contain only lowercase letters,
* use underscore separators.
* Ensures that class attribute names are prefixed with an underscore,
* only when they are private.
* Ensure that variable names are longer than 3 chars except those declared
* in for loops.
*
* @todo Try to avoid overly long and verbose names in using property rule and
* configuration variable to set limits. Have a look at
* CodeIgniter_Sniffs_NamingConventions_ValidMethodNameSniff.
* @todo Use a property rule or a configuration variable to allow users to set
* minimum variable name length. Have a look at
* CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff and application root.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Thomas Ernest <thomas.ernest@baoabz.com>
* @copyright 2010 Thomas Ernest
* @license http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
namespace CodeIgniter\Sniffs\NamingConventions;
use PHP_CodeSniffer\Sniffs\AbstractVariableSniff;
use PHP_CodeSniffer\Files\File;
class ValidVariableNameSniff extends AbstractVariableSniff
{
/**
* Processes class member variables.
*
* @param File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
protected function processMemberVar(File $phpcsFile, $stackPtr)
{
// get variable name and properties
$tokens = $phpcsFile->getTokens();
$varTk = $tokens[$stackPtr];
$varName = substr($varTk['content'], 1);
$varProps = $phpcsFile->getMemberProperties($stackPtr);
// check(s)
if ( ! $this->checkLowerCase($phpcsFile, $stackPtr, $varName) ) {
return;
}
if ( ! $this->checkVisibilityPrefix($phpcsFile, $stackPtr, $varName, $varProps)) {
return;
}
if ( ! $this->checkLength($phpcsFile, $stackPtr, $varName)) {
return;
}
}//end processMemberVar()
/**
* Processes normal variables.
*
* @param File $phpcsFile The file where this token was found.
* @param int $stackPtr The position where the token was found.
*
* @return void
*/
protected function processVariable(File $phpcsFile, $stackPtr)
{
// get variable name
$tokens = $phpcsFile->getTokens();
$varTk = $tokens[$stackPtr];
$varName = substr($varTk['content'], 1);
// skip the current object variable, i.e. $this
if (0 === strcmp($varName, 'this')) {
return;
}
// check(s)
if ( ! $this->checkLowerCase($phpcsFile, $stackPtr, $varName)) {
return;
}
if ( ! $this->checkLength($phpcsFile, $stackPtr, $varName)) {
return;
}
}//end processVariable()
/**
* Processes variables in double quoted strings.
*
* @param File $phpcsFile The file where this token was found.
* @param int $stackPtr The position where the token was found.
*
* @return void
*/
protected function processVariableInString(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$stringTk = $tokens[$stackPtr];
$stringString = $stringTk['content'];
$varAt = self::_getVariablePosition($stringString, 0);
while (false !== $varAt) {
// get variable name
$matches = array();
preg_match('/^\$\{?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}?/', substr($stringString, $varAt), $matches);
$varName = $matches[1];
// check(s)
if ( ! $this->checkLowerCase($phpcsFile, $stackPtr, $varName)) {
return;
}
if ( ! $this->checkLength($phpcsFile, $stackPtr, $varName)) {
return;
}
// prepare checking next variable
$varAt = self::_getVariablePosition($stringString, $varAt + 1);
}
}//end processVariableInString()
/**
* Checks that the variable name is all in lower case, else it add an error
* to $phpcsFile. Returns true if variable name is all in lower case, false
* otherwise.
*
* @param File $phpcsFile The current file being processed.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $varName The name of the variable to
* procced without $, { nor }.
*
* @return bool true if variable name is all in lower case, false otherwise.
*/
protected function checkLowerCase(File $phpcsFile, $stackPtr, $varName)
{
$isInLowerCase = true;
if (0 !== strcmp($varName, strtolower($varName))) {
// get the expected variable name
$varNameWithUnderscores = preg_replace('/([A-Z])/', '_${1}', $varName);
$expectedVarName = strtolower(ltrim($varNameWithUnderscores, '_'));
// adapts the error message to the error case
if (strlen($varNameWithUnderscores) > strlen($varName)) {
$error = 'Variables should not use CamelCasing or start with a Capital.';
} else {
$error = 'Variables should be entirely lowercased.';
}
$error = $error . 'Please consider "' . $expectedVarName
. '" instead of "' . $varName . '".';
// adds the error and changes return value
$phpcsFile->addError($error, $stackPtr);
$isInLowerCase = false;
}
return $isInLowerCase;
}//end checkLowerCase()
/**
* Checks that an underscore is used at the beginning of a variable only if
* it is about a private variable. If it isn't a private variable, then it
* must not be prefixed with an underscore. Returns true if $varName is
* properly prefixed according to the variable visibility provided in
* $varProps, false otherwise.
*
* @param File $phpcsFile The current file being processed.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $varName The name of the variable to
* procced without $, { nor }.
* @param array $varProps Member variable properties like
* its visibility.
*
* @return bool true if variable name is prefixed with an underscore only
* when it is about a private variable, false otherwise.
*/
protected function checkVisibilityPrefix(File $phpcsFile, $stackPtr, $varName, $varProps)
{
$isVisibilityPrefixRight = true;
$scope = $varProps['scope'];
// If it's a private variable, it must have an underscore on the front.
if ($scope === 'private' && $varName{0} !== '_') {
$error = "Private variable name \"$varName\" must be prefixed with an underscore";
$phpcsFile->addError($error, $stackPtr);
$isVisibilityPrefixRight = false;
} else if ($scope !== 'private' && $varName{0} === '_') {
// If it's not a private variable,
// then it must not start with an underscore.
if (isset ($scopeSpecified) && true === $scopeSpecified) {
$error = "Public variable name \"$varName\" must not be prefixed with an underscore";
} else {
$error = ucfirst($scope) . " variable name \"$varName\" must not be prefixed with an underscore";
}
$phpcsFile->addError($error, $stackPtr);
$isVisibilityPrefixRight = false;
}
return $isVisibilityPrefixRight;
}//end checkVisibilityPrefix()
/**
* Checks that variable name length is not too short. Returns true, if it
* meets minimum length requirement, false otherwise.
*
* A variable name is too short if it is shorter than the minimal
* length and it isn't in the list of allowed short names nor declared in a
* for loop (in which it would be nested).
* The minimal length is defined in the function. It is 3 chars now.
* The list of allowed short names is defined in the function.
* It is case-sensitive. It contains only 'ci' now.
*
* @param File $phpcsFile The current file being processed.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $varName The name of the variable to
* procced without $, { nor }.
*
* @return bool false if variable name $varName is shorter than the minimal
* length and it isn't in the list of allowed short names nor declared in a
* for loop (in which it would be nested), otherwise true.
*/
protected function checkLength(File $phpcsFile, $stackPtr, $varName)
{
$minLength = 3;
$allowedShortName = array('ci');
$isLengthRight = true;
// cleans variable name
$varName = ltrim($varName, '_');
if (strlen($varName) <= $minLength) {
// skips adding an error, if it is a specific variable name
if (in_array($varName, $allowedShortName)) {
return $isLengthRight;
}
// skips adding an error, if the variable is in a for loop
if (false !== self::_isInForLoop($phpcsFile, $stackPtr, $varName)) {
return $isLengthRight;
}
// adds the error message finally
$error = 'Very short'
. (
$minLength > 0 ?
' (i.e. less than ' . ($minLength + 1) . ' chars)'
: ''
)
. ', non-word variables like "' . $varName
. '" should only be used as iterators in for() loops.';
$phpcsFile->addError($error, $stackPtr);
$isLengthRight = false;
}
return $isLengthRight;
}//end checkLength()
/**
* Returns the position of closest previous T_FOR, if token associated with
* $stackPtr in $phpcsFile is in a for loop, otherwise false.
*
* @param File $phpcsFile The current file being processed.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param string $varName The name of the variable to
* procced without $, { nor }.
*
* @return int|bool Position of T_FOR if token associated with $stackPtr in
* $phpcsFile is in the head of a for loop, otherwise false.
*/
private static function _isInForLoop(File $phpcsFile, $stackPtr, $varName)
{
$keepLookingFromPtr = $stackPtr;
while (false !== $keepLookingFromPtr) {
// looks if it is in (head or body) of a for loop
$forPtr = self::_isInForLoopHead($phpcsFile, $keepLookingFromPtr);
if (false === $forPtr) {
$forPtr = self::_isInForLoopBody($phpcsFile, $keepLookingFromPtr);
}
// checks if it is declared in here and prepares next step
if (false !== $forPtr) {
if (false !== self::_isDeclaredInForLoop($phpcsFile, $forPtr, $varName)) {
return $forPtr;
}
$keepLookingFromPtr = $forPtr;
} else {
$keepLookingFromPtr = false;
}
}
return false;
}//end _isInForLoop()
/**
* Returns the position of closest previous T_FOR, if token associated with
* $stackPtr in $phpcsFile is in the head of a for loop, otherwise false.
* The head is the code placed between parenthesis next to the key word
* 'for' : for (<loop_head>) {<loop_body>}.
*
* @param File $phpcsFile The current file being processed.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return int|bool Position of T_FOR if token associated with $stackPtr in
* $phpcsFile is in the head of a for loop, otherwise false.
*/
private static function _isInForLoopHead(File $phpcsFile, $stackPtr)
{
$isInForLoop = false;
$tokens = $phpcsFile->getTokens();
$currentTk = $tokens[$stackPtr];
if (array_key_exists('nested_parenthesis', $currentTk)) {
$nestedParenthesis = $currentTk['nested_parenthesis'];
foreach ( $nestedParenthesis as $openParPtr => $closeParPtr) {
$nonWhitspacePtr = $phpcsFile->findPrevious(
array(T_WHITESPACE),
$openParPtr - 1,
null,
true,
null,
true
);
if (false !== $nonWhitspacePtr) {
$isFor = T_FOR === $tokens[$nonWhitspacePtr]['code'];
if ($isFor) {
$isInForLoop = $nonWhitspacePtr;
break;
}
}
}
}
return $isInForLoop;
}//end _isInForLoopHead()
/**
* Returns the position of closest previous T_FOR, if token associated with
* $stackPtr in $phpcsFile is in the body of a for loop, otherwise false.
* The body are the instructions placed after parenthesis of a 'for'
* declaration, enclosed with curly brackets usually.
* 'for' : for (<loop_head>) {<loop_body>}.
*
* @param File $phpcsFile The current file being processed.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return int|bool Position of T_FOR if token associated with $stackPtr in
* $phpcsFile is in the body of a for loop, otherwise false.
*/
private static function _isInForLoopBody(File $phpcsFile, $stackPtr)
{
$isInForLoop = false;
$tokens = $phpcsFile->getTokens();
// get englobing hierarchy
$parentPtrAndCode = $tokens[$stackPtr]['conditions'];
krsort($parentPtrAndCode);
// looks for a for loop having a body not enclosed with curly brackets,
// which involves that its body contains only one instruction.
if (is_array($parentPtrAndCode) && ! empty($parentPtrAndCode)) {
$parentCode = reset($parentPtrAndCode);
$parentPtr = key($parentPtrAndCode);
$openBracketPtr = $tokens[$parentPtr]['scope_opener'];
} else {
$parentCode = 0;
$parentPtr = 0;
$openBracketPtr = 0;
}
$openResearchScopePtr = $stackPtr;
// recursive search, since a for statement may englobe other inline
// control statement or may be near to function calls, etc...
while (false !== $openResearchScopePtr) {
$closeParPtr = $phpcsFile->findPrevious(
array(T_CLOSE_PARENTHESIS),
$openResearchScopePtr,
null,
false,
null,
true
);
// is there a closing parenthesis with a control statement before
// the previous instruction ?
if (false !== $closeParPtr) {
// is there no opening curly bracket specific to
// set of instructions, between the closing parenthesis
// and the current token ?
if ($openBracketPtr < $closeParPtr) {
// starts the search from the token before the closing
// parenthesis, if it isn't a for statement
$openResearchScopePtr = $closeParPtr - 1;
// is this parenthesis associated with a for statement ?
$closeParenthesisTk = $tokens[$closeParPtr];
if (array_key_exists('parenthesis_owner', $closeParenthesisTk)) {
$mayBeForPtr = $closeParenthesisTk['parenthesis_owner'];
$mayBeForTk = $tokens[$mayBeForPtr];
if (T_FOR === $mayBeForTk['code']) {
return $mayBeForPtr;
}
}
} else {
// if it is about a for loop, don't go further
// and detect it after one more loop execution, do it now
if (T_FOR === $parentCode) {
return $parentPtr;
}
// starts the search from the token before the one
// englobing the current statement
$openResearchScopePtr = $parentPtr - 1;
// re-initialize variables about the englobing structure
if (is_array($parentPtrAndCode)) {
$parentCode = next($parentPtrAndCode);
$parentPtr = key($parentPtrAndCode);
$openBracketPtr = $tokens[$parentPtr]['scope_opener'];
}
}
} else {
$openResearchScopePtr = false;
}
}
// looks for a for loop having a body enclosed with curly brackets
foreach ($parentPtrAndCode as $parentPtr => $parentCode) {
if (T_FOR === $parentCode) {
return $parentPtr;
}
}
return false;
}//end _isInForLoopBody()
/**
* Returns true if a variable declared in the head of the for loop pointed
* by $forPtr in file $phpcsFile has the name $varName.
*
* @param File $phpcsFile The current file being processed.
* @param int $forPtr The position of the 'for' token
* in the stack passed in $tokens.
* @param string $varName The name of the variable to
* procced without $, { nor }.
*
* @return int|bool true if a variable declared in the head of the for loop
* pointed by $forPtr in file $phpcsFile has the name $varName.
*/
private static function _isDeclaredInForLoop(File $phpcsFile, $forPtr, $varName)
{
$isDeclaredInFor = false;
$tokens = $phpcsFile->getTokens();
$forVarPtrs = self::_getVarDeclaredInFor($phpcsFile, $forPtr);
foreach ($forVarPtrs as $forVarPtr) {
$forVarTk = $tokens[$forVarPtr];
// get variable name
$matches = array();
preg_match('/^\$\{?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}?/', $forVarTk['content'], $matches);
$forVarName = $matches[1];
if (0 === strcmp($forVarName, $varName)) {
$isDeclaredInFor = $forVarPtr;
break;
}
}
return $isDeclaredInFor;
}//end _isDeclaredInForLoop()
/**
* Returns list of pointers to variables declared in for loop associated to
* $forPtr in file $phpcsFile.
*
* All pointers in the result list are pointing to token with code
* T_VARIABLE. An exception is raised, if $forPtr doesn't point a token with
* code T_FOR.
*
* @param File $phpcsFile The current file being processed.
* @param int $forPtr The position of the current token
* in the stack passed in $tokens.
*
* @return array List of pointers to variables declared in for loop $forPtr.
*/
private static function _getVarDeclaredInFor(File $phpcsFile, $forPtr)
{
$tokens = $phpcsFile->getTokens();
$forTk = $tokens[$forPtr];
if (T_FOR !== $forTk['code']) {
throw new PHP_CodeSniffer_Exception('$forPtr must be of type T_FOR');
}
$openParPtr = $forTk['parenthesis_opener'];
$openParenthesisTk = $tokens[$openParPtr];
$endOfDeclPtr = $phpcsFile->findNext(array(T_SEMICOLON), $openParPtr);
$forVarPtrs = array();
$varPtr = $phpcsFile->findNext(
array(T_VARIABLE),
$openParPtr + 1,
$endOfDeclPtr
);
while (false !== $varPtr) {
$forVarPtrs [] = $varPtr;
$varPtr = $phpcsFile->findNext(
array(T_VARIABLE),
$varPtr + 1,
$endOfDeclPtr
);
}
return $forVarPtrs;
}//end _getVarDeclaredInFor()
/**
* Returns the position of first occurrence of a PHP variable starting with
* $ in $haystack from $offset.
*
* @param string $haystack The string to search in.
* @param int $offset The optional offset parameter allows you to
* specify which character in haystack to start
* searching. The returned position is still
* relative to the beginning of haystack.
*
* @return mixed The position as an integer
* or the boolean false, if no variable is found.
*/
private static function _getVariablePosition($haystack, $offset = 0)
{
$var_starts_at = strpos($haystack, '$', $offset);
$is_a_var = false;
while (false !== $var_starts_at && ! $is_a_var) {
// makes sure that $ is used for a variable and not as a symbol,
// if $ is protected with the escape char, then it is a symbol.
if (0 !== strcmp($haystack[$var_starts_at - 1], '\\')) {
if (0 === strcmp($haystack[$var_starts_at + 1], '{')) {
// there is an opening brace in the right place
// so it looks for the closing brace in the right place
$hsChunk2 = substr($haystack, $var_starts_at + 2);
if (1 === preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\}/', $hsChunk2)) {
$is_a_var = true;
}
} else {
$hsChunk1 = substr($haystack, $var_starts_at + 1);
if (1 === preg_match('/^[a-zA-Z_\x7f-\xff]/', $hsChunk1)) {
// $ is used for a variable and not as a symbol,
// since what follows $ matchs the definition of
// a variable label for PHP.
$is_a_var = true;
}
}
}
// update $var_starts_at for the next variable
// only if no variable was found, since it is returned otherwise.
if ( ! $is_a_var) {
$var_starts_at = strpos($haystack, '$', $var_starts_at + 1);
}
}
if ($is_a_var) {
return $var_starts_at;
} else {
return false;
}
}//end _getVariablePosition()
}//end class
?>

View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8" ?>
<ruleset name="CodeIgniter">
<description>CodeIgniter coding standard as described at http://codeigniter.com/user_guide/general/styleguide.html.</description>
<rule ref="Generic.Files.LineEndings">
<properties>
<property name="eolChar" value="\n"/>
</properties>
</rule>
<!-- PHP files should OMIT the closing PHP tag -->
<rule ref="Zend.Files.ClosingTag"/>
<!-- Always use full PHP opening tags -->
<rule ref="Generic.PHP.DisallowShortOpenTag"/>
<!-- Constants should always be fully uppercase -->
<rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
<!-- TRUE, FALSE, and NULL keywords should always be fully uppercase -->
<rule ref="Generic.PHP.UpperCaseConstant"/>
<!-- One statement per line -->
<rule ref="Generic.Formatting.DisallowMultipleStatements"/>
<!-- Classes and functions should be commented -->
<rule ref="PEAR.Commenting.ClassComment"/>
<rule ref="PEAR.Commenting.FunctionComment"/>
<rule ref="Squiz.Commenting.FunctionCommentThrowTag"/>
<!-- Use warnings for docblock comments for files and variables, since nothing is cleary explained -->
<rule ref="PEAR.Commenting.FileComment">
<properties>
<property name="error" value="false"/>
</properties>
</rule>
<rule ref="Squiz.Commenting.VariableComment">
<properties>
<property name="error" value="false"/>
</properties>
</rule>
<!-- Use Allman style indenting. With the exception of Class declarations,
braces are always placed on a line by themselves, and indented at the same level as the control statement that "owns" them. -->
<rule ref="Generic.Functions.OpeningFunctionBraceBsdAllman"/>
<rule ref="PEAR.WhiteSpace.ScopeClosingBrace"/>
<rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>
<!-- @todo Please see PHP_CodeSniffer_Standards_CodeIgniter_CodeIgniterCodingStandard for more details about what there is to do -->
</ruleset>

View File

@ -1,11 +0,0 @@
/**
* Hummingbird Anime Client
*
* An API client for Hummingbird to manage anime and manga watch lists
*
* @package HummingbirdAnimeClient
* @author Timothy J. Warren
* @copyright Copyright (c) 2015 - 2016
* @link https://github.com/timw4mail/HummingBirdAnimeClient
* @license MIT
*/

38
build/docker_install.sh Normal file
View File

@ -0,0 +1,38 @@
#!/bin/bash
# We need to install dependencies only for Docker
[[ ! -e /.dockerenv ]] && [[ ! -e /.dockerinit ]] && exit 0
# Where am I?
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
set -xe
# Install git (the php image doesn't have it) which is required by composer
apt-get update -yqq
apt-get install \
git \
unzip \
libfreetype6 \
libjpeg62-turbo \
libmcrypt4 \
libpng12-0 \
libfreetype6-dev \
libjpeg-dev \
libmcrypt-dev \
libpng12-dev \
libxslt1-dev \
libxslt1.1 \
zlib1g-dev \
-yqq
# Install phpunit, the tool that we will use for testing
curl -Lo /usr/local/bin/phpunit https://phar.phpunit.de/phpunit.phar
chmod +x /usr/local/bin/phpunit
# Install gd
docker-php-ext-configure gd --enable-gd-native-ttf --with-jpeg-dir=/usr/lib/x86_64-linux-gnu --with-png-dir=/usr/lib/x86_64-linux-gnu --with-freetype-dir=/usr/lib/x86_64-linux-gnu
docker-php-ext-install gd
docker-php-ext-install mcrypt
docker-php-ext-install xsl
docker-php-ext-install zip

15
build/header_comment.txt Normal file
View File

@ -0,0 +1,15 @@
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/

View File

@ -1,10 +0,0 @@
/**
* Ion
*
* Building blocks for web development
*
* @package Ion
* @author Timothy J. Warren
* @copyright Copyright (c) 2015 - 2016
* @license MIT
*/

84
build/phpcs.xml Normal file
View File

@ -0,0 +1,84 @@
<?xml version="1.0"?>
<ruleset name="Tim's Coding Standard">
<description>A variation of the CodeIgniter standard</description>
<file>../src/</file>
<encoding>utf-8</encoding>
<rule ref="Generic.Files.LineEndings">
<properties>
<property name="eolChar" value="\n"/>
</properties>
</rule>
<!-- PHP files should OMIT the closing PHP tag -->
<rule ref="Zend.Files.ClosingTag"/>
<!-- Always use full PHP opening tags -->
<rule ref="Generic.PHP.DisallowShortOpenTag"/>
<!-- Constants should always be fully uppercase -->
<rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
<!-- TRUE, FALSE, and NULL keywords should always be fully uppercase -->
<rule ref="Generic.PHP.UpperCaseConstant"/>
<!-- One statement per line -->
<rule ref="Generic.Formatting.DisallowMultipleStatements"/>
<!-- Classes and functions should be commented -->
<rule ref="PEAR.Commenting.ClassComment">
<exclude name="PEAR.Commenting.ClassComment.MissingCategoryTag" />
<exclude name="PEAR.Commenting.ClassComment.MissingPackageTag" />
<exclude name="PEAR.Commenting.ClassComment.MissingAuthorTag" />
<exclude name="PEAR.Commenting.ClassComment.MissingLicenseTag" />
<exclude name="PEAR.Commenting.ClassComment.MissingLinkTag" />
</rule>
<rule ref="PEAR.Commenting.FunctionComment">
<!-- Exclude this sniff because it doesn't understand multiple types -->
<exclude name="PEAR.Commenting.FunctionComment.MissingParamComment" />
<exclude name="PEAR.Commenting.FunctionComment.SpacingAfterParamType" />
<exclude name="PEAR.Commenting.FunctionComment.SpacingAfterParamName" />
</rule>
<!-- Use warnings for docblock comments for files and variables, since nothing is clearly explained -->
<rule ref="PEAR.Commenting.FileComment">
<exclude name="PEAR.Commenting.FileComment.InvalidVersion" />
<exclude name="PEAR.Commenting.FileComment.MissingCategoryTag" />
<properties>
<property name="error" value="false"/>
</properties>
</rule>
<rule ref="Squiz.Commenting.FunctionCommentThrowTag"/>
<rule ref="Squiz.Commenting.VariableComment">
<properties>
<property name="error" value="false"/>
</properties>
</rule>
<!-- Use Allman style indenting. With the exception of Class declarations,
braces are always placed on a line by themselves, and indented at the same level as the control statement that "owns" them. -->
<rule ref="Generic.Functions.OpeningFunctionBraceBsdAllman"/>
<rule ref="PEAR.WhiteSpace.ScopeClosingBrace">
<exclude name="PEAR.WhiteSpace.ScopeClosingBrace.BreakIndent" />
</rule>
<rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>
<!-- Use only short array syntax -->
<rule ref="Generic.Arrays.DisallowLongArraySyntax" />
<rule ref="Generic.PHP.ForbiddenFunctions">
<properties>
<property name="forbiddenFunctions" type="array" value="create_function=>null,eval=>null" />
</properties>
</rule>
<!-- Inherit CodeIgniter Rules -->
<rule ref="./CodeIgniter">
<properties>
<property name="error" value="false" />
</properties>
</rule>
</ruleset>

View File

@ -1,131 +1,128 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<!-- This is a skeleton phpDox config file - Check http://phpDox.de for latest version and more info --> <!-- This is a skeleton phpDox config file - Check http://phpDox.de for latest version and more info -->
<phpdox xmlns="http://xml.phpdox.net/config" silent="false"> <phpdox xmlns="http://xml.phpdox.net/config" silent="false">
<!-- @silent: true | false to enable or disable visual output of progress --> <!-- @silent: true | false to enable or disable visual output of progress -->
<!-- Additional bootstrap files to load for additional parsers, enrichers and/or engines --> <!-- Additional bootstrap files to load for additional parsers, enrichers and/or engines -->
<!-- Place as many require nodes as you feel like in this container --> <!-- Place as many require nodes as you feel like in this container -->
<!-- syntax: <require file="/path/to/file.php" /> --> <!-- syntax: <require file="/path/to/file.php" /> -->
<bootstrap /> <bootstrap />
<!-- A phpDox project to process, you can have multiple projects in one config file --> <!-- A phpDox project to process, you can have multiple projects in one config file -->
<project name="Hummingbird Anime Client" source="../src" workdir="phpdox/xml"> <project name="Hummingbird Anime Client" source="../src" workdir="phpdox/xml">
<!-- @name - The name of the project --> <!-- @name - The name of the project -->
<!-- @source - The source directory of the application to process --> <!-- @source - The source directory of the application to process -->
<!-- @workdir - The directory to store the xml data files in --> <!-- @workdir - The directory to store the xml data files in -->
<!-- A phpDox config file can define additional variables (properties) per project --> <!-- A phpDox config file can define additional variables (properties) per project -->
<!-- <property name="some.name" value="the.value" /> --> <!-- <property name="some.name" value="the.value" /> -->
<!-- Values can make use of previously defined properties --> <!-- Values can make use of previously defined properties -->
<!-- The following are defined by default: <!-- The following are defined by default:
${basedir} Directory the loaded config file is in ${basedir} Directory the loaded config file is in
${phpDox.home} Directory of the phpDox installation ${phpDox.home} Directory of the phpDox installation
${phpDox.file} The current config file ${phpDox.file} The current config file
${phpDox.version} phpDox' version number ${phpDox.version} phpDox' version number
${phpDox.project.name} The value of project/@name if set, otherwise 'unnamed' ${phpDox.project.name} The value of project/@name if set, otherwise 'unnamed'
${phpDox.project.source} The value of project/@source if set, otherwise '${basedir}/src' ${phpDox.project.source} The value of project/@source if set, otherwise '${basedir}/src'
${phpDox.project.workdir} The value of project/@workdir if set, otherwise '${basedir}/build/phpdox/xml' ${phpDox.project.workdir} The value of project/@workdir if set, otherwise '${basedir}/build/phpdox/xml'
${phpDox.php.version} The PHP Version of the interpreter in use ${phpDox.php.version} The PHP Version of the interpreter in use
--> -->
<!-- Additional configuration for the collecting process (parsing of php code, generation of xml data) --> <!-- Additional configuration for the collecting process (parsing of php code, generation of xml data) -->
<collector publiconly="false" backend="parser" encoding="auto"> <collector publiconly="false" backend="parser" encoding="auto">
<!-- @publiconly - Flag to disable/enable processing of non public methods and members --> <!-- @publiconly - Flag to disable/enable processing of non public methods and members -->
<!-- @backend - The collector backend to use, currently only shipping with 'parser' --> <!-- @backend - The collector backend to use, currently only shipping with 'parser' -->
<!-- @encoding - Charset encoding of source files (overwrite default 'auto' if detection fails) --> <!-- @encoding - Charset encoding of source files (overwrite default 'auto' if detection fails) -->
<!-- <include / exclude filter for filelist generator, mask must follow fnmatch() requirements --> <!-- <include / exclude filter for filelist generator, mask must follow fnmatch() requirements -->
<include mask="*.php" /> <include mask="*.php" />
<exclude mask="" /> <exclude mask="" />
<!-- How to handle inheritance --> <!-- How to handle inheritance -->
<inheritance resolve="true"> <inheritance resolve="true">
<!-- @resolve - Flag to enable/disable resolving of inheritance --> <!-- @resolve - Flag to enable/disable resolving of inheritance -->
<!-- You can define multiple (external) dependencies to be included --> <!-- You can define multiple (external) dependencies to be included -->
<!-- <dependency path="" --> <!-- <dependency path="" -->
<!-- @path - path to a directory containing an index.xml for a dependency project --> <!-- @path - path to a directory containing an index.xml for a dependency project -->
</inheritance> </inheritance>
</collector> </collector>
<!-- Configuration of generation process --> <!-- Configuration of generation process -->
<generator output="../docs"> <generator output="../docs">
<!-- @output - (Base-)Directory to store output data in --> <!-- @output - (Base-)Directory to store output data in -->
<!-- A generation process consists of one or more build tasks and of (optional) enrich sources --> <!-- A generation process consists of one or more build tasks and of (optional) enrich sources -->
<enrich base="logs"> <enrich base="logs">
<!-- @base - (Base-)Directory of datafiles used for enrich process --> <!-- @base - (Base-)Directory of datafiles used for enrich process -->
<!--<source type="...">--> <!--<source type="...">-->
<!-- @type - the handler for the enrichment --> <!-- @type - the handler for the enrichment -->
<!-- known types by default are: build, checkstyle, git, phpcs, phploc, phpunit, pmd --> <!-- known types by default are: build, checkstyle, git, phpcs, phploc, phpunit, pmd -->
<!-- every enrichment source can have additional configuration nodes, most probably need a logfile --> <!-- every enrichment source can have additional configuration nodes, most probably need a logfile -->
<!-- <file name="path/to/log.xml" /> --> <!-- <file name="path/to/log.xml" /> -->
<!--</source> --> <!--</source> -->
<!-- add phploc output --> <!-- add phploc output -->
<source type="phploc"> <source type="phploc">
<file name="phploc.xml" /> <file name="phploc.xml" />
</source> </source>
<!-- git vcs information --> <!-- git vcs information -->
<source type="git"> <source type="git">
<git binary="/usr/bin/git" /> <git binary="/usr/bin/git" />
<history enabled="true" limit="15" cache="${phpDox.project.workdir}/gitlog.xml" /> <history enabled="true" limit="15" cache="${phpDox.project.workdir}/gitlog.xml" />
</source> </source>
<!-- PHP Code Sniffer findings --> <!-- PHP Code Sniffer findings -->
<!-- <source type="checkstyle">
<source type="phpcs"> <file name="phpcs.xml" />
<file name="logs/phpcs.xml" /> </source>
</source>
-->
<!-- PHPMessDetector --> <!-- PHPMessDetector -->
<!-- <!--
<source type="pmd"> <source type="pmd">
<file name="pmd.xml" /> <file name="pmd.xml" />
</source> </source>
--> -->
<!-- PHPUnit Coverage XML --> <!-- PHPUnit Coverage XML -->
<source type="phpunit"> <source type="phpunit">
<!-- <coverage path="clover.xml" />--> <coverage path="coverage/clover.xml" />
<!-- @path - the directory where the xml code coverage report can be found --> <!-- <coverage path="clover.xml" />-->
<!--<filter directory="${phpDox.project.source}" />--> <!-- @path - the directory where the xml code coverage report can be found -->
<!-- @directory - path of the phpunit config whitelist filter directory --> <!--<filter directory="${phpDox.project.source}" />-->
</source> <!-- @directory - path of the phpunit config whitelist filter directory -->
<!-- </source>
<source type="phpunit"> <source type="phpunit">
<filter directory="${phpDox.project.source}" /> <filter directory="${phpDox.project.source}" />
</source> </source>
-->
</enrich> </enrich>
<!-- <build engine="..." enabled="true" output="..." /> --> <!-- <build engine="..." enabled="true" output="..." /> -->
<!-- @engine - The name of the engine this build task uses, use ./phpDox - -engines to get a list of available engines --> <!-- @engine - The name of the engine this build task uses, use ./phpDox - -engines to get a list of available engines -->
<!-- @enabled - Flag to enable/disable this engine, default: enabled=true --> <!-- @enabled - Flag to enable/disable this engine, default: enabled=true -->
<!-- @output - (optional) Output directory; if relative (no / as first char) it is interpreted as relative to generator/@output --> <!-- @output - (optional) Output directory; if relative (no / as first char) it is interpreted as relative to generator/@output -->
<!-- An engine and thus build node can have additional configuration child nodes, please check the documentation for the engine to find out more --> <!-- An engine and thus build node can have additional configuration child nodes, please check the documentation for the engine to find out more -->
<!-- default engine "html" --> <!-- default engine "html" -->
<build engine="html" enabled="true"> <build engine="html" enabled="true">
<template dir="${phpDox.home}/templates/html" /> <template dir="${phpDox.home}/templates/html" />
<file extension="html" /> <file extension="html" />
</build> </build>
</generator> </generator>
</project> </project>
</phpdox> </phpdox>

View File

@ -8,20 +8,16 @@
> >
<filter> <filter>
<whitelist> <whitelist>
<directory suffix=".php">../src/Aviat/Ion</directory> <directory suffix=".php">../src</directory>
<directory suffix=".php">../src/Aviat/AnimeClient</directory>
</whitelist> </whitelist>
</filter> </filter>
<testsuites> <testsuites>
<testsuite name="Ion">
<directory>../tests/Ion</directory>
</testsuite>
<testsuite name="AnimeClient"> <testsuite name="AnimeClient">
<directory>../tests/AnimeClient</directory> <directory>../tests</directory>
</testsuite> </testsuite>
</testsuites> </testsuites>
<logging> <logging>
<log type="coverage-html" target="coverage"/> <log type="coverage-html" target="../coverage"/>
<log type="coverage-clover" target="logs/clover.xml"/> <log type="coverage-clover" target="logs/clover.xml"/>
<log type="coverage-crap4j" target="logs/crap4j.xml"/> <log type="coverage-crap4j" target="logs/crap4j.xml"/>
<log type="coverage-xml" target="logs/coverage" /> <log type="coverage-xml" target="logs/coverage" />

View File

@ -1,14 +1,11 @@
<?php <?php
declare(strict_types=1);
$animeclient_file_patterns = [ $file_patterns = [
'app/config/*.php', 'app/bootstrap.php',
'app/booststrap.php', 'migrations/*.php',
'src/functions.php', 'src/**/*.php',
'src/Aviat/AnimeClient/*.php' 'tests/**/*.php',
];
$ion_file_patterns = [
'src/Aviat/Ion/*.php'
]; ];
if ( ! function_exists('glob_recursive')) if ( ! function_exists('glob_recursive'))
@ -30,21 +27,30 @@ if ( ! function_exists('glob_recursive'))
function get_text_to_replace($tokens) function get_text_to_replace($tokens)
{ {
if ($tokens[0][0] !== T_OPEN_TAG) $output = '';
// Tokens have the follow structure if arrays:
// [0] => token type constant
// [1] => raw sytax parsed to that token
// [2] => line number
foreach($tokens as $token)
{ {
return NULL; // Since we only care about opening docblocks,
// bail out when we get to the namespace token
if (is_array($token) && $token[0] === T_NAMESPACE)
{
break;
}
if (is_array($token))
{
$token = $token[1];
}
$output .= $token;
} }
// If there is already a docblock, as the second token after the return $output;
// open tag, get the contents of that token to replace
if ($tokens[1][0] === T_DOC_COMMENT)
{
return "<?php\n" . $tokens[1][1];
}
else if ($tokens[1][0] !== T_DOC_COMMENT)
{
return "<?php";
}
} }
function get_tokens($source) function get_tokens($source)
@ -57,33 +63,27 @@ function replace_files(array $files, $template)
foreach ($files as $file) foreach ($files as $file)
{ {
$source = file_get_contents($file); $source = file_get_contents($file);
if (stripos($source, 'namespace') === FALSE)
{
continue;
}
$tokens = get_tokens($source); $tokens = get_tokens($source);
$text_to_replace = get_text_to_replace($tokens); $text_to_replace = get_text_to_replace($tokens);
$header = file_get_contents(__DIR__ . $template); $header = file_get_contents(__DIR__ . $template);
$new_text = "<?php\n{$header}"; $new_text = "<?php declare(strict_types=1);\n{$header}";
$new_source = str_replace($text_to_replace, $new_text, $source); $new_source = str_replace($text_to_replace, $new_text, $source);
file_put_contents($file, $new_source); file_put_contents($file, $new_source);
} }
} }
foreach ($animeclient_file_patterns as $glob) foreach ($file_patterns as $glob)
{ {
$files = glob_recursive($glob); $files = glob_recursive($glob);
replace_files($files, '/animeclient_header_comment.txt'); replace_files($files, '/header_comment.txt');
}
$loose_files = [
__DIR__ . '/../index.php',
__DIR__ . '/../public/css.php',
__DIR__ . '/../public/js.php'
];
replace_files($loose_files, '/animeclient_header_comment.txt');
foreach ($ion_file_patterns as $glob)
{
$files = glob_recursive($glob);
replace_files($files, '/ion_header_comment.txt');
} }
echo "Successfully updated headers \n"; echo "Successfully updated headers \n";

View File

@ -2,25 +2,48 @@
"name": "timw4mail/hummingbird-anime-client", "name": "timw4mail/hummingbird-anime-client",
"description": "A self-hosted anime/manga client for hummingbird.", "description": "A self-hosted anime/manga client for hummingbird.",
"license":"MIT", "license":"MIT",
"autoload": {
"psr-4": {
"Aviat\\AnimeClient\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Aviat\\AnimeClient\\Tests\\": "tests/",
"CodeIgniter\\": "build/CodeIgniter/"
}
},
"require": { "require": {
"abeautifulsite/simpleimage": "2.5.*", "abeautifulsite/simpleimage": "2.5.*",
"aura/html": "2.*", "aura/html": "2.*",
"aura/router": "3.*", "aura/router": "3.*",
"aura/session": "2.*", "aura/session": "2.*",
"aviat4ion/query": "2.5.*", "aviat/banker": "dev-master",
"container-interop/container-interop": "1.*", "aviat/ion": "1.0.*",
"danielstjules/stringy": "~2.1",
"filp/whoops": "2.0.*", "filp/whoops": "2.0.*",
"guzzlehttp/guzzle": "6.*", "guzzlehttp/guzzle": "6.*",
"monolog/monolog": "1.*", "monolog/monolog": "1.*",
"psr/http-message": "~1.0", "psr/http-message": "~1.0",
"psr/log": "~1.0", "psr/log": "~1.0",
"robmorgan/phinx": "0.4.*",
"yosymfony/toml": "0.3.*", "yosymfony/toml": "0.3.*",
"zendframework/zend-diactoros": "1.3.*", "zendframework/zend-diactoros": "1.3.*",
"maximebf/consolekit": "^1.0" "maximebf/consolekit": "^1.0"
}, },
"require-dev": { "require-dev": {
"codeclimate/php-test-reporter": "dev-master" "pdepend/pdepend": "^2.2",
"sebastian/phpcpd": "^2.0",
"theseer/phpdox": "0.8.1.1",
"phploc/phploc": "^3.0",
"phpmd/phpmd": "^2.4",
"phpunit/phpunit": "^5.4",
"robmorgan/phinx": "^0.6.4",
"humbug/humbug": "~1.0@dev",
"consolidation/robo": "~1.0@RC",
"henrikbjorn/lurker": "^1.1.0",
"symfony/var-dumper": "^3.1",
"squizlabs/php_codesniffer": "^3.0.0@beta"
},
"scripts": {
"build:css": "cd public && npm run build && cd .."
} }
} }

20
console
View File

@ -1,6 +1,5 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php declare(strict_types=1);
use Aviat\AnimeClient\Model;
if ( ! function_exists('_dir')) if ( ! function_exists('_dir'))
{ {
@ -23,23 +22,6 @@ $APP_DIR = __DIR__ . '/app/';
$SRC_DIR = __DIR__ . '/src/'; $SRC_DIR = __DIR__ . '/src/';
$CONF_DIR = realpath("${APP_DIR}/config/"); $CONF_DIR = realpath("${APP_DIR}/config/");
/**
* Set up autoloaders
*
* @codeCoverageIgnore
* @return void
*/
spl_autoload_register(function($class) use ($SRC_DIR) {
$class_parts = explode('\\', $class);
$ns_path = $SRC_DIR . '/' . implode('/', $class_parts) . ".php";
if (file_exists($ns_path))
{
require_once($ns_path);
return;
}
});
// Set up autoloader for third-party dependencies // Set up autoloader for third-party dependencies
require_once realpath(__DIR__ . '/vendor/autoload.php'); require_once realpath(__DIR__ . '/vendor/autoload.php');

12
humbug.json.dist Normal file
View File

@ -0,0 +1,12 @@
{
"source": {
"directories": [
"src"
]
},
"timeout": 10,
"logs": {
"text": "build\/humbuglog.txt",
"json": "build\/humbug.json"
}
}

View File

@ -4,15 +4,20 @@
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* PHP version 5.6
*
* @package HummingbirdAnimeClient * @package HummingbirdAnimeClient
* @author Timothy J. Warren * @author Timothy J. Warren <tim@timshomepage.net>
* @copyright Copyright (c) 2015 - 2016 * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @link https://github.com/timw4mail/HummingBirdAnimeClient
* @license MIT
*/ */
namespace Aviat\AnimeClient;
use Aviat\AnimeClient\AnimeClient; use Aviat\AnimeClient\AnimeClient;
use Whoops\Handler\PrettyPageHandler; use Whoops\Handler\PrettyPageHandler;
use Whoops\Handler\JsonResponseHandler; use Whoops\Run;
// Work around the silly timezone error // Work around the silly timezone error
$timezone = ini_get('date.timezone'); $timezone = ini_get('date.timezone');
@ -34,44 +39,25 @@ function _dir()
// Define base directories // Define base directories
$APP_DIR = _dir(__DIR__, 'app'); $APP_DIR = _dir(__DIR__, 'app');
$SRC_DIR = _dir(__DIR__, 'src');
$CONF_DIR = _dir($APP_DIR, 'config'); $CONF_DIR = _dir($APP_DIR, 'config');
/** // Load composer autoloader
* Set up autoloaders
*
* @codeCoverageIgnore
* @return void
*/
spl_autoload_register(function($class) use ($SRC_DIR) {
$class_parts = explode('\\', $class);
$ns_path = $SRC_DIR . '/' . implode('/', $class_parts) . ".php";
if (file_exists($ns_path))
{
require_once($ns_path);
return;
}
});
// Set up autoloader for third-party dependencies
require _dir(__DIR__, '/vendor/autoload.php'); require _dir(__DIR__, '/vendor/autoload.php');
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Setup error handling // Setup error handling
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
$whoops = new \Whoops\Run(); $whoops = new Run();
// Set up default handler for general errors // Set up default handler for general errors
$defaultHandler = new PrettyPageHandler(); $defaultHandler = new PrettyPageHandler();
$whoops->pushHandler($defaultHandler); $whoops->pushHandler($defaultHandler);
// Set up json handler for ajax errors
//$jsonHandler = new JsonResponseHandler();
//$whoops->pushHandler($jsonHandler);
// Register as the error handler // Register as the error handler
$whoops->register(); if (array_key_exists('whoops', $_GET))
{
$whoops->register();
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Dependency Injection setup // Dependency Injection setup
@ -79,14 +65,13 @@ $whoops->register();
require _dir($CONF_DIR, 'base_config.php'); // $base_config require _dir($CONF_DIR, 'base_config.php'); // $base_config
$di = require _dir($APP_DIR, 'bootstrap.php'); $di = require _dir($APP_DIR, 'bootstrap.php');
$config = AnimeClient::load_toml($CONF_DIR); $config = AnimeClient::loadToml($CONF_DIR);
$config_array = array_merge($base_config, $config); $config_array = array_merge($base_config, $config);
$container = $di($config_array); $container = $di($config_array);
// Unset 'constants' // Unset 'constants'
unset($APP_DIR); unset($APP_DIR);
unset($SRC_DIR);
unset($CONF_DIR); unset($CONF_DIR);
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------

View File

@ -1,4 +1,4 @@
<?php <?php declare(strict_types=1);
use Phinx\Migration\AbstractMigration; use Phinx\Migration\AbstractMigration;

View File

@ -2,15 +2,17 @@
<phpdoc> <phpdoc>
<title>Hummingbird Anime Client</title> <title>Hummingbird Anime Client</title>
<parser> <parser>
<target>docs</target> <target>phpdoc</target>
</parser> </parser>
<transformer> <transformer>
<target>docs</target> <target>phpdoc</target>
</transformer> </transformer>
<transformations> <transformations>
<template name="clean" /> <template name="zend" />
</transformations> </transformations>
<files> <files>
<directory>src/Aviat</directory> <directory>src</directory>
<directory>vendor/aviat/ion/src</directory>
<directory>vendor/container-interop/container-interop/src</directory>
</files> </files>
</phpdoc> </phpdoc>

25
phpunit.xml Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
colors="true"
stopOnFailure="false"
bootstrap="tests/bootstrap.php"
beStrictAboutTestsThatDoNotTestAnything="true"
>
<filter>
<whitelist>
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<testsuites>
<testsuite name="AnimeClient">
<directory>tests</directory>
</testsuite>
</testsuites>
<php>
<server name="HTTP_USER_AGENT" value="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0" />
<server name="HTTP_HOST" value="localhost" />
<server name="SERVER_NAME" value="localhost" />
<server name="REQUEST_URI" value="/" />
<server name="REQUEST_METHOD" value="GET" />
</php>
</phpunit>

View File

@ -1,14 +1,17 @@
<?php <?php declare(strict_types=1);
/** /**
* Hummingbird Anime Client * Hummingbird Anime Client
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* @package HummingbirdAnimeClient * PHP version 7
* @author Timothy J. Warren *
* @copyright Copyright (c) 2015 - 2016 * @package HummingbirdAnimeClient
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @author Timothy J. Warren <tim@timshomepage.net>
* @license MIT * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/ */
namespace Aviat\EasyMin; namespace Aviat\EasyMin;

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,5 @@
@import "./marx.myth.css";
:root { :root {
--link-shadow: 1px 1px 1px #000; --link-shadow: 1px 1px 1px #000;
--shadow: 1px 2px 1px rgba(0, 0, 0, 0.85); --shadow: 1px 2px 1px rgba(0, 0, 0, 0.85);
@ -296,7 +298,7 @@ a:hover, a:active {
display:inline-block; display:inline-block;
text-align:center; text-align:center;
width:220px; width:220px;
height:319px; height:311px;
margin: var(--normal-padding); margin: var(--normal-padding);
} }
@ -352,7 +354,9 @@ a:hover, a:active {
display:block; display:block;
} }
.media > .name > a { .media > .name a,
.media > .name a small
{
background:none; background:none;
color:#fff; color:#fff;
text-shadow: var(--shadow); text-shadow: var(--shadow);
@ -427,8 +431,7 @@ a:hover, a:active {
.manga .media { .manga .media {
border:1px solid #ddd; border:1px solid #ddd;
width:200px; height:310px;
height:290px;
margin:0.25em; margin:0.25em;
} }
@ -436,8 +439,8 @@ a:hover, a:active {
position:absolute; position:absolute;
top: 86px; top: 86px;
top: calc(50% - 58.5px); top: calc(50% - 58.5px);
left: 5px; left: 43.5px;
left: calc(50% - 95px); left: calc(50% - 66.5px);
} }
@ -481,9 +484,14 @@ a:hover, a:active {
position:absolute; position:absolute;
display:block; display:block;
top:0; top:0;
left:0;
height:100%; height:100%;
width:100%; width:100%;
vertical-align:middle; vertical-align:middle;
line-height: 1.25em;
}
#series_list .name small {
color: #fff;
} }
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------

View File

@ -1,629 +0,0 @@
:root {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
box-sizing: border-box;
cursor: default;
font-family: 'Open Sans', 'Nimbus Sans L', 'Helvetica Neue', Helvetica, 'Lucida Grande', sans-serif;
line-height: 1.4;
overflow-y: scroll;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
text-size-adjust: 100%;
}
audio:not([controls]) {
display: none;
}
details {
display: block;
}
input[type=search] {
-webkit-appearance: textfield;
}
input[type=search]::-webkit-search-cancel-button,
input[type=search]::-webkit-search-decoration {
-webkit-appearance: none;
}
main {
display: block;
margin: 0 auto;
padding: 0 1.6em 1.6em;
padding: 0 1.6rem 1.6rem;
}
summary {
display: block;
}
pre {
background: #efefef;
color: #444;
display: block;
font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;
font-size: 1.4em;
font-size: 1.4rem;
margin: 1.6em 0;
margin: 1.6rem 0;
overflow: auto;
padding: 1.6em;
padding: 1.6rem;
word-break: break-all;
word-wrap: break-word;
}
progress {
display: inline-block;
}
small {
color: #777;
font-size: 75%;
}
big {
font-size: 125%;
}
template {
display: none;
}
textarea {
border: .1rem solid #ccc;
border-radius: 0;
display: block;
margin-bottom: .8rem;
overflow: auto;
padding: .8rem;
resize: vertical;
vertical-align: middle;
}
[hidden] {
display: none;
}
[unselectable] {
-moz-user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
user-select: none;
}
*,
::before,
::after {
border-style: solid;
border-width: 0;
box-sizing: inherit;
}
* {
font-size: inherit;
line-height: inherit;
margin: 0;
padding: 0;
}
::before,
::after {
text-decoration: inherit;
vertical-align: inherit;
}
a {
-webkit-transition: .25s ease;
color: #1271db;
text-decoration: none;
-webkit-transition: .25s ease;
transition: .25s ease;
}
audio,
canvas,
iframe,
img,
svg,
video {
vertical-align: middle;
}
button,
input,
select,
textarea {
border: .1rem solid #ccc;
color: inherit;
font-family: inherit;
font-style: inherit;
font-weight: inherit;
min-height: 1.4em;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, 'Courier New', monospace, monospace;
}
table {
border-collapse: collapse;
border-spacing: 0;
margin-bottom: 1.6rem;
}
::-moz-selection {
background-color: #b3d4fc;
text-shadow: none;
}
::selection {
background-color: #b3d4fc;
text-shadow: none;
}
button::-moz-focus-inner {
border: 0;
}
body {
color: #444;
font-family: 'Open Sans', 'Nimbus Sans L', 'Helvetica Neue', Helvetica, 'Lucida Grande', sans-serif;
font-size: 1.6rem;
font-style: normal;
font-weight: 400;
padding: 0;
}
p {
margin: 0 0 1.6rem;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: Lato, 'Open Sans', 'Nimbus Sans L', 'Helvetica Neue', Helvetica, 'Lucida Grande', sans-serif;
margin: 2em 0 1.6em;
margin: 2rem 0 1.6rem;
}
h1 {
border-bottom: .1rem solid rgba(0,0,0,0.2);
font-size: 3.6em;
font-size: 3.6rem;
font-style: normal;
font-weight: 500;
}
h2 {
font-size: 3em;
font-size: 3rem;
font-style: normal;
font-weight: 500;
}
h3 {
font-size: 2.4em;
font-size: 2.4rem;
font-style: normal;
font-weight: 500;
margin: 1.6rem 0 .4rem;
}
h4 {
font-size: 1.8em;
font-size: 1.8rem;
font-style: normal;
font-weight: 600;
margin: 1.6rem 0 .4rem;
}
h5 {
font-size: 1.6em;
font-size: 1.6rem;
font-style: normal;
font-weight: 600;
margin: 1.6rem 0 .4rem;
}
h6 {
color: #777;
font-size: 1.4em;
font-size: 1.4rem;
font-style: normal;
font-weight: 600;
margin: 1.6rem 0 .4rem;
}
code {
background: #efefef;
color: #444;
font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;
font-size: 1.4rem;
word-break: break-all;
word-wrap: break-word;
}
a:hover,
a:focus {
text-decoration: none;
}
dl {
margin-bottom: 1.6rem;
}
dd {
margin-left: 4rem;
}
ul,
ol {
margin-bottom: .8rem;
padding-left: 2rem;
}
blockquote {
border-left: .2rem solid #1271db;
font-family: Georgia, Times, 'Times New Roman', serif;
font-style: italic;
margin: 1.6rem 0;
padding-left: 1.6rem;
}
figcaption {
font-family: Georgia, Times, 'Times New Roman', serif;
}
html {
font-size: 62.5%;
}
main,
header,
footer,
article,
section,
aside,
details,
summary {
display: block;
height: auto;
margin: 0 auto;
width: 100%;
}
footer {
border-top: .1rem solid rgba(0,0,0,0.2);
clear: both;
display: inline-block;
float: left;
max-width: 100%;
padding: 1rem 0;
text-align: center;
}
hr {
border-top: .1rem solid rgba(0,0,0,0.2);
display: block;
margin-bottom: 1.6rem;
width: 100%;
}
img {
height: auto;
max-width: 100%;
vertical-align: baseline;
}
input[type=text],
input[type=password],
input[type=email],
input[type=url],
input[type=date],
input[type=month],
input[type=time],
input[type=datetime],
input[type=datetime-local],
input[type=week],
input[type=number],
input[type=search],
input[type=tel],
input[type=color],
select {
border: .1rem solid #ccc;
border-radius: 0;
display: inline-block;
padding: .8rem;
vertical-align: middle;
}
input:not([type]) {
-webkit-appearance: none;
background-clip: padding-box;
background-color: #fff;
border: .1rem solid #ccc;
border-radius: 0;
color: #444;
display: inline-block;
padding: .8rem;
text-align: left;
}
input[type=color] {
padding: .8rem 1.6rem;
}
input[type=text]:focus,
input[type=password]:focus,
input[type=email]:focus,
input[type=url]:focus,
input[type=date]:focus,
input[type=month]:focus,
input[type=time]:focus,
input[type=datetime]:focus,
input[type=datetime-local]:focus,
input[type=week]:focus,
input[type=number]:focus,
input[type=search]:focus,
input[type=tel]:focus,
input[type=color]:focus,
select:focus,
textarea:focus {
border-color: #b3d4fc;
}
input:not([type]):focus {
border-color: #b3d4fc;
}
input[type=radio],
input[type=checkbox] {
vertical-align: middle;
}
input[type=file]:focus,
input[type=radio]:focus,
input[type=checkbox]:focus {
outline: .1rem solid thin #444;
}
input[type=text][disabled],
input[type=password][disabled],
input[type=email][disabled],
input[type=url][disabled],
input[type=date][disabled],
input[type=month][disabled],
input[type=time][disabled],
input[type=datetime][disabled],
input[type=datetime-local][disabled],
input[type=week][disabled],
input[type=number][disabled],
input[type=search][disabled],
input[type=tel][disabled],
input[type=color][disabled],
select[disabled],
textarea[disabled] {
background-color: #efefef;
color: #777;
cursor: not-allowed;
}
input:not([type])[disabled] {
background-color: #efefef;
color: #777;
cursor: not-allowed;
}
input[readonly],
select[readonly],
textarea[readonly] {
background-color: #efefef;
border-color: #ccc;
color: #777;
}
input:focus:invalid,
textarea:focus:invalid,
select:focus:invalid {
border-color: #e9322d;
color: #b94a48;
}
input[type=file]:focus:invalid:focus,
input[type=radio]:focus:invalid:focus,
input[type=checkbox]:focus:invalid:focus {
outline-color: #ff4136;
}
select {
background-color: #fff;
border: .1rem solid #ccc;
}
select[multiple] {
height: auto;
}
label {
line-height: 2;
}
fieldset {
border: 0;
margin: 0;
padding: .8rem 0;
}
legend {
border-bottom: .1rem solid #ccc;
color: #444;
display: block;
margin-bottom: .8rem;
padding: .8rem 0;
width: 100%;
}
input[type=submit],
button {
-moz-user-select: none;
-ms-user-select: none;
-webkit-transition: .25s ease;
-webkit-user-drag: none;
-webkit-user-select: none;
border: .2rem solid #444;
border-radius: 0;
color: #444;
cursor: pointer;
display: inline-block;
margin-bottom: .8rem;
margin-right: .4rem;
padding: .8rem 1.6rem;
text-align: center;
text-decoration: none;
text-transform: uppercase;
-webkit-transition: .25s ease;
transition: .25s ease;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
vertical-align: baseline;
}
input[type=submit] a,
button a {
color: #444;
}
input[type=submit]::-moz-focus-inner,
button::-moz-focus-inner {
padding: 0;
}
input[type=submit]:hover,
button:hover {
background: #444;
border-color: #444;
color: #fff;
}
input[type=submit]:hover a,
button:hover a {
color: #fff;
}
input[type=submit]:active,
button:active {
background: #6a6a6a;
border-color: #6a6a6a;
color: #fff;
}
input[type=submit]:active a,
button:active a {
color: #fff;
}
input[type=submit]:disabled,
button:disabled {
box-shadow: none;
cursor: not-allowed;
opacity: .40;
}
nav ul {
list-style: none;
margin: 0;
padding: 0;
text-align: center;
}
nav ul li {
display: inline;
}
nav a {
-webkit-transition: .25s ease;
border-bottom: .2rem solid transparent;
color: #444;
padding: .8rem 1.6rem;
text-decoration: none;
-webkit-transition: .25s ease;
transition: .25s ease;
}
nav a:hover,
nav li.selected a {
border-color: rgba(0,0,0,0.2);
}
nav a:active {
border-color: rgba(0,0,0,0.56);
}
caption {
padding: .8rem 0;
}
thead th {
background: #efefef;
color: #444;
}
tr {
background: #fff;
margin-bottom: .8rem;
}
th,
td {
border: .1rem solid #ccc;
padding: .8rem 1.6rem;
text-align: center;
vertical-align: inherit;
}
tfoot tr {
background: none;
}
tfoot td {
color: #efefef;
font-size: .8rem;
font-style: italic;
padding: 1.6rem .4rem;
}
@media screen {
[hidden~=screen] {
display: inherit;
}
[hidden~=screen]:not(:active):not(:focus):not(:target) {
clip: rect(0000)!important;
position: absolute!important;
}
}
@media screen and max-width 40rem {
article,
section,
aside {
clear: both;
display: block;
max-width: 100%;
}
img {
margin-right: 1.6rem;
}
}

View File

@ -1,14 +1,17 @@
<?php <?php declare(strict_types=1);
/** /**
* Hummingbird Anime Client * Hummingbird Anime Client
* *
* An API client for Hummingbird to manage anime and manga watch lists * An API client for Hummingbird to manage anime and manga watch lists
* *
* @package HummingbirdAnimeClient * PHP version 7
* @author Timothy J. Warren *
* @copyright Copyright (c) 2015 - 2016 * @package HummingbirdAnimeClient
* @link https://github.com/timw4mail/HummingBirdAnimeClient * @author Timothy J. Warren <tim@timshomepage.net>
* @license MIT * @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 3.1
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/ */
namespace Aviat\EasyMin; namespace Aviat\EasyMin;
@ -115,7 +118,7 @@ class JSMin extends BaseMin {
protected function check_minify_errors($options) protected function check_minify_errors($options)
{ {
$error_res = $this->closure_call($options); $error_res = $this->closure_call($options);
$error_json = $error_res->getBody(); $error_json = (string)$error_res->getBody();
$error_obj = json_decode($error_json) ?: (object)[]; $error_obj = json_decode($error_json) ?: (object)[];
// Show error if exists // Show error if exists
@ -198,7 +201,7 @@ class JSMin extends BaseMin {
// Now actually retrieve the compiled code // Now actually retrieve the compiled code
$options['output_info'] = 'compiled_code'; $options['output_info'] = 'compiled_code';
$res = $this->closure_call($options); $res = $this->closure_call($options);
$json = $res->getBody(); $json = (string)$res->getBody();
$obj = json_decode($json); $obj = json_decode($json);
return $obj->compiledCode; return $obj->compiledCode;

2
public/js/anime_collection.js Executable file → Normal file
View File

@ -10,7 +10,7 @@
// Give mustache a key to iterate over // Give mustache a key to iterate over
searchResults = { searchResults = {
anime: searchResults data: searchResults.data
}; };
Mustache.parse(tempHtml); Mustache.parse(tempHtml);

18
public/js/anime_edit.js Executable file → Normal file
View File

@ -6,7 +6,7 @@
'use strict'; 'use strict';
// Action to increment episode count // Action to increment episode count
_.on('body.anime.list', 'click', '.plus_one', function(e) { _.on('body.anime.list', 'click', '.plus_one', function() {
let parent_sel = _.closestParent(this, 'article'); let parent_sel = _.closestParent(this, 'article');
let watched_count = parseInt(_.$('.completed_number', parent_sel)[0].textContent, 10); let watched_count = parseInt(_.$('.completed_number', parent_sel)[0].textContent, 10);
let total_count = parseInt(_.$('.total_number', parent_sel)[0].textContent, 10); let total_count = parseInt(_.$('.total_number', parent_sel)[0].textContent, 10);
@ -15,19 +15,20 @@
// Setup the update data // Setup the update data
let data = { let data = {
id: parent_sel.id, id: parent_sel.id,
increment_episodes: true data: {
progress: watched_count + 1
}
}; };
// If the episode count is 0, and incremented, // If the episode count is 0, and incremented,
// change status to currently watching // change status to currently watching
if (isNaN(watched_count) || watched_count === 0) { if (isNaN(watched_count) || watched_count === 0) {
data.status = 'currently-watching'; data.data.status = 'current';
} }
// If you increment at the last episode, mark as completed // If you increment at the last episode, mark as completed
if (( ! isNaN(watched_count)) && (watched_count + 1) == total_count) { if (( ! isNaN(watched_count)) && (watched_count + 1) == total_count) {
delete data.increment_episodes; data.data.status = 'completed';
data.status = 'completed';
} }
// okay, lets actually make some changes! // okay, lets actually make some changes!
@ -35,9 +36,8 @@
data: data, data: data,
dataType: 'json', dataType: 'json',
type: 'POST', type: 'POST',
mimeType: 'application/json', success: () => {
success: (res) => { if (data.data.status == 'completed') {
if (data.status == 'completed') {
_.hide(parent_sel); _.hide(parent_sel);
} }
@ -47,7 +47,7 @@
}, },
error: (xhr, errorType, error) => { error: (xhr, errorType, error) => {
console.error(error); console.error(error);
_.showMessage('error', `Failed to updated ${title}. `); _.showMessage('error', `Failed to update ${title}. `);
_.scrollToTop(); _.scrollToTop();
} }
}); });

View File

@ -235,7 +235,7 @@ var AnimeClient = (function(w) {
* data: // data to send with the request * data: // data to send with the request
* type: // http verb of the request, defaults to GET * type: // http verb of the request, defaults to GET
* success: // success callback * success: // success callback
* error: // error callback * error: // error callback
* } * }
* *
* @param {string} url - the url to request * @param {string} url - the url to request
@ -249,6 +249,7 @@ var AnimeClient = (function(w) {
config.type = config.type || 'GET'; config.type = config.type || 'GET';
config.dataType = config.dataType || ''; config.dataType = config.dataType || '';
config.success = config.success || _.noop; config.success = config.success || _.noop;
config.mimeType = config.mimeType || 'application/x-www-form-urlencoded';
config.error = config.error || _.noop; config.error = config.error || _.noop;
let request = new XMLHttpRequest(); let request = new XMLHttpRequest();
@ -280,14 +281,22 @@ var AnimeClient = (function(w) {
} }
}; };
if (config.dataType === 'json') {
config.data = JSON.stringify(config.data);
config.mimeType = 'application/json';
} else {
config.data = ajaxSerialize(config.data);
}
request.setRequestHeader('Content-Type', config.mimeType);
switch (method) { switch (method) {
case "GET": case "GET":
request.send(null); request.send(null);
break; break;
default: default:
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send(config.data);
request.send(ajaxSerialize(config.data));
break; break;
} }
}; };

View File

@ -21,7 +21,7 @@
}); });
// Clear the api cache // Clear the api cache
ac.on('.js-clear-cache', 'click', function (event) { ac.on('.js-clear-cache', 'click', function () {
ac.get('/cache_purge', () => { ac.get('/cache_purge', () => {
ac.showMessage('success', `Sucessfully purged api cache`); ac.showMessage('success', `Sucessfully purged api cache`);
}); });

27
public/js/manga_edit.js Executable file → Normal file
View File

@ -5,7 +5,7 @@
'use strict'; 'use strict';
_.on('.manga.list', 'click', '.edit_buttons button', function(e) { _.on('.manga.list', 'click', '.edit_buttons button', function() {
let this_sel = this; let this_sel = this;
let parent_sel = _.closestParent(this, 'article'); let parent_sel = _.closestParent(this, 'article');
let manga_id = parent_sel.id.replace("manga-", ""); let manga_id = parent_sel.id.replace("manga-", "");
@ -18,19 +18,38 @@
completed = 0; completed = 0;
} }
// Setup the update data
let data = { let data = {
id: manga_id id: manga_id,
data: {
progress: completed
}
}; };
// If the episode count is 0, and incremented,
// change status to currently reading
if (isNaN(completed) || completed === 0) {
data.data.status = 'current';
}
// If you increment at the last chapter, mark as completed
if (( ! isNaN(completed)) && (completed + 1) == total) {
data.data.status = 'completed';
}
// Update the total count // Update the total count
data[type + "s_read"] = ++completed; data.data.progress = ++completed;
_.ajax(_.url('/manga/update'), { _.ajax(_.url('/manga/update'), {
data: data, data: data,
dataType: 'json', dataType: 'json',
type: 'POST', type: 'POST',
mimeType: 'application/json', mimeType: 'application/json',
success: (res) => { success: () => {
if (data.data.status == 'completed') {
_.hide(parent_sel);
}
_.$(`.${type}s_read`, parent_sel)[0].textContent = completed; _.$(`.${type}s_read`, parent_sel)[0].textContent = completed;
_.showMessage('success', `Sucessfully updated ${manga_name}`); _.showMessage('success', `Sucessfully updated ${manga_name}`);
_.scrollToTop(); _.scrollToTop();

View File

@ -1,11 +1,14 @@
{ {
"scripts": { "scripts": {
"watch": "npm-run-all --parallel watch:base watch:marx", "build": "postcss -u postcss-import --autoprefixer.browsers \"> 5%\" -u postcss-cssnext -o css/base.css css/base.myth.css",
"watch:base": "myth -w css/base.myth.css css/base.css", "watch": "postcss -u postcss-import --autoprefixer.browsers \"> 5%\" -u postcss-cssnext -w -o css/base.css css/base.myth.css"
"watch:marx": "myth -w css/marx.myth.css css/marx.css" },
}, "devDependencies": {
"devDependencies": { "autoprefixer": "^6.6.1",
"myth": "^1.5.0", "npm-run-all": "^4.0.0",
"npm-run-all": "^1.7.0" "postcss-cachify": "^1.3.1",
} "postcss-cli": "^2.6.0",
} "postcss-cssnext": "^2.9.0",
"postcss-import": "^9.0.0"
}
}

View File

@ -1,10 +1,18 @@
{{#anime}} {{#data}}
<article class="media search"> <article class="media search">
<div class="name" style="background-image:url({{cover_image}})"> <div class="name" style="background-image:url({{attributes.posterImage.small}})">
<input type="radio" class="big-check" id="{{slug}}" name="id" value="{{id}}" /> <input type="radio" class="big-check" id="{{attributes.slug}}" name="id" value="{{id}}" />
<label for="{{slug}}"> <label for="{{attributes.slug}}">
<span>{{title}}<br />{{alternate_title}}</span> <span class="name">
{{attributes.canonicalTitle}}
<br />
<small>
{{#attributes.titles}}
{{.}}<br />
{{/attributes.titles}}
</small>
</span>
</label> </label>
</div> </div>
</article> </article>
{{/anime}} {{/data}}

View File

@ -1,10 +1,18 @@
{{#search}} {{#data}}
<article class="media search"> <article class="media search">
<div class="name" style="background-image:url({{image}})"> <div class="name" style="background-image:url({{attributes.posterImage.small}})">
<input type="radio" class="big-check" id="{{link}}" name="id" value="{{link}}" /> <input type="radio" class="big-check" id="{{attributes.slug}}" name="id" value="{{id}}" />
<label for="{{link}}"> <label for="{{attributes.slug}}">
<span>{{title}}</span> <span class="name">
{{attributes.canonicalTitle}}
<br />
<small>
{{#attributes.titles}}
{{.}}<br />
{{/attributes.titles}}
</small>
</span>
</label> </label>
</div> </div>
</article> </article>
{{/search}} {{/data}}

View File

@ -1,6 +0,0 @@
sonar.projectKey=animeclient
sonar.projectName=Anime Client
sonar.projectVersion=3.0.0
sonar.sources=src
sonar.php.coverage.reportPath=build/logs/clover.xml
sonar.php.tests.reportPath=build/logs/junit.xml

View File

@ -0,0 +1,21 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API;
abstract class AbstractListItem implements ListItemInterface {
}

41
src/API/GuzzleTrait.php Normal file
View File

@ -0,0 +1,41 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API;
/**
* Base trait for api interaction
*/
trait GuzzleTrait {
/**
* The Guzzle http client object
* @var object
*/
protected $client;
/**
* Cookie jar object for api requests
* @var object
*/
protected $cookieJar;
/**
* Set up the class properties
*
* @return void
*/
abstract protected function init();
}

66
src/API/JsonAPI.php Normal file
View File

@ -0,0 +1,66 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API;
/**
* Class encapsulating Json API data structure for a request or response
*/
class JsonAPI {
/**
* The full data array
*
* Basic structure is generally like so:
* @example [
* 'id' => '12016665',
* 'type' => 'libraryEntries',
* 'links' => [
* 'self' => 'https://kitsu.io/api/edge/library-entries/13016665'
* ],
* 'attributes' => [
*
* ]
* ]
*
* @var array
*/
protected $data = [];
/**
* Related objects included with the request
*
* @var array
*/
protected $included = [];
/**
* Pagination links
*
* @var array
*/
protected $links = [];
/**
* Parse a JsonAPI response into its components
*
* @param array $data
*/
public function parse(array $data)
{
}
}

201
src/API/Kitsu.php Normal file
View File

@ -0,0 +1,201 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API;
use Aviat\AnimeClient\API\Kitsu\Enum\{
AnimeAiringStatus,
AnimeWatchingStatus,
MangaReadingStatus
};
use DateTimeImmutable;
/**
* Constants and mappings for the Kitsu API
*/
class Kitsu {
const AUTH_URL = 'https://kitsu.io/api/oauth/token';
/**
* Map of Kitsu status to label for select menus
*
* @return array
*/
public static function getStatusToSelectMap()
{
return [
AnimeWatchingStatus::WATCHING => 'Currently Watching',
AnimeWatchingStatus::PLAN_TO_WATCH => 'Plan to Watch',
AnimeWatchingStatus::COMPLETED => 'Completed',
AnimeWatchingStatus::ON_HOLD => 'On Hold',
AnimeWatchingStatus::DROPPED => 'Dropped'
];
}
public static function getStatusToMangaSelectMap()
{
return [
MangaReadingStatus::READING => 'Currently Reading',
MangaReadingStatus::PLAN_TO_READ => 'Plan to Read',
MangaReadingStatus::COMPLETED => 'Completed',
MangaReadingStatus::ON_HOLD => 'On Hold',
MangaReadingStatus::DROPPED => 'Dropped'
];
}
/**
* Determine whether an anime is airing, finished airing, or has not yet aired
*
* @param string $startDate
* @param string $endDate
* @return string
*/
public static function getAiringStatus(string $startDate = null, string $endDate = null): string
{
$startAirDate = new DateTimeImmutable($startDate ?? 'tomorrow');
$endAirDate = new DateTimeImmutable($endDate ?? 'tomorrow');
$now = new DateTimeImmutable();
$isDoneAiring = $now > $endAirDate;
$isCurrentlyAiring = ($now > $startAirDate) && ! $isDoneAiring;
switch (true)
{
case $isCurrentlyAiring:
return AnimeAiringStatus::AIRING;
case $isDoneAiring:
return AnimeAiringStatus::FINISHED_AIRING;
default:
return AnimeAiringStatus::NOT_YET_AIRED;
}
}
/**
* Filter out duplicate and very similar names from
*
* @param array $data The 'attributes' section of the api data response
* @return array List of alternate titles
*/
public static function filterTitles(array $data): array
{
// The 'canonical' title is always returned
$valid = [$data['canonicalTitle']];
if (array_key_exists('titles', $data))
{
foreach($data['titles'] as $alternateTitle)
{
if (self::titleIsUnique($alternateTitle, $valid))
{
$valid[] = $alternateTitle;
}
}
}
return $valid;
}
/**
* Reorganizes 'included' data to be keyed by
* type => [
* id => data/attributes,
* ]
*
* @param array $includes
* @return array
*/
public static function organizeIncludes(array $includes): array
{
$organized = [];
foreach ($includes as $item)
{
$type = $item['type'];
$id = $item['id'];
$organized[$type] = $organized[$type] ?? [];
$organized[$type][$id] = $item['attributes'];
if (array_key_exists('relationships', $item))
{
$organized[$type][$id]['relationships'] = self::organizeRelationships($item['relationships']);
}
}
return $organized;
}
/**
* Reorganize relationship mappings to make them simpler to use
*
* Remove verbose structure, and just map:
* type => [ idArray ]
*
* @param array $relationships
* @return array
*/
public static function organizeRelationships(array $relationships): array
{
$organized = [];
foreach($relationships as $key => $data)
{
if ( ! array_key_exists('data', $data))
{
continue;
}
$organized[$key] = $organized[$key] ?? [];
foreach ($data['data'] as $item)
{
$organized[$key][] = $item['id'];
}
}
return $organized;
}
/**
* Determine if an alternate title is unique enough to list
*
* @param string $title
* @param array $existingTitles
* @return bool
*/
private static function titleIsUnique(string $title = null, array $existingTitles): bool
{
if (empty($title))
{
return false;
}
foreach($existingTitles as $existing)
{
$isSubset = stripos($existing, $title) !== FALSE;
$diff = levenshtein($existing, $title);
$onlydifferentCase = (mb_strtolower($existing) === mb_strtolower($title));
if ($diff < 3 || $isSubset || $onlydifferentCase)
{
return false;
}
}
return true;
}
}

108
src/API/Kitsu/Auth.php Normal file
View File

@ -0,0 +1,108 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu;
use Aviat\AnimeClient\AnimeClient;
use Aviat\Ion\Di\{ContainerAware, ContainerInterface};
/**
* Kitsu API Authentication
*/
class Auth {
use ContainerAware;
/**
* Anime API Model
*
* @var \Aviat\AnimeClient\API\Kitsu\Model
*/
protected $model;
/**
* Session object
*
* @var Aura\Session\Segment
*/
protected $segment;
/**
* Constructor
*
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
$this->segment = $container->get('session')
->getSegment(AnimeClient::SESSION_SEGMENT);
$this->model = $container->get('kitsu-model');
}
/**
* Make the appropriate authentication call,
* and save the resulting auth token if successful
*
* @param string $password
* @return boolean
*/
public function authenticate($password)
{
$config = $this->container->get('config');
$username = $config->get(['kitsu_username']);
$auth_token = $this->model->authenticate($username, $password);
if (FALSE !== $auth_token)
{
$this->segment->set('auth_token', $auth_token);
return TRUE;
}
return FALSE;
}
/**
* Check whether the current user is authenticated
*
* @return boolean
*/
public function is_authenticated()
{
return ($this->get_auth_token() !== FALSE);
}
/**
* Clear authentication values
*
* @return void
*/
public function logout()
{
$this->segment->clear();
}
/**
* Retrieve the authentication token from the session
*
* @return string|false
*/
public function get_auth_token()
{
return $this->segment->get('auth_token', FALSE);
}
}
// End of KitsuAuth.php

View File

@ -0,0 +1,29 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu\Enum;
use Aviat\Ion\Enum as BaseEnum;
/**
* Status of when anime is being/was/will be aired
*/
class AnimeAiringStatus extends BaseEnum {
const NOT_YET_AIRED = 'Not Yet Aired';
const AIRING = 'Currently Airing';
const FINISHED_AIRING = 'Finished Airing';
}
// End of AnimeAiringStatus.php

View File

@ -0,0 +1,31 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu\Enum;
use Aviat\Ion\Enum as BaseEnum;
/**
* Possible values for watching status for the current anime
*/
class AnimeWatchingStatus extends BaseEnum {
const WATCHING = 'current';
const PLAN_TO_WATCH = 'planned';
const COMPLETED = 'completed';
const ON_HOLD = 'on_hold';
const DROPPED = 'dropped';
}
// End of AnimeWatchingStatus.php

View File

@ -0,0 +1,31 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu\Enum;
use Aviat\Ion\Enum as BaseEnum;
/**
* Possible values for current reading status of manga
*/
class MangaReadingStatus extends BaseEnum {
const READING = 'current';
const PLAN_TO_READ = 'planned';
const DROPPED = 'dropped';
const ON_HOLD = 'on_hold';
const COMPLETED = 'completed';
}
// End of MangaReadingStatus.php

View File

@ -0,0 +1,320 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu;
use Aviat\AnimeClient\API\Kitsu as K;
use Aviat\AnimeClient\API\Kitsu\Transformer\{
AnimeTransformer, AnimeListTransformer, MangaTransformer, MangaListTransformer
};
use Aviat\Ion\Di\ContainerAware;
use Aviat\Ion\Json;
use GuzzleHttp\Exception\ClientException;
/**
* Kitsu API Model
*/
class KitsuModel {
use ContainerAware;
use KitsuTrait;
/**
* Class to map anime list items
* to a common format used by
* templates
*
* @var AnimeListTransformer
*/
protected $animeListTransformer;
/**
* @var AnimeTransformer
*/
protected $animeTransformer;
/**
* @var ListItem
*/
protected $listItem;
/**
* @var MangaTransformer
*/
protected $mangaTransformer;
/**
* @var MangaListTransformer
*/
protected $mangaListTransformer;
/**
* KitsuModel constructor.
*/
public function __construct(ListItem $listItem)
{
// Set up Guzzle trait
$this->init();
$this->animeTransformer = new AnimeTransformer();
$this->animeListTransformer = new AnimeListTransformer();
$this->listItem = $listItem;
$this->mangaTransformer = new MangaTransformer();
$this->mangaListTransformer = new MangaListTransformer();
}
/**
* Get the userid for a username from Kitsu
*
* @param string $username
* @return string
*/
public function getUserIdByUsername(string $username)
{
$data = $this->getRequest('users', [
'query' => [
'filter' => [
'name' => $username
]
]
]);
return $data['data'][0]['id'];
}
/**
* Get the access token from the Kitsu API
*
* @param string $username
* @param string $password
* @return bool|string
*/
public function authenticate(string $username, string $password)
{
$response = $this->getResponse('POST', K::AUTH_URL, [
'headers' => [],
'form_params' => [
'grant_type' => 'password',
'username' => $username,
'password' => $password
]
]);
$data = Json::decode((string)$response->getBody());
if (array_key_exists('access_token', $data))
{
return $data['access_token'];
}
return false;
}
/**
* Get information about a particular anime
*
* @param string $animeId
* @return array
*/
public function getAnime(string $animeId): array
{
$baseData = $this->getRawMediaData('anime', $animeId);
return $this->animeTransformer->transform($baseData);
}
/**
* Get information about a particular manga
*
* @param string $mangaId
* @return array
*/
public function getManga(string $mangaId): array
{
$baseData = $this->getRawMediaData('manga', $mangaId);
return $this->mangaTransformer->transform($baseData);
}
public function getAnimeList($status): array
{
$options = [
'query' => [
'filter' => [
'user_id' => $this->getUserIdByUsername($this->getUsername()),
'media_type' => 'Anime',
'status' => $status,
],
'include' => 'media,media.genres',
'page' => [
'offset' => 0,
'limit' => 1000
],
'sort' => '-updated_at'
]
];
$data = $this->getRequest('library-entries', $options);
$included = K::organizeIncludes($data['included']);
foreach($data['data'] as $i => &$item)
{
$item['anime'] = $included['anime'][$item['relationships']['media']['data']['id']];
$animeGenres = $item['anime']['relationships']['genres'];
foreach($animeGenres as $id)
{
$item['genres'][] = $included['genres'][$id]['name'];
}
}
$transformed = $this->animeListTransformer->transformCollection($data['data']);
return $transformed;
}
public function getMangaList($status): array
{
$options = [
'query' => [
'filter' => [
'user_id' => $this->getUserIdByUsername($this->getUsername()),
'media_type' => 'Manga',
'status' => $status,
],
'include' => 'media',
'page' => [
'offset' => 0,
'limit' => 200
],
'sort' => '-updated_at'
]
];
$data = $this->getRequest('library-entries', $options);
foreach($data['data'] as $i => &$item)
{
$item['manga'] = $data['included'][$i];
}
$transformed = $this->mangaListTransformer->transformCollection($data['data']);
return $transformed;
}
public function search(string $type, string $query): array
{
$options = [
'query' => [
'filter' => [
'text' => $query
],
'page' => [
'offset' => 0,
'limit' => 20
],
]
];
$raw = $this->getRequest($type, $options);
foreach ($raw['data'] as &$item)
{
$item['attributes']['titles'] = K::filterTitles($item['attributes']);
array_shift($item['attributes']['titles']);
}
return $raw;
}
public function createListItem(array $data): bool
{
$data['user_id'] = $this->getUserIdByUsername($this->getUsername());
return $this->listItem->create($data);
}
public function getListItem(string $listId): array
{
$baseData = $this->listItem->get($listId);
switch ($baseData['included'][0]['type'])
{
case 'anime':
$baseData['data']['anime'] = $baseData['included'][0];
return $this->animeListTransformer->transform($baseData['data']);
case 'manga':
$baseData['data']['manga'] = $baseData['included'][0];
return $this->mangaListTransformer->transform($baseData['data']);
default:
return $baseData['data']['attributes'];
}
}
public function updateListItem(array $data)
{
try
{
$response = $this->listItem->update($data['id'], $data['data']);
return [
'statusCode' => $response->getStatusCode(),
'body' => $response->getBody(),
];
}
catch(ClientException $e)
{
return [
'statusCode' => $e->getResponse()->getStatusCode(),
'body' => Json::decode((string)$e->getResponse()->getBody())
];
}
}
public function deleteListItem(string $id): bool
{
return $this->listItem->delete($id);
}
private function getUsername(): string
{
return $this->getContainer()
->get('config')
->get(['kitsu_username']);
}
private function getRawMediaData(string $type, string $slug): array
{
$options = [
'query' => [
'filter' => [
'slug' => $slug
],
'include' => ($type === 'anime')
? 'genres,mappings,streamingLinks'
: 'genres,mappings',
]
];
$data = $this->getRequest($type, $options);
$baseData = $data['data'][0]['attributes'];
$rawGenres = array_pluck($data['included'], 'attributes');
$genres = array_pluck($rawGenres, 'name');
$baseData['genres'] = $genres;
$baseData['included'] = $data['included'];
return $baseData;
}
}

View File

@ -0,0 +1,211 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu;
use Aviat\AnimeClient\AnimeClient;
use Aviat\AnimeClient\API\GuzzleTrait;
use Aviat\AnimeClient\API\Kitsu as K;
use Aviat\Ion\Json;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Psr7\Response;
use InvalidArgumentException;
use RuntimeException;
trait KitsuTrait {
use GuzzleTrait;
/**
* The base url for api requests
* @var string $base_url
*/
protected $baseUrl = "https://kitsu.io/api/edge/";
/**
* HTTP headers to send with every request
*
* @var array
*/
protected $defaultHeaders = [
'User-Agent' => "Tim's Anime Client/4.0",
'Accept-Encoding' => 'application/vnd.api+json',
'Content-Type' => 'application/vnd.api+json',
'client_id' => 'dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd',
'client_secret' => '54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151',
];
/**
* Set up the class properties
*
* @return void
*/
protected function init()
{
$defaults = [
'cookies' => $this->cookieJar,
'headers' => $this->defaultHeaders,
'timeout' => 25,
'connect_timeout' => 25
];
$this->cookieJar = new CookieJar();
$this->client = new Client([
'base_uri' => $this->baseUrl,
'cookies' => TRUE,
'http_errors' => TRUE,
'defaults' => $defaults
]);
}
/**
* Make a request via Guzzle
*
* @param string $type
* @param string $url
* @param array $options
* @return Response
*/
private function getResponse(string $type, string $url, array $options = [])
{
$logger = null;
$validTypes = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
if ( ! in_array($type, $validTypes))
{
throw new InvalidArgumentException('Invalid http request type');
}
$defaultOptions = [
'headers' => $this->defaultHeaders
];
$logger = $this->container->getLogger('request');
$sessionSegment = $this->getContainer()
->get('session')
->getSegment(AnimeClient::SESSION_SEGMENT);
if ($sessionSegment->get('auth_token') !== null && $url !== K::AUTH_URL)
{
$token = $sessionSegment->get('auth_token');
$defaultOptions['headers']['Authorization'] = "bearer {$token}";
}
$options = array_merge($defaultOptions, $options);
$logger->debug(Json::encode([$type, $url]));
$logger->debug(Json::encode($options));
return $this->client->request($type, $url, $options);
}
/**
* Make a request via Guzzle
*
* @param string $type
* @param string $url
* @param array $options
* @return array
*/
private function request(string $type, string $url, array $options = []): array
{
$logger = null;
if ($this->getContainer())
{
$logger = $this->container->getLogger('request');
}
$response = $this->getResponse($type, $url, $options);
if ((int) $response->getStatusCode() > 299 || (int) $response->getStatusCode() < 200)
{
if ($logger)
{
$logger->warning('Non 200 response for api call');
$logger->warning($response->getBody());
}
// throw new RuntimeException($response->getBody());
}
return JSON::decode($response->getBody(), TRUE);
}
/**
* Remove some boilerplate for get requests
*
* @param array $args
* @return array
*/
protected function getRequest(...$args): array
{
return $this->request('GET', ...$args);
}
/**
* Remove some boilerplate for patch requests
*
* @param array $args
* @return array
*/
protected function patchRequest(...$args): array
{
return $this->request('PATCH', ...$args);
}
/**
* Remove some boilerplate for post requests
*
* @param array $args
* @return array
*/
protected function postRequest(...$args): array
{
$logger = null;
if ($this->getContainer())
{
$logger = $this->container->getLogger('request');
}
$response = $this->getResponse('POST', ...$args);
$validResponseCodes = [200, 201];
if ( ! in_array((int) $response->getStatusCode(), $validResponseCodes))
{
if ($logger)
{
$logger->warning('Non 201 response for POST api call');
$logger->warning($response->getBody());
}
// throw new RuntimeException($response->getBody());
}
return JSON::decode($response->getBody(), TRUE);
}
/**
* Remove some boilerplate for delete requests
*
* @param array $args
* @return bool
*/
protected function deleteRequest(...$args): bool
{
$response = $this->getResponse('DELETE', ...$args);
return ((int) $response->getStatusCode() === 204);
}
}

101
src/API/Kitsu/ListItem.php Normal file
View File

@ -0,0 +1,101 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu;
use Aviat\AnimeClient\API\AbstractListItem;
use Aviat\Ion\Di\ContainerAware;
use Aviat\Ion\Json;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Psr7\Response;
use RuntimeException;
/**
* CRUD operations for Kitsu list items
*/
class ListItem extends AbstractListItem {
use ContainerAware;
use KitsuTrait;
public function __construct()
{
$this->init();
}
public function create(array $data): bool
{
/*?><pre><?= print_r($data, TRUE) ?></pre><?php */
$response = $this->getResponse('POST', 'library-entries', [
'body' => Json::encode([
'data' => [
'type' => 'libraryEntries',
'attributes' => [
'status' => $data['status'],
'progress' => $data['progress'] ?? 0
],
'relationships' => [
'user' => [
'data' => [
'id' => $data['user_id'],
'type' => 'users'
]
],
'media' => [
'data' => [
'id' => $data['id'],
'type' => $data['type']
]
]
]
]
])
]);
return ($response->getStatusCode() === 201);
}
public function delete(string $id): bool
{
$response = $this->getResponse('DELETE', "library-entries/{$id}");
return ($response->getStatusCode() === 204);
}
public function get(string $id): array
{
return $this->getRequest("library-entries/{$id}", [
'query' => [
'include' => 'media'
]
]);
}
public function update(string $id, array $data): Response
{
$requestData = [
'data' => [
'id' => $id,
'type' => 'libraryEntries',
'attributes' => $data
]
];
$response = $this->getResponse('PATCH', "library-entries/{$id}", [
'body' => JSON::encode($requestData)
]);
return $response;
}
}

View File

@ -0,0 +1,120 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu\Transformer;
use Aviat\AnimeClient\API\Kitsu;
use Aviat\Ion\Transformer\AbstractTransformer;
/**
* Transformer for anime list
*/
class AnimeListTransformer extends AbstractTransformer {
/**
* Convert raw api response to a more
* logical and workable structure
*
* @param array $item API library item
* @return array
*/
public function transform($item)
{
/* ?><pre><?= print_r($item, TRUE) ?></pre><?php
// die(); */
$anime = $item['anime']['attributes'] ?? $item['anime'];
$genres = $item['genres'] ?? [];
$rating = (int) 2 * $item['attributes']['rating'];
$total_episodes = array_key_exists('episodeCount', $anime) && (int) $anime['episodeCount'] !== 0
? (int) $anime['episodeCount']
: '-';
return [
'id' => $item['id'],
'episodes' => [
'watched' => $item['attributes']['progress'],
'total' => $total_episodes,
'length' => $anime['episodeLength'],
],
'airing' => [
'status' => Kitsu::getAiringStatus($anime['startDate'], $anime['endDate']),
'started' => $anime['startDate'],
'ended' => $anime['endDate']
],
'anime' => [
'age_rating' => $anime['ageRating'],
'titles' => Kitsu::filterTitles($anime),
'slug' => $anime['slug'],
'url' => $anime['url'] ?? '',
'type' => $this->string($anime['showType'])->upperCaseFirst()->__toString(),
'image' => $anime['posterImage']['small'],
'genres' => $genres,
],
'watching_status' => $item['attributes']['status'],
'notes' => $item['attributes']['notes'],
'rewatching' => (bool) $item['attributes']['reconsuming'],
'rewatched' => (int) $item['attributes']['reconsumeCount'],
'user_rating' => ($rating === 0) ? '-' : $rating,
'private' => (bool) $item['attributes']['private'] ?? false,
];
}
/**
* Convert transformed data to
* api response format
*
* @param array $item Transformed library item
* @return array API library item
*/
public function untransform($item)
{
// Messy mapping of boolean values to their API string equivalents
$privacy = 'false';
if (array_key_exists('private', $item) && $item['private'])
{
$privacy = 'true';
}
$rewatching = 'false';
if (array_key_exists('rewatching', $item) && $item['rewatching'])
{
$rewatching = 'true';
}
$untransformed = [
'id' => $item['id'],
'data' => [
'status' => $item['watching_status'],
'rating' => $item['user_rating'] / 2,
'reconsuming' => $rewatching,
'reconsumeCount' => $item['rewatched'],
'notes' => $item['notes'],
'progress' => $item['episodes_watched'],
'private' => $privacy
]
];
if ((int) $untransformed['data']['rating'] === 0)
{
unset($untransformed['data']['rating']);
}
return $untransformed;
}
}
// End of AnimeListTransformer.php

View File

@ -0,0 +1,53 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu\Transformer;
use Aviat\AnimeClient\API\Kitsu;
use Aviat\Ion\Transformer\AbstractTransformer;
/**
* Transformer for anime description page
*/
class AnimeTransformer extends AbstractTransformer {
/**
* Convert raw api response to a more
* logical and workable structure
*
* @param array $item API library item
* @return array
*/
public function transform($item)
{
$item['genres'] = $item['genres'] ?? [];
sort($item['genres']);
return [
'titles' => Kitsu::filterTitles($item),
'status' => Kitsu::getAiringStatus($item['startDate'], $item['endDate']),
'cover_image' => $item['posterImage']['small'],
'show_type' => $item['showType'],
'episode_count' => $item['episodeCount'],
'episode_length' => $item['episodeLength'],
'synopsis' => $item['synopsis'],
'age_rating' => $item['ageRating'],
'age_rating_guide' => $item['ageRatingGuide'],
'url' => "https://kitsu.io/anime/{$item['slug']}",
'genres' => $item['genres'],
];
}
}

View File

@ -0,0 +1,113 @@
<?php declare(strict_types=1);
/**
* Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package AnimeListClient
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2015 - 2016 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://github.com/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu\Transformer;
use Aviat\AnimeClient\API\Kitsu;
use Aviat\Ion\StringWrapper;
use Aviat\Ion\Transformer\AbstractTransformer;
/**
* Data transformation class for zippered Hummingbird manga
*/
class MangaListTransformer extends AbstractTransformer {
use StringWrapper;
/**
* Remap zipped anime data to a more logical form
*
* @param array $item manga entry item
* @return array
*/
public function transform($item)
{
/*?><pre><?= print_r($item, TRUE) ?></pre><?php*/
$manga =& $item['manga'];
$rating = (is_numeric($item['attributes']['rating']))
? intval(2 * $item['attributes']['rating'])
: '-';
$total_chapters = ($manga['attributes']['chapterCount'] > 0)
? $manga['attributes']['chapterCount']
: '-';
$total_volumes = ($manga['attributes']['volumeCount'] > 0)
? $manga['attributes']['volumeCount']
: '-';
$map = [
'id' => $item['id'],
'chapters' => [
'read' => $item['attributes']['progress'],
'total' => $total_chapters
],
'volumes' => [
'read' => '-', //$item['attributes']['volumes_read'],
'total' => $total_volumes
],
'manga' => [
'titles' => Kitsu::filterTitles($manga['attributes']),
'alternate_title' => NULL,
'slug' => $manga['attributes']['slug'],
'url' => 'https://kitsu.io/manga/' . $manga['attributes']['slug'],
'type' => $manga['attributes']['mangaType'],
'image' => $manga['attributes']['posterImage']['small'],
'genres' => [], //$manga['genres'],
],
'reading_status' => $item['attributes']['status'],
'notes' => $item['attributes']['notes'],
'rereading' => (bool)$item['attributes']['reconsuming'],
'reread' => $item['attributes']['reconsumeCount'],
'user_rating' => $rating,
];
return $map;
}
/**
* Untransform data to update the api
*
* @param array $item
* @return array
*/
public function untransform($item)
{
$rereading = (array_key_exists('rereading', $item)) && (bool)$item['rereading'];
$map = [
'id' => $item['id'],
'data' => [
'status' => $item['status'],
'progress' => (int)$item['chapters_read'],
'reconsuming' => $rereading,
'reconsumeCount' => (int)$item['reread_count'],
'notes' => $item['notes'],
],
];
if ($item['new_rating'] !== $item['old_rating'] && $item['new_rating'] !== "")
{
$map['data']['rating'] = ($item['new_rating'] > 0)
? $item['new_rating'] / 2
: $item['old_rating'] / 2;
}
return $map;
}
}
// End of MangaListTransformer.php

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