diff --git a/composer.json b/composer.json index 80aab22e1..cf0215262 100644 --- a/composer.json +++ b/composer.json @@ -29,28 +29,15 @@ }, "autoload" : { "psr-4" : { + "Joindin\\Api\\": "src/", "Joindin\\Modifier\\" : "src/Modifier/" - }, - "classmap" : [ - "src/controllers", - "src/inc", - "src/models", - "src/routers", - "src/services", - "src/views" - ] + } }, "autoload-dev" : { "psr-4" : { - "JoindinTest\\" : "tests/" + "Joindin\\Api\\Test\\" : "tests/" }, - "classmap" : [ - "tests/controllers", - "tests/inc", - "tests/models", - "tests/routers", - "tests/views" - ] + "files": ["tests/compatibility/File.php"] }, "scripts": { "test": "phpunit -c . tests/", diff --git a/composer.lock b/composer.lock index e076e6519..8a0e1ed6b 100644 --- a/composer.lock +++ b/composer.lock @@ -786,57 +786,6 @@ ], "time": "2018-06-11T23:09:50+00:00" }, - { - "name": "nikic/php-parser", - "version": "v4.2.1", - "source": { - "type": "git", - "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "5221f49a608808c1e4d436df32884cbc1b821ac0" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/5221f49a608808c1e4d436df32884cbc1b821ac0", - "reference": "5221f49a608808c1e4d436df32884cbc1b821ac0", - "shasum": "" - }, - "require": { - "ext-tokenizer": "*", - "php": ">=7.0" - }, - "require-dev": { - "phpunit/phpunit": "^6.5 || ^7.0" - }, - "bin": [ - "bin/php-parse" - ], - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "4.2-dev" - } - }, - "autoload": { - "psr-4": { - "PhpParser\\": "lib/PhpParser" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Nikita Popov" - } - ], - "description": "A PHP parser written in PHP", - "keywords": [ - "parser", - "php" - ], - "time": "2019-02-16T20:54:15+00:00" - }, { "name": "phar-io/manifest", "version": "1.0.3", @@ -1154,6 +1103,50 @@ ], "time": "2018-08-05T17:53:17+00:00" }, + { + "name": "phpstan/phpstan-shim", + "version": "0.11.5", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan-shim.git", + "reference": "d09662232a3d8e352c6fad4d30a57c16eb5342b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan-shim/zipball/d09662232a3d8e352c6fad4d30a57c16eb5342b5", + "reference": "d09662232a3d8e352c6fad4d30a57c16eb5342b5", + "shasum": "" + }, + "require": { + "php": "~7.1" + }, + "replace": { + "nikic/php-parser": "^4.0.2", + "phpstan/phpdoc-parser": "^0.3", + "phpstan/phpstan": "self.version" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.11-dev" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan Phar distribution", + "time": "2019-03-25T21:30:19+00:00" + }, { "name": "phpunit/php-code-coverage", "version": "7.0.3", @@ -1538,65 +1531,18 @@ ], "time": "2019-04-05T05:27:33+00:00" }, - { - "name": "psr/log", - "version": "1.1.0", - "source": { - "type": "git", - "url": "https://github.com/php-fig/log.git", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Log\\": "Psr/Log/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for logging libraries", - "homepage": "https://github.com/php-fig/log", - "keywords": [ - "log", - "psr", - "psr-3" - ], - "time": "2018-11-20T15:27:04+00:00" - }, { "name": "roave/security-advisories", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/Roave/SecurityAdvisories.git", - "reference": "3521da8036ce31b11490433aaae47f9601774191" + "reference": "018ec51b676a4d1efc971950d1d9619570b71676" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/3521da8036ce31b11490433aaae47f9601774191", - "reference": "3521da8036ce31b11490433aaae47f9601774191", + "url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/018ec51b676a4d1efc971950d1d9619570b71676", + "reference": "018ec51b676a4d1efc971950d1d9619570b71676", "shasum": "" }, "conflict": { @@ -1631,8 +1577,8 @@ "doctrine/mongodb-odm-bundle": ">=2,<3.0.1", "doctrine/orm": ">=2,<2.4.8|>=2.5,<2.5.1", "dompdf/dompdf": ">=0.6,<0.6.2", - "drupal/core": ">=7,<7.62|>=8,<8.5.11|>=8.6,<8.6.10", - "drupal/drupal": ">=7,<7.62|>=8,<8.5.11|>=8.6,<8.6.10", + "drupal/core": ">=7,<7.64|>=8,<8.5.13|>=8.6,<8.6.12", + "drupal/drupal": ">=7,<7.64|>=8,<8.5.13|>=8.6,<8.6.12", "erusev/parsedown": "<1.7", "ezsystems/ezpublish-kernel": ">=5.3,<5.3.12.1|>=5.4,<5.4.13.1|>=6,<6.7.9.1|>=6.8,<6.13.5.1|>=7,<7.2.4.1|>=7.3,<7.3.2.1", "ezsystems/ezpublish-legacy": ">=5.3,<5.3.12.6|>=5.4,<5.4.12.3|>=2011,<2017.12.4.3|>=2018.6,<2018.6.1.4|>=2018.9,<2018.9.1.3", @@ -1660,7 +1606,7 @@ "la-haute-societe/tcpdf": "<6.2.22", "laravel/framework": ">=4,<4.0.99|>=4.1,<=4.1.31|>=4.2,<=4.2.22|>=5,<=5.0.35|>=5.1,<=5.1.46|>=5.2,<=5.2.45|>=5.3,<=5.3.31|>=5.4,<=5.4.36|>=5.5,<5.5.42|>=5.6,<5.6.30", "laravel/socialite": ">=1,<1.0.99|>=2,<2.0.10", - "league/commonmark": ">=0.15.6,<0.18.1", + "league/commonmark": "<0.18.3", "magento/magento1ce": "<1.9.4", "magento/magento1ee": ">=1.9,<1.14.4", "magento/product-community-edition": ">=2,<2.2.7", @@ -1729,7 +1675,7 @@ "symfony/yaml": ">=2,<2.0.22|>=2.1,<2.1.7", "tecnickcom/tcpdf": "<6.2.22", "thelia/backoffice-default-template": ">=2.1,<2.1.2", - "thelia/thelia": ">=2.1.0-beta1,<2.1.3|>=2.1,<2.1.2", + "thelia/thelia": ">=2.1,<2.1.2|>=2.1.0-beta1,<2.1.3", "theonedemon/phpwhois": "<=4.2.5", "titon/framework": ">=0,<9.9.99", "truckersmp/phpwhois": "<=4.3.1", @@ -1787,7 +1733,7 @@ } ], "description": "Prevents installation of composer packages with known security vulnerabilities: no API, simply require it", - "time": "2019-03-12T13:04:55+00:00" + "time": "2019-03-22T05:18:50+00:00" }, { "name": "sebastian/code-unit-reverse-lookup", @@ -2457,21 +2403,21 @@ }, { "name": "symfony/console", - "version": "v3.4.22", + "version": "v4.2.4", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "069bf3f0e8f871a2169a06e43d9f3f03f355e9be" + "reference": "9dc2299a016497f9ee620be94524e6c0af0280a9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/069bf3f0e8f871a2169a06e43d9f3f03f355e9be", - "reference": "069bf3f0e8f871a2169a06e43d9f3f03f355e9be", + "url": "https://api.github.com/repos/symfony/console/zipball/9dc2299a016497f9ee620be94524e6c0af0280a9", + "reference": "9dc2299a016497f9ee620be94524e6c0af0280a9", "shasum": "" }, "require": { - "php": "^5.5.9|>=7.0.8", - "symfony/debug": "~2.8|~3.0|~4.0", + "php": "^7.1.3", + "symfony/contracts": "^1.0", "symfony/polyfill-mbstring": "~1.0" }, "conflict": { @@ -2483,11 +2429,11 @@ }, "require-dev": { "psr/log": "~1.0", - "symfony/config": "~3.3|~4.0", + "symfony/config": "~3.4|~4.0", "symfony/dependency-injection": "~3.4|~4.0", - "symfony/event-dispatcher": "~2.8|~3.0|~4.0", + "symfony/event-dispatcher": "~3.4|~4.0", "symfony/lock": "~3.4|~4.0", - "symfony/process": "~3.3|~4.0" + "symfony/process": "~3.4|~4.0" }, "suggest": { "psr/log": "For using the console logger", @@ -2498,7 +2444,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "3.4-dev" + "dev-master": "4.2-dev" } }, "autoload": { @@ -2525,44 +2471,48 @@ ], "description": "Symfony Console Component", "homepage": "https://symfony.com", - "time": "2019-01-25T10:42:12+00:00" + "time": "2019-02-23T15:17:42+00:00" }, { - "name": "symfony/debug", - "version": "v3.4.22", + "name": "symfony/contracts", + "version": "v1.0.2", "source": { "type": "git", - "url": "https://github.com/symfony/debug.git", - "reference": "667a26c4dd6bc75c67f06bc9bcd015bdecc7cbb8" + "url": "https://github.com/symfony/contracts.git", + "reference": "1aa7ab2429c3d594dd70689604b5cf7421254cdf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/debug/zipball/667a26c4dd6bc75c67f06bc9bcd015bdecc7cbb8", - "reference": "667a26c4dd6bc75c67f06bc9bcd015bdecc7cbb8", + "url": "https://api.github.com/repos/symfony/contracts/zipball/1aa7ab2429c3d594dd70689604b5cf7421254cdf", + "reference": "1aa7ab2429c3d594dd70689604b5cf7421254cdf", "shasum": "" }, "require": { - "php": "^5.5.9|>=7.0.8", - "psr/log": "~1.0" - }, - "conflict": { - "symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2" + "php": "^7.1.3" }, "require-dev": { - "symfony/http-kernel": "~2.8|~3.0|~4.0" + "psr/cache": "^1.0", + "psr/container": "^1.0" + }, + "suggest": { + "psr/cache": "When using the Cache contracts", + "psr/container": "When using the Service contracts", + "symfony/cache-contracts-implementation": "", + "symfony/service-contracts-implementation": "", + "symfony/translation-contracts-implementation": "" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.4-dev" + "dev-master": "1.0-dev" } }, "autoload": { "psr-4": { - "Symfony\\Component\\Debug\\": "" + "Symfony\\Contracts\\": "" }, "exclude-from-classmap": [ - "/Tests/" + "**/Tests/" ] }, "notification-url": "https://packagist.org/downloads/", @@ -2571,17 +2521,25 @@ ], "authors": [ { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" + "name": "Nicolas Grekas", + "email": "p@tchwork.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony Debug Component", + "description": "A set of abstractions extracted out of the Symfony components", "homepage": "https://symfony.com", - "time": "2019-01-25T10:19:25+00:00" + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "time": "2018-12-05T08:06:11+00:00" }, { "name": "symfony/polyfill-ctype", @@ -2628,7 +2586,7 @@ }, { "name": "Gert de Pagter", - "email": "backendtea@gmail.com" + "email": "BackEndTea@gmail.com" } ], "description": "Symfony polyfill for ctype functions", @@ -2643,16 +2601,16 @@ }, { "name": "symfony/polyfill-mbstring", - "version": "v1.10.0", + "version": "v1.11.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "c79c051f5b3a46be09205c73b80b346e4153e494" + "reference": "fe5e94c604826c35a32fa832f35bd036b6799609" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/c79c051f5b3a46be09205c73b80b346e4153e494", - "reference": "c79c051f5b3a46be09205c73b80b346e4153e494", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/fe5e94c604826c35a32fa832f35bd036b6799609", + "reference": "fe5e94c604826c35a32fa832f35bd036b6799609", "shasum": "" }, "require": { @@ -2664,7 +2622,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.9-dev" + "dev-master": "1.11-dev" } }, "autoload": { @@ -2698,7 +2656,66 @@ "portable", "shim" ], - "time": "2018-09-21T13:07:52+00:00" + "time": "2019-02-06T07:57:58+00:00" + }, + { + "name": "symfony/yaml", + "version": "v4.2.4", + "source": { + "type": "git", + "url": "https://github.com/symfony/yaml.git", + "reference": "761fa560a937fd7686e5274ff89dcfa87a5047df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/yaml/zipball/761fa560a937fd7686e5274ff89dcfa87a5047df", + "reference": "761fa560a937fd7686e5274ff89dcfa87a5047df", + "shasum": "" + }, + "require": { + "php": "^7.1.3", + "symfony/polyfill-ctype": "~1.8" + }, + "conflict": { + "symfony/console": "<3.4" + }, + "require-dev": { + "symfony/console": "~3.4|~4.0" + }, + "suggest": { + "symfony/console": "For validating YAML files using the lint command" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.2-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Yaml\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "https://symfony.com", + "time": "2019-02-23T15:17:42+00:00" }, { "name": "theseer/tokenizer", diff --git a/tests/frisby/package.json b/package.json similarity index 68% rename from tests/frisby/package.json rename to package.json index 44432ce19..ba9511bfd 100644 --- a/tests/frisby/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "joindin-api-tests", "scripts": { - "test": "JOINDIN_API_BASE_URL=http://api.dev.joind.in ./node_modules/.bin/jasmine-node api_spec.js", - "test_write": "JOINDIN_API_BASE_URL=http://api.dev.joind.in ./node_modules/.bin/jasmine-node api_write_spec.js" + "test": "JOINDIN_API_BASE_URL=http://api.dev.joind.in ./node_modules/.bin/jasmine-node tests/frisby/api_spec.js", + "test_write": "JOINDIN_API_BASE_URL=http://api.dev.joind.in ./node_modules/.bin/jasmine-node tests/frisby/api_write_spec.js" }, "dependencies": { "frisby": "^0.8.5", diff --git a/phpunit.xml.dist b/phpunit.xml.dist index a43d18fea..8541c8f76 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -20,15 +20,7 @@ - src/controllers - src/inc - src/models - src/services - src/views - - - inc/Autoloader.php - + src diff --git a/src/inc/ContainerFactory.php b/src/ContainerFactory.php similarity index 71% rename from src/inc/ContainerFactory.php rename to src/ContainerFactory.php index ba92852d9..ba145038e 100644 --- a/src/inc/ContainerFactory.php +++ b/src/ContainerFactory.php @@ -1,5 +1,29 @@ factory(function ($c) use ($config) { + $container[EmailsController::class] = $container->factory(function ($c) use ($config) { return new EmailsController($config); }); - $container[Event_commentsController::class] = $container->factory(function ($c) use ($config) { - return new Event_commentsController($config); + $container[EventCommentsController::class] = $container->factory(function ($c) use ($config) { + return new EventCommentsController($config); }); - $container[Event_hostsController::class] = $container->factory(function ($c) use ($config) { - return new Event_hostsController($config); + $container[EventHostsController::class] = $container->factory(function ($c) use ($config) { + return new EventHostsController($config); }); $container[EventImagesController::class] = $container->factory(function ($c) use ($config) { @@ -84,8 +108,8 @@ public static function build(array $config, $rebuild = false) return new LanguagesController($config); }); - $container[Talk_commentsController::class] = $container->factory(function ($c) use ($config) { - return new Talk_commentsController($config); + $container[TalkCommentsController::class] = $container->factory(function ($c) use ($config) { + return new TalkCommentsController($config); }); $container[TalkLinkController::class] = $container->factory(function ($c) use ($config) { diff --git a/src/controllers/ApplicationsController.php b/src/Controller/ApplicationsController.php similarity index 88% rename from src/controllers/ApplicationsController.php rename to src/Controller/ApplicationsController.php index cb73729ed..579a20ca7 100644 --- a/src/controllers/ApplicationsController.php +++ b/src/Controller/ApplicationsController.php @@ -1,10 +1,17 @@ user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } @@ -20,7 +27,7 @@ public function getApplication(Request $request, PDO $db) public function listApplications(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } @@ -37,7 +44,7 @@ public function listApplications(Request $request, PDO $db) public function createApplication(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } @@ -74,16 +81,16 @@ public function createApplication(Request $request, PDO $db) throw new Exception(implode(". ", $errors), 400); } - $app['user_id'] = $request->user_id; + $app['user_id'] = $request->user_id; $clientMapper = $this->getClientMapper($db, $request); - $clientId = $clientMapper->createClient($app); + $clientId = $clientMapper->createClient($app); $uri = $request->base . '/' . $request->version . '/applications/' . $clientId; $request->getView()->setResponseCode(201); $request->getView()->setHeader('Location', $uri); - $mapper = $this->getClientMapper($db, $request); + $mapper = $this->getClientMapper($db, $request); $newClient = $mapper->getClientByIdAndUser($clientId, $request->user_id); return $newClient->getOutputView($request); @@ -91,7 +98,7 @@ public function createApplication(Request $request, PDO $db) public function editApplication(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } @@ -128,7 +135,7 @@ public function editApplication(Request $request, PDO $db) $app['user_id'] = $request->user_id; $clientMapper = $this->getClientMapper($db, $request); - $clientId = $clientMapper->updateClient($this->getItemId($request), $app); + $clientId = $clientMapper->updateClient($this->getItemId($request), $app); $uri = $request->base . '/' . $request->version . '/applications/' . $clientId; $request->getView()->setResponseCode(201); @@ -141,7 +148,7 @@ public function editApplication(Request $request, PDO $db) public function deleteApplication(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } @@ -152,7 +159,7 @@ public function deleteApplication(Request $request, PDO $db) $request->user_id ); - if (! $client->getClients()) { + if (!$client->getClients()) { throw new Exception('No application found', 404); } @@ -171,7 +178,7 @@ public function deleteApplication(Request $request, PDO $db) } /** - * @param PDO $db + * @param PDO $db * @param Request $request * * @return ClientMapper diff --git a/src/controllers/BaseApiController.php b/src/Controller/BaseApiController.php similarity index 77% rename from src/controllers/BaseApiController.php rename to src/Controller/BaseApiController.php index 246f211b4..6945bf29f 100644 --- a/src/controllers/BaseApiController.php +++ b/src/Controller/BaseApiController.php @@ -1,5 +1,9 @@ url_elements[3]) - && is_numeric($request->url_elements[3]) + if (!empty($request->url_elements[3]) + && is_numeric($request->url_elements[3]) ) { - return (int) $request->url_elements[3]; + return (int)$request->url_elements[3]; } return false; @@ -24,7 +28,7 @@ public function getItemId(Request $request) public function getVerbosity(Request $request) { - if (! isset($request->parameters['verbose'])) { + if (!isset($request->parameters['verbose'])) { return false; } @@ -42,7 +46,7 @@ public function getStart(Request $request) public function getResultsPerPage(Request $request) { - return (int) $request->paginationParameters['resultsperpage']; + return (int)$request->paginationParameters['resultsperpage']; } public function getSort(Request $request) diff --git a/src/controllers/BaseTalkController.php b/src/Controller/BaseTalkController.php similarity index 80% rename from src/controllers/BaseTalkController.php rename to src/Controller/BaseTalkController.php index 8df0ba40a..26d505d77 100644 --- a/src/controllers/BaseTalkController.php +++ b/src/Controller/BaseTalkController.php @@ -1,5 +1,17 @@ TalkMapper::class, + 'talk' => TalkMapper::class, 'talkcomment' => TalkCommentMapper::class, ]; @@ -17,10 +29,10 @@ class BaseTalkController extends BaseApiController protected function checkLoggedIn(Request $request) { $failMessages = [ - 'POST' => 'create data', + 'POST' => 'create data', 'DELETE' => 'remove data', - 'GET' => 'view data', - 'PUT' => 'update data' + 'GET' => 'view data', + 'PUT' => 'update data' ]; if (!isset($request->user_id)) { @@ -55,7 +67,7 @@ public function setEventMapper(EventMapper $event_mapper) public function getEventMapper(PDO $db, Request $request) { - if (! isset($this->event_mapper)) { + if (!isset($this->event_mapper)) { $this->event_mapper = new EventMapper($db, $request); } @@ -70,7 +82,7 @@ public function setUserMapper(UserMapper $user_mapper) public function getUserMapper(PDO $db, Request $request) { - if (! isset($this->user_mapper)) { + if (!isset($this->user_mapper)) { $this->user_mapper = new UserMapper($db, $request); } @@ -81,9 +93,9 @@ public function getUserMapper(PDO $db, Request $request) /** * Get a single talk * - * @param Request $request - * @param PDO $db - * @param integer $talk_id + * @param Request $request + * @param PDO $db + * @param integer $talk_id * @param boolean $verbose * * @throws Exception if the talk is not found @@ -110,13 +122,13 @@ protected function getTalkById( protected function setDbAndRequest(PDO $db, Request $request) { - $this->db = $db; + $this->db = $db; $this->request = $request; } /** - * @param string $type - * @param PDO|null $db + * @param string $type + * @param PDO|null $db * @param Request|null $request * * @return ApiMapper diff --git a/src/controllers/ContactController.php b/src/Controller/ContactController.php similarity index 80% rename from src/controllers/ContactController.php rename to src/Controller/ContactController.php index 623f7667e..13329fd1b 100644 --- a/src/controllers/ContactController.php +++ b/src/Controller/ContactController.php @@ -1,5 +1,14 @@ emailService = $emailService; + $this->emailService = $emailService; $this->spamCheckService = $spamCheckService; parent::__construct($config); @@ -50,7 +59,7 @@ public function handle(Request $request, PDO $db) * - comment * * @param Request $request - * @param PDO $db + * @param PDO $db * * @throws Exception * @return void @@ -58,10 +67,10 @@ public function handle(Request $request, PDO $db) public function contact(Request $request, PDO $db) { // only trusted clients can contact us to save on spam - $clientId = $request->getParameter('client_id'); - $clientSecret = $request->getParameter('client_secret'); - $oauthModel = $request->getOauthModel($db); - if (! $oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { + $clientId = $request->getParameter('client_id'); + $clientSecret = $request->getParameter('client_secret'); + $oauthModel = $request->getOauthModel($db); + if (!$oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { throw new Exception("This client cannot perform this action", 403); } @@ -76,7 +85,7 @@ public function contact(Request $request, PDO $db) $data[$name] = $value; } - if (! empty($error)) { + if (!empty($error)) { $message = 'The field'; $message .= count($error) == 1 ? ' ' : 's '; $message .= implode(', ', $error); diff --git a/src/controllers/DefaultController.php b/src/Controller/DefaultController.php similarity index 91% rename from src/controllers/DefaultController.php rename to src/Controller/DefaultController.php index 24e86e998..c9fa71fa8 100644 --- a/src/controllers/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -1,5 +1,10 @@ getView(); $view->setHeader('Content-Length', 0); $view->setResponseCode(202); + return; } throw new Exception("Can't find that email address", 400); @@ -49,6 +60,7 @@ public function usernameReminder(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Content-Length', 0); $view->setResponseCode(202); + return; } throw new Exception("Can't find that email address", 400); @@ -73,7 +85,7 @@ public function passwordReset(Request $request, PDO $db) // we need a token to send so we know it is a valid reset $token = $user_mapper->generatePasswordResetTokenForUserId($user_id); - if (! $token) { + if (!$token) { throw new Exception("Unable to generate a reset token", 400); } @@ -83,6 +95,7 @@ public function passwordReset(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Content-Length', 0); $view->setResponseCode(202); + return; } throw new Exception("Can't find that user", 400); diff --git a/src/controllers/Event_commentsController.php b/src/Controller/EventCommentsController.php similarity index 88% rename from src/controllers/Event_commentsController.php rename to src/Controller/EventCommentsController.php index 2fa413b00..f088f5a5e 100644 --- a/src/controllers/Event_commentsController.php +++ b/src/Controller/EventCommentsController.php @@ -1,6 +1,18 @@ user_id) || empty($request->user_id)) { + if (!isset($request->user_id) || empty($request->user_id)) { throw new Exception("You must log in to do that", 401); } if ($event_mapper->thisUserHasAdminOn($event_id)) { $list = $comment_mapper->getReportedCommentsByEventId($event_id); + return $list->getOutputView($request); } else { throw new Exception("You don't have permission to do that", 403); @@ -64,7 +77,7 @@ public function createComment(Request $request, PDO $db) } // no anonymous comments over the API - if (! isset($request->user_id) || empty($request->user_id)) { + if (!isset($request->user_id) || empty($request->user_id)) { throw new Exception('You must log in to comment'); } $user_mapper = new UserMapper($db, $request); @@ -104,7 +117,7 @@ public function createComment(Request $request, PDO $db) $request->getClientIP(), $request->getClientUserAgent() ); - if (! $isValid) { + if (!$isValid) { throw new Exception("Comment failed spam check", 400); } } @@ -144,18 +157,18 @@ public function createComment(Request $request, PDO $db) public function reportComment(Request $request, PDO $db) { // must be logged in to report a comment - if (! isset($request->user_id) || empty($request->user_id)) { + if (!isset($request->user_id) || empty($request->user_id)) { throw new Exception('You must log in to report a comment', 401); } $comment_mapper = new EventCommentMapper($db, $request); - $commentId = $this->getItemId($request); + $commentId = $this->getItemId($request); $commentInfo = $comment_mapper->getCommentInfo($commentId); if (false === $commentInfo) { throw new Exception('Comment not found', 404); } - + $eventId = $commentInfo['event_id']; $comment_mapper->userReportedComment($commentId, $request->user_id); @@ -187,27 +200,27 @@ public function reportComment(Request $request, PDO $db) * means that the comment is viewable again. * * @param Request $request the request - * @param PDO $db the database adapter + * @param PDO $db the database adapter * * @throws Exception */ public function moderateReportedComment(Request $request, PDO $db) { // must be logged in - if (! isset($request->user_id) || empty($request->user_id)) { + if (!isset($request->user_id) || empty($request->user_id)) { throw new Exception('You must log in to moderate a comment', 401); } $comment_mapper = new EventCommentMapper($db, $request); - $commentId = $this->getItemId($request); + $commentId = $this->getItemId($request); $commentInfo = $comment_mapper->getCommentInfo($commentId); if (false === $commentInfo) { throw new Exception('Comment not found', 404); } $event_mapper = new EventMapper($db, $request); - $event_id = $commentInfo['event_id']; + $event_id = $commentInfo['event_id']; if (false == $event_mapper->thisUserHasAdminOn($event_id)) { throw new Exception("You don't have permission to do that", 403); } @@ -219,7 +232,7 @@ public function moderateReportedComment(Request $request, PDO $db) $comment_mapper->moderateReportedComment($decision, $commentId, $request->user_id); - $uri = $request->base . '/' . $request->version . '/events/' . $event_id . "/comments"; + $uri = $request->base . '/' . $request->version . '/events/' . $event_id . "/comments"; $view = $request->getView(); $view->setHeader('Location', $uri); diff --git a/src/controllers/Event_hostsController.php b/src/Controller/EventHostsController.php similarity index 89% rename from src/controllers/Event_hostsController.php rename to src/Controller/EventHostsController.php index c8bc50ddf..49b1977c2 100644 --- a/src/controllers/Event_hostsController.php +++ b/src/Controller/EventHostsController.php @@ -1,6 +1,15 @@ getResultsPerPage($request); $mapper = $this->getEventHostMapper($request, $db); - if (! $event_id) { + if (!$event_id) { throw new Exception('Event not found', 404); } @@ -55,14 +64,14 @@ public function listHosts(Request $request, PDO $db) */ public function addHost(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to create data", 401); } $event_id = $this->getItemId($request); $eventMapper = $this->getEventMapper($request, $db); - $event = $eventMapper->getEventById($event_id); + $event = $eventMapper->getEventById($event_id); if (false === $event) { throw new Exception('Event not found', 404); } @@ -71,13 +80,13 @@ public function addHost(Request $request, PDO $db) if (!$isAdmin) { throw new Exception("You do not have permission to add hosts to this event", 403); } - $username = filter_var( + $username = filter_var( $request->getParameter('host_name'), FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES ); $userMapper = $this->getUserMapper($request, $db); - $user_id = $userMapper->getUserIdFromUsername($username); + $user_id = $userMapper->getUserIdFromUsername($username); if (false === $user_id) { throw new Exception('No User found', 404); } @@ -112,7 +121,7 @@ public function addHost(Request $request, PDO $db) */ public function removeHostFromEvent(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to remove data", 401); } @@ -124,7 +133,7 @@ public function removeHostFromEvent(Request $request, PDO $db) $event_id = $this->getItemId($request); $eventMapper = $this->getEventMapper($request, $db); - $event = $eventMapper->getEventById($event_id); + $event = $eventMapper->getEventById($event_id); if (false === $event) { throw new Exception('Event not found', 404); } @@ -135,7 +144,7 @@ public function removeHostFromEvent(Request $request, PDO $db) } $userMapper = $this->getUserMapper($request, $db); - $user = $userMapper->getUserById($user_id); + $user = $userMapper->getUserById($user_id); if (false === $user) { throw new Exception('No User found', 404); } diff --git a/src/controllers/EventImagesController.php b/src/Controller/EventImagesController.php similarity index 85% rename from src/controllers/EventImagesController.php rename to src/Controller/EventImagesController.php index 34124621f..04b82d6b9 100644 --- a/src/controllers/EventImagesController.php +++ b/src/Controller/EventImagesController.php @@ -1,10 +1,17 @@ user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to create data", 401); } @@ -54,12 +61,12 @@ public function createImage(Request $request, PDO $db) } // save the file - overwrite current one if there is one - $extensions[IMAGETYPE_GIF] = '.gif'; + $extensions[IMAGETYPE_GIF] = '.gif'; $extensions[IMAGETYPE_JPEG] = '.jpg'; - $extensions[IMAGETYPE_PNG] = '.png'; - $saved_filename = 'icon-' . $event_id . '-orig' . $extensions[$filetype]; - $event_image_path = $request->getConfigValue('event_image_path'); - $result = move_uploaded_file($uploaded_name, $event_image_path . $saved_filename); + $extensions[IMAGETYPE_PNG] = '.png'; + $saved_filename = 'icon-' . $event_id . '-orig' . $extensions[$filetype]; + $event_image_path = $request->getConfigValue('event_image_path'); + $result = move_uploaded_file($uploaded_name, $event_image_path . $saved_filename); if (false === $result) { throw new Exception("The file could not be saved"); @@ -73,7 +80,7 @@ public function createImage(Request $request, PDO $db) $orig_image = imagecreatefromstring(file_get_contents($event_image_path . $saved_filename)); imagealphablending($orig_image, false); imagesavealpha($orig_image, true); - $small_width = 140; + $small_width = 140; $small_height = 140; $small_image = imagecreatetruecolor($small_width, $small_height); @@ -102,11 +109,11 @@ public function createImage(Request $request, PDO $db) public function deleteImage(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to create data", 401); } - $event_id = $this->getItemId($request); + $event_id = $this->getItemId($request); $event_mapper = new EventMapper($db, $request); $event_mapper->removeImages($event_id); diff --git a/src/controllers/EventsController.php b/src/Controller/EventsController.php similarity index 91% rename from src/controllers/EventsController.php rename to src/Controller/EventsController.php index 798dbc571..d591b6274 100644 --- a/src/controllers/EventsController.php +++ b/src/Controller/EventsController.php @@ -1,5 +1,24 @@ url_elements[4]) { case 'talks': $talk_mapper = new TalkMapper($db, $request); - $talks = $talk_mapper->getTalksByEventId($event_id, $resultsperpage, $start); - $list = $talks->getOutputView($request, $verbose); + $talks = $talk_mapper->getTalksByEventId($event_id, $resultsperpage, $start); + $list = $talks->getOutputView($request, $verbose); break; case 'comments': $event_comment_mapper = new EventCommentMapper($db, $request); @@ -76,12 +95,12 @@ public function getAction(Request $request, PDO $db) // for pending events we need a logged in user with the correct permissions if ($params["filter"] == 'pending') { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to view pending events", 400); } $user_mapper = new UserMapper($db, $request); $canApproveEvents = $user_mapper->isSiteAdmin($request->user_id); - if (! $canApproveEvents) { + if (!$canApproveEvents) { throw new Exception("You don't have permission to view pending events", 403); } } @@ -146,7 +165,7 @@ public function getAction(Request $request, PDO $db) public function postAction(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to create data", 401); } if (isset($request->url_elements[4])) { @@ -161,6 +180,7 @@ public function postAction(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Location', $request->base . $request->path_info); $view->setResponseCode(201); + return; default: @@ -202,7 +222,7 @@ public function postAction(Request $request, PDO $db) $start_date = strtotime($request->getParameter("start_date")); $end_date = strtotime($request->getParameter("end_date")); - if (! $start_date || ! $end_date) { + if (!$start_date || ! $end_date) { $errors[] = "Both 'start_date' and 'end_date' must be supplied in a recognised format"; } elseif ($start_date > $end_date) { $errors[] = "The event start date must be before its end date"; @@ -228,14 +248,14 @@ public function postAction(Request $request, PDO $db) $event['end_date'] = $end_date->format('U'); } catch (Exception $e) { // the time zone isn't right - $errors[] = "The fields 'tz_continent' and 'tz_place' must be supplied and valid ". + $errors[] = "The fields 'tz_continent' and 'tz_place' must be supplied and valid " . "(e.g. Europe and London)"; } } // optional fields - only check if we have no errors as we may need // access to $tz. - if (! $errors) { + if (!$errors) { $href = filter_var($request->getParameter("href"), FILTER_VALIDATE_URL); if ($href) { $event['href'] = $href; @@ -297,7 +317,7 @@ function ($tag) { $current_pending = $event_mapper->getPendingEventsCountByUser($request->user_id); if ($current_pending >= $max_pending_events) { - $suffix = $max_pending_events == 1 ? '' : 's'; + $suffix = $max_pending_events == 1 ? '' : 's'; $errors[] = sprintf('You may only have %d pending event%s at one time', $max_pending_events, $suffix); } @@ -305,7 +325,7 @@ function ($tag) { if ($errors) { throw new Exception(implode(". ", $errors), 400); } else { - $user_mapper = new UserMapper($db, $request); + $user_mapper = new UserMapper($db, $request); $event_owner = $user_mapper->getUserById($request->user_id); $event['contact_name'] = $event_owner['users'][0]['full_name']; @@ -315,7 +335,7 @@ function ($tag) { * then approve the event straight away */ $approveEventOnCreation = $user_mapper->isSiteAdmin($request->user_id) - || $user_mapper->isTrusted($request->user_id); + || $user_mapper->isTrusted($request->user_id); // Do we want to automatically approve when testing? if (isset($this->config['features']['allow_auto_approve_events']) @@ -352,13 +372,14 @@ function ($tag) { } // Send an email if we didn't auto-approve - if (! $user_mapper->isSiteAdmin($request->user_id)) { + if (!$user_mapper->isSiteAdmin($request->user_id)) { $event = $event_mapper->getPendingEventById($event_id); $count = $event_mapper->getPendingEventsCount(); $recipients = $user_mapper->getSiteAdminEmails(); $emailService = new EventSubmissionEmailService($this->config, $recipients, $event, $count); $emailService->sendEmail(); } + return; } } @@ -366,7 +387,7 @@ function ($tag) { public function deleteAction(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to delete data", 401); } if (isset($request->url_elements[4])) { @@ -379,6 +400,7 @@ public function deleteAction(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Location', $request->base . $request->path_info); $view->setResponseCode(200); + return; break; @@ -392,16 +414,16 @@ public function deleteAction(Request $request, PDO $db) public function putAction(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception('You must be logged in to edit data', 401); } $event_id = $this->getItemId($request); - if (! isset($request->url_elements[4])) { + if (!isset($request->url_elements[4])) { // Edit an Event $event_mapper = new EventMapper($db, $request); $existing_event = $event_mapper->getEventById($event_id, true); - if (! $existing_event) { + if (!$existing_event) { throw new Exception(sprintf( 'There is no event with ID "%s"', $event_id @@ -445,7 +467,7 @@ public function putAction(Request $request, PDO $db) $start_date = strtotime($request->getParameter("start_date")); $end_date = strtotime($request->getParameter("end_date")); - if (! $start_date || ! $end_date) { + if (!$start_date || ! $end_date) { $errors[] = "Both 'start_date' and 'end_date' must be supplied in a recognised format"; } elseif ($start_date > $end_date) { $errors[] = "The event start date must be before its end date"; @@ -470,7 +492,7 @@ public function putAction(Request $request, PDO $db) $event['end_date'] = $end_date->format('U'); } catch (Exception $e) { // the time zone isn't right - $errors[] = "The fields 'tz_continent' and 'tz_place' must be supplied and valid ". + $errors[] = "The fields 'tz_continent' and 'tz_place' must be supplied and valid " . "(e.g. Europe and London)"; } } @@ -493,13 +515,13 @@ public function putAction(Request $request, PDO $db) } $event['cfp_start_date'] = null; - $cfp_start_date = $request->getParameter("cfp_start_date", false); + $cfp_start_date = $request->getParameter("cfp_start_date", false); if (false !== $cfp_start_date && strtotime($cfp_start_date)) { $cfp_start_date = new DateTime($cfp_start_date, $tz); $event['cfp_start_date'] = $cfp_start_date->format('U'); } $event['cfp_end_date'] = null; - $cfp_end_date = $request->getParameter("cfp_end_date", false); + $cfp_end_date = $request->getParameter("cfp_end_date", false); if (false !== $cfp_end_date && strtotime($cfp_end_date)) { $cfp_end_date = new DateTime($cfp_end_date, $tz); $event['cfp_end_date'] = $cfp_end_date->format('U'); @@ -538,6 +560,7 @@ function ($tag) { $view = $request->getView(); $view->setHeader('Location', $request->base . $request->path_info); $view->setResponseCode(204); + return; } } @@ -545,15 +568,15 @@ function ($tag) { public function pendingClaims(Request $request, PDO $db) { // Check for login - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to view pending claims", 401); } - $event_id = $this->getItemId($request); + $event_id = $this->getItemId($request); $event_mapper = $this->getEventMapper($db, $request); $pending_talk_claim_mapper = $this->getPendingTalkClaimMapper($db, $request); - if (! $event_mapper->thisUserHasAdminOn($event_id)) { + if (!$event_mapper->thisUserHasAdminOn($event_id)) { throw new Exception('You do not have permission to edit this track', 403); } @@ -563,6 +586,7 @@ public function pendingClaims(Request $request, PDO $db) if (!$list = $pending_talk_claim_mapper->getPendingClaimsByEventId($event_id)) { $list = new PendingTalkClaimModelCollection([], 0); } + return $list->getOutputView($request, $verbose); } @@ -570,7 +594,7 @@ public function pendingClaims(Request $request, PDO $db) * Create track * * @param Request $request - * @param PDO $db + * @param PDO $db * * @throws Exception * @return void @@ -578,13 +602,13 @@ public function pendingClaims(Request $request, PDO $db) public function createTrack(Request $request, PDO $db) { // Check for login - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to create a track", 401); } - $track = array(); - $event_id = $this->getItemId($request); - $track['event_id']= $event_id; + $track = array(); + $event_id = $this->getItemId($request); + $track['event_id'] = $event_id; if (empty($track['event_id'])) { throw new Exception( "POST expects a track representation sent to a specific event URL", @@ -593,7 +617,7 @@ public function createTrack(Request $request, PDO $db) } $event_mapper = new EventMapper($db, $request); - $events = $event_mapper->getEventById($event_id, true); + $events = $event_mapper->getEventById($event_id, true); if (!$events || $events['meta']['count'] == 0) { throw new Exception("Associated event not found", 404); } @@ -602,7 +626,7 @@ public function createTrack(Request $request, PDO $db) } // validate fields - $errors = []; + $errors = []; $track['track_name'] = filter_var( $request->getParameter("track_name"), FILTER_SANITIZE_STRING, @@ -624,9 +648,9 @@ public function createTrack(Request $request, PDO $db) } $track_mapper = new TrackMapper($db, $request); - $track_id = $track_mapper->createEventTrack($track, $event_id); + $track_id = $track_mapper->createEventTrack($track, $event_id); - $uri = $request->base . '/' . $request->version . '/tracks/' . $track_id; + $uri = $request->base . '/' . $request->version . '/tracks/' . $track_id; $view = $request->getView(); $view->setHeader('Location', $uri); @@ -640,26 +664,26 @@ public function createTrack(Request $request, PDO $db) * endpoint is all that's needed to approve an pending event * * @param Request $request - * @param PDO $db + * @param PDO $db * * @throws Exception * @return void */ public function approveAction(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to create data", 401); } $event_id = $this->getItemId($request); $event_mapper = new EventMapper($db, $request); - if (! $event_mapper->thisUserCanApproveEvents()) { + if (!$event_mapper->thisUserCanApproveEvents()) { throw new Exception("You are not allowed to approve this event", 403); } $result = $event_mapper->approve($event_id, $request->user_id); - if (! $result) { + if (!$result) { throw new Exception("This event cannot be approved", 400); } @@ -682,26 +706,26 @@ public function approveAction(Request $request, PDO $db) * Reject a pending event by DELETEing to /events/{id}/approval * * @param Request $request - * @param PDO $db + * @param PDO $db * * @throws Exception * @return void */ public function rejectAction(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to create data", 401); } $event_id = $this->getItemId($request); $event_mapper = new EventMapper($db, $request); - if (! $event_mapper->thisUserCanApproveEvents()) { + if (!$event_mapper->thisUserCanApproveEvents()) { throw new Exception("You are not allowed to reject this event", 403); } $result = $event_mapper->reject($event_id, $request->user_id); - if (! $result) { + if (!$result) { throw new Exception("This event cannot be rejected", 400); } @@ -718,7 +742,7 @@ public function setEventMapper(EventMapper $event_mapper) public function getEventMapper(PDO $db, Request $request) { - if (! isset($this->event_mapper)) { + if (!isset($this->event_mapper)) { $this->event_mapper = new EventMapper($db, $request); } @@ -732,7 +756,7 @@ public function setPendingTalkClaimMapper(PendingTalkClaimMapper $pending_talk_c public function getPendingTalkClaimMapper(PDO $db, Request $request) { - if (! isset($this->pending_talk_claim_mapper)) { + if (!isset($this->pending_talk_claim_mapper)) { $this->pending_talk_claim_mapper = new PendingTalkClaimMapper($db, $request); } diff --git a/src/controllers/FacebookController.php b/src/Controller/FacebookController.php similarity index 76% rename from src/controllers/FacebookController.php rename to src/Controller/FacebookController.php index 34130d468..93a80cebe 100644 --- a/src/controllers/FacebookController.php +++ b/src/Controller/FacebookController.php @@ -4,7 +4,12 @@ * Facebook-specific endpoints live here */ +namespace Joindin\Api\Controller; + +use Exception; use GuzzleHttp\Client; +use PDO; +use Joindin\Api\Request; class FacebookController extends BaseApiController { @@ -17,7 +22,7 @@ class FacebookController extends BaseApiController * the same format as we do when logging in a user * * @param Request $request - * @param PDO $db + * @param PDO $db * * @throws Exception * @return array @@ -29,8 +34,8 @@ public function logUserIn(Request $request, PDO $db) throw new Exception("Cannot login via Facebook", 501); } - $clientId = $request->getParameter('client_id'); - $clientSecret = $request->getParameter('client_secret'); + $clientId = $request->getParameter('client_id'); + $clientSecret = $request->getParameter('client_secret'); $this->oauthModel = $request->getOauthModel($db); if (!$this->oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { throw new Exception("This client cannot perform this action", 403); @@ -48,22 +53,22 @@ public function logUserIn(Request $request, PDO $db) $res = $client->get('https://graph.facebook.com/v2.10/oauth/access_token', [ 'query' => [ - 'client_id' => $this->config['facebook']['app_id'], - 'redirect_uri' => $this->config['website_url'] . '/user/facebook-access', + 'client_id' => $this->config['facebook']['app_id'], + 'redirect_uri' => $this->config['website_url'] . '/user/facebook-access', 'client_secret' => $this->config['facebook']['app_secret'], - 'code' => $code, + 'code' => $code, ] ]); if ($res->getStatusCode() == 200) { - $data = json_decode((string)$res->getBody(), true); + $data = json_decode((string)$res->getBody(), true); $access_token = $data['access_token']; // retrieve email address from Facebook profile $res = $client->get('https://graph.facebook.com/me', [ 'query' => [ 'access_token' => $access_token, - 'fields' => 'name,email', + 'fields' => 'name,email', ] ]); if ($res->getStatusCode() == 200) { @@ -71,10 +76,10 @@ public function logUserIn(Request $request, PDO $db) if (!array_key_exists('email', $data)) { throw new Exception("Email address is unavailable", 403); } - $email = $data['email']; + $email = $data['email']; $fullName = $data['name']; - $id = $data['id']; - + $id = $data['id']; + $result = $this->oauthModel->createAccessTokenFromTrustedEmail( $clientId, $email, @@ -90,8 +95,14 @@ public function logUserIn(Request $request, PDO $db) throw new Exception("Could not sign in with Facebook", 403); } - trigger_error('Unexpected Facebook error (' . $res->getStatusCode() - . ': ' . $res->getBody() . ')', E_USER_WARNING); + trigger_error( + sprintf( + 'Unexpected Facebook error (%s: %s)', + $res->getStatusCode(), + $res->getBody() + ), + E_USER_WARNING + ); throw new Exception("Unexpected Facebook error", 500); } } diff --git a/src/controllers/LanguagesController.php b/src/Controller/LanguagesController.php similarity index 90% rename from src/controllers/LanguagesController.php rename to src/Controller/LanguagesController.php index 5728c76e5..9eb91b0c9 100644 --- a/src/controllers/LanguagesController.php +++ b/src/Controller/LanguagesController.php @@ -1,5 +1,12 @@ getResultsPerPage($request); $mapper = new LanguageMapper($db, $request); + return $mapper->getLanguageList($resultsperpage, $start, $verbose); } } diff --git a/src/controllers/Talk_commentsController.php b/src/Controller/TalkCommentsController.php similarity index 86% rename from src/controllers/Talk_commentsController.php rename to src/Controller/TalkCommentsController.php index 08fc18628..39640014d 100644 --- a/src/controllers/Talk_commentsController.php +++ b/src/Controller/TalkCommentsController.php @@ -1,7 +1,17 @@ user_id) || empty($request->user_id)) { + if (!isset($request->user_id) || empty($request->user_id)) { throw new Exception("You must log in to do that", 401); } if ($event_mapper->thisUserHasAdminOn($event_id)) { $list = $comment_mapper->getReportedCommentsByEventId($event_id); + return $list->getOutputView($request); } else { throw new Exception("You don't have permission to do that", 403); @@ -54,7 +65,7 @@ public function getReported(Request $request, PDO $db) public function reportComment(Request $request, PDO $db) { // must be logged in to report a comment - if (! isset($request->user_id) || empty($request->user_id)) { + if (!isset($request->user_id) || empty($request->user_id)) { throw new Exception('You must log in to report a comment', 401); } @@ -98,27 +109,27 @@ public function reportComment(Request $request, PDO $db) * means that the comment is viewable again. * * @param Request $request the request - * @param PDO $db the database adapter + * @param PDO $db the database adapter * * @throws Exception */ public function moderateReportedComment(Request $request, PDO $db) { // must be logged in - if (! isset($request->user_id) || empty($request->user_id)) { + if (!isset($request->user_id) || empty($request->user_id)) { throw new Exception('You must log in to moderate a comment', 401); } $comment_mapper = new TalkCommentMapper($db, $request); - $commentId = $this->getItemId($request); + $commentId = $this->getItemId($request); $commentInfo = $comment_mapper->getCommentInfo($commentId); if (false === $commentInfo) { throw new Exception('Comment not found', 404); } $event_mapper = new EventMapper($db, $request); - $event_id = $commentInfo['event_id']; + $event_id = $commentInfo['event_id']; if (false == $event_mapper->thisUserHasAdminOn($event_id)) { throw new Exception("You don't have permission to do that", 403); } @@ -130,8 +141,8 @@ public function moderateReportedComment(Request $request, PDO $db) $comment_mapper->moderateReportedComment($decision, $commentId, $request->user_id); - $talk_id = $commentInfo['talk_id']; - $uri = $request->base . '/' . $request->version . '/talks/' . $talk_id . "/comments"; + $talk_id = $commentInfo['talk_id']; + $uri = $request->base . '/' . $request->version . '/talks/' . $talk_id . "/comments"; $view = $request->getView(); $view->setHeader('Location', $uri); @@ -150,9 +161,9 @@ public function updateComment(Request $request, PDO $db) throw new Exception('The field "comment" is required', 400); } - $comment_id = $this->getItemId($request); + $comment_id = $this->getItemId($request); $comment_mapper = new TalkCommentMapper($db, $request); - $comment = $comment_mapper->getRawComment($comment_id); + $comment = $comment_mapper->getRawComment($comment_id); if (false === $comment) { throw new Exception('Comment not found', 404); diff --git a/src/controllers/TalkLinkController.php b/src/Controller/TalkLinkController.php similarity index 75% rename from src/controllers/TalkLinkController.php rename to src/Controller/TalkLinkController.php index 1f4d24885..e789bf914 100644 --- a/src/controllers/TalkLinkController.php +++ b/src/Controller/TalkLinkController.php @@ -1,21 +1,29 @@ getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; $talk_mapper = $this->getTalkMapper($db, $request); + return ['talk_links' => ($talk_mapper->getTalkMediaLinks($talk_id))]; } public function getTalkLink(Request $request, PDO $db) { - $talk = $this->getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; $talk_mapper = $this->getTalkMapper($db, $request); - $links = $talk_mapper->getTalkMediaLinks($talk_id, $request->url_elements[5]); + $links = $talk_mapper->getTalkMediaLinks($talk_id, $request->url_elements[5]); if (count($links) !== 1) { throw new Exception( @@ -29,15 +37,15 @@ public function getTalkLink(Request $request, PDO $db) public function updateTalkLink(Request $request, PDO $db) { - $talk = $this->getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; $talk_mapper = $this->getTalkMapper($db, $request); $this->checkAdminOrSpeaker($request, $talk_mapper, $talk_id); - $link_id = $request->url_elements[5]; + $link_id = $request->url_elements[5]; $display_name = $request->getParameter('display_name'); - $url = $request->getParameter('url'); + $url = $request->getParameter('url'); if (!$talk_mapper->updateTalkLink($talk_id, $link_id, $display_name, $url)) { throw new Exception( @@ -53,8 +61,8 @@ public function updateTalkLink(Request $request, PDO $db) public function removeTalkLink(Request $request, PDO $db) { - $talk = $this->getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; $talk_mapper = $this->getTalkMapper($db, $request); $this->checkAdminOrSpeaker($request, $talk_mapper, $talk_id); @@ -73,15 +81,15 @@ public function removeTalkLink(Request $request, PDO $db) public function addTalkLink(Request $request, PDO $db) { - $talk = $this->getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; $talk_mapper = $this->getTalkMapper($db, $request); $this->checkAdminOrSpeaker($request, $talk_mapper, $talk_id); //Check the content is in the correct format $display_name = $request->getParameter('display_name'); - $url = $request->getParameter('url'); - if (!$display_name || !$url) { + $url = $request->getParameter('url'); + if (!$display_name || ! $url) { throw new Exception( "Missing required fields URL OR Display Name", 400 @@ -97,19 +105,20 @@ public function addTalkLink(Request $request, PDO $db) } $this->sucessfullyAltered($request, $talk_id, $link_id); + return true; } /** - * @param Request $request + * @param Request $request * @param TalkMapper $mapper - * @param int $talk_id + * @param int $talk_id * * @throws Exception */ protected function checkAdminOrSpeaker(Request $request, TalkMapper $mapper, $talk_id) { - $is_admin = $mapper->thisUserHasAdminOn($talk_id); + $is_admin = $mapper->thisUserHasAdminOn($talk_id); $is_speaker = $mapper->isUserASpeakerOnTalk($talk_id, $request->user_id); if (!($is_admin || $is_speaker)) { throw new Exception( @@ -121,8 +130,8 @@ protected function checkAdminOrSpeaker(Request $request, TalkMapper $mapper, $ta /** * @param Request $request - * @param int $talk_id - * @param int $link_id + * @param int $talk_id + * @param int $link_id */ protected function sucessfullyAltered(Request $request, $talk_id, $link_id) { diff --git a/src/controllers/TalkTypesController.php b/src/Controller/TalkTypesController.php similarity index 80% rename from src/controllers/TalkTypesController.php rename to src/Controller/TalkTypesController.php index 7ac0a7ea4..59c6eb492 100644 --- a/src/controllers/TalkTypesController.php +++ b/src/Controller/TalkTypesController.php @@ -1,4 +1,12 @@ getVerbosity($request); // pagination settings - $start = $this->getStart($request); + $start = $this->getStart($request); $resultsperpage = $this->getResultsPerPage($request); $mapper = new TalkTypeMapper($db, $request); @@ -22,11 +30,12 @@ public function getTalkType(Request $request, PDO $db) $verbose = $this->getVerbosity($request); $mapper = new TalkTypeMapper($db, $request); - $list = $mapper->getTalkTypeById($talk_type_id, $verbose); + $list = $mapper->getTalkTypeById($talk_type_id, $verbose); if (count($list['talk_types']) == 0) { throw new Exception('Talk type not found', 404); } + return $list; } } diff --git a/src/controllers/TalksController.php b/src/Controller/TalksController.php similarity index 86% rename from src/controllers/TalksController.php rename to src/Controller/TalksController.php index f8c17cdc5..c4ef8fa97 100644 --- a/src/controllers/TalksController.php +++ b/src/Controller/TalksController.php @@ -1,5 +1,26 @@ getVerbosity($request); - $talk = $this->getTalkById($request, $db, $talk_id, $verbose); + $talk = $this->getTalkById($request, $db, $talk_id, $verbose); $collection = new TalkModelCollection([$talk], 1); return $collection->getOutputView($request, $verbose); @@ -34,7 +55,7 @@ public function getTalkStarred(Request $request, PDO $db) { $this->setDbAndRequest($db, $request); $talk_id = $this->getItemId($request); - $mapper = $this->getMapper('talk'); + $mapper = $this->getMapper('talk'); return $mapper->getUserStarred($talk_id, $this->request->user_id); } @@ -59,7 +80,7 @@ public function getTalkByKeyWord(Request $request, PDO $db) $resultsperpage = $this->getResultsPerPage($this->request); $mapper = $this->getMapper('talk'); - $talks = $mapper->getTalksByTitleSearch($keyword, $resultsperpage, $start); + $talks = $mapper->getTalksByTitleSearch($keyword, $resultsperpage, $start); return $talks->getOutputView($this->request, $verbose); } @@ -113,7 +134,7 @@ public function postAction(Request $request, PDO $db) $request->getClientIP(), $request->getClientUserAgent() ); - if (! $isValid) { + if (!$isValid) { throw new Exception("Comment failed spam check", 400); } } @@ -153,6 +174,7 @@ public function postAction(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Location', $uri); $view->setResponseCode(201); + return; } else { throw new Exception("The comment could not be stored", 400); @@ -167,6 +189,7 @@ public function postAction(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Location', $request->base . $request->path_info); $view->setResponseCode(201); + return; default: throw new Exception("Operation not supported, sorry", 404); @@ -215,7 +238,7 @@ public function deleteTalk(Request $request, PDO $db) * Add a track to a talk by POSTing to /talks/123/tracks with the `track_uri` * in the body * - * @param PDO $db + * @param PDO $db * @param Request $request * * @throws Exception @@ -231,17 +254,17 @@ public function addTrackToTalk(Request $request, PDO $db) } $talk_mapper = new TalkMapper($db, $request); - $talk = $this->getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; - $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); + $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); $is_speaker = $talk_mapper->isUserASpeakerOnTalk($talk_id, $request->user_id); if (!($is_admin || $is_speaker)) { throw new Exception("You do not have permission to add this talk to a track", 400); } $track_uri = $request->getParameter("track_uri"); - $pattern ='@/' . $request->version . '/tracks/([\d]+)$@'; + $pattern = '@/' . $request->version . '/tracks/([\d]+)$@'; if (!preg_match($pattern, $track_uri, $matches)) { throw new Exception('Invalid track_uri', 400); } @@ -250,7 +273,7 @@ public function addTrackToTalk(Request $request, PDO $db) // is this track on this event? $event_mapper = new EventMapper($db, $request); $track_events = $event_mapper->getEventByTrackId($track_id, true, false, false); - if (!$track_events || !$track_events[0]['ID']) { + if (!$track_events || ! $track_events[0]['ID']) { throw new Exception("Associated event not found", 400); } $track_event_id = $track_events[0]['ID']; @@ -271,7 +294,7 @@ public function addTrackToTalk(Request $request, PDO $db) /** * Remove a track from a talk by DELETEing to /talks/123/tracks/456 * - * @param PDO $db + * @param PDO $db * @param Request $request * * @throws Exception @@ -289,10 +312,10 @@ public function removeTrackFromTalk(Request $request, PDO $db) $track_id = $request->url_elements[5]; $talk_mapper = new TalkMapper($db, $request); - $talk = $this->getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; - $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); + $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); $is_speaker = $talk_mapper->isUserASpeakerOnTalk($talk_id, $request->user_id); if (!($is_admin || $is_speaker)) { throw new Exception("You do not have permission to remove this talk from this track", 400); @@ -301,7 +324,7 @@ public function removeTrackFromTalk(Request $request, PDO $db) // is this track on this event? $event_mapper = new EventMapper($db, $request); $track_events = $event_mapper->getEventByTrackId($track_id, true, false, false); - if (!$track_events || !$track_events[0]['ID']) { + if (!$track_events || ! $track_events[0]['ID']) { throw new Exception("Associated event not found", 400); } $track_event_id = $track_events[0]['ID']; @@ -343,7 +366,7 @@ public function createTalkAction(Request $request, PDO $db) } $event_mapper = new EventMapper($db, $request); - $talk_mapper = new TalkMapper($db, $request); + $talk_mapper = new TalkMapper($db, $request); $is_admin = $event_mapper->thisUserHasAdminOn($event_id); if (!$is_admin) { @@ -351,7 +374,7 @@ public function createTalkAction(Request $request, PDO $db) } // retrieve the talk data from the request - $talk = $this->getTalkDataFromRequest($db, $request, $event_id); + $talk = $this->getTalkDataFromRequest($db, $request, $event_id); $talk['event_id'] = $event_id; // create the talk @@ -372,7 +395,7 @@ public function createTalkAction(Request $request, PDO $db) $request->getView()->setResponseCode(201); $request->getView()->setHeader('Location', $uri); - $new_talk = $this->getTalkById($request, $db, $new_id); + $new_talk = $this->getTalkById($request, $db, $new_id); $collection = new TalkModelCollection([$new_talk], 1); return $collection->getOutputView($request); @@ -399,7 +422,7 @@ public function editTalk(Request $request, PDO $db) $talk = $this->getTalkById($request, $db); - $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); + $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); $is_speaker = $talk_mapper->isUserASpeakerOnTalk($talk_id, $request->user_id); if (!($is_admin || $is_speaker)) { throw new Exception("You do not have permission to update this talk", 403); @@ -433,7 +456,7 @@ protected function getTalkDataFromRequest(PDO $db, Request $request, $event_id) { // get the event so we can get the timezone info & it $event_mapper = new EventMapper($db, $request); - $list = $event_mapper->getEventById($event_id, true); + $list = $event_mapper->getEventById($event_id, true); if (count($list['events']) == 0) { throw new Exception('Event not found', 404); } @@ -464,8 +487,8 @@ protected function getTalkDataFromRequest(PDO $db, Request $request, $event_id) ); $talk_type_mapper = new TalkTypeMapper($db, $request); - $talk_types = $talk_type_mapper->getTalkTypesLookupList(); - if (! array_key_exists($talk['type'], $talk_types)) { + $talk_types = $talk_type_mapper->getTalkTypesLookupList(); + if (!array_key_exists($talk['type'], $talk_types)) { throw new Exception("The type '{$talk['type']}' is unknown", 400); } $talk['type_id'] = $talk_types[$talk['type']]; @@ -478,11 +501,11 @@ protected function getTalkDataFromRequest(PDO $db, Request $request, $event_id) if (empty($start_date)) { throw new Exception("Please give the date and time of the talk", 400); } - $tz = new DateTimeZone($event['tz_continent'] . '/' . $event['tz_place']); + $tz = new DateTimeZone($event['tz_continent'] . '/' . $event['tz_place']); $talk['date'] = (new DateTime($start_date, $tz))->format('U'); $event_start_date = (new DateTime($event['start_date']))->format('U'); - $event_end_date = (new DateTime($event['end_date']))->add(new DateInterval('P1D'))->format('U'); + $event_end_date = (new DateTime($event['end_date']))->add(new DateInterval('P1D'))->format('U'); if ($talk['date'] < $event_start_date || $talk['date'] >= $event_end_date) { throw new Exception("The talk must be held between the start and end date of the event", 400); } @@ -498,7 +521,7 @@ protected function getTalkDataFromRequest(PDO $db, Request $request, $event_id) } // When the language doesn't exist, the talk will not be found $language_mapper = new LanguageMapper($db, $request); - if (! $language_mapper->isLanguageValid($talk['language'])) { + if (!$language_mapper->isLanguageValid($talk['language'])) { throw new Exception("The language '{$talk['type']}' is unknown", 400); } @@ -519,9 +542,10 @@ protected function getTalkDataFromRequest(PDO $db, Request $request, $event_id) function ($speaker) { $speaker = filter_var($speaker, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); $speaker = trim($speaker); + return $speaker; }, - (array) $request->getParameter('speakers') + (array)$request->getParameter('speakers') ); return $talk; @@ -530,7 +554,8 @@ function ($speaker) { public function getSpeakersForTalk(Request $request, PDO $db) { $talk_id = $this->getItemId($request); - $talk = $this->getTalkById($request, $db, $talk_id); + $talk = $this->getTalkById($request, $db, $talk_id); + return $talk->speakers; } @@ -538,17 +563,17 @@ public function setSpeakerForTalk(Request $request, PDO $db) { $this->checkLoggedIn($request); - $talk = $this->getTalkById($request, $db); - $talk_id = $talk->ID; + $talk = $this->getTalkById($request, $db); + $talk_id = $talk->ID; $talk_mapper = $this->getTalkMapper($db, $request); - $event_id = $talk->event_id; + $event_id = $talk->event_id; $event_mapper = $this->getEventMapper($db, $request); - $event = $event_mapper->getEventById($event_id); + $event = $event_mapper->getEventById($event_id); - $user_id = $request->user_id; + $user_id = $request->user_id; $user_mapper = $this->getUserMapper($db, $request); - $user = $user_mapper->getUserById($user_id)['users'][0]; + $user = $user_mapper->getUserById($user_id)['users'][0]; $data = $this->getLinkUserDataFromRequest($request); @@ -570,13 +595,13 @@ public function setSpeakerForTalk(Request $request, PDO $db) } $speaker_id = $user_mapper->getUserIdFromUsername($data['username']); - if (! $speaker_id) { + if (!$speaker_id) { throw new Exception("Specified user not found", 404); } $speaker_name = $user_mapper->getUserById($speaker_id)['users'][0]['full_name']; $pending_talk_claim_mapper = $this->getPendingTalkClaimMapper($db, $request); - $claim_exists = $pending_talk_claim_mapper->claimExists($talk_id, $speaker_id, $claim['ID']); + $claim_exists = $pending_talk_claim_mapper->claimExists($talk_id, $speaker_id, $claim['ID']); if ($claim_exists === false) { //This is a new claim //Is the speaker this user? @@ -592,7 +617,7 @@ public function setSpeakerForTalk(Request $request, PDO $db) $pending_talk_claim_mapper->assignTalkAsHost($talk_id, $speaker_id, $claim['ID'], $user_id); //We need to send an email to the speaker asking for confirmation $recipients = [$user_mapper->getEmailByUserId($speaker_id)]; - $username = $data['username']; + $username = $data['username']; $emailService = new TalkAssignEmailService($this->config, $recipients, $event, $talk, $username); if (!defined('UNIT_TEST')) { $emailService->sendEmail(); @@ -603,8 +628,8 @@ public function setSpeakerForTalk(Request $request, PDO $db) } elseif ($claim_exists === PendingTalkClaimMapper::SPEAKER_CLAIM) { //The host needs to approve if ($talk_mapper->thisUserHasAdminOn($talk_id)) { - $method = $this->getRequestParameter($request, 'action', 'approve'); - $recipients = [$user_mapper->getEmailByUserId($speaker_id)]; + $method = $this->getRequestParameter($request, 'action', 'approve'); + $recipients = [$user_mapper->getEmailByUserId($speaker_id)]; $success = $pending_talk_claim_mapper->approveClaimAsHost($talk_id, $speaker_id, $claim['ID']) && $talk_mapper->assignTalkToSpeaker($talk_id, $claim['ID'], $speaker_id, $speaker_name); @@ -623,7 +648,7 @@ public function setSpeakerForTalk(Request $request, PDO $db) } else { if ($speaker_id == $request->getUserId()) { throw new Exception("You already have a pending claim for this talk. " . - "Please wait for an event admin to approve your claim.", 401); + "Please wait for an event admin to approve your claim.", 401); } throw new Exception("You must be an event admin to approve this claim", 401); } @@ -631,7 +656,7 @@ public function setSpeakerForTalk(Request $request, PDO $db) //The speaker needs to approve if ($data['username'] === $user['username']) { if ($pending_talk_claim_mapper->approveAssignmentAsSpeaker($talk_id, $user_id, $claim['ID'])) { - if (! $talk_mapper->assignTalkToSpeaker($talk_id, $claim['ID'], $speaker_id, $speaker_name)) { + if (!$talk_mapper->assignTalkToSpeaker($talk_id, $claim['ID'], $speaker_id, $speaker_name)) { throw new Exception("There was a problem assigning the talk", 500); } @@ -664,7 +689,7 @@ public function setPendingTalkClaimMapper(PendingTalkClaimMapper $pending_talk_c public function getPendingTalkClaimMapper(PDO $db, Request $request) { - if (! isset($this->pending_talk_claim_mapper)) { + if (!isset($this->pending_talk_claim_mapper)) { $this->pending_talk_claim_mapper = new PendingTalkClaimMapper($db, $request); } @@ -674,18 +699,18 @@ public function getPendingTalkClaimMapper(PDO $db, Request $request) public function removeApprovedSpeakerFromTalk(Request $request, PDO $db) { $this->checkLoggedIn($request); - $talk_id = $this->getItemId($request); + $talk_id = $this->getItemId($request); $speaker_id = $request->url_elements[5]; $talk_mapper = new TalkMapper($db, $request); - $talk = $this->getTalkById($request, $db, $talk_id); + $talk = $this->getTalkById($request, $db, $talk_id); $speaker = $talk_mapper->isUserASpeakerOnTalk($talk_id, $speaker_id); if (!$speaker) { throw new Exception("Provided user is not a speaker on this talk", 404); } - $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); + $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); $is_speaker = $talk_mapper->isUserASpeakerOnTalk($talk_id, $request->user_id); if (!($is_admin || $is_speaker)) { throw new Exception("You do not have permission to remove this speaker from this talk", 403); @@ -709,13 +734,13 @@ public function getTalkCommentEmailService($config, $recipients, $talk, $comment public function removeSpeakerForTalk(Request $request, PDO $db) { $this->checkLoggedIn($request); - $talk = $this->getTalkById($request, $db); + $talk = $this->getTalkById($request, $db); $talk_mapper = $this->getTalkMapper($db, $request); - $talk_id = $talk->ID; + $talk_id = $talk->ID; - $event_id = $talk->event_id; + $event_id = $talk->event_id; $event_mapper = $this->getEventMapper($db, $request); - $event = $event_mapper->getEventById($event_id); + $event = $event_mapper->getEventById($event_id); $is_admin = $talk_mapper->thisUserHasAdminOn($talk_id); if (!($is_admin)) { @@ -725,8 +750,8 @@ public function removeSpeakerForTalk(Request $request, PDO $db) $data = $this->getLinkUserDataFromRequest($request); $user_mapper = $this->getUserMapper($db, $request); - $speaker_id = $user_mapper->getUserIdFromUsername($data['username']); - if (! $speaker_id) { + $speaker_id = $user_mapper->getUserIdFromUsername($data['username']); + if (!$speaker_id) { throw new Exception("Specified user not found", 404); } @@ -745,13 +770,13 @@ public function removeSpeakerForTalk(Request $request, PDO $db) } $pending_talk_claim_mapper = $this->getPendingTalkClaimMapper($db, $request); - $claim_exists = $pending_talk_claim_mapper->claimExists($talk_id, $speaker_id, $claim['ID']); + $claim_exists = $pending_talk_claim_mapper->claimExists($talk_id, $speaker_id, $claim['ID']); if ($claim_exists !== PendingTalkClaimMapper::SPEAKER_CLAIM) { throw new Exception("There was a problem with the claim", 500); } - $method = $this->getRequestParameter($request, 'action', 'approve'); - $recipients = [$user_mapper->getEmailByUserId($speaker_id)]; + $method = $this->getRequestParameter($request, 'action', 'approve'); + $recipients = [$user_mapper->getEmailByUserId($speaker_id)]; $success = $pending_talk_claim_mapper->rejectClaimAsHost($talk_id, $speaker_id, $claim['ID']); diff --git a/src/controllers/TokenController.php b/src/Controller/TokenController.php similarity index 86% rename from src/controllers/TokenController.php rename to src/Controller/TokenController.php index 8d1d1a0f2..a6259b319 100644 --- a/src/controllers/TokenController.php +++ b/src/Controller/TokenController.php @@ -1,5 +1,12 @@ getParameter('client_id'); $clientSecret = $request->getParameter('client_secret'); - if (! $this->oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { + if (!$this->oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { throw new Exception("This client cannot authenticate using the password grant type", 403); } @@ -60,13 +67,13 @@ public function postAction(Request $request, PDO $db) public function listTokensForUser(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } $mapper = $this->getTokenMapper($db, $request); - if (! $mapper->tokenBelongsToTrustedApplication($request->getAccessToken())) { + if (!$mapper->tokenBelongsToTrustedApplication($request->getAccessToken())) { throw new Exception("You can not access the token list with this client", 403); } @@ -81,13 +88,13 @@ public function listTokensForUser(Request $request, PDO $db) public function getToken(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } $mapper = $this->getTokenMapper($db, $request); - if (! $mapper->tokenBelongsToTrustedApplication($request->getAccessToken())) { + if (!$mapper->tokenBelongsToTrustedApplication($request->getAccessToken())) { throw new Exception("You can not access the token list with this client", 403); } @@ -101,13 +108,13 @@ public function getToken(Request $request, PDO $db) public function revokeToken(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in", 401); } $tokenMapper = $this->getTokenMapper($db, $request); - if (! $tokenMapper->tokenBelongsToTrustedApplication($request->getAccessToken())) { + if (!$tokenMapper->tokenBelongsToTrustedApplication($request->getAccessToken())) { throw new Exception("You can not access the token list with this client", 403); } @@ -116,7 +123,7 @@ public function revokeToken(Request $request, PDO $db) $request->user_id ); - if (! $token->getTokens()) { + if (!$token->getTokens()) { throw new Exception('No tokens found', 404); } @@ -136,7 +143,7 @@ public function revokeToken(Request $request, PDO $db) private function getTokenMapper(PDO $db, Request $request) { - if (! $this->tokenMapper) { + if (!$this->tokenMapper) { $this->tokenMapper = new TokenMapper($db, $request); } diff --git a/src/controllers/TracksController.php b/src/Controller/TracksController.php similarity index 80% rename from src/controllers/TracksController.php rename to src/Controller/TracksController.php index d95d82bbc..b450a72e3 100644 --- a/src/controllers/TracksController.php +++ b/src/Controller/TracksController.php @@ -1,5 +1,13 @@ user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to edit this track", 401); } $track_id = $this->getItemId($request); $track_mapper = new TrackMapper($db, $request); - $tracks = $track_mapper->getTrackById($track_id, true); + $tracks = $track_mapper->getTrackById($track_id, true); if (!$tracks) { throw new Exception("Track not found", 404); } $event_mapper = new EventMapper($db, $request); - $events = $event_mapper->getEventByTrackId($track_id, true, false, false); - if (!$events || !$events[0]['ID']) { + $events = $event_mapper->getEventByTrackId($track_id, true, false, false); + if (!$events || ! $events[0]['ID']) { throw new Exception("Associated event not found", 404); } $event_id = $events[0]['ID']; @@ -49,7 +57,7 @@ public function editTrack(Request $request, PDO $db) } // validate fields - $errors = []; + $errors = []; $track['track_name'] = filter_var( $request->getParameter("track_name"), FILTER_SANITIZE_STRING, @@ -72,7 +80,7 @@ public function editTrack(Request $request, PDO $db) $track_mapper->editEventTrack($track, $track_id); - $uri = $request->base . '/' . $request->version . '/tracks/' . $track_id; + $uri = $request->base . '/' . $request->version . '/tracks/' . $track_id; $view = $request->getView(); $view->setHeader('Location', $uri); @@ -82,21 +90,21 @@ public function editTrack(Request $request, PDO $db) public function deleteTrack(Request $request, PDO $db) { // Check for login - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to delete this track", 401); } $track_id = $this->getItemId($request); $track_mapper = new TrackMapper($db, $request); - $tracks = $track_mapper->getTrackById($track_id, true); + $tracks = $track_mapper->getTrackById($track_id, true); if (!$tracks) { throw new Exception("Track not found", 404); } $event_mapper = new EventMapper($db, $request); - $events = $event_mapper->getEventByTrackId($track_id, true, false, false); - if (!$events || !$events[0]['ID']) { + $events = $event_mapper->getEventByTrackId($track_id, true, false, false); + if (!$events || ! $events[0]['ID']) { throw new Exception("Associated event not found", 404); } $event_id = $events[0]['ID']; diff --git a/src/controllers/TwitterController.php b/src/Controller/TwitterController.php similarity index 92% rename from src/controllers/TwitterController.php rename to src/Controller/TwitterController.php index d0a57b30b..d961f18f4 100644 --- a/src/controllers/TwitterController.php +++ b/src/Controller/TwitterController.php @@ -4,8 +4,14 @@ * Twitter-specific endpoints live here */ +namespace Joindin\Api\Controller; + +use Exception; use GuzzleHttp\Client; use GuzzleHttp\Subscriber\Oauth\Oauth1; +use Joindin\Api\Model\TwitterRequestTokenMapper; +use PDO; +use Joindin\Api\Request; class TwitterController extends BaseApiController { @@ -15,7 +21,7 @@ public function getRequestToken(Request $request, PDO $db) $clientId = $request->getParameter('client_id'); $clientSecret = $request->getParameter('client_secret'); $this->oauthModel = $request->getOauthModel($db); - if (! $this->oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { + if (!$this->oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { throw new Exception("This client cannot perform this action", 403); } @@ -56,7 +62,7 @@ public function getRequestToken(Request $request, PDO $db) * new access token and return the same format as we do when logging in a user * * @param Request $request - * @param PDO $db + * @param PDO $db * * @throws Exception * @return array @@ -66,7 +72,7 @@ public function logUserIn(Request $request, PDO $db) $clientId = $request->getParameter('client_id'); $clientSecret = $request->getParameter('client_secret'); $this->oauthModel = $request->getOauthModel($db); - if (! $this->oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { + if (!$this->oauthModel->isClientPermittedPasswordGrant($clientId, $clientSecret)) { throw new Exception("This client cannot perform this action", 403); } @@ -101,7 +107,7 @@ public function logUserIn(Request $request, PDO $db) $twitterUsername = $data['screen_name']; $result = $this->oauthModel->createAccessTokenFromTwitterUsername($clientId, $twitterUsername); - if (! $result) { + if (!$result) { // try to create the user. $stack1 = \GuzzleHttp\HandlerStack::create(); $oauth1 = new Oauth1([ @@ -128,11 +134,11 @@ public function logUserIn(Request $request, PDO $db) } } - if (! $result) { + if (!$result) { throw new Exception("Could not sign in with Twitter", 403); } - // clean up request token data + // clean up request token data $requestTokenMapper = new TwitterRequestTokenMapper($db); $requestTokenMapper->delete($request_token); diff --git a/src/controllers/UsersController.php b/src/Controller/UsersController.php similarity index 94% rename from src/controllers/UsersController.php rename to src/Controller/UsersController.php index 2139dec69..572c9332d 100644 --- a/src/controllers/UsersController.php +++ b/src/Controller/UsersController.php @@ -1,5 +1,17 @@ getTalksBySpeaker($user_id, $resultsperpage, $start); + return $talks->getOutputView($request, $verbose); case 'hosted': $event_mapper = new EventMapper($db, $request); + return $event_mapper->getEventsHostedByUser($user_id, $resultsperpage, $start, $verbose); case 'attended': $event_mapper = new EventMapper($db, $request); + return $event_mapper->getEventsAttendedByUser($user_id, $resultsperpage, $start, $verbose); case 'talk_comments': $talkComment_mapper = new TalkCommentMapper($db, $request); + return $talkComment_mapper->getCommentsByUserId( $user_id, $resultsperpage, @@ -54,6 +70,7 @@ public function getAction(Request $request, PDO $db) if (count($list['users']) == 0) { throw new Exception('User not found', 404); } + return $list; } @@ -63,10 +80,11 @@ public function getAction(Request $request, PDO $db) FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES ); - $list = $mapper->getUserByUsername($username, $verbose); + $list = $mapper->getUserByUsername($username, $verbose); if ($list === false) { throw new Exception('Username not found', 404); } + return $list; } @@ -76,6 +94,7 @@ public function getAction(Request $request, PDO $db) FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES ); + return $mapper->getUserByKeyword($keyword, $resultsperpage, $start, $verbose); } @@ -98,6 +117,7 @@ public function postAction(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Content-Length', 0); $view->setResponseCode(204); + return; } else { throw new Exception("Verification failed", 400); @@ -175,7 +195,7 @@ public function postAction(Request $request, PDO $db) FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES ); - $user['biography'] = filter_var( + $user['biography'] = filter_var( trim($request->getParameter("biography")), FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES @@ -186,7 +206,7 @@ public function postAction(Request $request, PDO $db) throw new Exception(implode(". ", $errors), 400); } else { $user_id = $user_mapper->createUser($user); - $view = $request->getView(); + $view = $request->getView(); $view->setHeader('Location', $request->base . $request->path_info . '/' . $user_id); $view->setResponseCode(201); @@ -236,7 +256,7 @@ public function updateUser(Request $request, PDO $db) $accessToken = $request->getAccessToken(); // only trusted clients can change account details - if (! $oauthModel->isAccessTokenPermittedPasswordGrant($accessToken)) { + if (!$oauthModel->isAccessTokenPermittedPasswordGrant($accessToken)) { throw new Exception("This client does not have permission to perform this operation", 403); } @@ -246,7 +266,7 @@ public function updateUser(Request $request, PDO $db) // start with passwords $password = $request->getParameter('password'); - if (! empty($password)) { + if (!empty($password)) { // they must supply their old password to be allowed to set a new one $old_password = $request->getParameter('old_password'); if (empty($old_password)) { @@ -254,7 +274,7 @@ public function updateUser(Request $request, PDO $db) } // is the old password correct before we proceed? - if (! $oauthModel->reverifyUserPassword($userId, $old_password)) { + if (!$oauthModel->reverifyUserPassword($userId, $old_password)) { throw new Exception("The credentials could not be verified", 403); } @@ -338,7 +358,7 @@ public function updateUser(Request $request, PDO $db) throw new Exception(implode(". ", $errors), 400); } else { // now update the user - if (! $user_mapper->editUser($user, $userId)) { + if (!$user_mapper->editUser($user, $userId)) { throw new Exception("User not updated", 400); } @@ -346,6 +366,7 @@ public function updateUser(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Content-Length', 0); $view->setResponseCode(204); + return; } } @@ -373,6 +394,7 @@ public function passwordReset(Request $request, PDO $db) $view = $request->getView(); $view->setHeader('Content-Length', 0); $view->setResponseCode(204); + return; } else { throw new Exception("Password could not be reset", 400); @@ -385,7 +407,7 @@ public function passwordReset(Request $request, PDO $db) public function deleteUser(Request $request, PDO $db) { - if (! isset($request->user_id)) { + if (!isset($request->user_id)) { throw new Exception("You must be logged in to delete data", 401); } // delete the user @@ -394,11 +416,11 @@ public function deleteUser(Request $request, PDO $db) $user_mapper = $this->getUserMapper($db, $request); $is_admin = $user_mapper->isSiteAdmin($user_id); - if (! $is_admin) { + if (!$is_admin) { throw new Exception("You do not have permission to do that", 403); } - if (! $user_mapper->delete($user_id)) { + if (!$user_mapper->delete($user_id)) { throw new Exception("There was a problem trying to delete the user", 400); } @@ -446,7 +468,7 @@ public function setUserMapper(UserMapper $user_mapper) public function getUserMapper(PDO $db, Request $request) { - if (! $this->user_mapper) { + if (!$this->user_mapper) { $this->user_mapper = new UserMapper($db, $request); } @@ -460,7 +482,7 @@ public function setUserRegistrationEmailService(UserRegistrationEmailService $ma public function getUserRegistrationEmailService($config, $recipient, $token) { - if (! $this->user_registration_email_service) { + if (!$this->user_registration_email_service) { $this->user_registration_email_service = new UserRegistrationEmailService( $config, $recipient, diff --git a/src/inc/Header.php b/src/Header.php similarity index 91% rename from src/inc/Header.php rename to src/Header.php index 817a0a741..6aa43daf3 100644 --- a/src/inc/Header.php +++ b/src/Header.php @@ -16,6 +16,8 @@ * THE SOFTWARE. */ +namespace Joindin\Api; + /** * Represents a header and all of the values stored by that header */ @@ -26,17 +28,17 @@ class Header protected $glue; /** - * @param string $header Name of the header + * @param string $header Name of the header * @param array|string $values Values of the header as an array or a scalar - * @param string $glue Glue used to combine multiple values into a string + * @param string $glue Glue used to combine multiple values into a string */ public function __construct($header, $values = array(), $glue = ',') { $this->header = trim($header); $this->glue = $glue; - foreach ((array) $values as $value) { - foreach ((array) $value as $v) { + foreach ((array)$values as $value) { + foreach ((array)$value as $v) { $this->values[] = $v; } } @@ -83,7 +85,7 @@ public function normalize() { $values = $this->toArray(); - for ($i = 0, $total = count($values); $i < $total; $i ++) { + for ($i = 0, $total = count($values); $i < $total; $i++) { if (strpos($values[$i], $this->glue) !== false) { // Explode on glue when the glue is not inside of a comma foreach (preg_split('/' . preg_quote($this->glue) . '(?=([^"]*"[^"]*")*[^"]*$)/', $values[$i]) as $v) { @@ -165,10 +167,10 @@ public function parseParams() foreach ($this->normalize()->toArray() as $val) { $part = array(); foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) { - if (! preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { + if (!preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { continue; } - $pieces = array_map($callback, $matches[0]); + $pieces = array_map($callback, $matches[0]); $part[$pieces[0]] = isset($pieces[1]) ? $pieces[1] : ''; } if ($part) { diff --git a/src/models/ApiMapper.php b/src/Model/ApiMapper.php similarity index 88% rename from src/models/ApiMapper.php rename to src/Model/ApiMapper.php index 07e7a4531..a8c3619bf 100644 --- a/src/models/ApiMapper.php +++ b/src/Model/ApiMapper.php @@ -1,18 +1,26 @@ _db = $db; if (isset($request)) { - $this->_request = $request; + $this->_request = $request; $this->website_url = $request->getConfigValue('website_url'); } @@ -32,7 +40,7 @@ public function getVerboseFields() /** * Turn results into arrays with correct fields, add hypermedia * - * @param array $results Results of the database query + * @param array $results Results of the database query * @param boolean $verbose whether to return detailed information * * @return array A dataset now with each record having its links, @@ -48,13 +56,13 @@ public function transformResults(array $results, $verbose) $entry = array(); foreach ($fields as $key => $value) { // special handling for dates - if (substr($key, - 5) == '_date' && ! empty($row[ $value ])) { + if (substr($key, -5) == '_date' && ! empty($row[$value])) { if ($row['event_tz_place'] != '' && $row['event_tz_cont'] != '') { $tz = new DateTimeZone($row['event_tz_cont'] . '/' . $row['event_tz_place']); } else { $tz = new DateTimeZone('UTC'); } - $entry[ $key ] = (new DateTime('@' . $row[$value]))->setTimezone($tz)->format('c'); + $entry[$key] = (new DateTime('@' . $row[$value]))->setTimezone($tz)->format('c'); } else { if (array_key_exists($value, $row)) { $entry[$key] = $row[$value]; @@ -89,7 +97,7 @@ protected function buildLimit($resultsperpage, $start) * get a total-results count * * @param string $sqlQuery - * @param array $data + * @param array $data * * @return int */ @@ -116,7 +124,7 @@ public function getTotalCount($sqlQuery, array $data = array()) protected function getPaginationLinks(array $list, $total = 0) { - $request = $this->_request; + $request = $this->_request; $meta['count'] = count($list); $meta['total'] = $total; @@ -149,7 +157,7 @@ protected function getPaginationLinks(array $list, $total = 0) protected function inflect($string) { // code ported from web2 - $alpha = preg_replace("/[^0-9a-zA-Z- ]/", "", $string); + $alpha = preg_replace("/[^0-9a-zA-Z- ]/", "", $string); return strtolower(str_replace(' ', '-', $alpha)); } diff --git a/src/models/BaseModel.php b/src/Model/BaseModel.php similarity index 89% rename from src/models/BaseModel.php rename to src/Model/BaseModel.php index c4fda9b5b..4adeb2e1d 100644 --- a/src/models/BaseModel.php +++ b/src/Model/BaseModel.php @@ -1,5 +1,11 @@ data[ $field ])) { - return $this->data[ $field ]; + if (isset($this->data[$field])) { + return $this->data[$field]; } return null; @@ -63,7 +69,7 @@ public function getSubResources() * Return this object with client-facing fields and hypermedia, ready for output * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ @@ -90,7 +96,7 @@ public function getOutputView(Request $request, $verbose = false) $value = $this->$name; // override if it is a date - if (substr($output_name, - 5) == '_date' && ! empty($value)) { + if (substr($output_name, -5) == '_date' && ! empty($value)) { if (is_numeric($value)) { $value = '@' . $value; } diff --git a/src/models/BaseModelCollection.php b/src/Model/BaseModelCollection.php similarity index 96% rename from src/models/BaseModelCollection.php rename to src/Model/BaseModelCollection.php index 971ba9240..70e394729 100644 --- a/src/models/BaseModelCollection.php +++ b/src/Model/BaseModelCollection.php @@ -1,5 +1,9 @@ total; $meta['this_page'] = $request->base . $request->path_info . '?' . http_build_query($request->paginationParameters); - + $next_params = $prev_params = $counter_params = $request->paginationParameters; $firstOnNextPage = $counter_params['start'] + $counter_params['resultsperpage']; diff --git a/src/models/ClientMapper.php b/src/Model/ClientMapper.php similarity index 78% rename from src/models/ClientMapper.php rename to src/Model/ClientMapper.php index 891d2ac01..807a4abde 100644 --- a/src/models/ClientMapper.php +++ b/src/Model/ClientMapper.php @@ -1,5 +1,12 @@ $user_id )); - if (! $response) { + if (!$response) { return false; } $results = $stmt->fetchAll(PDO::FETCH_ASSOC); - $total = $this->getTotalCount($sql, [':user_id' => $user_id]); + $total = $this->getTotalCount($sql, [':user_id' => $user_id]); $results = $this->processResults($results); return new ClientModelCollection($results, $total); @@ -72,11 +79,11 @@ public function getClientByIdAndUser($clientId, $userId) $stmt = $this->_db->prepare($sql); $response = $stmt->execute([ - ':user_id' => $userId, + ':user_id' => $userId, ':client_id' => $clientId, ]); - if (! $response) { + if (!$response) { return false; } @@ -97,12 +104,12 @@ public function getClientByIdAndUser($clientId, $userId) public function createClient(array $data) { $clientSql = 'INSERT INTO oauth_consumers (consumer_key, consumer_secret,' - . 'created_date, user_id, application, description, ' - . 'callback_url, enable_password_grant) VALUES (:consumer_key, ' - . ':consumer_secret, :created_date, :user_id, :application, ' - . ':description, :callback_url, :enable_password_grant);'; + . 'created_date, user_id, application, description, ' + . 'callback_url, enable_password_grant) VALUES (:consumer_key, ' + . ':consumer_secret, :created_date, :user_id, :application, ' + . ':description, :callback_url, :enable_password_grant);'; - $stmt = $this->_db->prepare($clientSql); + $stmt = $this->_db->prepare($clientSql); $stmt->execute([ ':consumer_key' => base64_encode(openssl_random_pseudo_bytes(48)), ':consumer_secret' => base64_encode(openssl_random_pseudo_bytes(48)), @@ -114,7 +121,7 @@ public function createClient(array $data) ':enable_password_grant' => 1, ]); - $clientId = $this->_db->lastInsertId(); + $clientId = $this->_db->lastInsertId(); if (0 == $clientId) { throw new Exception('There has been an error storing the application'); @@ -135,8 +142,8 @@ public function createClient(array $data) public function updateClient($clientId, array $data) { $clientSql = 'UPDATE oauth_consumers SET ' - . 'application = :application, description = :description, ' - . 'callback_url = :callback_url WHERE id = :client_id;'; + . 'application = :application, description = :description, ' + . 'callback_url = :callback_url WHERE id = :client_id;'; $stmt = $this->_db->prepare($clientSql); @@ -147,7 +154,7 @@ public function updateClient($clientId, array $data) ':client_id' => $clientId, ]); - if (! $result) { + if (!$result) { throw new Exception('There has been an error updating the application'); } @@ -167,7 +174,7 @@ public function deleteClient($clientId) $stmt = $this->_db->prepare($clientSql); - if (! $stmt->execute([':client_id' => $clientId])) { + if (!$stmt->execute([':client_id' => $clientId])) { throw new Exception('There has been an error updating the application'); } } diff --git a/src/models/ClientModel.php b/src/Model/ClientModel.php similarity index 94% rename from src/models/ClientModel.php rename to src/Model/ClientModel.php index 71086491b..1176bfbda 100644 --- a/src/models/ClientModel.php +++ b/src/Model/ClientModel.php @@ -1,5 +1,9 @@ total = $total; - $this->list = []; + $this->list = []; // hydrate the model objects if necessary and store to list foreach ($data as $item) { @@ -40,7 +44,7 @@ public function __construct(array $data, $total) * and pagination * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ diff --git a/src/models/EventCommentMapper.php b/src/Model/EventCommentMapper.php similarity index 81% rename from src/models/EventCommentMapper.php rename to src/Model/EventCommentMapper.php index 748fe1a67..47579338f 100644 --- a/src/models/EventCommentMapper.php +++ b/src/Model/EventCommentMapper.php @@ -1,5 +1,10 @@ getBasicSQL(); - $sql .= 'and event_id = :event_id order by date_made desc '; - $sql .= $this->buildLimit($resultsperpage, $start); + $sql = $this->getBasicSQL(); + $sql .= 'and event_id = :event_id order by date_made desc '; + $sql .= $this->buildLimit($resultsperpage, $start); $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array( ':event_id' => $event_id @@ -50,7 +55,7 @@ public function getEventCommentsByEventId($event_id, $resultsperpage, $start, $v } /** - * @param int $comment_id + * @param int $comment_id * @param bool $verbose * @param bool $include_hidden * @@ -58,8 +63,8 @@ public function getEventCommentsByEventId($event_id, $resultsperpage, $start, $v */ public function getCommentById($comment_id, $verbose = false, $include_hidden = false) { - $sql = $this->getBasicSQL($include_hidden); - $sql .= 'and ec.ID = :comment_id '; + $sql = $this->getBasicSQL($include_hidden); + $sql .= 'and ec.ID = :comment_id '; $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array( ':comment_id' => $comment_id @@ -85,7 +90,7 @@ public function transformResults(array $results, $verbose) $total = $results['total']; unset($results['total']); - $list = parent::transformResults($results, $verbose); + $list = parent::transformResults($results, $verbose); if (is_array($list) && count($list)) { foreach ($results as $key => $row) { @@ -98,7 +103,7 @@ public function transformResults(array $results, $verbose) return [ 'comments' => $list, - 'meta' => $this->getPaginationLinks($list, $total), + 'meta' => $this->getPaginationLinks($list, $total), ]; } @@ -107,8 +112,8 @@ public function transformResults(array $results, $verbose) * * This is used so we can nest comments inside other not-list settings * - * @param array $row The database row with the comment result - * @param bool $verbose The verbosity level + * @param array $row The database row with the comment result + * @param bool $verbose The verbosity level * * @return array The extra fields to add to the existing data for this record */ @@ -126,22 +131,22 @@ protected function formatOneComment($row, $verbose) $result['user_display_name'] = $row['full_name']; $result['username'] = $row['username']; $result['user_uri'] = $base . '/' . $version . '/users/' - . $row['user_id']; + . $row['user_id']; } else { $result['user_display_name'] = $row['cname']; } // useful links $result['comment_uri'] = $base . '/' . $version . '/event_comments/' - . $row['ID']; + . $row['ID']; $result['verbose_comment_uri'] = $base . '/' . $version . '/event_comments/' - . $row['ID'] . '?verbose=yes'; + . $row['ID'] . '?verbose=yes'; $result['event_uri'] = $base . '/' . $version . '/events/' - . $row['event_id']; + . $row['event_id']; $result['event_comments_uri'] = $base . '/' . $version . '/events/' - . $row['event_id'] . '/comments'; + . $row['event_id'] . '/comments'; $result['reported_uri'] = $base . '/' . $version . '/event_comments/' - . $row['ID'] . '/reported'; + . $row['ID'] . '/reported'; return $result; } @@ -157,6 +162,7 @@ protected function getBasicSQL($include_hidden = false) if (!$include_hidden) { $sql .= 'and ec.active = 1 '; } + return $sql; } @@ -249,7 +255,7 @@ public function getCommentInfo($comment_id) * pending moderation * * @param int $comment_id the comment that was reported - * @param int $user_id the user that reported it + * @param int $user_id the user that reported it */ public function userReportedComment($comment_id, $user_id) { @@ -259,14 +265,15 @@ public function userReportedComment($comment_id, $user_id) reporting_date = NOW()"; $report_stmt = $this->_db->prepare($report_sql); - $result = $report_stmt->execute([ + $result = $report_stmt->execute([ "event_comment_id" => $comment_id, - "user_id" => $user_id]); + "user_id" => $user_id + ]); - $hide_sql = "update event_comments + $hide_sql = "update event_comments set active = 0 where ID = :event_comment_id"; $hide_stmt = $this->_db->prepare($hide_sql); - $result = $hide_stmt->execute(["event_comment_id" => $comment_id]); + $result = $hide_stmt->execute(["event_comment_id" => $comment_id]); } /** @@ -274,8 +281,8 @@ public function userReportedComment($comment_id, $user_id) * * Includes verbose nested comment info * - * @param int $event_id The event whose comments should be returned - * @param bool $moderated Whether to include comments that have been moderated + * @param int $event_id The event whose comments should be returned + * @param bool $moderated Whether to include comments that have been moderated * * @return EventCommentReportModelCollection */ @@ -297,14 +304,14 @@ public function getReportedCommentsByEventId($event_id, $moderated = false) $sql .= " and rc.decision is null"; } - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); $result = $stmt->execute(['event_id' => $event_id]); // need to also set the comment info - $list = []; - $total = 0; - $comment_sql = $this->getBasicSQL(true) - . " and ec.ID = :comment_id"; + $list = []; + $total = 0; + $comment_sql = $this->getBasicSQL(true) + . " and ec.ID = :comment_id"; $comment_stmt = $this->_db->prepare($comment_sql); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { @@ -312,13 +319,14 @@ public function getReportedCommentsByEventId($event_id, $moderated = false) $comment_result = $comment_stmt->execute(['comment_id' => $row['event_comment_id']]); if ($comment_result && $comment = $comment_stmt->fetch(PDO::FETCH_ASSOC)) { // work around the existing transform logic - $comment_array = [$comment]; - $comment_array = parent::transformResults($comment_array, true); - $item = current($comment_array); + $comment_array = [$comment]; + $comment_array = parent::transformResults($comment_array, true); + $item = current($comment_array); $row['comment'] = array_merge($item, $this->formatOneComment($comment, true)); } $list[] = new EventCommentReportModel($row); } + return new EventCommentReportModelCollection($list, $total); } @@ -326,29 +334,29 @@ public function getReportedCommentsByEventId($event_id, $moderated = false) * A comment has been moderated. Record the decision and if the decision * is 'denied' then set the comment back to active. * - * @param string $decision the decision: 'approved' or 'denied' - * @param int $comment_id the comment that was reported - * @param int $user_id the user that reported it + * @param string $decision the decision: 'approved' or 'denied' + * @param int $comment_id the comment that was reported + * @param int $user_id the user that reported it */ public function moderateReportedComment($decision, $comment_id, $user_id) { if (in_array($decision, ['approved', 'denied'])) { // record the decision - $sql = 'update reported_event_comments set + $sql = 'update reported_event_comments set decision = :decision, deciding_user_id = :user_id, deciding_date = NOW() where event_comment_id = :comment_id'; $stmt = $this->_db->prepare($sql); $stmt->execute([ - 'decision' => $decision, - 'user_id' => $user_id, + 'decision' => $decision, + 'user_id' => $user_id, 'comment_id' => $comment_id, ]); if ($decision == 'denied') { // the report is denied, therefore make the comment active again - $show_sql = "update event_comments set active = 1 where ID = :comment_id"; + $show_sql = "update event_comments set active = 1 where ID = :comment_id"; $show_stmt = $this->_db->prepare($show_sql); $show_stmt->execute(["comment_id" => $comment_id]); } diff --git a/src/models/EventCommentReportModel.php b/src/Model/EventCommentReportModel.php similarity index 80% rename from src/models/EventCommentReportModel.php rename to src/Model/EventCommentReportModel.php index 2a4c2febd..2d7070e6f 100644 --- a/src/models/EventCommentReportModel.php +++ b/src/Model/EventCommentReportModel.php @@ -1,5 +1,9 @@ 'comment', + 'comment' => 'comment', ]; } /** * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array with client-facing fields and hypermedia, ready for output */ public function getOutputView(Request $request, $verbose = false) { $item = parent::getOutputView($request, $verbose); - + // add Hypermedia $base = $request->base; $version = $request->version; - $item['reporting_user_uri'] = $base . '/' . $version . '/users/' . $this->reporting_user_id; + $item['reporting_user_uri'] = $base . '/' . $version . '/users/' . $this->reporting_user_id; if (!empty($this->deciding_user_id)) { - $item['deciding_user_uri'] = $base . '/' . $version . '/users/' . $this->deciding_user_id; + $item['deciding_user_uri'] = $base . '/' . $version . '/users/' . $this->deciding_user_id; } - $item['event_uri'] = $base . '/' . $version . '/events/' . $this->event_id; + $item['event_uri'] = $base . '/' . $version . '/events/' . $this->event_id; return $item; } diff --git a/src/models/EventCommentReportModelCollection.php b/src/Model/EventCommentReportModelCollection.php similarity index 92% rename from src/models/EventCommentReportModelCollection.php rename to src/Model/EventCommentReportModelCollection.php index 8882c25a5..6b9710cd9 100644 --- a/src/models/EventCommentReportModelCollection.php +++ b/src/Model/EventCommentReportModelCollection.php @@ -1,5 +1,9 @@ execute(array( ':event_id' => $event_id )); - if (! $response) { + if (!$response) { return false; } @@ -57,7 +61,7 @@ public function getHostsByEventId($event_id, $resultsperpage, $start, $verbose = */ public function addHostToEvent($event_id, $host_id) { - $sql = 'INSERT INTO user_admin (uid, rid, rtype) VALUES (:host_id, :event_id, :type)'; + $sql = 'INSERT INTO user_admin (uid, rid, rtype) VALUES (:host_id, :event_id, :type)'; $stmt = $this->_db->prepare($sql); $response = $stmt->execute([ @@ -66,7 +70,7 @@ public function addHostToEvent($event_id, $host_id) ':type' => 'event', ]); - if (! $response) { + if (!$response) { return false; } @@ -81,7 +85,7 @@ public function addHostToEvent($event_id, $host_id) */ public function removeHostFromEvent($host_id, $event_id) { - $sql = 'DELETE FROM user_admin WHERE uid = :user_id AND rid = :event_id AND rtype = :type'; + $sql = 'DELETE FROM user_admin WHERE uid = :user_id AND rid = :event_id AND rtype = :type'; $stmt = $this->_db->prepare($sql); return $stmt->execute([ @@ -99,9 +103,9 @@ public function removeHostFromEvent($host_id, $event_id) protected function getHostSql() { return 'select a.uid as user_id, u.full_name as host_name ' - . 'from user_admin a ' - . 'inner join user u on u.ID = a.uid ' - . 'where rid = :event_id and rtype="event" and (rcode!="pending" OR rcode is null)'; + . 'from user_admin a ' + . 'inner join user u on u.ID = a.uid ' + . 'where rid = :event_id and rtype="event" and (rcode!="pending" OR rcode is null)'; } /** @@ -116,7 +120,7 @@ public function transformResults(array $results, $verbose) $version = $this->_request->version; // add per-item links - if (! is_array($list)) { + if (!is_array($list)) { return []; } @@ -132,7 +136,7 @@ public function transformResults(array $results, $verbose) return [ 'hosts' => $list, - 'meta' => $this->getPaginationLinks($list, $total), + 'meta' => $this->getPaginationLinks($list, $total), ]; } } diff --git a/src/models/EventMapper.php b/src/Model/EventMapper.php similarity index 84% rename from src/models/EventMapper.php rename to src/Model/EventMapper.php index b98163080..3659a0253 100644 --- a/src/models/EventMapper.php +++ b/src/Model/EventMapper.php @@ -1,9 +1,15 @@ transformResults($results, $verbose); } @@ -123,9 +129,9 @@ public function getEventByTrackId($track_id, $verbose = false, $activeEventsOnly /** * Internal function called by other event-fetching code, with changeable SQL * - * @param int $resultsperpage how many records to return - * @param int $start offset to start returning records from - * @param array $params filters and other parameters to limit/order the collection + * @param int $resultsperpage how many records to return + * @param int $start offset to start returning records from + * @param array $params filters and other parameters to limit/order the collection * * @return false|array the raw database results */ @@ -160,14 +166,14 @@ protected function getEvents($resultsperpage, $start, array $params = []) } if (array_key_exists("track_id", $params)) { - $sql .= "right join event_track on event_track.event_id = events.ID and event_track.ID = :track_id"; + $sql .= "right join event_track on event_track.event_id = events.ID and event_track.ID = :track_id"; $data['track_id'] = $params['track_id']; } $sql .= ' where (events.private <> "y" OR events.private IS NULL) '; if (array_key_exists("event_id", $params)) { - $where .= "and events.ID = :event_id "; + $where .= "and events.ID = :event_id "; $data["event_id"] = $params["event_id"]; } @@ -202,9 +208,9 @@ protected function getEvents($resultsperpage, $start, array $params = []) $order .= 'events.event_cfp_end'; break; case "pending": // events to be approved - $order .= 'events.event_start'; + $order .= 'events.event_start'; $active = false; - $where .= ' and pending = 1'; + $where .= ' and pending = 1'; break; default: $order .= 'events.event_start desc'; @@ -220,14 +226,14 @@ protected function getEvents($resultsperpage, $start, array $params = []) } if (array_key_exists("stub", $params)) { - $where .= ' and events.event_stub = :stub'; + $where .= ' and events.event_stub = :stub'; $data['stub'] = $params['stub']; } // fuzzy/partial match for title if (array_key_exists("title", $params)) { - $order .= ', events.event_start desc'; - $where .= ' and LOWER(events.event_name) like :title'; + $order .= ', events.event_start desc'; + $where .= ' and LOWER(events.event_name) like :title'; $data['title'] = "%" . strtolower($params['title']) . "%"; } @@ -241,8 +247,8 @@ protected function getEvents($resultsperpage, $start, array $params = []) $where .= " OR "; } - $where .= "tags.tag_value = :tag" . $i; - $data[ "tag" . $i] = $tag; + $where .= "tags.tag_value = :tag" . $i; + $data["tag" . $i] = $tag; $i++; } @@ -250,12 +256,12 @@ protected function getEvents($resultsperpage, $start, array $params = []) } if (array_key_exists("startdate", $params)) { - $where .= ' and events.event_start >= :startdate '; + $where .= ' and events.event_start >= :startdate '; $data["startdate"] = $params["startdate"]; } if (array_key_exists("enddate", $params)) { - $where .= ' and events.event_start < :enddate '; + $where .= ' and events.event_start < :enddate '; $data["enddate"] = $params["enddate"]; } @@ -265,12 +271,12 @@ protected function getEvents($resultsperpage, $start, array $params = []) if (array_key_exists("filter", $params) && $params['filter'] == 'all' && $start === null) { // How many events are there up to "now"? $this_sql = $sql . $where . ' and (events.event_start <' . (mktime(0, 0, 0)) . ')'; - $start = $this->getTotalCount($this_sql, $data); + $start = $this->getTotalCount($this_sql, $data); // store back into paginationParameters so that meta is correct $this->_request->paginationParameters['start'] = $start; } - + // now add all that where clause $sql .= $where; @@ -283,7 +289,7 @@ protected function getEvents($resultsperpage, $start, array $params = []) $sql .= $order; // limit clause - $sql .= $this->buildLimit($resultsperpage, $start); + $sql .= $this->buildLimit($resultsperpage, $start); $stmt = $this->_db->prepare($sql); $response = $stmt->execute($data); if ($response) { @@ -299,10 +305,10 @@ protected function getEvents($resultsperpage, $start, array $params = []) /** * getEventList * - * @param int $resultsperpage how many records to return - * @param int $start offset to start returning records from - * @param array $params filters and other parameters to limit/order the collection - * @param bool $verbose used to determine how many fields are needed + * @param int $resultsperpage how many records to return + * @param int $start offset to start returning records from + * @param array $params filters and other parameters to limit/order the collection + * @param bool $verbose used to determine how many fields are needed * * @return false|array the data, or false if something went wrong */ @@ -320,7 +326,7 @@ public function getEventList($resultsperpage, $start, array $params, $verbose = * Set a user as attending for an event * * @param int $event_id The event ID to update for - * @param int $user_id The user's ID + * @param int $user_id The user's ID * * @return bool */ @@ -337,7 +343,7 @@ public function setUserAttendance($event_id, $user_id) * Set a user as not attending an event * * @param int $event_id The event ID - * @param int $user_id The user's ID + * @param int $user_id The user's ID * * @return bool */ @@ -355,7 +361,7 @@ public function setUserNonAttendance($event_id, $user_id) * User attending an event? * * @param int $event_id the event to check - * @param int $user_id the user you're interested in + * @param int $user_id the user you're interested in * * @return array */ @@ -369,7 +375,7 @@ public function getUserAttendance($event_id, $user_id) * Is this user attending this event? * * @param int $event_id the Event of interest - * @param int $user_id which user (often the current one) + * @param int $user_id which user (often the current one) * * @return bool */ @@ -418,10 +424,10 @@ public function transformResults(array $results, $verbose) $list[$key]['images'] = $this->getImages($row['ID']); $list[$key]['tags'] = $this->getTags($row['ID']); $list[$key]['uri'] = $base . '/' . $version . '/events/' . $row['ID']; - $list[ $key ]['verbose_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '?verbose=yes'; + $list[$key]['verbose_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '?verbose=yes'; $list[$key]['comments_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '/comments'; $list[$key]['talks_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '/talks'; - $list[ $key]['tracks_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '/tracks'; + $list[$key]['tracks_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '/tracks'; $list[$key]['attending_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '/attending'; $list[$key]['images_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '/images'; @@ -436,12 +442,12 @@ public function transformResults(array $results, $verbose) if ($verbose) { if ($this->thisUserHasAdminOn($row['ID'])) { - $list[$key]['reported_comments_uri'] = $base . '/' . $version . '/events/' - . $row['ID'] . '/comments/reported'; + $list[$key]['reported_comments_uri'] = $base . '/' . $version . '/events/' + . $row['ID'] . '/comments/reported'; $list[$key]['reported_talk_comments_uri'] = $base . '/' . $version . '/events/' - . $row['ID'] . '/talk_comments/reported'; - $list[$key]['pending_claims_uri'] = $base . '/' . $version . '/events/' - . $row['ID'] . '/claims'; + . $row['ID'] . '/talk_comments/reported'; + $list[$key]['pending_claims_uri'] = $base . '/' . $version . '/events/' + . $row['ID'] . '/claims'; } $list[$key]['all_talk_comments_uri'] = $base . '/' . $version . '/events/' . $row['ID'] . '/talk_comments'; @@ -459,7 +465,7 @@ public function transformResults(array $results, $verbose) return [ 'events' => $list, - 'meta' => $this->getPaginationLinks($list, $total), + 'meta' => $this->getPaginationLinks($list, $total), ]; } @@ -478,7 +484,7 @@ protected function getHosts($event_id) $host_sql = $this->getHostSql(); $host_stmt = $this->_db->prepare($host_sql); $host_stmt->execute(array("event_id" => $event_id)); - $hosts = $host_stmt->fetchAll(PDO::FETCH_ASSOC); + $hosts = $host_stmt->fetchAll(PDO::FETCH_ASSOC); if (!is_array($hosts)) { return []; @@ -488,7 +494,7 @@ protected function getHosts($event_id) foreach ($hosts as $person) { $retval[] = [ 'host_name' => $person['full_name'], - 'host_uri' => $base . '/' . $version . '/users/' . $person['user_id'], + 'host_uri' => $base . '/' . $version . '/users/' . $person['user_id'], ]; } @@ -502,10 +508,10 @@ protected function getHosts($event_id) */ protected function getHostSql() { - return 'select a.uid as user_id, u.full_name' - . ' from user_admin a ' - . ' inner join user u on u.ID = a.uid ' - . ' where rid = :event_id and rtype="event" and (rcode!="pending" OR rcode is null)'; + return 'select a.uid as user_id, u.full_name' + . ' from user_admin a ' + . ' inner join user u on u.ID = a.uid ' + . ' where rid = :event_id and rtype="event" and (rcode!="pending" OR rcode is null)'; } /** @@ -545,7 +551,7 @@ protected function getTags($event_id) . ' where te.event_id = :event_id'; $tag_stmt = $this->_db->prepare($tag_sql); $tag_stmt->execute(array("event_id" => $event_id)); - $tags = $tag_stmt->fetchAll(PDO::FETCH_ASSOC); + $tags = $tag_stmt->fetchAll(PDO::FETCH_ASSOC); if (!is_array($tags)) { return []; @@ -562,16 +568,16 @@ protected function getTags($event_id) /** * Events that a particular user has admin privileges on * - * @param int $user_id - * @param int $resultsperpage how many records to return - * @param int $start offset to start returning records from - * @param boolean $verbose used to determine how many fields are needed + * @param int $user_id + * @param int $resultsperpage how many records to return + * @param int $start offset to start returning records from + * @param boolean $verbose used to determine how many fields are needed * * @return false|array the data, or false if something went wrong */ public function getEventsHostedByUser($user_id, $resultsperpage, $start, $verbose = false) { - $data = array("user_id" => (int) $user_id); + $data = array("user_id" => (int)$user_id); $sql = 'select events.*, ' . '(select count(*) from user_attend where user_attend.eid = events.ID) as attendee_count, ' @@ -597,16 +603,16 @@ public function getEventsHostedByUser($user_id, $resultsperpage, $start, $verbos /** * Events that a particular user is marked as attending * - * @param int $user_id - * @param int $resultsperpage how many records to return - * @param int $start offset to start returning records from - * @param boolean $verbose used to determine how many fields are needed + * @param int $user_id + * @param int $resultsperpage how many records to return + * @param int $start offset to start returning records from + * @param boolean $verbose used to determine how many fields are needed * * @return false|array the data, or false if something went wrong */ public function getEventsAttendedByUser($user_id, $resultsperpage, $start, $verbose = false) { - $data = array("user_id" => (int) $user_id); + $data = array("user_id" => (int)$user_id); $sql = 'select events.*, ' . '(select count(*) from user_attend where user_attend.eid = events.ID) as attendee_count, ' . 'abs(datediff(from_unixtime(events.event_start), from_unixtime(' . @@ -678,22 +684,22 @@ public function thisUserCanApproveEvents() /** * Is this user * - * @param int $user_id The identifier of the user to check + * @param int $user_id The identifier of the user to check * @param int $event_id The identifier of the event to check * * @return bool if the user is a host */ public function isUserAHostOn($user_id, $event_id) { - $sql = $this->getHostSql(); - $sql .= ' AND u.ID = :user_id'; + $sql = $this->getHostSql(); + $sql .= ' AND u.ID = :user_id'; $stmt = $this->_db->prepare($sql); $stmt->execute(array( "event_id" => $event_id, "user_id" => $user_id, )); - return !empty($stmt->fetchAll()); + return ! empty($stmt->fetchAll()); } /** @@ -722,8 +728,8 @@ protected function getTalkCommentCount($event_id) * ensure uniqueness, by adding year, then year-month and then finally * year-month-day to the inflected title. * - * @param string $name The event name to inflect - * @param int $event_id The event to store it against + * @param string $name The event name to inflect + * @param int $event_id The event to store it against * @param string $start_date * * @return string The value we stored @@ -744,7 +750,7 @@ protected function generateInflectedName($name, $event_id, $start_date) foreach ($name_choices as $inflected_name) { $sql = "update events set url_friendly_name = :inflected_name where ID = :event_id"; - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); try { $result = $stmt->execute(array( @@ -767,8 +773,8 @@ protected function generateInflectedName($name, $event_id, $start_date) * * Accepts a subset of event fields * - * @param array $event Event data to insert into the database. - * @param bool $auto_approve if false an event is registered as 'pending' first and must be actively approved. + * @param array $event Event data to insert into the database. + * @param bool $auto_approve if false an event is registered as 'pending' first and must be actively approved. * * @throws Exception * @return integer|false @@ -777,7 +783,7 @@ public function createEvent(array $event, $auto_approve = false) { // Sanity check: ensure all mandatory fields are present. - $mandatory_fields = array( + $mandatory_fields = array( 'name', 'description', 'start_date', @@ -825,8 +831,8 @@ public function createEvent(array $event, $auto_approve = false) * * Accepts a subset of event fields * - * @param array $event Event data to insert into the database. - * @param int $event_id The ID of the event to be edited + * @param array $event Event data to insert into the database. + * @param int $event_id The ID of the event to be edited * * @throws Exception * @return integer|false @@ -834,7 +840,7 @@ public function createEvent(array $event, $auto_approve = false) public function editEvent(array $event, $event_id) { // Sanity check: ensure all mandatory fields are present. - $mandatory_fields = array( + $mandatory_fields = array( 'name', 'description', 'start_date', @@ -857,7 +863,7 @@ public function editEvent(array $event, $event_id) continue; } if (array_key_exists($api_name, $event)) { - $pairs[] = "$column_name = :$api_name"; + $pairs[] = "$column_name = :$api_name"; $items[$api_name] = $event[$api_name]; } } @@ -889,8 +895,8 @@ public function editEvent(array $event, $event_id) */ public function addUserAsHost($event_id, $user_id) { - $sql = "insert into user_admin set rtype = 'event', rid = :event_id, uid = :user_id"; - $stmt = $this->_db->prepare($sql); + $sql = "insert into user_admin set rtype = 'event', rid = :event_id, uid = :user_id"; + $stmt = $this->_db->prepare($sql); return $stmt->execute(array("event_id" => $event_id, "user_id" => $user_id)); } @@ -905,8 +911,8 @@ public function addUserAsHost($event_id, $user_id) */ public function removeUserAsHost($event_id, $user_id) { - $sql = "delete from user_admin where rtype = 'event' and rid = :event_id and uid = :user_id"; - $stmt = $this->_db->prepare($sql); + $sql = "delete from user_admin where rtype = 'event' and rid = :event_id and uid = :user_id"; + $stmt = $this->_db->prepare($sql); return $stmt->execute(array("event_id" => $event_id, "user_id" => $user_id)); } @@ -920,9 +926,9 @@ public function removeUserAsHost($event_id, $user_id) */ public function cacheTalkCount($event_id) { - $sql = "UPDATE events e SET talk_count = (SELECT COUNT(*) FROM talks t WHERE t.event_id = e.ID) ". - "WHERE e.ID = :event_id;"; - $stmt = $this->_db->prepare($sql); + $sql = "UPDATE events e SET talk_count = (SELECT COUNT(*) FROM talks t WHERE t.event_id = e.ID) " . + "WHERE e.ID = :event_id;"; + $stmt = $this->_db->prepare($sql); return $stmt->execute(array("event_id" => $event_id)); } @@ -936,9 +942,9 @@ public function cacheTalkCount($event_id) */ public function cacheCommentCount($event_id) { - $sql = "UPDATE events e SET comment_count = ". - "(SELECT COUNT(*) FROM event_comments ec WHERE ec.event_id = e.ID) WHERE e.ID = :event_id;"; - $stmt = $this->_db->prepare($sql); + $sql = "UPDATE events e SET comment_count = " . + "(SELECT COUNT(*) FROM event_comments ec WHERE ec.event_id = e.ID) WHERE e.ID = :event_id;"; + $stmt = $this->_db->prepare($sql); return $stmt->execute(array("event_id" => $event_id)); } @@ -952,9 +958,9 @@ public function cacheCommentCount($event_id) */ public function cacheTrackCount($event_id) { - $sql = "UPDATE events e SET track_count = (SELECT COUNT(*) FROM event_track et WHERE et.event_id = e.ID) " . - "WHERE e.ID = :event_id;"; - $stmt = $this->_db->prepare($sql); + $sql = "UPDATE events e SET track_count = (SELECT COUNT(*) FROM event_track et WHERE et.event_id = e.ID) " . + "WHERE e.ID = :event_id;"; + $stmt = $this->_db->prepare($sql); return $stmt->execute(array("event_id" => $event_id)); } @@ -1013,10 +1019,10 @@ public function getPendingEventsCount() public function getPendingEventsCountByUser($user_id) { $sql = 'select count(*) as count ' - . 'from events e ' - . 'join user_admin ua ON e.ID=ua.rid ' - . 'where e.pending = 1 AND ua.rtype="event" ' - . 'AND ua.uid = :user_id '; + . 'from events e ' + . 'join user_admin ua ON e.ID=ua.rid ' + . 'where e.pending = 1 AND ua.rtype="event" ' + . 'AND ua.uid = :user_id '; $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array("user_id" => $user_id)); @@ -1034,7 +1040,7 @@ public function getPendingEventsCountByUser($user_id) * that table. Finally we add an entry to the tags_events-table for each * given tag to connect the new tags with the given event. * - * @param int $event_id + * @param int $event_id * @param array $tags * * @return bool @@ -1131,12 +1137,12 @@ public function reject($event_id, $reviewing_user_id) */ protected function getImages($event_id) { - $image_sql = 'select i.type, i.url, i.width, i.height' - . ' from event_images i ' - . ' where i.event_id = :event_id'; + $image_sql = 'select i.type, i.url, i.width, i.height' + . ' from event_images i ' + . ' where i.event_id = :event_id'; $image_stmt = $this->_db->prepare($image_sql); $image_stmt->execute(array("event_id" => $event_id)); - $images = $image_stmt->fetchAll(PDO::FETCH_ASSOC); + $images = $image_stmt->fetchAll(PDO::FETCH_ASSOC); // add named keys so we can easily refer to these results $collection = []; @@ -1145,6 +1151,7 @@ protected function getImages($event_id) $collection[$row['type']] = $row; } } + return $collection; } @@ -1152,14 +1159,15 @@ protected function getImages($event_id) * Remove all image records for this event * * Used when we are uploading new images + * * @param int $event_id the event to add an image to * * @return bool whether the record was saved */ public function removeImages($event_id) { - $sql = 'delete from event_images' - . ' where event_id = :event_id'; + $sql = 'delete from event_images' + . ' where event_id = :event_id'; $stmt = $this->_db->prepare($sql); return $stmt->execute(array("event_id" => $event_id)); @@ -1170,43 +1178,45 @@ public function removeImages($event_id) * * For legacy reasons, we'll add a "small" image to the events table also * - * @param int $event_id the event to add an image to + * @param int $event_id the event to add an image to * @param string $filename the filename we saved the image as (the rest of - * the URL is hardcoded here for now because images don't work the - * same way on dev as they do on live) - * @param int $width the width of the image - * @param int $height the height of the image - * @param string $type Freeform field for what sort of image it is, "orig" and "small" are our starter set + * the URL is hardcoded here for now because images don't work the + * same way on dev as they do on live) + * @param int $width the width of the image + * @param int $height the height of the image + * @param string $type Freeform field for what sort of image it is, "orig" and "small" are our starter set * * @return bool whether the record was saved */ public function saveNewImage($event_id, $filename, $width, $height, $type) { - $sql = 'insert into event_images set ' - . 'event_id = :event_id, width = :width, height = :height, ' - . 'url = :url, type = :type'; - $stmt = $this->_db->prepare($sql); + $sql = 'insert into event_images set ' + . 'event_id = :event_id, width = :width, height = :height, ' + . 'url = :url, type = :type'; + $stmt = $this->_db->prepare($sql); $result = $stmt->execute([ "event_id" => $event_id, - "type" => $type, - "width" => $width, - "height" => $height, - "url" => $this->website_url . "/inc/img/event_icons/" . $filename, + "type" => $type, + "width" => $width, + "height" => $height, + "url" => $this->website_url . "/inc/img/event_icons/" . $filename, ]); // for small images, update the old table too if ($type == "small") { - $legacy_sql = 'update events set event_icon = :filename where ID = :event_id'; + $legacy_sql = 'update events set event_icon = :filename where ID = :event_id'; $legacy_stmt = $this->_db->prepare($legacy_sql); $legacy_stmt->execute(["event_id" => $event_id, "filename" => $filename]); } + return $result; } /** * @param string $sql - * @param array $data - * @param bool $verbose + * @param array $data + * @param bool $verbose + * * @return false|array */ protected function getTransformedResultsFromSqlAndData($sql, array $data, $verbose = false) @@ -1230,6 +1240,7 @@ protected function getTransformedResultsFromSqlAndData($sql, array $data, $verbo /** * @param array $event * @param array $mandatoryFields + * * @throws Exception */ protected function verifyMandatoryFields(array $event, array $mandatoryFields) diff --git a/src/models/LanguageMapper.php b/src/Model/LanguageMapper.php similarity index 93% rename from src/models/LanguageMapper.php rename to src/Model/LanguageMapper.php index e012946e6..c06eb4b92 100644 --- a/src/models/LanguageMapper.php +++ b/src/Model/LanguageMapper.php @@ -1,5 +1,10 @@ getLanguages(1, 0, array('ID' => (int) $language_id)); + $results = $this->getLanguages(1, 0, array('ID' => (int)$language_id)); if ($results) { return $this->transformResults($results, $verbose); } @@ -41,8 +46,8 @@ public function getLanguageById($language_id, $verbose = false) } /** - * @param int $resultsperpage - * @param int $start + * @param int $resultsperpage + * @param int $start * @param bool $verbose * * @return false|array @@ -84,8 +89,8 @@ public function transformResults(array $results, $verbose) } /** - * @param int $resultsperpage - * @param int $start + * @param int $resultsperpage + * @param int $start * @param array $params * * @return false|array diff --git a/src/models/OAuthModel.php b/src/Model/OAuthModel.php similarity index 90% rename from src/models/OAuthModel.php rename to src/Model/OAuthModel.php index d8297c3f7..ee2b86d9a 100644 --- a/src/models/OAuthModel.php +++ b/src/Model/OAuthModel.php @@ -1,5 +1,11 @@ getUserId($username, $password); - if (! $userId) { + if (!$userId) { return false; } @@ -162,14 +168,14 @@ public function getUserUri($userId) * Generate, store and return a new access token to the user * * @param string $consumer_key the identifier for the consumer - * @param int $user_id the user granting access + * @param int $user_id the user granting access * * @return false|string access token */ public function createAccessToken($consumer_key, $user_id) { - $hash = $this->generateToken(); - $accessToken = substr($hash, 0, 16); + $hash = $this->generateToken(); + $accessToken = substr($hash, 0, 16); $sql = "INSERT INTO oauth_access_tokens set access_token = :access_token, @@ -181,9 +187,9 @@ public function createAccessToken($consumer_key, $user_id) $stmt = $this->_db->prepare($sql); $result = $stmt->execute( array( - 'access_token' => $accessToken, - 'consumer_key' => $consumer_key, - 'user_id' => $user_id, + 'access_token' => $accessToken, + 'consumer_key' => $consumer_key, + 'user_id' => $user_id, ) ); @@ -209,6 +215,7 @@ public function generateToken() fclose($fp); $hash = sha1($entropy); // sha1 gives us a 40-byte hash + return $hash; } @@ -267,7 +274,7 @@ public function getConsumerName($token) * Check whether a supplied consumer is permitted to use * the "password" grant type during the OAuth process * - * @param string $key An OAuth consumer key to check + * @param string $key An OAuth consumer key to check * @param string $secret The corresponding consumer secret * * @return bool Whether the consumer is permitted @@ -319,7 +326,7 @@ public function isAccessTokenPermittedPasswordGrant($token) * * Useful when confirming old password before changing to a new one * - * @param int $userId The ID of the user we're checking + * @param int $userId The ID of the user we're checking * @param string $password Their supplied password * * @return boolean True if the password is correct, false otherwise @@ -344,9 +351,9 @@ public function reverifyUserPassword($userId, $password) /** * Create an access token for someone identified by twitter username * - * @param string $clientId aka consumer_key (of the joindin client) + * @param string $clientId aka consumer_key (of the joindin client) * @param string $twitterUsername User's twitter nick - * (that we just got back from authenticating them) + * (that we just got back from authenticating them) * * @return false|array access token */ @@ -359,7 +366,7 @@ public function createAccessTokenFromTwitterUsername($clientId, $twitterUsername $stmt = $this->_db->prepare($sql); $stmt->execute(array("twitter_username" => $twitterUsername)); $result = $stmt->fetch(PDO::FETCH_ASSOC); - if (! $result) { + if (!$result) { return false; } @@ -380,7 +387,7 @@ public function createAccessTokenFromTwitterUsername($clientId, $twitterUsername * * email (optional): The users email-address * * @param string $clientId - * @param array $values + * @param array $values * * @throws Exception * @return array @@ -388,7 +395,7 @@ public function createAccessTokenFromTwitterUsername($clientId, $twitterUsername public function createUserFromTwitterUsername($clientId, array $values) { $sql = "select ID from user " - . "where twitter_username = :twitter_username"; + . "where twitter_username = :twitter_username"; $stmt = $this->_db->prepare($sql); $stmt->execute(array("twitter_username" => $values['screen_name'])); @@ -399,15 +406,15 @@ public function createUserFromTwitterUsername($clientId, array $values) throw new Exception('User exists already'); } - if (! isset($values['email'])) { + if (!isset($values['email'])) { $values['email'] = 'email@example.net'; } $sql = "insert into user(username, full_name, twitter_username, email, verified, active, admin) " - . "values(:screen_name, :name, :screen_name, :email, 1, 1, 0)"; + . "values(:screen_name, :name, :screen_name, :email, 1, 1, 0)"; $stmt = $this->_db->prepare($sql); - if (! $stmt->execute([ + if (!$stmt->execute([ 'screen_name' => $values['screen_name'], 'name' => $values['name'], 'email' => $values['email'], @@ -422,10 +429,11 @@ public function createUserFromTwitterUsername($clientId, array $values) * Create an access token for someone identified by email address via a * third party authentication system such as Facebook * - * @param string $clientId aka consumer_key (of the joindin client) - * @param string $email User's email address (that we just got back from authenticating them) - * @param string $fullName User's full name from Facebook - * @param string $userName Username to be created if not found + * @param string $clientId aka consumer_key (of the joindin client) + * @param string $email User's email address (that we just got back from authenticating them) + * @param string $fullName User's full name from Facebook + * @param string $userName Username to be created if not found + * * @return array|false Array of access token and user uri on success or false or failure */ public function createAccessTokenFromTrustedEmail($clientId, $email, $fullName = '', $userName = '') @@ -438,7 +446,7 @@ public function createAccessTokenFromTrustedEmail($clientId, $email, $fullName = $stmt = $this->_db->prepare($sql); $stmt->execute(array("email" => $email)); $result = $stmt->fetch(PDO::FETCH_ASSOC); - if (!$result && $fullName && $userName) { + if (!$result && $fullName && $userName) { $result = $this->createUserFromTrustedEmail($email, $fullName, $userName); } @@ -469,7 +477,7 @@ protected function createUserFromTrustedEmail($email, $fullName, $userName) $stmt = $this->_db->prepare($sql); $stmt->execute( [ - "email" => $email, + "email" => $email, 'fullName' => $fullName, 'userName' => $userName ] diff --git a/src/models/PendingTalkClaimMapper.php b/src/Model/PendingTalkClaimMapper.php similarity index 70% rename from src/models/PendingTalkClaimMapper.php rename to src/Model/PendingTalkClaimMapper.php index a99b1dded..ba4d479ce 100644 --- a/src/models/PendingTalkClaimMapper.php +++ b/src/Model/PendingTalkClaimMapper.php @@ -1,9 +1,14 @@ "username", - "speaker_id" => "full_name", + "talk_id" => "username", + "speaker_id" => "full_name", ]; } @@ -35,12 +40,12 @@ public function getDefaultFields() public function getVerboseFields() { return [ - "talk_id" => "username", - "speaker_id" => "full_name", - "date_added" => "date_added", - "claim_id" => "claim_id", - "user_approved_at" => "user_approved_at", - "host_approved_at" => "host_approved_at", + "talk_id" => "username", + "speaker_id" => "full_name", + "date_added" => "date_added", + "claim_id" => "claim_id", + "user_approved_at" => "user_approved_at", + "host_approved_at" => "host_approved_at", ]; } @@ -61,12 +66,13 @@ public function claimTalkAsSpeaker($talk_id, $speaker_id, $claim_id) (:talk_id,:submitted_by,:speaker_id,UNIX_TIMESTAMP(),:claim_id,NOW()) '; $stmt = $this->_db->prepare($sql); + return $stmt->execute( [ - 'talk_id' => $talk_id, - 'submitted_by' => $speaker_id, - 'speaker_id' => $speaker_id, - 'claim_id' => $claim_id + 'talk_id' => $talk_id, + 'submitted_by' => $speaker_id, + 'speaker_id' => $speaker_id, + 'claim_id' => $claim_id ] ); } @@ -89,12 +95,13 @@ public function assignTalkAsHost($talk_id, $speaker_id, $claim_id, $user_id) (:talk_id,:submitted_by,:speaker_id,UNIX_TIMESTAMP(),:claim_id,NOW()) '; $stmt = $this->_db->prepare($sql); + return $stmt->execute( [ - 'talk_id' => $talk_id, - 'submitted_by' => $user_id, - 'speaker_id' => $speaker_id, - 'claim_id' => $claim_id + 'talk_id' => $talk_id, + 'submitted_by' => $user_id, + 'speaker_id' => $speaker_id, + 'claim_id' => $claim_id ] ); } @@ -108,16 +115,16 @@ public function assignTalkAsHost($talk_id, $speaker_id, $claim_id, $user_id) */ public function claimExists($talk_id, $speaker_id, $claim_id) { - $sql = 'select * from pending_talk_claims WHERE + $sql = 'select * from pending_talk_claims WHERE talk_id = :talk_id AND claim_id = :claim_id AND speaker_id = :speaker_id LIMIT 1 '; - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); $response = $stmt->execute( [ - 'talk_id' => $talk_id, - 'speaker_id' => $speaker_id, - 'claim_id' => $claim_id + 'talk_id' => $talk_id, + 'speaker_id' => $speaker_id, + 'claim_id' => $claim_id ] ); if ($response) { @@ -132,6 +139,7 @@ public function claimExists($talk_id, $speaker_id, $claim_id) return false; } } + return false; } @@ -144,17 +152,18 @@ public function claimExists($talk_id, $speaker_id, $claim_id) */ public function approveAssignmentAsSpeaker($talk_id, $speaker_id, $claim_id) { - $sql = 'update pending_talk_claims SET user_approved_at = NOW() WHERE + $sql = 'update pending_talk_claims SET user_approved_at = NOW() WHERE talk_id = :talk_id AND claim_id = :claim_id AND speaker_id = :speaker_id AND user_approved_at IS NULL LIMIT 1 '; $stmt = $this->_db->prepare($sql); + return $stmt->execute( [ - 'talk_id' => $talk_id, - 'speaker_id' => $speaker_id, - 'claim_id' => $claim_id + 'talk_id' => $talk_id, + 'speaker_id' => $speaker_id, + 'claim_id' => $claim_id ] ); } @@ -168,17 +177,18 @@ public function approveAssignmentAsSpeaker($talk_id, $speaker_id, $claim_id) */ public function approveClaimAsHost($talk_id, $speaker_id, $claim_id) { - $sql = 'update pending_talk_claims SET host_approved_at = NOW() WHERE + $sql = 'update pending_talk_claims SET host_approved_at = NOW() WHERE talk_id = :talk_id AND claim_id = :claim_id AND speaker_id = :speaker_id AND host_approved_at IS NULL LIMIT 1 '; $stmt = $this->_db->prepare($sql); + return $stmt->execute( [ - 'talk_id' => $talk_id, - 'speaker_id' => $speaker_id, - 'claim_id' => $claim_id + 'talk_id' => $talk_id, + 'speaker_id' => $speaker_id, + 'claim_id' => $claim_id ] ); } @@ -192,18 +202,19 @@ public function approveClaimAsHost($talk_id, $speaker_id, $claim_id) */ public function rejectClaimAsHost($talk_id, $speaker_id, $claim_id) { - $sql = 'DELETE FROM pending_talk_claims + $sql = 'DELETE FROM pending_talk_claims WHERE talk_id = :talk_id AND claim_id = :claim_id AND speaker_id = :speaker_id AND host_approved_at IS NULL LIMIT 1 '; $stmt = $this->_db->prepare($sql); + return $stmt->execute( [ - 'talk_id' => $talk_id, - 'speaker_id' => $speaker_id, - 'claim_id' => $claim_id + 'talk_id' => $talk_id, + 'speaker_id' => $speaker_id, + 'claim_id' => $claim_id ] ); } @@ -215,33 +226,33 @@ public function rejectClaimAsHost($talk_id, $speaker_id, $claim_id) */ public function getPendingClaimsByEventId($event_id) { - $base = $this->_request->base; - $version = $this->_request->version; + $base = $this->_request->base; + $version = $this->_request->version; - $sql = 'select c.*, s.speaker_name from pending_talk_claims c + $sql = 'select c.*, s.speaker_name from pending_talk_claims c inner join talks t on t.ID = c.talk_id inner join talk_speaker s on s.ID = c.claim_id where t.event_id = :event_id and (host_approved_at IS NULL or user_approved_at IS NULL)'; - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); $response = $stmt->execute(['event_id' => $event_id]); - - if (! $response || $stmt->rowCount() < 1) { + + if (!$response || $stmt->rowCount() < 1) { return false; } - $list = []; + $list = []; $result = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($result as $row) { $date = new DateTime('@' . $row['date_added']); $list[] = new PendingTalkClaimModel( [ - 'date_added' => $date->format("c"), - 'display_name' => $row['speaker_name'], - 'talk_uri' => $base . '/' . $version . '/talks/' . $row['talk_id'], - 'speaker_uri' => $base . '/' . $version . '/users/' . $row['speaker_id'], - 'approve_claim_uri' => $base . '/' . $version . '/talks/' . $row['talk_id'] . '/speakers' + 'date_added' => $date->format("c"), + 'display_name' => $row['speaker_name'], + 'talk_uri' => $base . '/' . $version . '/talks/' . $row['talk_id'], + 'speaker_uri' => $base . '/' . $version . '/users/' . $row['speaker_id'], + 'approve_claim_uri' => $base . '/' . $version . '/talks/' . $row['talk_id'] . '/speakers' ] ); } diff --git a/src/models/PendingTalkClaimModel.php b/src/Model/PendingTalkClaimModel.php similarity index 80% rename from src/models/PendingTalkClaimModel.php rename to src/Model/PendingTalkClaimModel.php index 5265c5f73..b61aa94b5 100644 --- a/src/models/PendingTalkClaimModel.php +++ b/src/Model/PendingTalkClaimModel.php @@ -1,5 +1,9 @@ 'date_added', - 'display_name' => 'display_name', - 'speaker_uri' => 'speaker_uri', - 'talk_uri' => 'talk_uri', + 'date_added' => 'date_added', + 'display_name' => 'display_name', + 'speaker_uri' => 'speaker_uri', + 'talk_uri' => 'talk_uri', ); } @@ -43,14 +47,14 @@ public function getVerboseFields() * Return an array with client-facing fields and hypermedia, ready for output * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ public function getOutputView(Request $request, $verbose = false) { $item = parent::getOutputView($request, $verbose); - + // add Hypermedia $base = $request->base; $version = $request->version; diff --git a/src/models/PendingTalkClaimModelCollection.php b/src/Model/PendingTalkClaimModelCollection.php similarity index 91% rename from src/models/PendingTalkClaimModelCollection.php rename to src/Model/PendingTalkClaimModelCollection.php index e4dd960e7..96cc87285 100644 --- a/src/models/PendingTalkClaimModelCollection.php +++ b/src/Model/PendingTalkClaimModelCollection.php @@ -1,5 +1,9 @@ list = []; + $this->list = []; $this->total = $total; // hydrate the model objects if necessary and store to list @@ -39,7 +43,7 @@ public function __construct(array $data, $total) * and pagination * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ diff --git a/src/models/TalkCommentMapper.php b/src/Model/TalkCommentMapper.php similarity index 83% rename from src/models/TalkCommentMapper.php rename to src/Model/TalkCommentMapper.php index c7768a1b8..b339fa172 100644 --- a/src/models/TalkCommentMapper.php +++ b/src/Model/TalkCommentMapper.php @@ -1,5 +1,10 @@ buildLimit($resultsperpage, $start); + $sql .= $this->buildLimit($resultsperpage, $start); $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array( ':talk_id' => $talk_id @@ -63,9 +68,9 @@ public function getCommentsByTalkId($talk_id, $resultsperpage, $start, $verbose } /** - * @param int $event_id - * @param int $resultsperpage - * @param int $start + * @param int $event_id + * @param int $resultsperpage + * @param int $start * @param bool $verbose * * @return false|array @@ -95,9 +100,9 @@ public function getCommentsByEventId($event_id, $resultsperpage, $start, $verbos } /** - * @param int $user_id - * @param int $resultsperpage - * @param int $start + * @param int $user_id + * @param int $resultsperpage + * @param int $start * @param bool $verbose * * @return false|array @@ -127,7 +132,7 @@ public function getCommentsByUserId($user_id, $resultsperpage, $start, $verbose } /** - * @param int $comment_id + * @param int $comment_id * @param bool $verbose * @param bool $include_hidden * @@ -135,8 +140,8 @@ public function getCommentsByUserId($user_id, $resultsperpage, $start, $verbose */ public function getCommentById($comment_id, $verbose = false, $include_hidden = false) { - $sql = $this->getBasicSQL($include_hidden); - $sql .= ' and tc.ID = :comment_id '; + $sql = $this->getBasicSQL($include_hidden); + $sql .= ' and tc.ID = :comment_id '; $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array( ':comment_id' => $comment_id @@ -161,7 +166,7 @@ public function transformResults(array $results, $verbose) $total = $results['total']; unset($results['total']); - $list = parent::transformResults($results, $verbose); + $list = parent::transformResults($results, $verbose); // add per-item links if (is_array($list) && count($list)) { @@ -175,13 +180,13 @@ public function transformResults(array $results, $verbose) return [ 'comments' => $list, - 'meta' => $this->getPaginationLinks($list, $total), + 'meta' => $this->getPaginationLinks($list, $total), ]; } /** * @param array $row - * @param bool $verbose + * @param bool $verbose * * @return array */ @@ -195,14 +200,15 @@ protected function formatOneComment(array $row, $verbose) if (true === $verbose) { $result['gravatar_hash'] = md5(strtolower($row['email'])); } - $result['uri'] = $base . '/' . $version . '/talk_comments/' . $row['ID']; - $result['verbose_uri'] = $base . '/' . $version . '/talk_comments/' . $row['ID'] . '?verbose=yes'; - $result['talk_uri'] = $base . '/' . $version . '/talks/'. $row['talk_id']; + $result['uri'] = $base . '/' . $version . '/talk_comments/' . $row['ID']; + $result['verbose_uri'] = $base . '/' . $version . '/talk_comments/' . $row['ID'] . '?verbose=yes'; + $result['talk_uri'] = $base . '/' . $version . '/talks/' . $row['talk_id']; $result['talk_comments_uri'] = $base . '/' . $version . '/talks/' . $row['talk_id'] . '/comments'; - $result['reported_uri'] = $base . '/' . $version . '/talk_comments/' . $row['ID'] . '/reported'; + $result['reported_uri'] = $base . '/' . $version . '/talk_comments/' . $row['ID'] . '/reported'; if ($row['user_id']) { $result['user_uri'] = $base . '/' . $version . '/users/' . $row['user_id']; } + return $result; } @@ -327,7 +333,7 @@ public function getCommentInfo($comment_id) * pending moderation * * @param int $comment_id the comment that was reported - * @param int $user_id the user that reported it + * @param int $user_id the user that reported it */ public function userReportedComment($comment_id, $user_id) { @@ -337,14 +343,15 @@ public function userReportedComment($comment_id, $user_id) reporting_date = NOW()"; $report_stmt = $this->_db->prepare($report_sql); - $result = $report_stmt->execute([ + $result = $report_stmt->execute([ "talk_comment_id" => $comment_id, - "user_id" => $user_id]); + "user_id" => $user_id + ]); - $hide_sql = "update talk_comments + $hide_sql = "update talk_comments set active = 0 where ID = :talk_comment_id"; $hide_stmt = $this->_db->prepare($hide_sql); - $result = $hide_stmt->execute(["talk_comment_id" => $comment_id]); + $result = $hide_stmt->execute(["talk_comment_id" => $comment_id]); } /** @@ -352,7 +359,7 @@ public function userReportedComment($comment_id, $user_id) * * Includes verbose nested comment info * - * @param $event_id int The event whose comments should be returned + * @param $event_id int The event whose comments should be returned * @param $moderated bool Whether to include comments that have been moderated * * @return TalkCommentReportModelCollection @@ -376,27 +383,28 @@ public function getReportedCommentsByEventId($event_id, $moderated = false) $sql .= " and rc.decision is null"; } - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); $result = $stmt->execute(['event_id' => $event_id]); // need to also set the comment info - $list = []; - $total = 0; - $comment_sql = $this->getBasicSQL(true) - . " and tc.ID = :comment_id"; + $list = []; + $total = 0; + $comment_sql = $this->getBasicSQL(true) + . " and tc.ID = :comment_id"; $comment_stmt = $this->_db->prepare($comment_sql); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $total++; $comment_result = $comment_stmt->execute(['comment_id' => $row['talk_comment_id']]); if ($comment_result && $comment = $comment_stmt->fetch(PDO::FETCH_ASSOC)) { // work around the existing transform logic - $comment_array = [$comment]; - $comment_array = parent::transformResults($comment_array, true); - $item = current($comment_array); + $comment_array = [$comment]; + $comment_array = parent::transformResults($comment_array, true); + $item = current($comment_array); $row['comment'] = array_merge($item, $this->formatOneComment($comment, true)); } $list[] = new TalkCommentReportModel($row); } + return new TalkCommentReportModelCollection($list, $total); } @@ -404,29 +412,29 @@ public function getReportedCommentsByEventId($event_id, $moderated = false) * A comment has been moderated. Record the decision and if the decision * is 'denied' then set the comment back to active. * - * @param string $decision the decision: 'approved' or 'denied' - * @param int $comment_id the comment that was reported - * @param int $user_id the user that reported it + * @param string $decision the decision: 'approved' or 'denied' + * @param int $comment_id the comment that was reported + * @param int $user_id the user that reported it */ public function moderateReportedComment($decision, $comment_id, $user_id) { if (in_array($decision, ['approved', 'denied'])) { // record the decision - $sql = 'update reported_talk_comments set + $sql = 'update reported_talk_comments set decision = :decision, deciding_user_id = :user_id, deciding_date = NOW() where talk_comment_id = :comment_id'; $stmt = $this->_db->prepare($sql); $stmt->execute([ - 'decision' => $decision, - 'user_id' => $user_id, + 'decision' => $decision, + 'user_id' => $user_id, 'comment_id' => $comment_id, ]); if ($decision == 'denied') { // the report is denied, therefore make the comment active again - $show_sql = "update talk_comments set active = 1 where ID = :comment_id"; + $show_sql = "update talk_comments set active = 1 where ID = :comment_id"; $show_stmt = $this->_db->prepare($show_sql); $show_stmt->execute(["comment_id" => $comment_id]); } @@ -440,8 +448,8 @@ public function moderateReportedComment($decision, $comment_id, $user_id) */ public function getRawComment($comment_id) { - $sql = "select tc.* from talk_comments tc where tc.ID = :comment_id"; - $stmt = $this->_db->prepare($sql); + $sql = "select tc.* from talk_comments tc where tc.ID = :comment_id"; + $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array(':comment_id' => $comment_id)); if ($response) { $results = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -455,18 +463,18 @@ public function getRawComment($comment_id) /** * @param integer $comment_id - * @param string $new_comment_body + * @param string $new_comment_body * * @return bool */ public function updateCommentBody($comment_id, $new_comment_body) { - $sql = "update talk_comments set comment = :new_comment_body where ID = :comment_id"; + $sql = "update talk_comments set comment = :new_comment_body where ID = :comment_id"; $stmt = $this->_db->prepare($sql); return $stmt->execute([ "new_comment_body" => $new_comment_body, - "comment_id" => $comment_id + "comment_id" => $comment_id ]); } } diff --git a/src/models/TalkCommentReportModel.php b/src/Model/TalkCommentReportModel.php similarity index 82% rename from src/models/TalkCommentReportModel.php rename to src/Model/TalkCommentReportModel.php index 5322d26df..2ade537d3 100644 --- a/src/models/TalkCommentReportModel.php +++ b/src/Model/TalkCommentReportModel.php @@ -1,5 +1,9 @@ 'comment', + 'comment' => 'comment', ]; } @@ -54,24 +58,24 @@ public function getSubResources() * Return this object with client-facing fields and hypermedia, ready for output * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ public function getOutputView(Request $request, $verbose = false) { $item = parent::getOutputView($request, $verbose); - + // add Hypermedia $base = $request->base; $version = $request->version; $item['reporting_user_uri'] = $base . '/' . $version . '/users/' . $this->reporting_user_id; if (!empty($this->deciding_user_id)) { - $item['deciding_user_uri'] = $base . '/' . $version . '/users/' . $this->deciding_user_id; + $item['deciding_user_uri'] = $base . '/' . $version . '/users/' . $this->deciding_user_id; } - $item['event_uri'] = $base . '/' . $version . '/events/' . $this->event_id; - $item['talk_uri'] = $base . '/' . $version . '/talks/' . $this->talk_id; + $item['event_uri'] = $base . '/' . $version . '/events/' . $this->event_id; + $item['talk_uri'] = $base . '/' . $version . '/talks/' . $this->talk_id; return $item; } diff --git a/src/models/TalkCommentReportModelCollection.php b/src/Model/TalkCommentReportModelCollection.php similarity index 91% rename from src/models/TalkCommentReportModelCollection.php rename to src/Model/TalkCommentReportModelCollection.php index 59b8fd2db..418cd0d12 100644 --- a/src/models/TalkCommentReportModelCollection.php +++ b/src/Model/TalkCommentReportModelCollection.php @@ -1,5 +1,9 @@ list = []; + $this->list = []; $this->total = $total; // hydrate the model objects if necessary and store to list @@ -39,7 +43,7 @@ public function __construct(array $data, $total) * and pagination * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ diff --git a/src/models/TalkMapper.php b/src/Model/TalkMapper.php similarity index 88% rename from src/models/TalkMapper.php rename to src/Model/TalkMapper.php index a2a66213e..0116a18fe 100644 --- a/src/models/TalkMapper.php +++ b/src/Model/TalkMapper.php @@ -1,5 +1,10 @@ getTracks($row['ID']); } } + return $results; } /** * Get all the talks for this event * - * @param int $event_id The event to fetch talks for - * @param int $resultsperpage How many results to return on each page - * @param int $start Which result to start with + * @param int $event_id The event to fetch talks for + * @param int $resultsperpage How many results to return on each page + * @param int $start Which result to start with * * @return false|TalkModelCollection */ @@ -79,7 +85,7 @@ public function getTalksByEventId($event_id, $resultsperpage, $start) )); if ($response) { $results = $stmt->fetchAll(PDO::FETCH_ASSOC); - $total = $this->getTotalCount($sql, array(':event_id' => $event_id)); + $total = $this->getTotalCount($sql, array(':event_id' => $event_id)); $results = $this->processResults($results); foreach ($results as &$talk) { $talk = $this->addTalkMediaTypes([$talk])[0]; @@ -95,14 +101,14 @@ public function getTalksByEventId($event_id, $resultsperpage, $start) * Retrieve a single talk * * @param integer $talk_id - * @param bool $verbose + * @param bool $verbose * * @return TalkModel|false */ public function getTalkById($talk_id, $verbose = false) { - $sql = $this->getBasicSQL(); - $sql .= ' and t.ID = :talk_id'; + $sql = $this->getBasicSQL(); + $sql .= ' and t.ID = :talk_id'; $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array("talk_id" => $talk_id)); if ($response) { @@ -124,8 +130,8 @@ public function getTalkById($talk_id, $verbose = false) * Search talks by title * * @param string $keyword - * @param int $resultsperpage - * @param int $start + * @param int $resultsperpage + * @param int $start * * @return TalkModelCollection|bool Result collection or false on failure */ @@ -145,9 +151,10 @@ public function getTalksByTitleSearch($keyword, $resultsperpage, $start) if ($response) { $results = $stmt->fetchAll(PDO::FETCH_ASSOC); - $total = $this->getTotalCount($sql, $data); + $total = $this->getTotalCount($sql, $data); $results = $this->processResults($results); + return new TalkModelCollection($results, $total); } @@ -290,11 +297,11 @@ protected function getTracks($talk_id) $retval = []; foreach ($tracks as $track) { // Make the track_uri - $track_uri = $base . '/' . $version . '/tracks/' . $track['ID']; + $track_uri = $base . '/' . $version . '/tracks/' . $track['ID']; $remove_track_uri = $base . '/' . $version . '/talks/' . $talk_id . '/tracks/' . $track['ID']; - $retval[] = array( - 'track_name' => $track['track_name'], - 'track_uri' => $track_uri, + $retval[] = array( + 'track_name' => $track['track_name'], + 'track_uri' => $track_uri, 'remove_track_uri' => $remove_track_uri, ); } @@ -337,7 +344,7 @@ public function getTalksBySpeaker($user_id, $resultsperpage, $start) )); if ($response) { $results = $stmt->fetchAll(PDO::FETCH_ASSOC); - $total = $this->getTotalCount($sql, array(':user_id' => $user_id)); + $total = $this->getTotalCount($sql, array(':user_id' => $user_id)); return new TalkModelCollection($this->processResults($results), $total); } @@ -415,7 +422,7 @@ public function createTalk(array $data) * - type_id (id of the talk's type) * * @param array $data - * @param int $talk_id + * @param int $talk_id * * @throws Exception */ @@ -432,16 +439,16 @@ public function editTalk(array $data, $talk_id) 'duration' => 'duration', 'slides_link' => 'slides_link', ]; - $items = []; - $pairs = []; + $items = []; + $pairs = []; foreach ($fields as $api_name => $column_name) { if (array_key_exists($api_name, $data)) { - $pairs[] = "$column_name = :$api_name"; + $pairs[] = "$column_name = :$api_name"; $items[$api_name] = $data[$api_name]; } } // language is special as we need to select the ID from lang - $pairs[] = 'lang = (select ID from lang where lang_name = :language)'; + $pairs[] = 'lang = (select ID from lang where lang_name = :language)'; $items['language'] = $data['language']; // add talk_id for where clause @@ -481,7 +488,7 @@ public function setType($talk_id, $type_id) $cat_stmt = $this->_db->prepare($cat_sql); $cat_stmt->execute(array( ':talk_id' => $talk_id, - ':type_id' => $type_id, + ':type_id' => $type_id, )); if (count($cat_stmt->fetchAll()) > 0) { @@ -499,7 +506,7 @@ public function setType($talk_id, $type_id) $cat_stmt = $this->_db->prepare($cat_sql); return $cat_stmt->execute(array( - ':talk_id' => $talk_id, + ':talk_id' => $talk_id, ':type_id' => $type_id, )); } @@ -521,24 +528,24 @@ public function setType($talk_id, $type_id) public function updateSpeakersOnTalk($talk_id, array $speakers) { // get the current speakers - $sql = 'select ' - . 'if(ts.speaker_id,user.full_name, ts.speaker_name) as val ' - . 'from talk_speaker AS ts ' - . 'left join user on user.ID = ts.speaker_id ' - . 'where ts.talk_id = :talk_id'; + $sql = 'select ' + . 'if(ts.speaker_id,user.full_name, ts.speaker_name) as val ' + . 'from talk_speaker AS ts ' + . 'left join user on user.ID = ts.speaker_id ' + . 'where ts.talk_id = :talk_id'; $stmt = $this->_db->prepare($sql); $stmt->execute(['talk_id' => $talk_id]); $current_speakers = $stmt->fetchAll(PDO::FETCH_COLUMN); // add the speakers that aren't already attached to the talk $new_speakers = array_diff($speakers, $current_speakers); - $sql = "insert into talk_speaker + $sql = "insert into talk_speaker (talk_id, speaker_name, status) values (:talk_id, :speaker_name, NULL)"; - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); foreach ($new_speakers as $name) { $params = [ - 'talk_id' => $talk_id, + 'talk_id' => $talk_id, 'speaker_name' => $name, ]; $stmt->execute($params); @@ -547,13 +554,13 @@ public function updateSpeakersOnTalk($talk_id, array $speakers) // remove speakers that are currently attached to the talk, but not // in the list provided $speakers_to_delete = array_diff($current_speakers, $speakers); - $sql = "delete from talk_speaker WHERE + $sql = "delete from talk_speaker WHERE talk_id = :talk_id and speaker_name = :speaker_name"; - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); foreach ($speakers_to_delete as $name) { $params = [ - 'talk_id' => $talk_id, + 'talk_id' => $talk_id, 'speaker_name' => $name, ]; $stmt->execute($params); @@ -601,7 +608,7 @@ protected function getUserRatingOnTalk($talk_id, $user_id) $result = $stmt->fetch(); - if (! $result) { + if (!$result) { return false; } @@ -620,7 +627,7 @@ public function isUserASpeakerOnTalk($talk_id, $user_id) { $sql = "select ID from talk_speaker where talk_id = :talk_id and speaker_id = :user_id"; $stmt = $this->_db->prepare($sql); - $stmt->execute(array("talk_id" => (int) $talk_id, "user_id" => (int) $user_id)); + $stmt->execute(array("talk_id" => (int)$talk_id, "user_id" => (int)$user_id)); if ($stmt->fetch()) { return true; @@ -640,7 +647,7 @@ protected function generateStub($talk_id) { $i = 0; while ($i < 5) { - $stub = substr(md5(mt_rand()), 3, 5); + $stub = substr(md5(mt_rand()), 3, 5); try { $stored = $this->storeStub($stub, $talk_id); // only return a value if we actually stored one @@ -649,7 +656,7 @@ protected function generateStub($talk_id) } catch (Exception $e) { // failed to store - try again } - $i ++; + $i++; } return $stored_stub; @@ -660,8 +667,8 @@ protected function generateStub($talk_id) * If not, we probably failed the unique check and the calling code can * decide what to do next * - * @param string $stub The stub for this talk - * @param int $talk_id The talk to store against + * @param string $stub The stub for this talk + * @param int $talk_id The talk to store against * * @return boolean whether we stored it or not */ @@ -681,8 +688,8 @@ protected function storeStub($stub, $talk_id) * ensure uniqueness, by adding hour and then hour-minute to the inflected * title. * - * @param string $title The talk title - * @param int $talk_id The talk to store the title against + * @param string $title The talk title + * @param int $talk_id The talk to store the title against * * @return string The value we stored */ @@ -697,7 +704,7 @@ protected function generateInflectedTitle($title, $talk_id) // If that doesn't work, try to store with the talk ID tacked on $inflected_title .= '-' . $talk_id; - $result = $this->storeInflectedTitle($inflected_title, $talk_id); + $result = $this->storeInflectedTitle($inflected_title, $talk_id); if ($result) { return $inflected_title; } @@ -715,7 +722,7 @@ protected function generateInflectedTitle($title, $talk_id) * update will fail. The calling code catches this and picks a new title * * @param string $inflected_title - * @param int $talk_id + * @param int $talk_id * * @return bool */ @@ -724,7 +731,7 @@ protected function storeInflectedTitle($inflected_title, $talk_id) $sql = "update talks set url_friendly_talk_title = :inflected_title where ID = :talk_id"; - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); try { $result = $stmt->execute(array( @@ -734,6 +741,7 @@ protected function storeInflectedTitle($inflected_title, $talk_id) } catch (Exception $e) { return false; } + return $result; } @@ -807,23 +815,24 @@ public function addTalkToTrack($talk_id, $track_id) { $params = [ 'track_id' => $track_id, - 'talk_id' => $talk_id, + 'talk_id' => $talk_id, ]; // is this link in the database already? - $sql = 'select ID from talk_track where track_id = :track_id and talk_id = :talk_id'; + $sql = 'select ID from talk_track where track_id = :track_id and talk_id = :talk_id'; $stmt = $this->_db->prepare($sql); $stmt->execute($params); $talk_track_id = $stmt->fetchColumn(); if ($talk_track_id === false) { // insert new row as not in database - $sql = 'insert into talk_track (track_id, talk_id) values (:track_id, :talk_id)'; + $sql = 'insert into talk_track (track_id, talk_id) values (:track_id, :talk_id)'; $stmt = $this->_db->prepare($sql); $stmt->execute($params); $talk_track_id = $this->_db->lastInsertId(); } + return $talk_track_id; } @@ -837,10 +846,10 @@ public function removeTrackFromTalk($talk_id, $track_id) { $params = [ 'track_id' => $track_id, - 'talk_id' => $talk_id, + 'talk_id' => $talk_id, ]; - $sql = 'delete from talk_track where track_id = :track_id and talk_id = :talk_id'; + $sql = 'delete from talk_track where track_id = :track_id and talk_id = :talk_id'; $stmt = $this->_db->prepare($sql); $stmt->execute($params); } @@ -877,25 +886,29 @@ public function delete($talk_id) { $this->_db->beginTransaction(); - if (! $this->removeAllTalkLinks($talk_id)) { + if (!$this->removeAllTalkLinks($talk_id)) { $this->_db->rollBack(); + return false; } - if (! $this->removeTalkFromAllTracks($talk_id)) { + if (!$this->removeTalkFromAllTracks($talk_id)) { $this->_db->rollBack(); + return false; } - if (! $this->removeAllSpeakersFromTalk($talk_id)) { + if (!$this->removeAllSpeakersFromTalk($talk_id)) { $this->_db->rollBack(); + return false; } $sql = "DELETE FROM talks WHERE ID = :talk_id"; $stmt = $this->_db->prepare($sql); - if (! $stmt->execute(array("talk_id" => $talk_id))) { + if (!$stmt->execute(array("talk_id" => $talk_id))) { $this->_db->rollBack(); + return false; } @@ -905,7 +918,7 @@ public function delete($talk_id) } /** - * @param int $talk_id + * @param int $talk_id * @param string $display_name * * @return bool @@ -913,7 +926,7 @@ public function delete($talk_id) public function getSpeakerFromTalk($talk_id, $display_name) { $speaker_sql = 'select ts.* from talk_speaker ts ' - . 'where ts.talk_id = :talk_id and ts.speaker_name = :display_name'; + . 'where ts.talk_id = :talk_id and ts.speaker_name = :display_name'; $speaker_stmt = $this->_db->prepare($speaker_sql); $speaker_stmt->execute(array("talk_id" => $talk_id, "display_name" => $display_name)); $speakers = $speaker_stmt->fetchAll(PDO::FETCH_ASSOC); @@ -927,11 +940,11 @@ public function getSpeakerFromTalk($talk_id, $display_name) */ public function removeApprovedSpeakerFromTalk($talk_id, $speaker_id) { - $sql = 'update talk_speaker set speaker_id = null where talk_id = :talk_id and speaker_id = :speaker_id'; + $sql = 'update talk_speaker set speaker_id = null where talk_id = :talk_id and speaker_id = :speaker_id'; $stmt = $this->_db->prepare($sql); $stmt->execute( [ - 'talk_id' => $talk_id, + 'talk_id' => $talk_id, 'speaker_id' => $speaker_id, ] ); @@ -952,32 +965,33 @@ public function removeAllSpeakersFromTalk($talk_id) } /** - * @param int $talk_id - * @param int $claim_id - * @param int $speaker_id + * @param int $talk_id + * @param int $claim_id + * @param int $speaker_id * @param string $speaker_name * * @return bool */ public function assignTalkToSpeaker($talk_id, $claim_id, $speaker_id, $speaker_name) { - $sql = 'update talk_speaker + $sql = 'update talk_speaker SET speaker_id = :speaker_id, speaker_name = :speaker_name WHERE ID = :claim_id AND talk_id = :talk_id'; $stmt = $this->_db->prepare($sql); + return $stmt->execute( [ - 'speaker_id' => $speaker_id, - 'talk_id' => $talk_id, - 'claim_id' => $claim_id, - 'speaker_name' => $speaker_name + 'speaker_id' => $speaker_id, + 'talk_id' => $talk_id, + 'claim_id' => $claim_id, + 'speaker_name' => $speaker_name ] ); } /** - * @param int $talk_id + * @param int $talk_id * @param int|null $link_id * * @return array @@ -1003,7 +1017,7 @@ public function getTalkMediaLinks($talk_id, $link_id = null) ]; if (is_numeric($link_id)) { - $sql .= "and tl.ID = :link_id"; + $sql .= "and tl.ID = :link_id"; $params['link_id'] = $link_id; } @@ -1023,7 +1037,7 @@ public function addTalkMediaTypes(array $talk) $links = $this->getTalkMediaLinks($talk[0]['ID']); foreach ($links as $link) { - $talk = $this->handleBackwardsCompatibleMedia($talk, $link); + $talk = $this->handleBackwardsCompatibleMedia($talk, $link); $talk[0]['talk_media'][] = [$link['display_name'] => $link['url']]; } @@ -1073,9 +1087,9 @@ public function removeAllTalkLinks($talk_id) } /** - * @param int $talk_id - * @param int $link_id - * @param string$display_name + * @param int $talk_id + * @param int $link_id + * @param string $display_name * @param string $url * * @return bool @@ -1098,9 +1112,9 @@ public function updateTalkLink($talk_id, $link_id, $display_name, $url) $stmt->execute( [ 'display_name' => $display_name, - 'link_id' => $link_id, - 'talk_id' => $talk_id, - 'url' => $url, + 'link_id' => $link_id, + 'talk_id' => $talk_id, + 'url' => $url, ] ); @@ -1108,7 +1122,7 @@ public function updateTalkLink($talk_id, $link_id, $display_name, $url) } /** - * @param int $talk_id + * @param int $talk_id * @param string $display_name * @param string $url * @@ -1131,11 +1145,12 @@ public function addTalkLink($talk_id, $display_name, $url) $stmt->execute( [ - 'talk_id' => $talk_id, + 'talk_id' => $talk_id, 'display_name' => $display_name, - 'url' => $url, + 'url' => $url, ] ); + return $this->_db->lastInsertId(); } diff --git a/src/models/TalkModel.php b/src/Model/TalkModel.php similarity index 97% rename from src/models/TalkModel.php rename to src/Model/TalkModel.php index 4068a9552..3e7003ab4 100644 --- a/src/models/TalkModel.php +++ b/src/Model/TalkModel.php @@ -1,5 +1,9 @@ base; $version = $request->version; diff --git a/src/models/TalkModelCollection.php b/src/Model/TalkModelCollection.php similarity index 90% rename from src/models/TalkModelCollection.php rename to src/Model/TalkModelCollection.php index 342144ea5..64739e308 100644 --- a/src/models/TalkModelCollection.php +++ b/src/Model/TalkModelCollection.php @@ -1,5 +1,9 @@ list = []; + $this->list = []; $this->total = $total; // hydrate the model objects if necessary and store to list @@ -40,14 +44,14 @@ public function __construct(array $data, $total) * and pagination * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ public function getOutputView(Request $request, $verbose = false) { // handle the collection first - $retval= ['talks' => []]; + $retval = ['talks' => []]; foreach ($this->list as $item) { $retval['talks'][] = $item->getOutputView($request, $verbose); } diff --git a/src/models/TalkTypeMapper.php b/src/Model/TalkTypeMapper.php similarity index 80% rename from src/models/TalkTypeMapper.php rename to src/Model/TalkTypeMapper.php index b0bd5bbb6..819425d55 100644 --- a/src/models/TalkTypeMapper.php +++ b/src/Model/TalkTypeMapper.php @@ -1,5 +1,9 @@ 'cat_title', + 'title' => 'cat_title', 'description' => 'cat_desc', ); } @@ -19,14 +23,14 @@ public function getDefaultFields() public function getVerboseFields() { return array( - 'title' => 'cat_title', + 'title' => 'cat_title', 'description' => 'cat_desc', ); } /** - * @param int $resultsperpage - * @param int $start + * @param int $resultsperpage + * @param int $start * @param bool $verbose * * @return false|array @@ -37,27 +41,29 @@ public function getTalkTypeList($resultsperpage, $start = 0, $verbose = false) if ($results) { return $this->transformResults($results, $verbose); } + return false; } /** - * @param int $talkType_id + * @param int $talkType_id * @param bool $verbose * * @return false|array */ public function getTalkTypeById($talkType_id, $verbose) { - $results = $this->getTalkTypes(1, 0, array('ID' => (int) $talkType_id)); + $results = $this->getTalkTypes(1, 0, array('ID' => (int)$talkType_id)); if ($results) { return $this->transformResults($results, $verbose); } + return false; } /** - * @param int $resultsperpage - * @param int $start + * @param int $resultsperpage + * @param int $start * @param array $params * * @return false|array @@ -69,7 +75,7 @@ protected function getTalkTypes($resultsperpage, $start, $params = array()) if (count($params) > 0) { $value = reset($params); - $key = key($params); + $key = key($params); $sql .= 'where c.' . $key . ' = :' . $key . ' '; @@ -83,14 +89,15 @@ protected function getTalkTypes($resultsperpage, $start, $params = array()) $sql .= 'order by c.ID '; $sql .= $this->buildLimit($resultsperpage, $start); - $stmt = $this->_db->prepare($sql); + $stmt = $this->_db->prepare($sql); $response = $stmt->execute($params); if ($response) { - $results = $stmt->fetchAll(PDO::FETCH_ASSOC); + $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $results['total'] = $this->getTotalCount($sql, $params); return $results; } + return false; } @@ -104,19 +111,19 @@ public function transformResults(array $results, $verbose) $list = parent::transformResults($results, $verbose); - $base = $this->_request->base; + $base = $this->_request->base; $version = $this->_request->version; if (is_array($list) && count($list)) { foreach ($results as $key => $row) { - $list[$key]['uri'] = $base . '/' . $version . '/talk_types/' . $row['ID']; + $list[$key]['uri'] = $base . '/' . $version . '/talk_types/' . $row['ID']; $list[$key]['verbose_uri'] = $base . '/' . $version . '/talk_types/' . $row['ID'] . '?verbose=yes'; } } return array( 'talk_types' => $list, - 'meta' => $this->getPaginationLinks($list, $total) + 'meta' => $this->getPaginationLinks($list, $total) ); } @@ -127,7 +134,7 @@ public function transformResults(array $results, $verbose) */ public function getTalkTypesLookupList() { - $sql = "select ID, cat_title from categories"; + $sql = "select ID, cat_title from categories"; $stmt = $this->_db->prepare($sql); $stmt->execute(); diff --git a/src/models/TokenMapper.php b/src/Model/TokenMapper.php similarity index 83% rename from src/models/TokenMapper.php rename to src/Model/TokenMapper.php index ececc70a5..22dff91f0 100644 --- a/src/models/TokenMapper.php +++ b/src/Model/TokenMapper.php @@ -1,5 +1,10 @@ buildLimit($resultsperpage, $start); $stmt = $this->_db->prepare($sql); @@ -50,12 +55,12 @@ public function getTokensForUser($user_id, $resultsperpage, $start) ':user_id' => $user_id )); - if (! $response) { + if (!$response) { return false; } $results = $stmt->fetchAll(PDO::FETCH_ASSOC); - $total = $this->getTotalCount($sql, [':user_id' => $user_id]); + $total = $this->getTotalCount($sql, [':user_id' => $user_id]); $results = $this->processResults($results); return new TokenModelCollection($results, $total); @@ -64,9 +69,9 @@ public function getTokensForUser($user_id, $resultsperpage, $start) /** * Get all tokens that are registered for a given user that can be revoked * - * @param int $user_id The user to fetch clients for - * @param int $resultsperpage How many results to return on each page - * @param int $start Which result to start with + * @param int $user_id The user to fetch clients for + * @param int $resultsperpage How many results to return on each page + * @param int $start Which result to start with * * @return TokenModelCollection|false */ @@ -84,19 +89,18 @@ public function getRevokableTokensForUser($user_id, $resultsperpage, $start) ':user_id' => $user_id )); - if (! $response) { + if (!$response) { return false; } $results = $stmt->fetchAll(PDO::FETCH_ASSOC); - $total = $this->getTotalCount($sql, [':user_id' => $user_id]); + $total = $this->getTotalCount($sql, [':user_id' => $user_id]); $results = $this->processResults($results); return new TokenModelCollection($results, $total); } - /** * Get a single token by id and user * @@ -120,7 +124,7 @@ public function getTokenByIdAndUser($token_id, $user_id) ':token_id' => $token_id, )); - if (! $response) { + if (!$response) { return new TokenModelCollection([], 1); } @@ -154,7 +158,7 @@ public function getRevokableTokenByIdAndUser($token_id, $user_id) ':token_id' => $token_id, )); - if (! $response) { + if (!$response) { return new TokenModelCollection([], 1); } @@ -178,7 +182,7 @@ public function deleteToken($tokenId) $stmt = $this->_db->prepare($tokenSql); - if (! $stmt->execute([':token_id' => $tokenId])) { + if (!$stmt->execute([':token_id' => $tokenId])) { throw new Exception('There has been an error removing the token'); } @@ -202,10 +206,10 @@ public function tokenBelongsToTrustedApplication($accessToken) $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array( - ':token' => $accessToken, + ':token' => $accessToken, )); - if (! $response) { + if (!$response) { return false; } diff --git a/src/models/TokenModel.php b/src/Model/TokenModel.php similarity index 79% rename from src/models/TokenModel.php rename to src/Model/TokenModel.php index 2f9d6b72e..59af670bf 100644 --- a/src/models/TokenModel.php +++ b/src/Model/TokenModel.php @@ -1,5 +1,9 @@ 'id', - 'application' => 'application', - 'created_date' => 'created_date', - 'last_used_date' => 'last_used_date', + 'token' => 'id', + 'application' => 'application', + 'created_date' => 'created_date', + 'last_used_date' => 'last_used_date', 'application_owner' => 'full_name', ); } @@ -39,7 +43,7 @@ public function getVerboseFields() * Return this object with client-facing fields and hypermedia, ready for output * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ diff --git a/src/models/TokenModelCollection.php b/src/Model/TokenModelCollection.php similarity index 92% rename from src/models/TokenModelCollection.php rename to src/Model/TokenModelCollection.php index 0bc220133..3e01535f0 100644 --- a/src/models/TokenModelCollection.php +++ b/src/Model/TokenModelCollection.php @@ -1,5 +1,9 @@ list = []; + $this->list = []; $this->total = $total; // hydrate the model objects if necessary and store to list @@ -40,7 +44,7 @@ public function __construct(array $data, $total) * and pagination * * @param Request $request - * @param bool $verbose + * @param bool $verbose * * @return array */ diff --git a/src/models/TrackMapper.php b/src/Model/TrackMapper.php similarity index 84% rename from src/models/TrackMapper.php rename to src/Model/TrackMapper.php index f08ee5b3b..6331014ac 100644 --- a/src/models/TrackMapper.php +++ b/src/Model/TrackMapper.php @@ -1,5 +1,10 @@ $list, - 'meta' => $this->getPaginationLinks($list, $total), + 'meta' => $this->getPaginationLinks($list, $total), ]; } /** - * @param int $track_id + * @param int $track_id * @param bool $verbose * * @return false|array */ public function getTrackById($track_id, $verbose = false) { - $sql = $this->getBasicSQL(); - $sql .= ' where t.ID = :track_id'; + $sql = $this->getBasicSQL(); + $sql .= ' where t.ID = :track_id'; $stmt = $this->_db->prepare($sql); $response = $stmt->execute(array("track_id" => $track_id)); if ($response) { @@ -108,7 +113,7 @@ public function getTrackById($track_id, $verbose = false) /** * @param array $data - * @param int $event_id + * @param int $event_id * * @throws Exception * @return string @@ -116,11 +121,11 @@ public function getTrackById($track_id, $verbose = false) public function createEventTrack(array $data, $event_id) { // Sanity check: ensure all mandatory fields are present. - $mandatory_fields = [ + $mandatory_fields = [ 'track_name', 'track_description', ]; - $contains_mandatory_fields = !array_diff($mandatory_fields, array_keys($data)); + $contains_mandatory_fields = ! array_diff($mandatory_fields, array_keys($data)); if (!$contains_mandatory_fields) { throw new Exception("Missing mandatory fields"); } @@ -134,20 +139,20 @@ public function createEventTrack(array $data, $event_id) continue; } if (array_key_exists($api_name, $data)) { - $column_names[] = $column_name; - $placeholders[] = ':' . $api_name; + $column_names[] = $column_name; + $placeholders[] = ':' . $api_name; $data_values[$api_name] = $data[$api_name]; } } // we also need to store the event_id - $column_names[] = 'event_id'; - $placeholders[] = ':event_id'; + $column_names[] = 'event_id'; + $placeholders[] = ':event_id'; $data_values['event_id'] = $event_id; // insert row - $sql = 'insert into event_track (' . implode(', ', $column_names) . ') '; - $sql .= 'values (' . implode(', ', $placeholders) . ')'; + $sql = 'insert into event_track (' . implode(', ', $column_names) . ') '; + $sql .= 'values (' . implode(', ', $placeholders) . ')'; $stmt = $this->_db->prepare($sql); try { $stmt->execute($data_values); @@ -185,11 +190,11 @@ public function getBasicSQL() public function editEventTrack(array $data, $track_id) { // Sanity check: ensure all mandatory fields are present. - $mandatory_fields = [ + $mandatory_fields = [ 'track_name', 'track_description', ]; - $contains_mandatory_fields = !array_diff($mandatory_fields, array_keys($data)); + $contains_mandatory_fields = ! array_diff($mandatory_fields, array_keys($data)); if (!$contains_mandatory_fields) { throw new Exception("Missing mandatory fields"); } @@ -206,7 +211,7 @@ public function editEventTrack(array $data, $track_id) continue; } if (array_key_exists($api_name, $data)) { - $pairs[] = "$column_name = :$api_name"; + $pairs[] = "$column_name = :$api_name"; $items[$api_name] = $data[$api_name]; } } @@ -236,12 +241,12 @@ public function editEventTrack(array $data, $track_id) public function deleteEventTrack($track_id) { // delete talk associations - $sql = "delete from event_track where ID = :track_id"; + $sql = "delete from event_track where ID = :track_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(['track_id' => $track_id]); // delete track - $sql = "delete from talk_track where track_id = :track_id"; + $sql = "delete from talk_track where track_id = :track_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(['track_id' => $track_id]); } diff --git a/src/models/TwitterRequestTokenMapper.php b/src/Model/TwitterRequestTokenMapper.php similarity index 97% rename from src/models/TwitterRequestTokenMapper.php rename to src/Model/TwitterRequestTokenMapper.php index 8cf1d1336..7187129bb 100644 --- a/src/models/TwitterRequestTokenMapper.php +++ b/src/Model/TwitterRequestTokenMapper.php @@ -1,5 +1,9 @@ getUsers(1, 0, 'user.ID=' . (int) $user_id, null); + $results = $this->getUsers(1, 0, 'user.ID=' . (int)$user_id, null); if ($results) { return $this->transformResults($results, $verbose); } @@ -59,7 +64,7 @@ public function getUserById($user_id, $verbose = false) /** * @param string $username - * @param bool $verbose + * @param bool $verbose * * @return false|array */ @@ -92,34 +97,34 @@ public function getUserByUsername($username, $verbose = false) * Search users by keyword * * @param string $keyword - * @param int $resultsperpage - * @param int $start - * @param bool $verbose + * @param int $resultsperpage + * @param int $start + * @param bool $verbose * * @return array|bool Result collection or false on failure */ public function getUserByKeyword($keyword, $resultsperpage, $start, $verbose) { $sql = 'select user.* ' - . 'from user ' - . 'where active = 1 ' - . ' and ( ' - . ' LOWER(user.username) like :keyword' - . ' or LOWER(user.full_name) like :keyword' - . ' or LOWER(user.twitter_username) like :keyword' - . ') ' - . ' order by user.full_name asc'; + . 'from user ' + . 'where active = 1 ' + . ' and ( ' + . ' LOWER(user.username) like :keyword' + . ' or LOWER(user.full_name) like :keyword' + . ' or LOWER(user.twitter_username) like :keyword' + . ') ' + . ' order by user.full_name asc'; $sql .= $this->buildLimit($resultsperpage, $start); $data = array( - ':keyword' => '%' . strtolower($keyword) . '%', + ':keyword' => '%' . strtolower($keyword) . '%', ); $stmt = $this->_db->prepare($sql); $response = $stmt->execute($data); if ($response) { - $results = $stmt->fetchAll(PDO::FETCH_ASSOC); + $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $results['total'] = $this->getTotalCount($sql, $data); return $this->transformResults($results, $verbose); @@ -147,8 +152,8 @@ public function getSiteAdminEmails() } /** - * @param int $resultsperpage - * @param int $start + * @param int $resultsperpage + * @param int $start * @param string|null $where * @param string|null $order * @@ -192,8 +197,8 @@ protected function getUsers($resultsperpage, $start, $where = null, $order = nul } /** - * @param int $resultsperpage - * @param int $start + * @param int $resultsperpage + * @param int $start * @param bool $verbose * * @return false|array @@ -210,9 +215,9 @@ public function getUserList($resultsperpage, $start, $verbose = false) } /** - * @param int $event_id - * @param int $resultsperpage - * @param int $start + * @param int $event_id + * @param int $resultsperpage + * @param int $start * @param bool $verbose * * @return false|array @@ -274,7 +279,7 @@ public function transformResults(array $results, $verbose) $list[$key]['attended_events_uri'] = $base . '/' . $version . '/users/' . $row['ID'] . '/attended/'; $list[$key]['hosted_events_uri'] = $base . '/' . $version . '/users/' . $row['ID'] . '/hosted/'; $list[$key]['talk_comments_uri'] = $base . '/' . $version . '/users/' . $row['ID'] - . '/talk_comments/'; + . '/talk_comments/'; if ($verbose && isset($this->_request->user_id)) { $list[$key]['can_edit'] = $canEdit; @@ -295,7 +300,7 @@ public function transformResults(array $results, $verbose) */ public function isSiteAdmin($user_id) { - $results = $this->getUsers(1, 0, 'user.ID=' . (int) $user_id, null); + $results = $this->getUsers(1, 0, 'user.ID=' . (int)$user_id, null); if (isset($results[0]) && $results[0]['admin'] == 1) { return true; } @@ -312,7 +317,7 @@ public function isSiteAdmin($user_id) */ public function isTrusted($user_id) { - $results = $this->getUsers(1, 0, 'user.ID=' . (int) $user_id, null); + $results = $this->getUsers(1, 0, 'user.ID=' . (int)$user_id, null); if (isset($results[0]) && $results[0]['trusted'] == 1) { return true; } @@ -324,17 +329,17 @@ public function isTrusted($user_id) * Update the trusted status for the given user * * @param bool $trustedStatus - * @param int $user_id + * @param int $user_id * * @return bool */ public function setTrustedStatus($trustedStatus, $user_id) { $verify_sql = "update user set trusted = :trusted_status " - . "where ID = :user_id"; + . "where ID = :user_id"; $verify_stmt = $this->_db->prepare($verify_sql); - $verify_data = array("trusted_status" => (int) $trustedStatus, "user_id" => $user_id); + $verify_data = array("trusted_status" => (int)$trustedStatus, "user_id" => $user_id); return $verify_stmt->execute($verify_data); } @@ -349,14 +354,14 @@ public function setTrustedStatus($trustedStatus, $user_id) public function createUser($user) { // Sanity check: ensure all mandatory fields are present. - $mandatory_fields = array( + $mandatory_fields = array( 'username', 'full_name', 'email', 'password', ); $contains_mandatory_fields = ! array_diff($mandatory_fields, array_keys($user)); - if (! $contains_mandatory_fields) { + if (!$contains_mandatory_fields) { throw new Exception("Missing mandatory fields"); } @@ -391,7 +396,7 @@ public function createUser($user) /** * @param string $email - * @param bool $verbose + * @param bool $verbose * * @return false|array */ @@ -600,8 +605,8 @@ public function thisUserHasAdminOn($user_id) /** * Update an existing user record * - * @param array $user An array of fields to change - * @param int $userId The user to update + * @param array $user An array of fields to change + * @param int $userId The user to update * * @throws Exception * @return bool if successful @@ -609,12 +614,12 @@ public function thisUserHasAdminOn($user_id) public function editUser(array $user, $userId) { // Sanity check: ensure all mandatory fields are present. - $mandatory_fields = array( + $mandatory_fields = array( 'full_name', 'email', ); $contains_mandatory_fields = ! array_diff($mandatory_fields, array_keys($user)); - if (! $contains_mandatory_fields) { + if (!$contains_mandatory_fields) { throw new Exception("Missing mandatory fields"); } @@ -797,32 +802,32 @@ public function delete($user_id) } try { // Delete the user - $sql = "delete from user where ID = :user_id"; + $sql = "delete from user where ID = :user_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(array("user_id" => $user_id)); // Unassign any talks - $sql = "update talk_speaker SET speaker_id = 0, status = NULL WHERE speaker_id = :speaker_id"; + $sql = "update talk_speaker SET speaker_id = 0, status = NULL WHERE speaker_id = :speaker_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(array("speaker_id" => $user_id)); // Remove any pending talk claims - $sql = "delete from pending_talk_claims where speaker_id = :speaker_id"; + $sql = "delete from pending_talk_claims where speaker_id = :speaker_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(array("speaker_id" => $user_id)); // Anonymise any comments - $sql = "update talk_comments SET user_id = 0 WHERE user_id = :user_id"; + $sql = "update talk_comments SET user_id = 0 WHERE user_id = :user_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(array("user_id" => $user_id)); // Remove any starred talks - $sql = "delete from user_talk_star where uid = :user_id"; + $sql = "delete from user_talk_star where uid = :user_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(array("user_id" => $user_id)); // Remove user attendence - $sql = "delete from user_attend where uid = :user_id"; + $sql = "delete from user_attend where uid = :user_id"; $stmt = $this->_db->prepare($sql); $stmt->execute(array("user_id" => $user_id)); @@ -831,6 +836,7 @@ public function delete($user_id) return true; } catch (Exception $e) { $this->_db->rollBack(); + return false; } } diff --git a/src/inc/Request.php b/src/Request.php similarity index 91% rename from src/inc/Request.php rename to src/Request.php index 3fd2513ea..699b7dc08 100644 --- a/src/inc/Request.php +++ b/src/Request.php @@ -4,6 +4,16 @@ * Request object */ +namespace Joindin\Api; + +use InvalidArgumentException; +use Joindin\Api\Model\OAuthModel; +use Joindin\Api\View\ApiView; +use Joindin\Api\View\HtmlView; +use Joindin\Api\View\JsonPView; +use Joindin\Api\View\JsonView; +use PDO; + class Request { @@ -65,9 +75,9 @@ class Request /** * Builds the request object * - * @param array|false $config The application configuration - * @param array $server The $_SERVER global, injected for testability - * @param bool $parseParams Set to false to skip parsing parameters on + * @param array|false $config The application configuration + * @param array $server The $_SERVER global, injected for testability + * @param bool $parseParams Set to false to skip parsing parameters on * construction */ public function __construct($config, array $server, $parseParams = true) @@ -185,14 +195,14 @@ public function setRouteParams(array $routeParams) * is provided and the parameter doesn't exist, the default value * will be returned instead * - * @param string $param Parameter to retrieve + * @param string $param Parameter to retrieve * @param string $default Default to return if parameter doesn't exist * * @return mixed */ public function getParameter($param, $default = '') { - if (! array_key_exists($param, $this->parameters)) { + if (!array_key_exists($param, $this->parameters)) { return $default; } @@ -204,15 +214,15 @@ public function getParameter($param, $default = '') * a default is provided, the default value will be returned. * * @param integer $index Index to retrieve - * @param string $default + * @param string $default * * @return string */ public function getUrlElement($index, $default = '') { - $index = (int) $index; + $index = (int)$index; - if (! isset($this->url_elements[$index])) { + if (!isset($this->url_elements[$index])) { return $default; } @@ -252,7 +262,7 @@ public function accepts($header) */ public function preferredContentTypeOutOf(array $formats = null) { - if (! $formats) { + if (!$formats) { $formats = $this->getFormatChoices(); } @@ -273,13 +283,13 @@ public function preferredContentTypeOutOf(array $formats = null) */ public function getView() { - if (! $this->view) { + if (!$this->view) { $format = $this->getParameter('format', $this->preferredContentTypeOutOf()); switch ($format) { case self::CONTENT_TYPE_HTML: case self::FORMAT_HTML: - $this->view = new \HtmlView(); + $this->view = new HtmlView(); break; case self::CONTENT_TYPE_JSON: @@ -288,9 +298,9 @@ public function getView() // JSONP? $callback = filter_var($this->getParameter('callback'), FILTER_SANITIZE_STRING); if ($callback) { - $this->view = new \JsonPView($callback); + $this->view = new JsonPView($callback); } else { - $this->view = new \JsonView(); + $this->view = new JsonView(); } } } @@ -301,9 +311,9 @@ public function getView() /** * Sets this Request's View object * - * @param \ApiView $view + * @param ApiView $view */ - public function setView(\ApiView $view) + public function setView(ApiView $view) { $this->view = $view; } @@ -313,7 +323,7 @@ public function setView(\ApiView $view) * variable on the request. * * @param string $auth_header Authorization header to send into model - * @param PDO $db Database adapter (needed to put into OAuthModel if it's not set already) + * @param PDO $db Database adapter (needed to put into OAuthModel if it's not set already) * * @throws InvalidArgumentException * @return bool @@ -330,7 +340,7 @@ public function identifyUser($auth_header, PDO $db = null) } // token type must be either 'bearer' or 'oauth' - if (! in_array(strtolower($oauth_pieces[0]), ["bearer", 'oauth'])) { + if (!in_array(strtolower($oauth_pieces[0]), ["bearer", 'oauth'])) { throw new InvalidArgumentException('Unknown Authorization Header Received', '400'); } $oauth_model = $this->getOauthModel($db); @@ -363,10 +373,10 @@ public function parseParameters(array $server) $this->paginationParameters = $parameters; } - if (! isset($this->paginationParameters['start'])) { + if (!isset($this->paginationParameters['start'])) { $this->paginationParameters['start'] = null; } - if (! isset($this->paginationParameters['resultsperpage'])) { + if (!isset($this->paginationParameters['resultsperpage'])) { $this->paginationParameters['resultsperpage'] = 20; } @@ -644,14 +654,14 @@ public function getClientUserAgent() * Fetch a config value by named key. If the value doesn't exist then * return the default value * - * @param string $param Parameter to retrieve + * @param string $param Parameter to retrieve * @param string $default Default to return if parameter doesn't exist * * @return string */ public function getConfigValue($key, $default = '') { - if (! array_key_exists($key, $this->config)) { + if (!array_key_exists($key, $this->config)) { return $default; } diff --git a/src/routers/ApiRouter.php b/src/Router/ApiRouter.php similarity index 90% rename from src/routers/ApiRouter.php rename to src/Router/ApiRouter.php index 416dc60c4..2c3a013aa 100644 --- a/src/routers/ApiRouter.php +++ b/src/Router/ApiRouter.php @@ -1,5 +1,10 @@ getUrlElement(1); - if (! $version) { + if (!$version) { // empty version, set request to use the latest $request->version = $this->latestVersion; } else { @@ -77,8 +82,8 @@ public function getRoute(Request $request) } // now route on the original $version - if (isset($this->routers[ $version ])) { - $router = $this->routers[ $version ]; + if (isset($this->routers[$version])) { + $router = $this->routers[$version]; return $router->getRoute($request); } diff --git a/src/routers/BaseRouter.php b/src/Router/BaseRouter.php similarity index 93% rename from src/routers/BaseRouter.php rename to src/Router/BaseRouter.php index 06f8084b4..64207ce3f 100644 --- a/src/routers/BaseRouter.php +++ b/src/Router/BaseRouter.php @@ -1,5 +1,9 @@ setUsername($config['email']['smtp']['username']) - ->setPassword($config['email']['smtp']['password']) - ; + ->setPassword($config['email']['smtp']['password']); $this->mailer = Swift_Mailer::newInstance($transport); $this->message = Swift_Message::newInstance(); if (isset($config['email']['forward_all_to']) - && !empty($config['email']['forward_all_to']) + && ! empty($config['email']['forward_all_to']) ) { $this->recipients = [$config['email']['forward_all_to']]; } else { @@ -81,12 +87,12 @@ public function __construct(array $config, array $recipients) */ public function parseEmail($templateName, array $replacements) { - $template = file_get_contents($this->templatePath.$templateName) - .file_get_contents($this->templatePath.'signature.md'); + $template = file_get_contents($this->templatePath . $templateName) + . file_get_contents($this->templatePath . 'signature.md'); $message = $template; foreach ($replacements as $field => $value) { - $message = str_replace('['.$field.']', $value, $message); + $message = str_replace('[' . $field . ']', $value, $message); } return $message; diff --git a/src/services/CommentReportedEmailService.php b/src/Service/CommentReportedEmailService.php similarity index 84% rename from src/services/CommentReportedEmailService.php rename to src/Service/CommentReportedEmailService.php index 6ed4e5e4b..399b50b40 100644 --- a/src/services/CommentReportedEmailService.php +++ b/src/Service/CommentReportedEmailService.php @@ -1,5 +1,7 @@ comment = $comment['comments'][0]; + $this->comment = $comment['comments'][0]; $this->website_url = $config['website_url']; - $this->event = $event['events'][0]; + $this->event = $event['events'][0]; } public function sendEmail() @@ -72,9 +74,9 @@ private function linkToReportedCommentsForEvent() } return '[' . $this->website_url - . '/event/' . $this->event['url_friendly_name'] - . '/reported-comments' . '](' . $this->website_url - . '/event/' . $this->event['url_friendly_name'] - . '/reported-comments' . ')'; + . '/event/' . $this->event['url_friendly_name'] + . '/reported-comments' . '](' . $this->website_url + . '/event/' . $this->event['url_friendly_name'] + . '/reported-comments' . ')'; } } diff --git a/src/services/ContactEmailService.php b/src/Service/ContactEmailService.php similarity index 89% rename from src/services/ContactEmailService.php rename to src/Service/ContactEmailService.php index 0100c341a..3c1acc578 100644 --- a/src/services/ContactEmailService.php +++ b/src/Service/ContactEmailService.php @@ -1,5 +1,7 @@ setSubject('Event approved'); - $date = new DateTime($this->event['start_date']); + $date = new DateTime($this->event['start_date']); $replacements = array( "title" => $this->event['name'], "description" => $this->event['description'], diff --git a/src/services/EventCommentReportedEmailService.php b/src/Service/EventCommentReportedEmailService.php similarity index 82% rename from src/services/EventCommentReportedEmailService.php rename to src/Service/EventCommentReportedEmailService.php index 7a0e99fac..1fbe447a0 100644 --- a/src/services/EventCommentReportedEmailService.php +++ b/src/Service/EventCommentReportedEmailService.php @@ -1,5 +1,7 @@ comment = $comment['comments'][0]; - $this->event = $event['events'][0]; + $this->comment = $comment['comments'][0]; + $this->event = $event['events'][0]; $this->website_url = $config['website_url']; } @@ -61,9 +63,9 @@ public function sendEmail() private function linkToReportedCommentsForEvent() { return '[' . $this->website_url - . '/event/' . $this->event['url_friendly_name'] - . '/reported-comments' . '](' . $this->website_url - . '/event/' . $this->event['url_friendly_name'] - . '/reported-comments' . ')'; + . '/event/' . $this->event['url_friendly_name'] + . '/reported-comments' . '](' . $this->website_url + . '/event/' . $this->event['url_friendly_name'] + . '/reported-comments' . ')'; } } diff --git a/src/services/EventSubmissionEmailService.php b/src/Service/EventSubmissionEmailService.php similarity index 88% rename from src/services/EventSubmissionEmailService.php rename to src/Service/EventSubmissionEmailService.php index bd31f8510..2e786e7d1 100644 --- a/src/services/EventSubmissionEmailService.php +++ b/src/Service/EventSubmissionEmailService.php @@ -1,14 +1,18 @@ event = $event; + $this->event = $event; $this->website_url = $config['website_url']; $this->count = $count; diff --git a/src/services/NullSpamCheckService.php b/src/Service/NullSpamCheckService.php similarity index 93% rename from src/services/NullSpamCheckService.php rename to src/Service/NullSpamCheckService.php index 751ee89bd..997ecaa78 100644 --- a/src/services/NullSpamCheckService.php +++ b/src/Service/NullSpamCheckService.php @@ -1,5 +1,6 @@ talk = $talk; + $this->talk = $talk; $this->website_url = $config['website_url']; - $this->event = $event['events'][0]; - $this->username = $username; + $this->event = $event['events'][0]; + $this->username = $username; } public function sendEmail() @@ -52,9 +56,9 @@ public function sendEmail() private function linkToEditUserPage() { return '[' . $this->website_url - . '/user/' . $this->username - . '/edit' . '](' . $this->website_url - . '/user/' . $this->username - . '/claims' . ')'; + . '/user/' . $this->username + . '/edit' . '](' . $this->website_url + . '/user/' . $this->username + . '/claims' . ')'; } } diff --git a/src/services/TalkClaimApprovedEmailService.php b/src/Service/TalkClaimApprovedEmailService.php similarity index 87% rename from src/services/TalkClaimApprovedEmailService.php rename to src/Service/TalkClaimApprovedEmailService.php index b306a862f..052a275fb 100644 --- a/src/services/TalkClaimApprovedEmailService.php +++ b/src/Service/TalkClaimApprovedEmailService.php @@ -1,5 +1,9 @@ website_url = $config['website_url']; - $this->talk = $talk; - $this->event = $event['events'][0]; + $this->talk = $talk; + $this->event = $event['events'][0]; } public function sendEmail() diff --git a/src/services/TalkClaimEmailService.php b/src/Service/TalkClaimEmailService.php similarity index 76% rename from src/services/TalkClaimEmailService.php rename to src/Service/TalkClaimEmailService.php index a5b07e308..b4edf90ed 100644 --- a/src/services/TalkClaimEmailService.php +++ b/src/Service/TalkClaimEmailService.php @@ -1,5 +1,9 @@ talk = $talk; + $this->talk = $talk; $this->website_url = $config['website_url']; - $this->event = $event['events'][0]; + $this->event = $event['events'][0]; } public function sendEmail() @@ -46,9 +50,9 @@ private function linkToPendingClaimsForEvent() { return '[' . $this->website_url - . '/event/' . $this->event['url_friendly_name'] - . '/claims' . '](' . $this->website_url - . '/event/' . $this->event['url_friendly_name'] - . '/claims' . ')'; + . '/event/' . $this->event['url_friendly_name'] + . '/claims' . '](' . $this->website_url + . '/event/' . $this->event['url_friendly_name'] + . '/claims' . ')'; } } diff --git a/src/services/TalkClaimRejectedEmailService.php b/src/Service/TalkClaimRejectedEmailService.php similarity index 90% rename from src/services/TalkClaimRejectedEmailService.php rename to src/Service/TalkClaimRejectedEmailService.php index 327d779a3..5d8f1ebd3 100644 --- a/src/services/TalkClaimRejectedEmailService.php +++ b/src/Service/TalkClaimRejectedEmailService.php @@ -1,5 +1,9 @@ talk = $talk; + $this->talk = $talk; $this->event = $event['events'][0]; } diff --git a/src/services/TalkCommentEmailService.php b/src/Service/TalkCommentEmailService.php similarity index 95% rename from src/services/TalkCommentEmailService.php rename to src/Service/TalkCommentEmailService.php index 80b4ac1a6..566f7da7d 100644 --- a/src/services/TalkCommentEmailService.php +++ b/src/Service/TalkCommentEmailService.php @@ -1,5 +1,9 @@ headers = $headers; + $this->headers = $headers; $this->responseCode = $responseCode; - $this->noRender = $noRender; + $this->noRender = $noRender; } /** @@ -72,6 +74,7 @@ public function setNoRender($noRender) */ public function render($content) { + ob_start(); $body = ''; if ($content && $this->noRender === false) { $body = $this->buildOutput($content); @@ -85,7 +88,7 @@ public function render($content) http_response_code($this->responseCode); echo $body; - + ob_end_flush(); return true; } diff --git a/src/views/HtmlView.php b/src/View/HtmlView.php similarity index 98% rename from src/views/HtmlView.php rename to src/View/HtmlView.php index db0ebdb90..0d2a33839 100755 --- a/src/views/HtmlView.php +++ b/src/View/HtmlView.php @@ -1,5 +1,7 @@ scalarNumericCheck('', $data); } $output = array(); @@ -50,7 +52,7 @@ protected function numericCheck($data) protected function scalarNumericCheck($key, $value) { if (is_numeric($value) && ! in_array($key, $this->string_fields) && $value < PHP_INT_MAX) { - return (float) $value; + return (float)$value; } return $value; diff --git a/src/views/emails/commentReported.md b/src/View/emails/commentReported.md similarity index 100% rename from src/views/emails/commentReported.md rename to src/View/emails/commentReported.md diff --git a/src/views/emails/commentTalk.md b/src/View/emails/commentTalk.md similarity index 100% rename from src/views/emails/commentTalk.md rename to src/View/emails/commentTalk.md diff --git a/src/views/emails/contact.md b/src/View/emails/contact.md similarity index 100% rename from src/views/emails/contact.md rename to src/View/emails/contact.md diff --git a/src/views/emails/eventApproved.md b/src/View/emails/eventApproved.md similarity index 100% rename from src/views/emails/eventApproved.md rename to src/View/emails/eventApproved.md diff --git a/src/views/emails/eventCommentReported.md b/src/View/emails/eventCommentReported.md similarity index 100% rename from src/views/emails/eventCommentReported.md rename to src/View/emails/eventCommentReported.md diff --git a/src/views/emails/eventSubmission.md b/src/View/emails/eventSubmission.md similarity index 100% rename from src/views/emails/eventSubmission.md rename to src/View/emails/eventSubmission.md diff --git a/src/views/emails/signature.md b/src/View/emails/signature.md similarity index 100% rename from src/views/emails/signature.md rename to src/View/emails/signature.md diff --git a/src/views/emails/talkAssigned.md b/src/View/emails/talkAssigned.md similarity index 100% rename from src/views/emails/talkAssigned.md rename to src/View/emails/talkAssigned.md diff --git a/src/views/emails/talkClaimApproved.md b/src/View/emails/talkClaimApproved.md similarity index 100% rename from src/views/emails/talkClaimApproved.md rename to src/View/emails/talkClaimApproved.md diff --git a/src/views/emails/talkClaimRejected.md b/src/View/emails/talkClaimRejected.md similarity index 100% rename from src/views/emails/talkClaimRejected.md rename to src/View/emails/talkClaimRejected.md diff --git a/src/views/emails/talkClaimed.md b/src/View/emails/talkClaimed.md similarity index 100% rename from src/views/emails/talkClaimed.md rename to src/View/emails/talkClaimed.md diff --git a/src/views/emails/testTemplate.md b/src/View/emails/testTemplate.md similarity index 100% rename from src/views/emails/testTemplate.md rename to src/View/emails/testTemplate.md diff --git a/src/views/emails/userPasswordReset.md b/src/View/emails/userPasswordReset.md similarity index 100% rename from src/views/emails/userPasswordReset.md rename to src/View/emails/userPasswordReset.md diff --git a/src/views/emails/userRegistration.md b/src/View/emails/userRegistration.md similarity index 100% rename from src/views/emails/userRegistration.md rename to src/View/emails/userRegistration.md diff --git a/src/views/emails/userUsernameReminder.md b/src/View/emails/userUsernameReminder.md similarity index 100% rename from src/views/emails/userUsernameReminder.md rename to src/View/emails/userUsernameReminder.md diff --git a/src/config/routes/2.1.json b/src/config/routes/2.1.json index 613ecf243..303049748 100644 --- a/src/config/routes/2.1.json +++ b/src/config/routes/2.1.json @@ -1,458 +1,458 @@ [ { "path": "/events(/[^/]+)*/hosts", - "controller": "Event_hostsController", + "controller": "Joindin\\Api\\Controller\\EventHostsController", "action": "listHosts", "verbs": ["GET"] }, { "path": "/events/[\\d]+/hosts", - "controller": "Event_hostsController", + "controller": "Joindin\\Api\\Controller\\EventHostsController", "action": "addHost", "verbs": ["POST"] }, { "path": "/events/[\\d]+/hosts/[\\d]+", - "controller": "Event_hostsController", + "controller": "Joindin\\Api\\Controller\\EventHostsController", "action": "removeHostFromEvent", "verbs": ["DELETE"] }, { "path": "/events(/[^/]+)*/comments/reported", - "controller": "Event_commentsController", + "controller": "Joindin\\Api\\Controller\\EventCommentsController", "action": "getReported", "verbs": ["GET"] }, { "path": "/events(/[\\d]+)/talk_comments/reported", - "controller": "Talk_commentsController", + "controller": "Joindin\\Api\\Controller\\TalkCommentsController", "action": "getReported", "verbs": ["GET"] }, { "path": "/events/(\\d+)/claims$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "pendingClaims", "verbs": ["GET"] }, { "path": "/events(/[^/]+)*/?$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "getAction", "verbs": ["GET"] }, { "path": "/events/(\\d+)/tracks$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "createTrack", "verbs": ["POST"] }, { "path": "/events/(\\d+)/approval$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "approveAction", "verbs": ["POST"] }, { "path": "/events/(\\d+)/approval$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "rejectAction", "verbs": ["DELETE"] }, { "path": "/events(/[^/]+)*/comments", - "controller": "Event_commentsController", + "controller": "Joindin\\Api\\Controller\\Event_commentsController", "action": "createComment", "verbs": ["POST"] }, { "path": "/events(/[\\d]+)/images", - "controller": "EventImagesController", + "controller": "Joindin\\Api\\Controller\\EventImagesController", "action": "createImage", "verbs": ["POST"] }, { "path": "/events(/[\\d]+)/images", - "controller": "EventImagesController", + "controller": "Joindin\\Api\\Controller\\EventImagesController", "action": "deleteImage", "verbs": ["DELETE"] }, { "path": "/events(/[\\d]+)/talks", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "createTalkAction", "verbs": ["POST"] }, { "path": "/events(/[^/]+)*/?$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "postAction", "verbs": ["POST"] }, { "path": "/events(/[^/]+)*/?$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "putAction", "verbs": ["PUT"] }, { "path": "/events(/[^/]+)*/?$", - "controller": "EventsController", + "controller": "Joindin\\Api\\Controller\\EventsController", "action": "deleteAction", "verbs": ["DELETE"] }, { "path": "/talks(/[\\d]+)/links/?$", - "controller": "TalkLinkController", + "controller": "Joindin\\Api\\Controller\\TalkLinkController", "action": "getTalkLinks", "verbs": ["GET"] }, { "path": "/talks(/[\\d]+)/links/?$", - "controller": "TalkLinkController", + "controller": "Joindin\\Api\\Controller\\TalkLinkController", "action": "addTalkLink", "verbs": ["POST"] }, { "path": "/talks(/[\\d]+)/links(/[\\d]+)$", - "controller": "TalkLinkController", + "controller": "Joindin\\Api\\Controller\\TalkLinkController", "action": "getTalkLink", "verbs": ["GET"] }, { "path": "/talks(/[\\d]+)/links(/[\\d]+)$", - "controller": "TalkLinkController", + "controller": "Joindin\\Api\\Controller\\TalkLinkController", "action": "removeTalkLink", "verbs": ["DELETE"] }, { "path": "/talks(/[\\d]+)/links(/[\\d]+)$", - "controller": "TalkLinkController", + "controller": "Joindin\\Api\\Controller\\TalkLinkController", "action": "updateTalkLink", "verbs": ["PUT"] }, { "path": "/talks(/[\\d]+)/speakers/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "getSpeakersForTalk", "verbs": ["GET"] }, { "path": "/talks(/[\\d]+)/speakers/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "setSpeakerForTalk", "verbs": ["POST"] }, { "path": "/talks(/[\\d]+)/speakers/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "removeSpeakerForTalk", "verbs": ["DELETE"] }, { "path": "/talks(/[\\d]+)$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "editTalk", "verbs": ["PUT"] }, { "path": "/talks/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "getTalkByKeyWord", "verbs": ["GET"] }, { "path": "/talks/[\\d]+/comments/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "getTalkComments", "verbs": ["GET"] }, { "path": "/talks/[\\d]+/starred/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "getTalkStarred", "verbs": ["GET"] }, { "path": "/talks/[\\d]+/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "getAction", "verbs": ["GET"] }, { "path": "/talks(/[\\d]+)/tracks$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "addTrackToTalk", "verbs": ["POST"] }, { "path": "/talks(/[\\d]+)/tracks(/[\\d]+)$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "removeTrackFromTalk", "verbs": ["DELETE"] }, { "path": "/talks(/[^/]+)*/?$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "postAction", "verbs": ["POST"] }, { "path": "/talks(/[\\d]+)/speakers(/[\\d]+)$", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "removeApprovedSpeakerFromTalk", "verbs": ["DELETE"] }, { "path": "/talks/[\\d+]]/starred?", - "controller": "TalksController", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "deleteAction", "verbs": ["DELETE"] }, { - "path": "/talks/[\\d]+/?$", - "controller": "TalksController", + "path": "/talks/[^\\d]/?$", + "controller": "Joindin\\Api\\Controller\\TalksController", "action": "deleteTalk", "verbs": ["DELETE"] }, { "path": "/token(/[^/]+)*/?$", - "controller": "TokenController", + "controller": "Joindin\\Api\\Controller\\TokenController", "action": "postAction", "verbs": ["POST"] }, { "path": "/token/?$", - "controller": "TokenController", + "controller": "Joindin\\Api\\Controller\\TokenController", "action": "listTokensForUser", "verbs": ["GET"] }, { "path": "/token(/[^/]+)/?$", - "controller": "TokenController", + "controller": "Joindin\\Api\\Controller\\TokenController", "action": "getToken", "verbs": ["GET"] }, { "path": "/token(/[^/]+)*/?$", - "controller": "TokenController", + "controller": "Joindin\\Api\\Controller\\TokenController", "action": "revokeToken", "verbs": ["DELETE"] }, { "path": "/tracks(/[^/]+)*/?$", - "controller": "TracksController", + "controller": "Joindin\\Api\\Controller\\TracksController", "action": "getAction", "verbs": ["GET"] }, { "path": "/tracks(/[\\d]+)/?$", - "controller": "TracksController", + "controller": "Joindin\\Api\\Controller\\TracksController", "action": "editTrack", "verbs": ["PUT"] }, { "path": "/tracks(/[\\d]+)/?$", - "controller": "TracksController", + "controller": "Joindin\\Api\\Controller\\TracksController", "action": "deleteTrack", "verbs": ["DELETE"] }, { "path": "/users/passwords$", - "controller": "UsersController", + "controller": "Joindin\\Api\\Controller\\UsersController", "action": "passwordReset", "verbs": ["POST"] }, { "path": "/users(/[0-9]+)/trusted?$", - "controller": "UsersController", + "controller": "Joindin\\Api\\Controller\\UsersController", "action": "setTrusted", "verbs": ["POST"] }, { "path": "/users(/[^/]+)*/?$", - "controller": "UsersController", + "controller": "Joindin\\Api\\Controller\\UsersController", "action": "getAction", "verbs": ["GET"] }, { "path": "/users(/[^/]+)*/?$", - "controller": "UsersController", + "controller": "Joindin\\Api\\Controller\\UsersController", "action": "postAction", "verbs": ["POST"] }, { "path": "/users(/[^/]+)*/?$", - "controller": "UsersController", + "controller": "Joindin\\Api\\Controller\\UsersController", "action": "deleteUser", "verbs": ["DELETE"] }, { "path": "/users(/[0-9]+)/?$", - "controller": "UsersController", + "controller": "Joindin\\Api\\Controller\\UsersController", "action": "updateUser", "verbs": ["PUT"] }, { "path": "/event_comments(/[^/]+)*/?$", - "controller": "Event_commentsController", + "controller": "Joindin\\Api\\Controller\\EventCommentsController", "action": "getComments", "verbs": ["GET"] }, { "path": "/event_comments(/[^/]+)*/reported?$", - "controller": "Event_commentsController", + "controller": "Joindin\\Api\\Controller\\EventCommentsController", "action": "reportComment", "verbs": ["POST"] }, { "path": "/event_comments(/[^/]+)*/reported?$", - "controller": "Event_commentsController", + "controller": "Joindin\\Api\\Controller\\EventCommentsController", "action": "moderateReportedComment", "verbs": ["PUT"] }, { "path": "/talk_comments(/[^/]+)*/?$", - "controller": "Talk_commentsController", + "controller": "Joindin\\Api\\Controller\\TalkCommentsController", "action": "getComments", "verbs": ["GET"] }, { "path": "/talk_comments(/[^/]+)*/reported?$", - "controller": "Talk_commentsController", + "controller": "Joindin\\Api\\Controller\\TalkCommentsController", "action": "reportComment", "verbs": ["POST"] }, { "path": "/talk_comments(/[^/]+)*/reported?$", - "controller": "Talk_commentsController", + "controller": "Joindin\\Api\\Controller\\TalkCommentsController", "action": "moderateReportedComment", "verbs": ["PUT"] }, { "path": "/talk_comments(/[^/]+)*/?$", - "controller": "Talk_commentsController", + "controller": "Joindin\\Api\\Controller\\TalkCommentsController", "action": "updateComment", "verbs": ["PUT"] }, { "path": "/emails/verifications", - "controller": "EmailsController", + "controller": "Joindin\\Api\\Controller\\EmailsController", "action": "verifications", "verbs": ["POST"] }, { "path": "/emails/reminders/username", - "controller": "EmailsController", + "controller": "Joindin\\Api\\Controller\\EmailsController", "action": "usernameReminder", "verbs": ["POST"] }, { "path": "/emails/reminders/password", - "controller": "EmailsController", + "controller": "Joindin\\Api\\Controller\\EmailsController", "action": "passwordReset", "verbs": ["POST"] }, { "path": "/twitter/request_token", - "controller": "TwitterController", + "controller": "Joindin\\Api\\Controller\\TwitterController", "action": "getRequestToken", "verbs": ["POST"] }, { "path": "/twitter/token", - "controller": "TwitterController", + "controller": "Joindin\\Api\\Controller\\TwitterController", "action": "logUserIn", "verbs": ["POST"] }, { "path": "/languages?$", - "controller": "LanguagesController", + "controller": "Joindin\\Api\\Controller\\LanguagesController", "action": "getAllLanguages", "verbs": ["GET"] }, { "path": "/languages(/[0-9]+)?/?$", - "controller": "LanguagesController", + "controller": "Joindin\\Api\\Controller\\LanguagesController", "action": "getLanguage", "verbs": ["GET"] }, { "path": "/contact", - "controller": "ContactController", + "controller": "Joindin\\Api\\Controller\\ContactController", "action": "contact", "verbs": ["POST"] }, { "path": "/talk_types/?$", - "controller": "TalkTypesController", + "controller": "Joindin\\Api\\Controller\\TalkTypesController", "action": "getAllTalkTypes", "verbs": ["GET"] }, { "path": "/talk_types(/[0-9]+)?/?$", - "controller": "TalkTypesController", + "controller": "Joindin\\Api\\Controller\\TalkTypesController", "action": "getTalkType", "verbs": ["GET"] }, { "path": "/facebook/token", - "controller": "FacebookController", + "controller": "Joindin\\Api\\Controller\\FacebookController", "action": "logUserIn", "verbs": ["POST"] }, { "path" : "/applications$", - "controller" : "ApplicationsController", + "controller" : "Joindin\\Api\\Controller\\ApplicationsController", "action" : "listApplications", "verbs" : ["GET"] }, { "path" : "/applications$", - "controller" : "ApplicationsController", + "controller" : "Joindin\\Api\\Controller\\ApplicationsController", "action" : "createApplication", "verbs" : ["POST"] }, { "path" : "/applications(/[0-9]+)$", - "controller" : "ApplicationsController", + "controller" : "Joindin\\Api\\Controller\\ApplicationsController", "action" : "getApplication", "verbs" : ["GET"] }, { "path" : "/applications(/[0-9]+)$", - "controller" : "ApplicationsController", + "controller" : "Joindin\\Api\\Controller\\ApplicationsController", "action" : "editApplication", "verbs" : ["PUT"] }, { "path" : "/applications(/[0-9]+)$", - "controller" : "ApplicationsController", + "controller" : "Joindin\\Api\\Controller\\ApplicationsController", "action" : "deleteApplication", "verbs" : ["DELETE"] }, { "path": "/?$", - "controller": "DefaultController", + "controller": "Joindin\\Api\\Controller\\DefaultController", "action": "handle" } ] diff --git a/src/database.php.dist b/src/database.php.dist index b6a29e5bc..e5b9b56d7 100644 --- a/src/database.php.dist +++ b/src/database.php.dist @@ -10,7 +10,7 @@ * @license http://github.com/joindin/joind.in/blob/master/doc/LICENSE JoindIn */ -if (! defined('BASEPATH')) { +if (!defined('BASEPATH')) { exit('No direct script access allowed'); } /* diff --git a/src/inc/Autoloader.php b/src/inc/Autoloader.php deleted file mode 100644 index a3030f944..000000000 --- a/src/inc/Autoloader.php +++ /dev/null @@ -1,64 +0,0 @@ - - * @license BSD see doc/LICENSE - * @link http://github.com/joindin/joind.in - */ - -include __DIR__ . '/../../vendor/autoload.php'; - -spl_autoload_register('apiv2Autoload'); - -/** - * Autoloader - * - * @param string $classname name of class to load - * - * @return boolean - */ -function apiv2Autoload($classname) -{ - if (false !== strpos($classname, '.')) { - // this was a filename, don't bother - exit; - } - - $filename = false; - if (strpos($classname, "JoindinTest" ) === 0) { - $rename = [ - 'Controller' => 'controllers', - '\\' => DIRECTORY_SEPARATOR, - 'JoindinTest' => __DIR__ . '/../../tests', - ]; - $filename = str_replace(array_keys($rename), $rename, $classname) . ".php"; - } - - if (preg_match('/[a-zA-Z]+Controller$/', $classname)) { - $filename = __DIR__ . '/../controllers/' . $classname . '.php'; - } elseif (preg_match('/[a-zA-Z]+Mapper$/', $classname)) { - $filename = __DIR__ . '/../models/' . $classname . '.php'; - } elseif (preg_match('/[a-zA-Z]+Model$/', $classname)) { - $filename = __DIR__ . '/../models/' . $classname . '.php'; - } elseif (preg_match('/[a-zA-Z]+ModelCollection$/', $classname)) { - $filename = __DIR__ . '/../models/' . $classname . '.php'; - } elseif (preg_match('/[a-zA-Z]+View$/', $classname)) { - $filename = __DIR__ . '/../views/' . $classname . '.php'; - } elseif (preg_match('/[a-zA-Z]+Service$/', $classname)) { - $filename = __DIR__ . '/../services/' . $classname . '.php'; - } elseif (preg_match('/Router?$/', $classname)) { - $filename = __DIR__ . '/../routers/' . $classname . '.php'; - } - - if (file_exists($filename)) { - include $filename; - - return true; - } -} diff --git a/src/public/index.php b/src/public/index.php index 54e4a397b..438a2011a 100644 --- a/src/public/index.php +++ b/src/public/index.php @@ -1,5 +1,11 @@ [ + 'apiKey' => 'key', + 'blog' => 'blog' + ], + 'email' => [ + 'contact' => 'excample@example.com', + "from" => "example@example.com", + 'smtp' => [ + 'host' => 'localhost', + 'port' => 25, + 'username' => 'username', + 'password' => 'ChangeMeSeymourChangeMe', + 'security' => null, + ], + ], + 'website_url' => 'www.example.com' + ]; + + /** + * @test + */ + public function containerIsCreated() + { + $this->assertInstanceOf(ContainerInterface::class, ContainerFactory::build($this->config)); + } + + /** + * @test + * @covers \Joindin\Api\ContainerFactory::build + * + * @dataProvider dataProvider + * @param string $service + */ + public function serviceIsDefined($service) + { + $container = ContainerFactory::build($this->config, true); + $this->assertTrue($container->has($service)); + } + + /** + * @test + * @covers \Joindin\Api\ContainerFactory::build + * + * @dataProvider dataProvider + * @param string $service + */ + public function servicesCanBeCreated($service) + { + $container = ContainerFactory::build($this->config, true); + $this->assertInstanceOf($service, $container->get($service)); + } + + /** + * @test + * @covers \Joindin\Api\ContainerFactory::build + */ + public function spamCheckServiceIsNullCheckerWhenDisabled() + { + $container = ContainerFactory::build([], true); + $this->assertTrue($container->has(Service\SpamCheckServiceInterface::class)); + $this->assertInstanceOf(Service\NullSpamCheckService::class, $container->get(Service\SpamCheckServiceInterface::class)); + } + + /** + * List of services which must be defined + * + * @return array + */ + public function dataProvider() + { + return [ + [Controller\ContactController::class], + [Service\SpamCheckServiceInterface::class], + [Service\ContactEmailService::class], + [Controller\ApplicationsController::class], + [Controller\DefaultController::class], + [Controller\EmailsController::class] , + [Controller\EventCommentsController::class], + [Controller\EventHostsController::class], + [Controller\EventImagesController::class], + [Controller\EventsController::class], + [Controller\FacebookController::class], + [Controller\LanguagesController::class], + [Controller\TalkCommentsController::class], + [Controller\TalkLinkController::class], + [Controller\TalksController::class], + [Controller\TalkTypesController::class], + [Controller\TokenController::class], + [Controller\TracksController::class], + [Controller\TwitterController::class], + [Controller\UsersController::class] + ]; + } +} diff --git a/tests/controllers/ContactControllerTest.php b/tests/Controller/ContactControllerTest.php similarity index 90% rename from tests/controllers/ContactControllerTest.php rename to tests/Controller/ContactControllerTest.php index bc1dd93ad..401738e7d 100644 --- a/tests/controllers/ContactControllerTest.php +++ b/tests/Controller/ContactControllerTest.php @@ -1,6 +1,6 @@ getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); - $oauthModel = $this->getMockBuilder('\OAuthModel')->disableOriginalConstructor()->getMock(); + $oauthModel = $this->getMockBuilder('\Joindin\Api\Model\OAuthModel')->disableOriginalConstructor()->getMock(); $oauthModel->expects($this->once())->method('isClientPermittedPasswordGrant')->willReturn($isClientPermittedPasswordGrant); $request->expects($this->once())->method('getOauthModel')->willReturn($oauthModel); $request @@ -40,7 +40,7 @@ public function testContactWorksAsExpected( $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $spamCheckService = $this->getMockBuilder(\SpamCheckServiceInterface::class) + $spamCheckService = $this->getMockBuilder(\Joindin\Api\Service\SpamCheckServiceInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -51,11 +51,11 @@ public function testContactWorksAsExpected( ->willReturn($isCommentAcceptable); } - $emailService = $this->getMockBuilder(\ContactEmailService::class) + $emailService = $this->getMockBuilder(\Joindin\Api\Service\ContactEmailService::class) ->disableOriginalConstructor() ->getMock(); - $contactController = new \ContactController($emailService, $spamCheckService); + $contactController = new \Joindin\Api\Controller\ContactController($emailService, $spamCheckService); if (null !== $expectedException) { $this->expectException($expectedException); @@ -66,7 +66,7 @@ public function testContactWorksAsExpected( } if ($emailShouldBeSent) { - $viewMock = $this->getMockBuilder(\ApiView::class) + $viewMock = $this->getMockBuilder(\Joindin\Api\View\ApiView::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/controllers/EventHostsControllerTest.php b/tests/Controller/EventHostsControllerTest.php similarity index 66% rename from tests/controllers/EventHostsControllerTest.php rename to tests/Controller/EventHostsControllerTest.php index a41f57f5a..f6537c500 100644 --- a/tests/controllers/EventHostsControllerTest.php +++ b/tests/Controller/EventHostsControllerTest.php @@ -1,6 +1,6 @@ expectExceptionMessage('You must be logged in to create data'); $this->expectExceptionCode(401); - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); $controller->addHost($request, $db); @@ -26,12 +26,12 @@ public function testThatRemovingHostWithoutLoginFails() $this->expectExceptionMessage('You must be logged in to remove data'); $this->expectExceptionCode(401); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->user_id = null; $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $constructor = new \Event_hostsController(); + $constructor = new \Joindin\Api\Controller\EventHostsController(); $constructor->removeHostFromEvent($request, $db); } @@ -41,14 +41,14 @@ public function testThatMissingEventThrowsException() $this->expectExceptionMessage('Event not found'); $this->expectExceptionCode(404); - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); - $em = $this->getMockBuilder('EventMapper')->disableOriginalConstructor()->getMock(); + $em = $this->getMockBuilder('Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $em->method('getEventById')->willReturn(false); $controller->setEventMapper($em); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->url_elements = [3 => 'foo']; $request->user_id = 2; @@ -63,13 +63,13 @@ public function testThatRemovingOneselfThrowsException() $this->expectExceptionMessage('You are not allowed to remove yourself from the host-list'); $this->expectExceptionCode(403); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->user_id = 1; $request->url_elements = [5 => 1]; $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $constructor = new \Event_hostsController(); + $constructor = new \Joindin\Api\Controller\EventHostsController(); $constructor->removeHostFromEvent($request, $db); } @@ -79,7 +79,7 @@ public function testThatInvalidEventThrowsException() $this->expectExceptionMessage('Event not found'); $this->expectExceptionCode(404); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->user_id = 1; $request->url_elements = [ 3 => 4, @@ -88,10 +88,10 @@ public function testThatInvalidEventThrowsException() $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $eventMapper = $this->getMockBuilder('\EventMapper')->disableOriginalConstructor()->getMock(); + $eventMapper = $this->getMockBuilder('\Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $eventMapper->method('getEventById')->willReturn(false); - $constructor = new \Event_hostsController(); + $constructor = new \Joindin\Api\Controller\EventHostsController(); $constructor->setEventMapper($eventMapper); $constructor->removeHostFromEvent($request, $db); @@ -103,15 +103,15 @@ public function testThatExceptionIsThrownWhenNonAdminUserTriesToAddHostToEvent() $this->expectExceptionMessage('You do not have permission to add hosts to this event'); $this->expectExceptionCode(403); - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); - $em = $this->getMockBuilder('EventMapper')->disableOriginalConstructor()->getMock(); + $em = $this->getMockBuilder('Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $em->method('getEventById')->willReturn(true); $em->method('thisUserHasAdminOn')->willReturn(false); $controller->setEventMapper($em); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->url_elements = [3 => 'foo']; $request->user_id = 2; @@ -126,7 +126,7 @@ public function testThatUserThatIsNotAdminOnEventWillThrowException() $this->expectExceptionMessage('You do not have permission to remove hosts from this event'); $this->expectExceptionCode(403); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->user_id = 1; $request->url_elements = [ 3 => 4, @@ -135,11 +135,11 @@ public function testThatUserThatIsNotAdminOnEventWillThrowException() $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $eventMapper = $this->getMockBuilder('\EventMapper')->disableOriginalConstructor()->getMock(); + $eventMapper = $this->getMockBuilder('\Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $eventMapper->method('getEventById')->willReturn(true); $eventMapper->method('thisUserHasAdminOn')->willReturn(false); - $constructor = new \Event_hostsController(); + $constructor = new \Joindin\Api\Controller\EventHostsController(); $constructor->setEventMapper($eventMapper); $constructor->removeHostFromEvent($request, $db); @@ -151,20 +151,20 @@ public function testThatExceptionIsThrownWhenUnknownUserShallBeAddedAsHostToEven $this->expectExceptionMessage('No User found'); $this->expectExceptionCode(404); - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\ControllerEventHostsController(); - $em = $this->getMockBuilder('EventMapper')->disableOriginalConstructor()->getMock(); + $em = $this->getMockBuilder('Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $em->method('getEventById')->willReturn(true); $em->method('thisUserHasAdminOn')->willReturn(true); $controller->setEventMapper($em); - $um = $this->getMockBuilder('UserMapper')->disableOriginalConstructor()->getMock(); + $um = $this->getMockBuilder('Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $um->method('getUserIdFromUsername')->with($this->equalTo('myhostname'))->willReturn(false); $controller->setUserMapper($um); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->url_elements = [3 => 'foo']; $request->user_id = 2; $request->method('getParameter')->willReturn('myhostname'); @@ -180,7 +180,7 @@ public function testThatSettingUnknownUserWillThrowException() $this->expectExceptionMessage('No User found'); $this->expectExceptionCode(404); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder(Joindin\Api\Request::class)->disableOriginalConstructor()->getMock(); $request->user_id = 1; $request->url_elements = [ 3 => 4, @@ -189,14 +189,14 @@ public function testThatSettingUnknownUserWillThrowException() $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $eventMapper = $this->getMockBuilder('\EventMapper')->disableOriginalConstructor()->getMock(); + $eventMapper = $this->getMockBuilder('\Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $eventMapper->method('getEventById')->willReturn(true); $eventMapper->method('thisUserHasAdminOn')->willReturn(true); - $userMapper = $this->getMockBuilder('\UserMapper')->disableOriginalConstructor()->getMock(); + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $userMapper->method('getUserById')->willReturn(false); - $constructor = new \Event_hostsController(); + $constructor = new \Joindin\Api\Controller\EventHostsController(); $constructor->setEventMapper($eventMapper); $constructor->setUserMapper($userMapper); @@ -209,25 +209,25 @@ public function testThatExceptionIsThrownWhenEventHostMapperHasProblems() $this->expectExceptionMessage('Something went wrong'); $this->expectExceptionCode(400); - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); - $em = $this->getMockBuilder('EventMapper')->disableOriginalConstructor()->getMock(); + $em = $this->getMockBuilder('Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $em->method('getEventById')->willReturn(true); $em->method('thisUserHasAdminOn')->willReturn(true); $controller->setEventMapper($em); - $um = $this->getMockBuilder('UserMapper')->disableOriginalConstructor()->getMock(); + $um = $this->getMockBuilder('Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $um->method('getUserIdFromUsername')->with($this->equalTo('myhostname'))->willReturn(13); $controller->setUserMapper($um); - $ehm = $this->getMockBuilder('EventHostMapper')->disableOriginalConstructor()->getMock(); + $ehm = $this->getMockBuilder('Joindin\Api\Model\EventHostMapper')->disableOriginalConstructor()->getMock(); $ehm->expects($this->once())->method('addHostToEvent')->with($this->equalTo(12, 13))->willReturn(false); $controller->setEventHostMapper($ehm); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->url_elements = [3 => 12]; $request->user_id = 2; $request->method('getParameter')->willReturn('myhostname'); @@ -239,25 +239,25 @@ public function testThatExceptionIsThrownWhenEventHostMapperHasProblems() public function testThatViewGetsCorrectValuesWhenEverythingWorksAsExpected() { - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); - $em = $this->getMockBuilder('EventMapper')->disableOriginalConstructor()->getMock(); + $em = $this->getMockBuilder('Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $em->method('getEventById')->willReturn(true); $em->method('thisUserHasAdminOn')->willReturn(true); $controller->setEventMapper($em); - $um = $this->getMockBuilder('UserMapper')->disableOriginalConstructor()->getMock(); + $um = $this->getMockBuilder('Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $um->method('getUserIdFromUsername')->with($this->equalTo('myhostname'))->willReturn(13); $controller->setUserMapper($um); - $ehm = $this->getMockBuilder('EventHostMapper')->disableOriginalConstructor()->getMock(); + $ehm = $this->getMockBuilder('Joindin\Api\Model\EventHostMapper')->disableOriginalConstructor()->getMock(); $ehm->expects($this->once())->method('addHostToEvent')->with($this->equalTo(12), $this->equalTo(13))->willReturn(true); $controller->setEventHostMapper($ehm); - $view = $this->getMockBuilder('\ApiView')->disableOriginalConstructor()->getMock(); + $view = $this->getMockBuilder('\Joindin\Api\View\ApiView')->disableOriginalConstructor()->getMock(); $view->expects($this->once())->method('setHeader')->with( $this->equalTo('Location'), $this->equalTo('foo//events/12/hosts') @@ -267,7 +267,7 @@ public function testThatViewGetsCorrectValuesWhenEverythingWorksAsExpected() $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->url_elements = [3 => 12]; $request->user_id = 2; $request->base = 'foo'; @@ -292,17 +292,17 @@ public function testThatFailureWhileRemovingUserAsHostWillThrowException() $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $eventMapper = $this->getMockBuilder('\EventMapper')->disableOriginalConstructor()->getMock(); + $eventMapper = $this->getMockBuilder('\Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $eventMapper->method('getEventById')->willReturn(true); $eventMapper->method('thisUserHasAdminOn')->willReturn(true); - $userMapper = $this->getMockBuilder('\UserMapper')->disableOriginalConstructor()->getMock(); + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $userMapper->method('getUserById')->willReturn(true); - $eventHostMapper = $this->getMockBuilder('\EventHostMapper')->disableOriginalConstructor()->getMock(); + $eventHostMapper = $this->getMockBuilder('\Joindin\Api\Model\EventHostMapper')->disableOriginalConstructor()->getMock(); $eventHostMapper->method('removeHostFromEvent')->willReturn(false); - $constructor = new \Event_hostsController(); + $constructor = new \Joindin\Api\Controller\EventHostsController(); $constructor->setEventMapper($eventMapper); $constructor->setUserMapper($userMapper); $constructor->setEventHostMapper($eventHostMapper); @@ -312,12 +312,12 @@ public function testThatFailureWhileRemovingUserAsHostWillThrowException() public function testThatRemovingUserAsHostSetsCorrectValues() { - $view = $this->getMockBuilder('\ApiView')->getMock(); + $view = $this->getMockBuilder('\Joindin\Api\View\ApiView')->getMock(); $view->method('setHeader')->with('Location', 'base/version/events/4/hosts'); $view->method('setResponseCode')->with(204); $view->method('setNoRender')->with(true); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->user_id = 1; $request->url_elements = [ 3 => 4, @@ -329,17 +329,17 @@ public function testThatRemovingUserAsHostSetsCorrectValues() $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $eventMapper = $this->getMockBuilder('\EventMapper')->disableOriginalConstructor()->getMock(); + $eventMapper = $this->getMockBuilder('\Joindin\Api\Model\EventMapper')->disableOriginalConstructor()->getMock(); $eventMapper->method('getEventById')->willReturn(true); $eventMapper->method('thisUserHasAdminOn')->willReturn(true); - $userMapper = $this->getMockBuilder('\UserMapper')->disableOriginalConstructor()->getMock(); + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $userMapper->method('getUserById')->willReturn(true); - $eventHostMapper = $this->getMockBuilder('\EventHostMapper')->disableOriginalConstructor()->getMock(); + $eventHostMapper = $this->getMockBuilder('\Joindin\Api\Model\EventHostMapper')->disableOriginalConstructor()->getMock(); $eventHostMapper->method('removeHostFromEvent')->willReturn(true); - $constructor = new \Event_hostsController(); + $constructor = new \Joindin\Api\Controller\EventHostsController(); $constructor->setEventMapper($eventMapper); $constructor->setUserMapper($userMapper); $constructor->setEventHostMapper($eventHostMapper); @@ -349,40 +349,40 @@ public function testThatRemovingUserAsHostSetsCorrectValues() public function testThatGettingEventHostWapperMithoutSettingFirstWorksAsExpected() { - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $automatedEventHostMapper = $controller->getEventHostMapper($request, $db); - $this->assertInstanceOf('EventHostMapper', $automatedEventHostMapper); + $this->assertInstanceOf(Joindin\Api\Model\EventHostMapper::class, $automatedEventHostMapper); $this->assertSame($automatedEventHostMapper, $controller->getEventHostMapper($request, $db)); } public function testThatGettingUserMapperWithoutSettingFirstWorksAsExpected() { - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $automatedUserMapper = $controller->getUserMapper($request, $db); - $this->assertInstanceOf('UserMapper', $automatedUserMapper); + $this->assertInstanceOf(Joindin\Api\Model\UserMapper::class, $automatedUserMapper); $this->assertSame($automatedUserMapper, $controller->getUserMapper($request, $db)); } public function testThatGettingEventMapperWithoutSettingFirstWorksAsExpected() { - $controller = new \Event_hostsController(); + $controller = new \Joindin\Api\Controller\EventHostsController(); $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $automatedEventMapper = $controller->getEventMapper($request, $db); - $this->assertInstanceOf('EventMapper', $automatedEventMapper); + $this->assertInstanceOf(Joindin\Api\Model\EventMapper::class, $automatedEventMapper); $this->assertSame($automatedEventMapper, $controller->getEventMapper($request, $db)); } } diff --git a/tests/controllers/TalkBase.php b/tests/Controller/TalkBase.php similarity index 94% rename from tests/controllers/TalkBase.php rename to tests/Controller/TalkBase.php index 062d39c88..954b966b8 100644 --- a/tests/controllers/TalkBase.php +++ b/tests/Controller/TalkBase.php @@ -1,16 +1,16 @@ willReturn(6); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper @@ -429,7 +430,7 @@ public function testClaimTalkAsUserIsSuccessful() ->willReturn(2); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper @@ -494,7 +495,7 @@ public function testAssignTalkAsHostIsSuccessful() ->willReturn(1); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper @@ -560,13 +561,13 @@ public function testApproveAssignmentAsUserWhoClaimedThrowsException() ->willReturn(false); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper ->expects($this->once()) ->method('claimExists') - ->willReturn(\PendingTalkClaimMapper::SPEAKER_CLAIM); + ->willReturn(\Joindin\Api\Model\PendingTalkClaimMapper::SPEAKER_CLAIM); $talks_controller->setPendingTalkClaimMapper($pending_talk_claim_mapper); @@ -623,13 +624,13 @@ public function testApproveAssignmentAsNonAdminUserThrowsException() ->willReturn(false); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper ->expects($this->once()) ->method('claimExists') - ->willReturn(\PendingTalkClaimMapper::SPEAKER_CLAIM); + ->willReturn(\Joindin\Api\Model\PendingTalkClaimMapper::SPEAKER_CLAIM); $talks_controller->setPendingTalkClaimMapper($pending_talk_claim_mapper); @@ -683,13 +684,13 @@ public function testApproveClaimAsHostWhoAssignedThrowsException() ->willReturn(1); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper ->expects($this->once()) ->method('claimExists') - ->willReturn(\PendingTalkClaimMapper::HOST_ASSIGN); + ->willReturn(\Joindin\Api\Model\PendingTalkClaimMapper::HOST_ASSIGN); $talks_controller->setPendingTalkClaimMapper($pending_talk_claim_mapper); @@ -742,13 +743,13 @@ public function testApproveAssignmentAsUserSucceeds() ->willReturn(2); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper ->expects($this->once()) ->method('claimExists') - ->willReturn(\PendingTalkClaimMapper::HOST_ASSIGN); + ->willReturn(\Joindin\Api\Model\PendingTalkClaimMapper::HOST_ASSIGN); $pending_talk_claim_mapper ->expects($this->once()) ->method('approveAssignmentAsSpeaker') @@ -813,13 +814,13 @@ public function testApproveClaimAsHostSucceeds() ->willReturn(1); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper ->expects($this->once()) ->method('claimExists') - ->willReturn(\PendingTalkClaimMapper::SPEAKER_CLAIM); + ->willReturn(\Joindin\Api\Model\PendingTalkClaimMapper::SPEAKER_CLAIM); $pending_talk_claim_mapper ->expects($this->once()) ->method('approveClaimAsHost') @@ -1065,7 +1066,7 @@ public function testRejectClaimAsHostSucceeds() $talks_controller->setTalkMapper($this->talk_mapper); - $user_mapper = $this->getMockBuilder('\UserMapper') + $user_mapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); @@ -1075,13 +1076,13 @@ public function testRejectClaimAsHostSucceeds() ->willReturn(1); $talks_controller->setUserMapper($user_mapper); - $pending_talk_claim_mapper = $this->getMockBuilder('\PendingTalkClaimMapper') + $pending_talk_claim_mapper = $this->getMockBuilder('\Joindin\Api\Model\PendingTalkClaimMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); $pending_talk_claim_mapper ->expects($this->once()) ->method('claimExists') - ->willReturn(\PendingTalkClaimMapper::SPEAKER_CLAIM); + ->willReturn(\Joindin\Api\Model\PendingTalkClaimMapper::SPEAKER_CLAIM); $pending_talk_claim_mapper ->expects($this->once()) ->method('rejectClaimAsHost') diff --git a/tests/controllers/TokenControllerTest.php b/tests/Controller/TokenControllerTest.php similarity index 75% rename from tests/controllers/TokenControllerTest.php rename to tests/Controller/TokenControllerTest.php index 1fb6ef66c..e814021f4 100644 --- a/tests/controllers/TokenControllerTest.php +++ b/tests/Controller/TokenControllerTest.php @@ -1,6 +1,6 @@ request = $this->getMockBuilder('Request')->disableOriginalConstructor()->getMock(); + $this->request = $this->getMockBuilder('Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $this->pdo = $this->getMockBuilder('PDO')->disableOriginalConstructor()->getMock(); } @@ -22,7 +22,7 @@ public function testThatDeletingATokenWithoutLoginThrowsException() $this->expectExceptionMessage('You must be logged in'); $this->expectExceptionCode(401); - $usersController = new \TokenController(); + $usersController = new \Joindin\Api\Controller\TokenController(); $usersController->revokeToken($this->request, $this->pdo); } @@ -33,7 +33,7 @@ public function testThatRetrievingTokensWithoutLoginThrowsException() $this->expectExceptionMessage('You must be logged in'); $this->expectExceptionCode(401); - $usersController = new \TokenController(); + $usersController = new \Joindin\Api\Controller\TokenController(); $usersController->listTokensForUser($this->request, $this->pdo); } diff --git a/tests/controllers/UsersControllerTest.php b/tests/Controller/UsersControllerTest.php similarity index 77% rename from tests/controllers/UsersControllerTest.php rename to tests/Controller/UsersControllerTest.php index 135c57a12..fc7631614 100644 --- a/tests/controllers/UsersControllerTest.php +++ b/tests/Controller/UsersControllerTest.php @@ -1,6 +1,6 @@ expectExceptionMessage('You must be logged in to delete data'); $this->expectExceptionCode(401); - $request = new \Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); + $request = new \Joindin\Api\Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); $db = $this->getMockBuilder('\JoindinTest\Inc\mockPDO')->getMock(); $usersController->deleteUser($request, $db); @@ -39,14 +39,14 @@ public function testDeleteUserWithNonAdminIdThrowsException() $this->expectExceptionMessage('You do not have permission to do that'); $this->expectExceptionCode(403); - $request = new \Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); + $request = new \Joindin\Api\Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); $request->user_id = 2; - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); $db = $this->getMockBuilder(\PDO::class)->disableOriginalConstructor()->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper') + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); @@ -71,14 +71,14 @@ public function testDeleteUserWithAdminAccessThrowsExceptionOnFailedDelete() $this->expectExceptionMessage('There was a problem trying to delete the user'); $this->expectExceptionCode(400); - $request = new \Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); + $request = new \Joindin\Api\Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); $request->user_id = 1; - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); // Please see below for explanation of why we're mocking a "mock" PDO // class $db = $this->getMockBuilder('\JoindinTest\Inc\mockPDO')->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper') + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); @@ -105,14 +105,14 @@ public function testDeleteUserWithAdminAccessThrowsExceptionOnFailedDelete() */ public function testDeleteUserWithAdminAccessDeletesSuccessfully() { - $request = new \Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); + $request = new \Joindin\Api\Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/3", 'REQUEST_METHOD' => 'DELETE']); $request->user_id = 1; - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); // Please see below for explanation of why we're mocking a "mock" PDO // class $db = $this->getMockBuilder('\JoindinTest\Inc\mockPDO')->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper') + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); @@ -132,7 +132,7 @@ public function testDeleteUserWithAdminAccessDeletesSuccessfully() public function testThatUserDataIsNotDoubleEscapedOnUserCreation() { - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->user_id = 1; $request->base = 'base'; $request->path_info = 'path_info'; @@ -152,14 +152,14 @@ public function testThatUserDataIsNotDoubleEscapedOnUserCreation() 'Bio"\'stuff' ); - $view = $this->getMockBuilder('\ApiView')->disableOriginalConstructor()->getMock(); + $view = $this->getMockBuilder('\Joindin\Api\View\ApiView')->disableOriginalConstructor()->getMock(); $view->expects($this->once())->method('setHeader')->with('Location', 'basepath_info/1'); $view->expects($this->once())->method('setResponseCode')->with(201); $request->method('getView')->willReturn($view); $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper')->disableOriginalConstructor()->getMock(); + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $userMapper->expects($this->once())->method('getUserByUsername')->with('user"\'stuff')->willReturn(false); $userMapper->expects($this->once())->method('checkPasswordValidity')->with('pass"\'stuff')->willReturn(true); $userMapper->expects($this->once())->method('generateEmailVerificationTokenForUserId')->willReturn('token'); @@ -172,10 +172,10 @@ public function testThatUserDataIsNotDoubleEscapedOnUserCreation() 'biography' => 'Bio"\'stuff' ])->willReturn(true); - $emailService = $this->getMockBuilder('\UserRegistrationEmailService')->disableOriginalConstructor()->getMock(); + $emailService = $this->getMockBuilder('\Joindin\Api\Service\UserRegistrationEmailService')->disableOriginalConstructor()->getMock(); $emailService->method('sendEmail'); - $controller = new \UsersController(); + $controller = new \Joindin\Api\Controller\UsersController(); $controller->setUserMapper($userMapper); $controller->setUserRegistrationEmailService($emailService); @@ -184,7 +184,7 @@ public function testThatUserDataIsNotDoubleEscapedOnUserCreation() public function testThatUserDataIsNotDoubleEscapedOnUserEdit() { - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->method('getUserId')->willReturn(1); $request->method('getParameter')->withConsecutive( ['password'], @@ -202,18 +202,18 @@ public function testThatUserDataIsNotDoubleEscapedOnUserEdit() 'Bio"\'stuff' ); - $oauthmodel = $this->getMockBuilder('\OAuthModel')->disableOriginalConstructor()->getMock(); + $oauthmodel = $this->getMockBuilder('\Joindin\Api\Model\OAuthModel')->disableOriginalConstructor()->getMock(); $oauthmodel->expects($this->once())->method('isAccessTokenPermittedPasswordGrant')->willReturn(true); $request->expects($this->once())->method('getOauthModel')->willReturn($oauthmodel); - $view = $this->getMockBuilder('\ApiView')->disableOriginalConstructor()->getMock(); + $view = $this->getMockBuilder('\Joindin\Api\View\ApiView')->disableOriginalConstructor()->getMock(); $view->expects($this->once())->method('setHeader')->with('Content-Length', 0); $view->expects($this->once())->method('setResponseCode')->with(204); $request->method('getView')->willReturn($view); $db = $this->getMockBuilder('\PDO')->disableOriginalConstructor()->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper')->disableOriginalConstructor()->getMock(); + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper')->disableOriginalConstructor()->getMock(); $userMapper->expects($this->once())->method('getUserByUsername')->with('user"\'stuff')->willReturn(false); $userMapper->expects($this->once())->method('thisUserHasAdminOn')->willReturn(true); $userMapper->expects($this->once())->method('editUser')->with([ @@ -225,7 +225,7 @@ public function testThatUserDataIsNotDoubleEscapedOnUserEdit() 'user_id' => false, ])->willReturn(true); - $controller = new \UsersController(); + $controller = new \Joindin\Api\Controller\UsersController(); $controller->setUserMapper($userMapper); $controller->updateUser($request, $db); @@ -245,7 +245,7 @@ public function testSetTrustedWithNoUserIdThrowsException() $request = new \Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/4/trusted", 'REQUEST_METHOD' => 'POST']); - $usersController = new \UsersController(); + $request = new \Joindin\Api\Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/4/trusted", 'REQUEST_METHOD' => 'POST']); $db = $this->getMockBuilder(\PDO::class)->disableOriginalConstructor()->getMock(); $usersController->setTrusted($request, $db); @@ -264,12 +264,12 @@ public function testSetTrustedWithNonAdminIdThrowsException() $this->expectExceptionMessage("You must be an admin to change a user's trusted state"); $this->expectExceptionCode(403); - $request = new \Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/4/trusted", 'REQUEST_METHOD' => 'POST']); + $request = new \Joindin\Api\Request([], ['REQUEST_URI' => "http://api.dev.joind.in/v2.1/users/4/trusted", 'REQUEST_METHOD' => 'POST']); $request->user_id = 2; - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); $db = $this->getMockBuilder(\PDO::class)->disableOriginalConstructor()->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper') + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); @@ -296,16 +296,16 @@ public function testSetTrustedWithoutStateThrowsException() $this->expectExceptionMessage('You must provide a trusted state'); $this->expectExceptionCode(400); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->method('getUserId')->willReturn(2); $request->method('getParameter') ->with("trusted") ->willReturn(null); - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); $db = $this->getMockBuilder(\PDO::class)->disableOriginalConstructor()->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper') + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); @@ -330,16 +330,16 @@ public function testSetTrustedWithFailureThrowsException() $this->expectExceptionMessage('Unable to update status'); $this->expectExceptionCode(500); - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->method('getUserId')->willReturn(2); $request->method('getParameter') ->with("trusted") ->willReturn(true); - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); $db = $this->getMockBuilder(\PDO::class)->disableOriginalConstructor()->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper') + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); @@ -366,13 +366,13 @@ public function testSetTrustedWithFailureThrowsException() */ public function testSetTrustedWithSuccessCreatesView() { - $request = $this->getMockBuilder('\Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('\Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $request->method('getUserId')->willReturn(2); $request->method('getParameter') ->with("trusted") ->willReturn(true); - $view = $this->getMockBuilder(\JsonView::class)->getMock(); + $view = $this->getMockBuilder(\Joindin\Api\View\JsonView::class)->getMock(); $view->expects($this->once()) ->method("setHeader") ->willReturn(true); @@ -386,10 +386,10 @@ public function testSetTrustedWithSuccessCreatesView() ->method("getView") ->willReturn($view); - $usersController = new \UsersController(); + $usersController = new \Joindin\Api\Controller\UsersController(); $db = $this->getMockBuilder(\PDO::class)->disableOriginalConstructor()->getMock(); - $userMapper = $this->getMockBuilder('\UserMapper') + $userMapper = $this->getMockBuilder('\Joindin\Api\Model\UserMapper') ->setConstructorArgs(array($db,$request)) ->getMock(); diff --git a/tests/inc/HeaderTest.php b/tests/HeaderTest.php similarity index 82% rename from tests/inc/HeaderTest.php rename to tests/HeaderTest.php index 57e90d507..f38087273 100644 --- a/tests/inc/HeaderTest.php +++ b/tests/HeaderTest.php @@ -1,18 +1,16 @@ parseParams(); $this->assertEquals(3, $header->count()); @@ -20,7 +18,7 @@ public function testParseParamsWithEmbededSeparator() public function testParseParamsWithTwoGlues() { $headerStr = 'For=10.0.0.1,For=10.0.0.2;user-agent="test;test;test;test";For=10.0.0.3;user-agent="secondLevel;some date"'; - $header = new \Header('Forwarded', $headerStr, ';'); + $header = new \Joindin\Api\Header('Forwarded', $headerStr, ';'); $header->parseParams(); $header->setGlue(','); @@ -31,7 +29,7 @@ public function testBuildEntityArray() { $headerStr = 'For=10.0.0.1;user-agent="test;test;test;test";For=10.0.0.2;user-agent="secondLevel; some date";for=10.0.0.3;user-agent="thirdLevel"'; - $header = new \Header('Forwarded', $headerStr, ';'); + $header = new \Joindin\Api\Header('Forwarded', $headerStr, ';'); $header->parseParams(); $header->setGlue(','); @@ -43,7 +41,7 @@ public function testBuildEntityArray() public function testBuildEntityArrayWithValueOnly() { $headerStr = '10.0.0.1,10.0.0.2,10.0.0.3'; - $header = new \Header('X-Forwarded-For', $headerStr, ','); + $header = new \Joindin\Api\Header('X-Forwarded-For', $headerStr, ','); $header->parseParams(); $this->assertEquals(3, $header->count()); $partsArray = $header->toArray(); diff --git a/tests/models/ApiMapperTest.php b/tests/Model/ApiMapperTest.php similarity index 67% rename from tests/models/ApiMapperTest.php rename to tests/Model/ApiMapperTest.php index aca03c252..4b5cf2af2 100644 --- a/tests/models/ApiMapperTest.php +++ b/tests/Model/ApiMapperTest.php @@ -1,8 +1,13 @@ pdo = $this->getMockBuilder('PDO') - ->disableOriginalConstructor() - ->getMock(); - $this->request = $this->getMockBuilder('Request') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); + $this->request = $this->getMockBuilder('Joindin\Api\Request') + ->disableOriginalConstructor() + ->getMock(); } public function testThatApiMapperHasNoDefaultFields() @@ -49,30 +54,41 @@ public function testThatDefaultMapperConvertsDateTimeFieldsCorrectly($expected, public function defaultMapperConvertsDateTimeFieldsCorrectlyProvider() { return [ - [[ - ['event_start_date' => '2016-09-19T05:54:18+00:00', - 'event_tz_place' => null, - 'event_tz_cont' => null, - 'name' => null, - ], + [ + [ + [ + 'event_start_date' => '2016-09-19T05:54:18+00:00', + 'event_tz_place' => null, + 'event_tz_cont' => null, + 'name' => null, + ], - ],[ - ['event_start_date' => 1474264458, - 'event_tz_place' => null, - 'event_tz_cont' => null, + ], + [ + [ + 'event_start_date' => 1474264458, + 'event_tz_place' => null, + 'event_tz_cont' => null, + ] ] - ]], - [[ - ['event_start_date' => '2016-09-19T07:54:18+02:00', - 'event_tz_place' => 'Berlin', - 'event_tz_cont' => 'Europe', - 'name' => null, + ], + [ + [ + [ + 'event_start_date' => '2016-09-19T07:54:18+02:00', + 'event_tz_place' => 'Berlin', + 'event_tz_cont' => 'Europe', + 'name' => null, + ] + ], + [ + [ + 'event_start_date' => 1474264458, + 'event_tz_place' => 'Berlin', + 'event_tz_cont' => 'Europe', + ] ] - ],[ - ['event_start_date' => 1474264458, - 'event_tz_place' => 'Berlin', - 'event_tz_cont' => 'Europe',] - ]], + ], ]; } @@ -81,10 +97,10 @@ public function testThatDefaultMappingReturnsOnlyDefaultFields() $mapper = new TestApiMapper($this->pdo, $this->request); $this->assertEquals([ - 'event_tz_place' => 'event_tz_place', - 'event_tz_cont' => 'event_tz_cont', + 'event_tz_place' => 'event_tz_place', + 'event_tz_cont' => 'event_tz_cont', 'event_start_date' => 'event_start_date', - 'name' => 'name', + 'name' => 'name', ], $mapper->getDefaultFields()); } @@ -102,30 +118,30 @@ public function testBuildingTheLimitClause() public function testThatRetrievingTotalCountFromQueryWorks($query, $countquery, $data, $returns, $exception = false) { $result = $this->getMockBuilder('PDOStatement') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); if ($exception) { $result->method('execute') ->with($this->equalTo($data)) - ->will($this->throwException(new Exception())); + ->will($this->throwException(new Exception())); } else { $result->method('execute') ->with($this->equalTo($data)); } $result->method('fetchColumn') - ->with($this->equalTo(0)) - ->willReturn($returns); + ->with($this->equalTo(0)) + ->willReturn($returns); $pdo = $this->getMockBuilder('PDO') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $pdo->method('prepare') ->with($this->equalTo($countquery)) ->willReturn($result); $mapper = new ApiMapper($pdo, $this->request); - $obj = new ReflectionClass('ApiMapper'); + $obj = new ReflectionClass('Joindin\Api\Model\ApiMapper'); $method = $obj->getMethod('getTotalCount'); $method->setAccessible(true); diff --git a/tests/models/EventHostMapperTest.php b/tests/Model/EventHostMapperTest.php similarity index 83% rename from tests/models/EventHostMapperTest.php rename to tests/Model/EventHostMapperTest.php index a9843b83a..4f2671042 100644 --- a/tests/models/EventHostMapperTest.php +++ b/tests/Model/EventHostMapperTest.php @@ -1,5 +1,8 @@ method('lastInsertId') ->willReturn(14); - $request = $this->getMockBuilder('Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $mapper = new EventHostMapper($pdo, $request); @@ -43,7 +46,7 @@ public function testThatFailingExecuteResultsInFalseBeingReturned() ->with('INSERT INTO user_admin (uid, rid, rtype) VALUES (:host_id, :event_id, :type)') ->willReturn($stmt); - $request = $this->getMockBuilder('Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $mapper = new EventHostMapper($pdo, $request); @@ -63,7 +66,7 @@ public function testThatGettingHostByEventIdReturnsSomethingSensibleWhenStatemen ->with('select a.uid as user_id, u.full_name as host_name from user_admin a inner join user u on u.ID = a.uid where rid = :event_id and rtype="event" and (rcode!="pending" OR rcode is null) order by host_name LIMIT 0,10') ->willReturn($stmt); - $request = $this->getMockBuilder('Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $mapper = new EventHostMapper($pdo, $request); @@ -99,22 +102,24 @@ public function testThatGettingHostByEventIdReturnsSomethingSensibleWhenStatemen ->method('prepare') ->with('SELECT count(*) AS count FROM (select a.uid as user_id, u.full_name as host_name from user_admin a inner join user u on u.ID = a.uid where rid = :event_id and rtype="event" and (rcode!="pending" OR rcode is null) order by host_name ) as counter') ->willReturn($stmt2); - $request = $this->getMockBuilder('Request')->disableOriginalConstructor()->getMock(); - $request->base = 'test'; - $request->version = '1'; - $request->path_info = '2'; + $request = $this->getMockBuilder('Joindin\Api\Request')->disableOriginalConstructor()->getMock(); + $request->base = 'test'; + $request->version = '1'; + $request->path_info = '2'; $request->paginationParameters = ['resultsperpage' => 10, 'start' => 0]; $mapper = new EventHostMapper($pdo, $request); $this->assertEquals([ - 'hosts' => [[ - 'host_name' => 'Karl Napp', - 'host_uri' => 'test/1/users/8', - ]], - 'meta' => [ - 'count' => 1, - 'total' => null, + 'hosts' => [ + [ + 'host_name' => 'Karl Napp', + 'host_uri' => 'test/1/users/8', + ] + ], + 'meta' => [ + 'count' => 1, + 'total' => null, 'this_page' => 'test2?resultsperpage=10&start=0' ] ], $mapper->getHostsByEventId(12, 10, 0)); @@ -137,7 +142,7 @@ public function testThatRemovingAHostFromAnEventCallsTheExpectedMethods() ->with('DELETE FROM user_admin WHERE uid = :user_id AND rid = :event_id AND rtype = :type') ->willReturn($stmt1); - $request = $this->getMockBuilder('Request')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder('Joindin\Api\Request')->disableOriginalConstructor()->getMock(); $mapper = new EventHostMapper($pdo, $request); $this->assertTrue($mapper->removeHostFromEvent(12, 14)); diff --git a/tests/models/OauthModelTest.php b/tests/Model/OauthModelTest.php similarity index 78% rename from tests/models/OauthModelTest.php rename to tests/Model/OauthModelTest.php index f1710759a..433abe65a 100644 --- a/tests/models/OauthModelTest.php +++ b/tests/Model/OauthModelTest.php @@ -1,18 +1,23 @@ pdo = $this->getMockBuilder('PDO') - ->disableOriginalConstructor() - ->getMock(); - $this->request = $this->getMockBuilder('Request') - ->disableOriginalConstructor() - ->getMock(); - $this->request->base = ""; + $this->pdo = $this->getMockBuilder('PDO') + ->disableOriginalConstructor() + ->getMock(); + $this->request = $this->getMockBuilder('Joindin\Api\Request') + ->disableOriginalConstructor() + ->getMock(); + $this->request->base = ""; $this->request->version = "2.1"; $this->oauth = new OAuthModel($this->pdo, $this->request); @@ -62,7 +67,7 @@ public function testLoggingInWorks() [ 'password' => password_hash(md5($pass), PASSWORD_BCRYPT), 'verified' => 1, - 'ID' => 1234, + 'ID' => 1234, ] ); $this->pdo->method('prepare')->willReturn($stmt); diff --git a/tests/models/TalkMapperTest.php b/tests/Model/TalkMapperTest.php similarity index 98% rename from tests/models/TalkMapperTest.php rename to tests/Model/TalkMapperTest.php index 88ca257ac..da4008d63 100644 --- a/tests/models/TalkMapperTest.php +++ b/tests/Model/TalkMapperTest.php @@ -1,11 +1,11 @@ 'event_tz_place', - 'event_tz_cont' => 'event_tz_cont', + 'event_tz_place' => 'event_tz_place', + 'event_tz_cont' => 'event_tz_cont', 'event_start_date' => 'event_start_date', - 'name' => 'name', + 'name' => 'name', ]; } diff --git a/tests/inc/RequestTest.php b/tests/RequestTest.php similarity index 79% rename from tests/inc/RequestTest.php rename to tests/RequestTest.php index decade7e9..b9b9ea460 100644 --- a/tests/inc/RequestTest.php +++ b/tests/RequestTest.php @@ -1,10 +1,9 @@ config = $config; } @@ -36,7 +35,7 @@ public function testGetParameterReturnsValueOfRequestedParameter() $server = [ 'QUERY_STRING' => $queryString ]; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $this->assertEquals('bar', $request->getParameter('foo')); $this->assertEquals('samoflange', $request->getParameter('baz')); @@ -51,7 +50,7 @@ public function testGetParameterReturnsValueOfRequestedParameter() public function testGetParameterReturnsDefaultIfParameterNotSet() { $uniq = uniqid(); - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $result = $request->getParameter('samoflange', $uniq); $this->assertSame($uniq, $result); @@ -70,7 +69,7 @@ public function testGetParameterReturnsDefaultIfParameterNotSet() */ public function testRequestMethodIsProperlyLoaded($method) { - $request = new \Request($this->config, ['REQUEST_METHOD' => $method]); + $request = new Request($this->config, ['REQUEST_METHOD' => $method]); $this->assertEquals($method, $request->getVerb()); } @@ -86,7 +85,7 @@ public function testRequestMethodIsProperlyLoaded($method) */ public function testSetVerbAllowsForSettingRequestVerb($verb) { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $request->setVerb($verb); $this->assertEquals($verb, $request->getVerb()); @@ -100,7 +99,7 @@ public function testSetVerbAllowsForSettingRequestVerb($verb) */ public function testSetVerbIsFluent() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertSame($request, $request->setVerb(uniqid())); } @@ -130,7 +129,7 @@ public function methodProvider() */ public function testGetUrlElementReturnsDefaultIfIndexIsNotFound() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $default = uniqid(); $result = $request->getUrlElement(22, $default); @@ -149,7 +148,7 @@ public function testGetUrlElementReturnsDefaultIfIndexIsNotFound() public function testGetUrlElementReturnsRequestedElementFromPath() { $server = ['PATH_INFO' => 'foo/bar/baz']; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $this->assertEquals('foo', $request->getUrlElement(0)); $this->assertEquals('bar', $request->getUrlElement(1)); $this->assertEquals('baz', $request->getUrlElement(2)); @@ -166,7 +165,7 @@ public function testAcceptsHeadersAreParsedCorrectly() { $server = ['HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8']; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $this->assertFalse($request->accepts('image/png')); $this->assertTrue($request->accepts('text/html')); @@ -187,7 +186,7 @@ public function testPreferredContentTypeOfReturnsADesiredFormatIfItIsAccepted() { $server = ['HTTP_ACCEPT' => 'text/text,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8']; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $result = $request->preferredContentTypeOutOf( array('text/html', 'application/json') @@ -212,7 +211,7 @@ public function testIfPreferredFormatIsNotAcceptedReturnJson() { $server =['HTTP_ACCEPT' => 'text/text,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8']; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $result = $request->preferredContentTypeOutOf( array('text/html'), @@ -232,7 +231,7 @@ public function testIfPreferredFormatIsNotAcceptedReturnJson() public function testHostIsSetCorrectlyFromTheHeaders() { $server = ['HTTP_HOST' => 'joind.in']; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $this->assertEquals('joind.in', $request->host); $this->assertEquals('joind.in', $request->getHost()); @@ -245,7 +244,7 @@ public function testHostIsSetCorrectlyFromTheHeaders() */ public function testSetHostIsFluent() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertSame($request, $request->setHost(uniqid())); } @@ -257,7 +256,7 @@ public function testSetHostIsFluent() public function testHostCanBeSetWithSetHost() { $host = uniqid() . '.com'; - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $request->setHost($host); $this->assertEquals($host, $request->getHost()); @@ -289,8 +288,8 @@ public function testJsonBodyIsParsedAsParameters($method) $server = [ 'REQUEST_METHOD' => $method, 'CONTENT_TYPE' => 'application/json', ]; - /* @var $request \Request */ - $request = $this->getMockBuilder('\Request') + /* @var $request Request */ + $request = $this->getMockBuilder('\Joindin\Api\Request') ->setMethods(array('getRawBody')) ->setConstructorArgs([[], $server]) ->getMock(); @@ -325,7 +324,7 @@ public function postPutProvider() */ public function testSchemeIsHttpByDefault() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertEquals('http://', $request->scheme); $this->assertEquals('http://', $request->getScheme()); @@ -342,7 +341,7 @@ public function testSchemeIsHttpByDefault() public function testSchemeIsHttpsIfHttpsValueIsOn() { $server = ['HTTPS' => 'on']; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $this->assertEquals('https://', $request->scheme); $this->assertEquals('https://', $request->getScheme()); @@ -355,7 +354,7 @@ public function testSchemeIsHttpsIfHttpsValueIsOn() */ public function testSetSchemeIsFluent() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertSame($request, $request->setScheme('http://')); } @@ -370,7 +369,7 @@ public function testSetSchemeIsFluent() */ public function testSchemeCanBeSetBySetSchemeMethod($scheme) { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $request->setScheme($scheme); $this->assertEquals($scheme, $request->getScheme()); @@ -401,7 +400,7 @@ public function testIfIdentificationDoesNotHaveTwoPartsExceptionIsThrown() $this->expectExceptionMessage('Invalid Authorization Header'); $this->expectExceptionCode(400); - $request = new \Request($this->config, ['HTTPS' => 'on']); + $request = new Request($this->config, ['HTTPS' => 'on']); $request->identifyUser('This is a bad header'); } @@ -417,7 +416,7 @@ public function testIfIdentificationHeaderDoesNotStartWithOauthThrowException() $this->expectExceptionMessage('Unknown Authorization Header Received'); $this->expectExceptionCode(400); - $request = new \Request($this->config, ['HTTPS' => 'on']); + $request = new Request($this->config, ['HTTPS' => 'on']); $request->identifyUser('Auth Me'); } @@ -429,7 +428,7 @@ public function testIfIdentificationHeaderDoesNotStartWithOauthThrowException() public function testIfRequestIsntHTTPSReturnsFalse() { $config = array_merge($this->config, array('mode' => 'production')); - $request = new \Request($config, []); + $request = new Request($config, []); $request->setScheme('http://'); $this->assertFalse($request->identifyUser('This is a bad header')); } @@ -449,10 +448,10 @@ public function testGetOauthModelProvidesAnOauthModel() )->getMock(); $db->method('getAvailableDrivers'); - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $result = $request->getOAuthModel($db); - $this->assertInstanceOf('OAuthModel', $result); + $this->assertInstanceOf('Joindin\Api\Model\OAuthModel', $result); } /** @@ -467,7 +466,7 @@ public function testCallingGetOauthModelWithoutADatabaseAdapterThrowsAnException $this->expectExceptionMessage('Db Must be provided to get Oauth Model'); $this->expectExceptionCode(0); - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $request->getOauthModel(); } @@ -478,9 +477,9 @@ public function testCallingGetOauthModelWithoutADatabaseAdapterThrowsAnException */ public function testSetOauthModelMethodIsFluent() { - /* @var $mockOauth \OAuthModel */ - $mockOauth = $this->getMockBuilder('OAuthModel')->disableOriginalConstructor()->getMock(); - $request = new \Request($this->config, []); + /* @var $mockOauth \Joindin\Api\Model\OAuthModel */ + $mockOauth = $this->getMockBuilder('Joindin\Api\Model\OAuthModel')->disableOriginalConstructor()->getMock(); + $request = new Request($this->config, []); $this->assertSame($request, $request->setOauthModel($mockOauth)); } @@ -493,9 +492,9 @@ public function testSetOauthModelMethodIsFluent() */ public function testSetOauthModelAllowsSettingOfOauthModel() { - /* @var $mockOauth \OAuthModel */ - $mockOauth = $this->getMockBuilder('OAuthModel')->disableOriginalConstructor()->getMock(); - $request = new \Request($this->config, []); + /* @var $mockOauth \Joindin\Api\Model\OAuthModel */ + $mockOauth = $this->getMockBuilder('Joindin\Api\Model\OAuthModel')->disableOriginalConstructor()->getMock(); + $request = new Request($this->config, []); $request->setOauthModel($mockOauth); $this->assertSame($mockOauth, $request->getOauthModel()); @@ -509,8 +508,8 @@ public function testSetOauthModelAllowsSettingOfOauthModel() */ public function testIdentifyUserWithOauthTokenTypeSetsUserIdForValidHeader() { - $request = new \Request($this->config, ['HTTPS' => 'on']); - $mockOauth = $this->getMockBuilder('OAuthModel')->disableOriginalConstructor()->getMock(); + $request = new Request($this->config, ['HTTPS' => 'on']); + $mockOauth = $this->getMockBuilder('Joindin\Api\Model\OAuthModel')->disableOriginalConstructor()->getMock(); $mockOauth->expects($this->once()) ->method('verifyAccessToken') ->with('authPart') @@ -532,8 +531,8 @@ public function testIdentifyUserWithOauthTokenTypeSetsUserIdForValidHeader() */ public function testIdentifyUserWithBearerTokenTypeSetsUserIdForValidHeader() { - $request = new \Request($this->config, ['HTTPS' => 'on']); - $mockOauth = $this->getMockBuilder('OAuthModel')->disableOriginalConstructor()->getMock(); + $request = new Request($this->config, ['HTTPS' => 'on']); + $mockOauth = $this->getMockBuilder('Joindin\Api\Model\OAuthModel')->disableOriginalConstructor()->getMock(); $mockOauth->expects($this->once()) ->method('verifyAccessToken') ->with('authPart') @@ -554,7 +553,7 @@ public function testIdentifyUserWithBearerTokenTypeSetsUserIdForValidHeader() */ public function testSetUserIdIsFluent() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertSame($request, $request->setUserId('TheUserToSet')); } @@ -566,7 +565,7 @@ public function testSetUserIdIsFluent() */ public function testSetUserIdAllowsForSettingOfUserId() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $user = uniqid(); $request->setUserId($user); @@ -582,7 +581,7 @@ public function testSetPathInfoAllowsSettingOfPathInfo() { $path = uniqid() . '/' . uniqid() . '/' . uniqid(); $parts = explode('/', $path); - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $request->setPathInfo($path); $this->assertEquals($path, $request->getPathInfo()); @@ -600,7 +599,7 @@ public function testSetPathInfoAllowsSettingOfPathInfo() */ public function testSetPathIsFluent() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertSame($request, $request->setPathInfo(uniqid())); } @@ -614,7 +613,7 @@ public function testSetAcceptSetsTheAcceptVariable() $accept = uniqid() . ',' . uniqid() . ',' . uniqid(); $acceptParts = explode(',', $accept); - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $request->setAccept($accept); $this->assertEquals($acceptParts, $request->accept); @@ -630,7 +629,7 @@ public function testSetAcceptSetsTheAcceptVariable() */ public function testSetAcceptsIsFluent() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertSame($request, $request->setAccept(uniqid())); } @@ -641,7 +640,7 @@ public function testSetAcceptsIsFluent() */ public function testSetBaseAllowsSettingOfBase() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $base = uniqid(); $request->setBase($base); $this->assertEquals($base, $request->getBase()); @@ -655,7 +654,7 @@ public function testSetBaseAllowsSettingOfBase() */ public function testSetBaseIsFluent() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertSame($request, $request->setBase(uniqid())); } @@ -671,73 +670,75 @@ public function getViewProvider() return array( array( // #0 'parameters' => array(), - 'expectedClass' => '\JsonView' + 'expectedClass' => '\Joindin\Api\View\JsonView' ), array( // #1 'parameters' => array('format' => 'html'), - 'expectedClass' => 'HtmlView' + 'expectedClass' => 'Joindin\Api\View\HtmlView' ), array( // #2 'parameters' => array('callback' => 'dave'), - 'expectedClass' => 'JsonPView' + 'expectedClass' => 'Joindin\Api\View\JsonPView' ), array( // #3 'parameters' => array('format' => 'html'), - 'expectedClass' => 'HtmlView' + 'expectedClass' => 'Joindin\Api\View\HtmlView' ), array( // #4 'parameters' => array('format' => 'html'), - 'expectedClass' => 'HtmlView', + 'expectedClass' => 'Joindin\Api\View\HtmlView', 'accepts' => 'text/html' ), array( // #5 'parameters' => array(), - 'expectedClass' => 'JsonView', + 'expectedClass' => 'Joindin\Api\View\JsonView', 'accepts' => 'application/json' ), array( // #6 'parameters' => array(), - 'expectedClass' => 'JsonView', + 'expectedClass' => 'Joindin\Api\View\JsonView', 'accepts' => 'application/json,text/html' ), array( // #7 'parameters' => array(), - 'expectedClass' => 'HtmlView', + 'expectedClass' => 'Joindin\Api\View\HtmlView', 'accepts' => 'text/html,applicaton/json', - 'view' => new \HtmlView(), + 'view' => new \Joindin\Api\View\HtmlView(), // 'skip' => true // Currently we're not applying Accept correctly // Can @choult check what's the reason for the skip? ), array( // #8 'parameters' => array('format' => 'html'), - 'expectedClass' => 'HtmlView', + 'expectedClass' => 'Joindin\Api\View\HtmlView', 'accepts' => 'applicaton/json,text/html' ), array( // #9 'parameters' => array(), 'expectedClass' => false, 'accepts' => '', - 'view' => new \ApiView() + 'view' => new \Joindin\Api\View\ApiView() ), ); } /** * @dataProvider getViewProvider - * @covers Request::getView - * @covers Request::setView + * @covers \Joindin\Api\Request::getView + * @covers \Joindin\Api\Request::setView + * + * @param array $parameters Request query parameters + * @param string $expectedClass The name of the expected class to be returned + * @param string $accept An HTTP Accept header + * @param \Joindin\Api\View\ApiView|null $view A plan getter/setter test + * @param boolean $skip Set to true to skip the test * - * @param array $parameters Request query parameters - * @param string $expectedClass The name of the expected class to be returned - * @param string $accept An HTTP Accept header - * @param \ApiView|null $view A plan getter/setter test - * @param boolean $skip Set to true to skip the test + * @test */ public function testGetView( array $parameters = array(), $expectedClass = '', $accept = '', - \ApiView $view = null, + \Joindin\Api\View\ApiView $view = null, $skip = false ) { @@ -748,7 +749,7 @@ public function testGetView( $server = [ 'QUERY_STRING' => http_build_query($parameters), 'HTTP_ACCEPT' => $accept]; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); if ($view) { $request->setView($view); $this->assertEquals($view, $request->getView()); @@ -769,14 +770,17 @@ public function getSetFormatChoicesProvider() { return array( array( // #0 - 'expected' => array(\Request::CONTENT_TYPE_JSON, - \Request::CONTENT_TYPE_HTML), + 'expected' => array( + Request::CONTENT_TYPE_JSON, + Request::CONTENT_TYPE_HTML), ), array( // #1 - 'expected' => array(\Request::CONTENT_TYPE_HTML, - \Request::CONTENT_TYPE_JSON), - 'choices' => array(\Request::CONTENT_TYPE_HTML, - \Request::CONTENT_TYPE_JSON), + 'expected' => array( + Request::CONTENT_TYPE_HTML, + Request::CONTENT_TYPE_JSON), + 'choices' => array( + Request::CONTENT_TYPE_HTML, + Request::CONTENT_TYPE_JSON), ), array( // #2 'expected' => array('a', 'b'), @@ -787,8 +791,8 @@ public function getSetFormatChoicesProvider() /** * @dataProvider getSetFormatChoicesProvider - * @covers \Request::getFormatChoices - * @covers \Request::setFormatChoices + * @covers \Joindin\Api\Request::getFormatChoices + * @covers \Joindin\Api\Request::setFormatChoices * * @param array $expected * @param array|null $choices @@ -798,7 +802,7 @@ public function testGetSetFormatChoices( array $choices = null ) { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); if ($choices) { $request->setFormatChoices($choices); } @@ -807,24 +811,24 @@ public function testGetSetFormatChoices( } /** - * @covers Request::getRouteParams - * @covers Request::setRouteParams + * @covers \Joindin\Api\Request::getRouteParams + * @covers \Joindin\Api\Request::setRouteParams */ public function testGetSetRouteParams() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $params = array('event_id' => 10); $request->setRouteParams($params); $this->assertEquals($params, $request->getRouteParams()); } /** - * @covers \Request::getAccessToken - * @covers \Request::setAccessToken + * @covers \Joindin\Api\Request::getAccessToken + * @covers \Joindin\Api\Request::setAccessToken */ public function testGetSetAccessToken() { - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $token = 'token'; $request->setAccessToken($token); $this->assertEquals($token, $request->getAccessToken()); @@ -837,7 +841,7 @@ public function testGetSetAccessToken() public function testConstructorParsesRequestUri() { $server = ['REQUEST_URI' => '/v2/one/two?three=four']; - $request = new \Request($this->config, $server); + $request = new Request($this->config, $server); $this->assertEquals('/v2/one/two', $request->getPathInfo()); } @@ -847,7 +851,7 @@ public function testConstructorParsesRequestUri() public function testGettingClientIp($header) { $_SERVER = array_merge($header, $_SERVER); - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertEquals('192.168.1.1', $request->getClientIP()); } @@ -864,7 +868,7 @@ public function clientIpProvider() public function testGettingClientUserAgent($header, $userAgent) { $_SERVER = array_merge($header, $_SERVER); - $request = new \Request($this->config, []); + $request = new Request($this->config, []); $this->assertEquals($userAgent, $request->getClientUserAgent()); } @@ -877,7 +881,7 @@ public function gettingClientUserAgentProvider() public function testGettingConfigValues() { - $request = new \Request(['Foo'=> 'Bar'], []); + $request = new Request(['Foo' => 'Bar'], []); $this->assertEquals('Bar', $request->getConfigValue('Foo')); $this->assertEquals('Foo', $request->getConfigValue('Bar', 'Foo')); } diff --git a/tests/routers/ApiRouterTest.php b/tests/Router/ApiRouterTest.php similarity index 74% rename from tests/routers/ApiRouterTest.php rename to tests/Router/ApiRouterTest.php index 723f29dc9..e11740ef0 100644 --- a/tests/routers/ApiRouterTest.php +++ b/tests/Router/ApiRouterTest.php @@ -1,13 +1,14 @@ array( + 'routers' => array( 2 => 'B', 1 => 'A', 3 => 'C' @@ -38,10 +39,10 @@ public function getSetRoutersProvider() /** * @dataProvider getSetRoutersProvider * - * @covers ApiRouter::getRouters - * @covers ApiRouter::setRouters + * @covers \Joindin\Api\Router\ApiRouter::getRouters + * @covers \Joindin\Api\Router\ApiRouter::setRouters * - * @param array $routers A list of Routers + * @param array $routers A list of Routers * @param array $expected The expected result of getRouters */ public function testGetSetRouters(array $routers, array $expected) diff --git a/tests/routers/DefaultRouterTest.php b/tests/Router/DefaultRouterTest.php similarity index 61% rename from tests/routers/DefaultRouterTest.php rename to tests/Router/DefaultRouterTest.php index 259d19084..3ce416fbd 100644 --- a/tests/routers/DefaultRouterTest.php +++ b/tests/Router/DefaultRouterTest.php @@ -1,13 +1,15 @@ $url]); - $router = new DefaultRouter([]); - $route = $router->getRoute($request); - $this->assertEquals('DefaultController', $route->getController()); + $router = new DefaultRouter([]); + $route = $router->getRoute($request); + $this->assertEquals('Joindin\Api\Controller\DefaultController', $route->getController()); $this->assertEquals('handle', $route->getAction()); } } diff --git a/tests/routers/RouteTest.php b/tests/Router/RouteTest.php similarity index 60% rename from tests/routers/RouteTest.php rename to tests/Router/RouteTest.php index 6da37565e..70ff072e8 100644 --- a/tests/routers/RouteTest.php +++ b/tests/Router/RouteTest.php @@ -1,11 +1,16 @@ array('config'), - 'controller' => 'TestController3', - 'action' => 'action', - 'request' => $this->getRequest('v1') + 'config' => array('config'), + 'controller' => 'Joindin\Api\Test\Router\TestController3', + 'action' => 'action', + 'Joindin\Api\Request' => $this->getRequest('v1') ), array( // #1 - 'config' => array('config'), - 'controller' => 'TestController3', - 'action' => 'action2', - 'request' => $this->getRequest('v1'), - 'expectedException' => 'Exception', + 'config' => array('config'), + 'controller' => 'Joindin\Api\Test\Router\TestController3', + 'action' => 'action2', + 'Joindin\Api\Request' => $this->getRequest('v1'), + 'expectedException' => 'Exception', 'expectedExceptionCode' => 500, ), array( // #2 - 'config' => array('config'), - 'controller' => 'TestController4', - 'action' => 'action2', - 'request' => $this->getRequest('v1'), - 'expectedException' => 'Exception', + 'config' => array('config'), + 'controller' => 'TestController4', + 'action' => 'action2', + 'Joindin\Api\Request' => $this->getRequest('v1'), + 'expectedException' => 'Exception', 'expectedExceptionCode' => 400, - 'controllerExists' => false + 'controllerExists' => false ) ); } @@ -114,23 +119,30 @@ public function dispatchProvider() /** * @dataProvider dispatchProvider * - * @covers Route::dispatch + * @covers \Joindin\Api\Router\Route::dispatch * - * @param array $config - * @param string $controller - * @param string $action + * @param array $config + * @param string $controller + * @param string $action * @param Request $request - * @param string $expectedException + * @param string $expectedException * @param integer $expectedExceptionCode * * @throws Exception */ - public function testDispatch(array $config, $controller, $action, Request $request, $expectedException = false, $expectedExceptionCode = false, $controllerExists = true) - { - $db = 'database'; + public function testDispatch( + array $config, + $controller, + $action, + Request $request, + $expectedException = false, + $expectedExceptionCode = false, + $controllerExists = true + ) { + $db = 'database'; $container = $this->getMockBuilder(\Psr\Container\ContainerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $container ->expects($this->atLeastOnce()) @@ -168,7 +180,7 @@ public function testDispatch(array $config, $controller, $action, Request $reque */ private function getRequest($urlElement) { - $request = $this->createMock('Request', array('getUrlElement'), array(), '', false); + $request = $this->createMock('Joindin\Api\Request', ['getUrlElement'], [], '', false); $request->expects($this->any()) ->method('getUrlElement') @@ -178,13 +190,3 @@ private function getRequest($urlElement) return $request; } } - -class TestController3 -{ - public function action(Request $request, $db) - { - if ($db == 'database') { - return 'val'; - } - } -} diff --git a/tests/routers/RouterTest.php b/tests/Router/RouterTest.php similarity index 51% rename from tests/routers/RouterTest.php rename to tests/Router/RouterTest.php index 6430ceaab..78875ef3f 100644 --- a/tests/routers/RouterTest.php +++ b/tests/Router/RouterTest.php @@ -1,13 +1,13 @@ assertEquals($config, $obj->getConfig()); } } - -class TestRouter3 extends BaseRouter -{ - - - /** - * {@inheritdoc} - */ - public function dispatch(Route $route, Request $request, $db) - { - throw new BadMethodCallException('Method not implemented'); - } - - /** - * {@inheritdoc} - */ - public function getRoute(Request $request) - { - throw new BadMethodCallException('Method not implemented'); - } - - public function route(Request $request, $db) - { - } -} diff --git a/tests/Router/TestController3.php b/tests/Router/TestController3.php new file mode 100644 index 000000000..51c334723 --- /dev/null +++ b/tests/Router/TestController3.php @@ -0,0 +1,15 @@ + '2.1', + 'rules' => array( + array( + 'path' => '/events', + 'controller' => 'EventController', + 'action' => 'getAction' + ) + ), + 'url' => '/v2.1/events', + 'method' => Request::HTTP_GET, + 'expectedController' => 'EventController', + 'expectedAction' => 'getAction' + ), + array( // #1 + 'version' => '2.1', + 'rules' => array( + array( + 'path' => '/aevents', + 'controller' => 'AEventController', + 'action' => 'getSAction' + ), + array( + 'path' => '/events', + 'controller' => 'EventController', + 'action' => 'getAction' + ) + ), + 'url' => '/v2.1/events', + 'method' => Request::HTTP_GET, + 'expectedController' => 'EventController', + 'expectedAction' => 'getAction' + ), + array( // #2 + 'version' => '2.1', + 'rules' => array( + array( + 'path' => '/events', + 'controller' => 'EventController', + 'action' => 'getAction', + 'verbs' => array(Request::HTTP_POST) + ), + array( + 'path' => '/events', + 'controller' => 'EventController2', + 'action' => 'getAction2', + 'verbs' => array(Request::HTTP_GET, Request::HTTP_PUT) + ) + ), + 'url' => '/v2.1/events', + 'method' => Request::HTTP_GET, + 'expectedController' => 'EventController2', + 'expectedAction' => 'getAction2' + ), + array( // #3 + 'version' => '2.1', + 'rules' => array( + array( + 'path' => '/events/(?P\d+)$', + 'controller' => 'EventController', + 'action' => 'getAction' + ), + ), + 'url' => '/v2.1/events/10', + 'method' => Request::HTTP_GET, + 'expectedController' => 'EventController', + 'expectedAction' => 'getAction', + 'routeParams' => array('event_id' => 10) + ), + array( // #4 + 'version' => '2.1', + 'rules' => array( + array( + 'path' => '/aevents', + 'controller' => 'AEventController', + 'action' => 'getSAction' + ), + array( + 'path' => '/events', + 'controller' => 'EventController', + 'action' => 'getAction', + 'verbs' => array(Request::HTTP_GET) + ) + ), + 'url' => '/v2.1/events', + 'method' => Request::HTTP_POST, + 'expectedController' => 'N/A', + 'expectedAction' => 'N/A', + 'routeParams' => array(), + 'expectedExceptionCode' => 415 + ), + array( // #5 + 'version' => '2.1', + 'rules' => array( + array( + 'path' => '/aevents', + 'controller' => 'AEventController', + 'action' => 'getSAction' + ), + array( + 'path' => '/events', + 'controller' => 'EventController', + 'action' => 'getAction', + 'verbs' => array(Request::HTTP_GET) + ) + ), + 'url' => '/v2.2/events', + 'method' => Request::HTTP_GET, + 'expectedController' => 'N/A', + 'expectedAction' => 'N/A', + 'routeParams' => array(), + 'expectedExceptionCode' => 404 + ) + ); + } + + /** + * @dataProvider getRouteProvider + * @covers \Joindin\Api\Router\VersionedRouter::getRoute + * + * @param float $version + * @param array $rules + * @param string $url + * @param string $method + * @param string $expectedController + * @param string $expectedAction + * @param array $routeParams + * @param integer|false $expectedExceptionCode + */ + public function testGetRoute( + $version, + array $rules, + $url, + $method, + $expectedController, + $expectedAction, + array $routeParams = array(), + $expectedExceptionCode = false + ) { + $request = new Request([], ['REQUEST_URI' => $url, 'REQUEST_METHOD' => $method]); + $router = new VersionedRouter($version, [], $rules); + try { + $route = $router->getRoute($request); + } catch (Exception $ex) { + if (!$expectedExceptionCode) { + throw $ex; + } + $this->assertEquals($expectedExceptionCode, $ex->getCode()); + + return; + } + $this->assertEquals($expectedController, $route->getController()); + $this->assertEquals($expectedAction, $route->getAction()); + $this->assertEquals($routeParams, $route->getParams()); + } +} diff --git a/tests/services/NullSpamCheckServiceTest.php b/tests/Service/NullSpamCheckServiceTest.php similarity index 70% rename from tests/services/NullSpamCheckServiceTest.php rename to tests/Service/NullSpamCheckServiceTest.php index dc8300b6d..e5dc0e8e1 100644 --- a/tests/services/NullSpamCheckServiceTest.php +++ b/tests/Service/NullSpamCheckServiceTest.php @@ -1,6 +1,6 @@ assertTrue($service->isCommentAcceptable([], '0.0.0.0', 'userAgent')); } } diff --git a/tests/inc/TalkCommentEmailServiceTest.php b/tests/Service/TalkCommentEmailServiceTest.php similarity index 91% rename from tests/inc/TalkCommentEmailServiceTest.php rename to tests/Service/TalkCommentEmailServiceTest.php index cf877b057..e8c5052aa 100644 --- a/tests/inc/TalkCommentEmailServiceTest.php +++ b/tests/Service/TalkCommentEmailServiceTest.php @@ -1,13 +1,11 @@ [["comment" => "test comment", "rating" => 3]]]; $service = new TalkCommentEmailService($this->config, $recipients, $talk, $comment); - $this->assertInstanceOf('TalkCommentEmailService', $service); + $this->assertInstanceOf('Joindin\Api\Service\TalkCommentEmailService', $service); } /** @@ -62,7 +60,7 @@ public function testTemplateReplacements() $comment = ["comments" => [["comment" => "test comment", "rating" => 3]]]; $service = new TalkCommentEmailService($this->config, $recipients, $talk, $comment); - $service->templatePath = __DIR__.'/../../src/views/emails/'; + $service->templatePath = __DIR__.'/../../src/View/emails/'; $template = "testTemplate.md"; $replacements = ["cat" => "Camel", "mat" => "magic carpet"]; diff --git a/tests/views/ApiViewTest.php b/tests/View/ApiViewTest.php similarity index 96% rename from tests/views/ApiViewTest.php rename to tests/View/ApiViewTest.php index e10912454..a79b4b2c5 100644 --- a/tests/views/ApiViewTest.php +++ b/tests/View/ApiViewTest.php @@ -1,9 +1,12 @@ array('a' => 'b', 'c' => 10), + 'input' => array('a' => 'b', 'c' => 10), 'expected' => '{"a":"b","c":10}' ), array( // #1 - 'input' => array('stub' => '10', 'b' => array('c', 'd')), + 'input' => array('stub' => '10', 'b' => array('c', 'd')), 'expected' => '{"stub":"10","b":["c","d"],"meta":{"count":2}}' ), array( // #2 - JOINDIN-519 - 'input' => false, + 'input' => false, 'expected' => 'false' ), ); @@ -34,9 +37,9 @@ public function buildOutputProvider() /** * @dataProvider buildOutputProvider * - * @covers JsonView::buildOutput + * @covers \Joindin\Api\View\JsonView::buildOutput * - * @param mixed $input + * @param mixed $input * @param string $expected */ public function testBuildOutput($input, $expected) diff --git a/tests/assets/PDOMock.php b/tests/assets/PDOMock.php new file mode 100644 index 000000000..e69de29bb diff --git a/tests/frisby/api_read.js b/tests/frisby/api_read.js index aada6d83b..6ccb17c40 100644 --- a/tests/frisby/api_read.js +++ b/tests/frisby/api_read.js @@ -6,183 +6,183 @@ var datatest = require('./data'); var baseURL = ''; function init(_baseURL) { - baseURL = _baseURL; - frisby.globalSetup({ // globalSetup is for ALL requests - request: { - headers: { 'Content-type': 'application/json' } - } - }); + baseURL = _baseURL; + frisby.globalSetup({ // globalSetup is for ALL requests + request: { + headers: { 'Content-type': 'application/json' } + } + }); } function testIndex() { - frisby.create('Initial discovery') - .get(baseURL) - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .expectJSON({ - 'events' : baseURL + '/v2.1/events', - 'hot-events' : baseURL + '/v2.1/events?filter=hot', - 'upcoming-events' : baseURL + '/v2.1/events?filter=upcoming', - 'past-events' : baseURL + '/v2.1/events?filter=past', - 'open-cfps' : baseURL + '/v2.1/events?filter=cfp', - 'docs' : 'http://joindin.github.io/joindin-api/' - }) - - .afterJSON(function(apis) { - - // Loop over all of the event types - for (var evType in apis) { - - // Ignore the "docs" link - if (evType == 'docs') continue; - - frisby.create('Event list for ' + evType) - .get(apis[evType]) - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(ev) { - // Check meta-data - expect(ev.meta).toContainJsonTypes({"count":Number}); - expect(ev).toContainJsonTypes({"events":Array}); - - for(var i in ev.events) { - datatest.checkEventData(ev.events[i]); - testEvent(ev.events[i]); - } - - }).toss(); - } - }) - .toss(); + frisby.create('Initial discovery') + .get(baseURL) + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .expectJSON({ + 'events' : baseURL + '/v2.1/events', + 'hot-events' : baseURL + '/v2.1/events?filter=hot', + 'upcoming-events' : baseURL + '/v2.1/events?filter=upcoming', + 'past-events' : baseURL + '/v2.1/events?filter=past', + 'open-cfps' : baseURL + '/v2.1/events?filter=cfp', + 'docs' : 'http://joindin.github.io/joindin-api/' + }) + + .afterJSON(function(apis) { + + // Loop over all of the event types + for (var evType in apis) { + + // Ignore the "docs" link + if (evType == 'docs') continue; + + frisby.create('Event list for ' + evType) + .get(apis[evType]) + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(ev) { + // Check meta-data + expect(ev.meta).toContainJsonTypes({"count":Number}); + expect(ev).toContainJsonTypes({"events":Array}); + + for(var i in ev.events) { + datatest.checkEventData(ev.events[i]); + testEvent(ev.events[i]); + } + + }).toss(); + } + }) + .toss(); } function testEvent(e) { - // Check for more detail in the events - frisby.create('Event detail for ' + e.name) - .get(e.verbose_uri) - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(detailedEv) { - expect(detailedEv.events[0]).toBeDefined(); - expect(typeof detailedEv.events[0]).toBe('object'); - var evt = detailedEv.events[0]; - datatest.checkVerboseEventData(evt); - - testEventComments(evt); - testEventCommentsVerbose(evt); - testTalksForEvent(evt); - testAttendeesForEvent(evt); - testAttendeesForEventVerbose(evt); - testTracksForEvent(evt); - - }).toss(); + // Check for more detail in the events + frisby.create('Event detail for ' + e.name) + .get(e.verbose_uri) + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(detailedEv) { + expect(detailedEv.events[0]).toBeDefined(); + expect(typeof detailedEv.events[0]).toBe('object'); + var evt = detailedEv.events[0]; + datatest.checkVerboseEventData(evt); + + testEventComments(evt); + testEventCommentsVerbose(evt); + testTalksForEvent(evt); + testAttendeesForEvent(evt); + testAttendeesForEventVerbose(evt); + testTracksForEvent(evt); + + }).toss(); } function testEventComments(evt) { - frisby.create('Event comments for ' + evt.name) - .get(evt.comments_uri + '?resultsperpage=3') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evComments) { - if(typeof evComments.comments == 'object') { - for(var i in evComments.comments) { - var comment = evComments.comments[i]; - datatest.checkEventCommentData(comment); - } - } - }).toss(); + frisby.create('Event comments for ' + evt.name) + .get(evt.comments_uri + '?resultsperpage=3') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evComments) { + if(typeof evComments.comments == 'object') { + for(var i in evComments.comments) { + var comment = evComments.comments[i]; + datatest.checkEventCommentData(comment); + } + } + }).toss(); } function testEventCommentsVerbose(evt) { - frisby.create('Event comments for ' + evt.name + ' (verbose mode)') - .get(evt.comments_uri + '?resultsperpage=3&verbose=yes') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evComments) { - if(typeof evComments.comments == 'object') { - for(var i in evComments.comments) { - var comment = evComments.comments[i]; - datatest.checkVerboseEventComment(comment); - } - } - }).toss(); + frisby.create('Event comments for ' + evt.name + ' (verbose mode)') + .get(evt.comments_uri + '?resultsperpage=3&verbose=yes') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evComments) { + if(typeof evComments.comments == 'object') { + for(var i in evComments.comments) { + var comment = evComments.comments[i]; + datatest.checkVerboseEventComment(comment); + } + } + }).toss(); } function testTalksForEvent(evt) { - frisby.create('Talks at ' + evt.name) - .get(evt.talks_uri + '?resultsperpage=3') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evTalks) { - var talk; - if(typeof evTalks.talks == 'object') { - for(var i in evTalks.talks) { - talk = evTalks.talks[i]; - datatest.checkTalkData(talk); - } - - if(typeof talk == 'object') { - // check some comments on the last talk - frisby.create('Comments on talk ' + talk.talk_title) - .get(talk.comments_uri + '?resultsperpage=3') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evTalkComments) { - if(typeof evTalkComments.comments == 'object') { - for(var i in evTalkComments.comments) { - var talkComment = evTalkComments.comments[i]; - datatest.checkTalkCommentData(talkComment); - } - } - }).toss(); - - // and in verbose mode - frisby.create('Comments on talk ' + talk.talk_title + ' (verbose mode)') - .get(talk.comments_uri + '?resultsperpage=3&verbose=yes') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evTalkComments) { - if(typeof evTalkComments.comments == 'object') { - for(var i in evTalkComments.comments) { - var talkComment = evTalkComments.comments[i]; - datatest.checkVerboseTalkCommentData(talkComment); - } - } - }).toss(); - } - } - }).toss(); + frisby.create('Talks at ' + evt.name) + .get(evt.talks_uri + '?resultsperpage=3') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evTalks) { + var talk; + if(typeof evTalks.talks == 'object') { + for(var i in evTalks.talks) { + talk = evTalks.talks[i]; + datatest.checkTalkData(talk); + } + + if(typeof talk == 'object') { + // check some comments on the last talk + frisby.create('Comments on talk ' + talk.talk_title) + .get(talk.comments_uri + '?resultsperpage=3') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evTalkComments) { + if(typeof evTalkComments.comments == 'object') { + for(var i in evTalkComments.comments) { + var talkComment = evTalkComments.comments[i]; + datatest.checkTalkCommentData(talkComment); + } + } + }).toss(); + + // and in verbose mode + frisby.create('Comments on talk ' + talk.talk_title + ' (verbose mode)') + .get(talk.comments_uri + '?resultsperpage=3&verbose=yes') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evTalkComments) { + if(typeof evTalkComments.comments == 'object') { + for(var i in evTalkComments.comments) { + var talkComment = evTalkComments.comments[i]; + datatest.checkVerboseTalkCommentData(talkComment); + } + } + }).toss(); + } + } + }).toss(); } function testAttendeesForEvent(evt) { - frisby.create('Attendees to ' + evt.name) - .get(evt.attendees_uri + '?resultsperpage=3') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evUsers) { - if(typeof evUsers.users == 'object') { - for(var i in evUsers.users) { - var user = evUsers.users[i]; - datatest.checkUserData(user); - } - } - }).toss(); + frisby.create('Attendees to ' + evt.name) + .get(evt.attendees_uri + '?resultsperpage=3') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evUsers) { + if(typeof evUsers.users == 'object') { + for(var i in evUsers.users) { + var user = evUsers.users[i]; + datatest.checkUserData(user); + } + } + }).toss(); } function testAttendeesForEventVerbose(evt) { - frisby.create('Attendees to ' + evt.name + ' (verbose format)') - .get(evt.attendees_uri + '?resultsperpage=3&verbose=yes') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evUsers) { - if(typeof evUsers.users == 'object') { - for(var i in evUsers.users) { - var user = evUsers.users[i]; - datatest.checkVerboseUserData(user); - } - } - }).toss(); + frisby.create('Attendees to ' + evt.name + ' (verbose format)') + .get(evt.attendees_uri + '?resultsperpage=3&verbose=yes') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evUsers) { + if(typeof evUsers.users == 'object') { + for(var i in evUsers.users) { + var user = evUsers.users[i]; + datatest.checkVerboseUserData(user); + } + } + }).toss(); } function testHostsForEvent(evt) { @@ -201,184 +201,184 @@ function testHostsForEvent(evt) { } function testTracksForEvent(evt) { - frisby.create('Tracks at ' + evt.name) - .get(evt.tracks_uri + '?resultsperpage=3') - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(evTracks) { - if(typeof evTracks.tracks == 'object') { - for(var i in evTracks.tracks) { - var track = evTracks.tracks[i]; - datatest.checkTrackData(track); + frisby.create('Tracks at ' + evt.name) + .get(evt.tracks_uri + '?resultsperpage=3') + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(evTracks) { + if(typeof evTracks.tracks == 'object') { + for(var i in evTracks.tracks) { + var track = evTracks.tracks[i]; + datatest.checkTrackData(track); testTrack(track); - } - } + } + } - }).toss(); + }).toss(); } function testSearchEventsByTitle() { - frisby.create('Event search by title') - .get(baseURL + "/v2.1/events/?resultsperpage=3&title=php") - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(response) { - // Check meta-data - expect(response.meta).toContainJsonTypes({"count":Number}); - expect(response).toContainJsonTypes({"events":Array}); - - // expect at least some serch results - expect(response.events.length).toBeGreaterThan(1); - - for(var i in response.events) { - datatest.checkEventData(response.events[i]); - testEvent(response.events[i]); - } - }) - .toss(); + frisby.create('Event search by title') + .get(baseURL + "/v2.1/events/?resultsperpage=3&title=php") + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(response) { + // Check meta-data + expect(response.meta).toContainJsonTypes({"count":Number}); + expect(response).toContainJsonTypes({"events":Array}); + + // expect at least some serch results + expect(response.events.length).toBeGreaterThan(1); + + for(var i in response.events) { + datatest.checkEventData(response.events[i]); + testEvent(response.events[i]); + } + }) + .toss(); } function testSearchEventsByNonexistingTitle() { - frisby.create('Event search by nonexisting title') - .get(baseURL + "/v2.1/events/?title=some_nonexisting_title") - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(response) { - // Check meta-data - expect(response.meta).toContainJsonTypes({"count":Number}); - expect(response).toContainJsonTypes({"events":Array}); - - // expect no serch results - expect(response.events.length).toBe(0); - }) - .toss(); + frisby.create('Event search by nonexisting title') + .get(baseURL + "/v2.1/events/?title=some_nonexisting_title") + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(response) { + // Check meta-data + expect(response.meta).toContainJsonTypes({"count":Number}); + expect(response).toContainJsonTypes({"events":Array}); + + // expect no serch results + expect(response.events.length).toBe(0); + }) + .toss(); } function testSearchEventsByTag() { - frisby.create('Event search by tags') - .get(baseURL + "/v2.1/events/?resultsperpage=3&tags[]=php") - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(response) { - // Check meta-data - expect(response.meta).toContainJsonTypes({"count":Number}); - expect(response).toContainJsonTypes({"events":Array}); - - for(var i in response.events) { - datatest.checkEventData(response.events[i]); - testEvent(response.events[i]); - } - }) - .toss(); + frisby.create('Event search by tags') + .get(baseURL + "/v2.1/events/?resultsperpage=3&tags[]=php") + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(response) { + // Check meta-data + expect(response.meta).toContainJsonTypes({"count":Number}); + expect(response).toContainJsonTypes({"events":Array}); + + for(var i in response.events) { + datatest.checkEventData(response.events[i]); + testEvent(response.events[i]); + } + }) + .toss(); } function testNonexistentEvent() { - frisby.create('Non-existent event') - .get(baseURL + '/v2.1/events/100100') - .expectStatus(404) - .expectHeader("content-type", "application/json; charset=utf8") - .toss(); + frisby.create('Non-existent event') + .get(baseURL + '/v2.1/events/100100') + .expectStatus(404) + .expectHeader("content-type", "application/json; charset=utf8") + .toss(); } function testTalksIndex() { - frisby.create('Talks index') - .get(baseURL + '/v2.1/talks') - .expectStatus(405) - .expectHeader("content-type", "application/json; charset=utf8") - .toss(); + frisby.create('Talks index') + .get(baseURL + '/v2.1/talks') + .expectStatus(405) + .expectHeader("content-type", "application/json; charset=utf8") + .toss(); } function testSearchTalksByTitle() { - frisby.create('Talk search by title') - .get(baseURL + "/v2.1/talks/?resultsperpage=3&title=php") - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(response) { - // Check meta-data - expect(response.meta).toContainJsonTypes({"count":Number}); - expect(response).toContainJsonTypes({"talks":Array}); - - // expect at least some serch results - expect(response.talks.length).toBeGreaterThan(1); - - for(var i in response.talks) { - datatest.checkTalkData(response.talks[i]); - } - }) - .toss(); + frisby.create('Talk search by title') + .get(baseURL + "/v2.1/talks/?resultsperpage=3&title=php") + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(response) { + // Check meta-data + expect(response.meta).toContainJsonTypes({"count":Number}); + expect(response).toContainJsonTypes({"talks":Array}); + + // expect at least some serch results + expect(response.talks.length).toBeGreaterThan(1); + + for(var i in response.talks) { + datatest.checkTalkData(response.talks[i]); + } + }) + .toss(); } function testSearchTalksByNonexistingTitle() { - frisby.create('Talk search by nonexisting title') - .get(baseURL + "/v2.1/talks/?resultsperpage=3&title=some_nonexisting_title") - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(response) { - // Check meta-data - expect(response.meta).toContainJsonTypes({"count":Number}); - expect(response).toContainJsonTypes({"talks":Array}); - - // expect no serch results - expect(response.talks.length).toBe(0); - }) - .toss(); + frisby.create('Talk search by nonexisting title') + .get(baseURL + "/v2.1/talks/?resultsperpage=3&title=some_nonexisting_title") + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(response) { + // Check meta-data + expect(response.meta).toContainJsonTypes({"count":Number}); + expect(response).toContainJsonTypes({"talks":Array}); + + // expect no serch results + expect(response.talks.length).toBe(0); + }) + .toss(); } function testNonexistentTalk() { - frisby.create('Non-existent talk') - .get(baseURL + '/v2.1/talks/100100100') - .expectStatus(404) - .expectHeader("content-type", "application/json; charset=utf8") - .toss(); + frisby.create('Non-existent talk') + .get(baseURL + '/v2.1/talks/100100100') + .expectStatus(404) + .expectHeader("content-type", "application/json; charset=utf8") + .toss(); } function testNonexistentEventComment() { - frisby.create('Non-existent event comment') - .get(baseURL + '/v2.1/event_comments/100100') - .expectStatus(404) - .expectHeader("content-type", "application/json; charset=utf8") - .toss(); + frisby.create('Non-existent event comment') + .get(baseURL + '/v2.1/event_comments/100100') + .expectStatus(404) + .expectHeader("content-type", "application/json; charset=utf8") + .toss(); } function testNonexistentTalkComment() { - frisby.create('Non-existent talk comment') - .get(baseURL + "/v2.1/talk_comments/100100100") - .expectStatus(404) - .expectHeader("content-type", "application/json; charset=utf8") - .expectJSON(["Comment not found"]) - .toss(); + frisby.create('Non-existent talk comment') + .get(baseURL + "/v2.1/talk_comments/100100100") + .expectStatus(404) + .expectHeader("content-type", "application/json; charset=utf8") + .expectJSON(["Comment not found"]) + .toss(); } function testNonexistentUser() { - frisby.create('Non-existent user') - .get(baseURL + "/v2.1/users/100100100") - .expectStatus(404) - .expectHeader("content-type", "application/json; charset=utf8") - .expectJSON(["User not found"]) - .toss(); + frisby.create('Non-existent user') + .get(baseURL + "/v2.1/users/100100100") + .expectStatus(404) + .expectHeader("content-type", "application/json; charset=utf8") + .expectJSON(["User not found"]) + .toss(); } function testExistingUser() { - frisby.create('Existing user') - .get(baseURL + "/v2.1/users/1") - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") - .afterJSON(function(allUsers) { - if (typeof allUsers.users == "object") { - for (var u in allUsers.users) { - var user = allUsers.users[u]; - datatest.checkUserData(user); - } - } - }) - .toss(); + frisby.create('Existing user') + .get(baseURL + "/v2.1/users/1") + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") + .afterJSON(function(allUsers) { + if (typeof allUsers.users == "object") { + for (var u in allUsers.users) { + var user = allUsers.users[u]; + datatest.checkUserData(user); + } + } + }) + .toss(); } function testTrack(track) { frisby.create('Single track') .get(track.uri) - .expectStatus(200) - .expectHeader("content-type", "application/json; charset=utf8") + .expectStatus(200) + .expectHeader("content-type", "application/json; charset=utf8") .toss(); } @@ -403,27 +403,27 @@ function testLanguages() { } module.exports = { - init : init, - testIndex : testIndex, - testEvent : testEvent, - testEventComments : testEventComments, - testEventCommentsVerbose : testEventCommentsVerbose, - testTalksForEvent : testTalksForEvent, - testAttendeesForEvent : testAttendeesForEvent, - testAttendeesForEventVerbose : testAttendeesForEventVerbose, + init : init, + testIndex : testIndex, + testEvent : testEvent, + testEventComments : testEventComments, + testEventCommentsVerbose : testEventCommentsVerbose, + testTalksForEvent : testTalksForEvent, + testAttendeesForEvent : testAttendeesForEvent, + testAttendeesForEventVerbose : testAttendeesForEventVerbose, testHostsForEvent : testHostsForEvent, - testTracksForEvent : testTracksForEvent, - testSearchEventsByTitle : testSearchEventsByTitle, - testSearchEventsByNonexistingTitle : testSearchEventsByNonexistingTitle, - testSearchEventsByTag : testSearchEventsByTag, - testNonexistentEvent : testNonexistentEvent, - testTalksIndex : testTalksIndex, - testSearchTalksByTitle : testSearchTalksByTitle, - testSearchTalksByNonexistingTitle : testSearchTalksByNonexistingTitle, - testNonexistentTalk : testNonexistentTalk, - testNonexistentEventComment : testNonexistentEventComment, - testNonexistentTalkComment : testNonexistentTalkComment, - testNonexistentUser : testNonexistentUser, - testExistingUser : testExistingUser, + testTracksForEvent : testTracksForEvent, + testSearchEventsByTitle : testSearchEventsByTitle, + testSearchEventsByNonexistingTitle : testSearchEventsByNonexistingTitle, + testSearchEventsByTag : testSearchEventsByTag, + testNonexistentEvent : testNonexistentEvent, + testTalksIndex : testTalksIndex, + testSearchTalksByTitle : testSearchTalksByTitle, + testSearchTalksByNonexistingTitle : testSearchTalksByNonexistingTitle, + testNonexistentTalk : testNonexistentTalk, + testNonexistentEventComment : testNonexistentEventComment, + testNonexistentTalkComment : testNonexistentTalkComment, + testNonexistentUser : testNonexistentUser, + testExistingUser : testExistingUser, testLanguages : testLanguages } diff --git a/tests/frisby/api_spec.js b/tests/frisby/api_spec.js index 28abcb244..bf89dfc63 100644 --- a/tests/frisby/api_spec.js +++ b/tests/frisby/api_spec.js @@ -6,9 +6,9 @@ var datatest = require('./data'); var baseURL; if (typeof process.env.JOINDIN_API_BASE_URL != 'undefined') { - baseURL = process.env.JOINDIN_API_BASE_URL; + baseURL = process.env.JOINDIN_API_BASE_URL; } else { - baseURL = "http://api.dev.joind.in"; + baseURL = "http://api.dev.joind.in"; } apitest.init(baseURL); diff --git a/tests/frisby/api_write.js b/tests/frisby/api_write.js index 255d01355..fcbcc6575 100644 --- a/tests/frisby/api_write.js +++ b/tests/frisby/api_write.js @@ -7,29 +7,29 @@ var util = require('util'); var baseURL = ''; function init(_baseURL) { - baseURL = _baseURL; - frisby.globalSetup({ // globalSetup is for ALL requests - request: { - headers: { 'Content-type': 'application/json' } - } - }); + baseURL = _baseURL; + frisby.globalSetup({ // globalSetup is for ALL requests + request: { + headers: { 'Content-type': 'application/json' } + } + }); } function testRegisterUser() { - var randomSuffix = parseInt(Math.random() * 1000000).toString(); + var randomSuffix = parseInt(Math.random() * 1000000).toString(); var username = "testUser" + randomSuffix; var password = "pwpwpwpwpwpw"; var email = "testuser"+randomSuffix+"@example.com"; - frisby.create('Register user') - .post(baseURL + "/v2.1/users", { - "username" : username, - "password" : password, - "full_name" : "A test user", - "email" : email - }, {json:true}) - .expectStatus(201) - .expectHeaderContains("Location", baseURL + "/v2.1/users") - .after(function(err, res, body) { + frisby.create('Register user') + .post(baseURL + "/v2.1/users", { + "username" : username, + "password" : password, + "full_name" : "A test user", + "email" : email + }, {json:true}) + .expectStatus(201) + .expectHeaderContains("Location", baseURL + "/v2.1/users") + .after(function(err, res, body) { if(res.statusCode == 201) { // Call the get user method on the place we're told to go testUserByUrl(res.headers.location); @@ -41,44 +41,44 @@ function testRegisterUser() { testForgotUsernameFails("doesntexist@lornajane.net"); testSendResetPasswordEmailFails("doesntexist"); } - }) - .toss(); + }) + .toss(); } function testRegisterVerifiedUser() { - var randomSuffix = parseInt(Math.random() * 1000000).toString(); + var randomSuffix = parseInt(Math.random() * 1000000).toString(); var username = "testUser" + randomSuffix; var password = "pwpwpwpwpwpw"; - frisby.create('Register user') - .post(baseURL + "/v2.1/users", { - "username" : username, - "password" : password, - "full_name" : "A test user", - "email" : "testuser"+randomSuffix+"@example.com", - "auto_verify_user" : "true" - }, {json:true}) - .expectStatus(201) - .expectHeaderContains("Location", baseURL + "/v2.1/users") - .after(function(err, res, body) { + frisby.create('Register user') + .post(baseURL + "/v2.1/users", { + "username" : username, + "password" : password, + "full_name" : "A test user", + "email" : "testuser"+randomSuffix+"@example.com", + "auto_verify_user" : "true" + }, {json:true}) + .expectStatus(201) + .expectHeaderContains("Location", baseURL + "/v2.1/users") + .after(function(err, res, body) { if(res.statusCode == 201) { // Call the get user method on the place we're told to go testUserByUrl(res.headers.location); testUserLogin(username, password); testEditUser(username, password); } - }) - .toss(); + }) + .toss(); } function testUserByUrl(url) { - frisby.create('Get user') - .get(url) - .expectStatus(200) - .expectJSONLength("users", 1) - .afterJSON(function (users) { - datatest.checkUserData(users.users[0]); - }) - .toss(); + frisby.create('Get user') + .get(url) + .expectStatus(200) + .expectJSONLength("users", 1) + .afterJSON(function (users) { + datatest.checkUserData(users.users[0]); + }) + .toss(); } function testUnverifiedUserFailsLogin(username, password) { @@ -212,7 +212,7 @@ function testEditUser(username, password) { } module.exports = { - init : init, - testRegisterUser : testRegisterUser, - testRegisterVerifiedUser : testRegisterVerifiedUser + init : init, + testRegisterUser : testRegisterUser, + testRegisterVerifiedUser : testRegisterVerifiedUser } diff --git a/tests/frisby/api_write_spec.js b/tests/frisby/api_write_spec.js index 7dc3e0826..f4b27e613 100644 --- a/tests/frisby/api_write_spec.js +++ b/tests/frisby/api_write_spec.js @@ -8,9 +8,9 @@ var datatest = require('./data'); var baseURL; if (typeof process.env.JOINDIN_API_BASE_URL != 'undefined') { - baseURL = process.env.JOINDIN_API_BASE_URL; + baseURL = process.env.JOINDIN_API_BASE_URL; } else { - baseURL = "http://api.dev.joind.in"; + baseURL = "http://api.dev.joind.in"; } apitest.init(baseURL); @@ -18,4 +18,4 @@ apitest.testRegisterUser(); apitest.testRegisterVerifiedUser(); eventstest.init(baseURL); -eventstest.setupAndRunEventTests(); \ No newline at end of file +eventstest.setupAndRunEventTests(); diff --git a/tests/frisby/data.js b/tests/frisby/data.js index 60fbc83a3..cd1393005 100644 --- a/tests/frisby/data.js +++ b/tests/frisby/data.js @@ -1,68 +1,68 @@ // Expose the methods outside of this module module.exports = { - checkEventData : checkEventData, - checkVerboseEventData : checkVerboseEventData, - checkEventCommentData : checkEventCommentData, - checkVerboseEventComment : checkVerboseEventComment, - checkTalkData : checkTalkData, - checkUserData : checkUserData, + checkEventData : checkEventData, + checkVerboseEventData : checkVerboseEventData, + checkEventCommentData : checkEventCommentData, + checkVerboseEventComment : checkVerboseEventComment, + checkTalkData : checkTalkData, + checkUserData : checkUserData, checkHostData : checkHostData, - checkVerboseUserData : checkVerboseUserData, - checkTrackData : checkTrackData, - checkTalkCommentData : checkTalkCommentData, - checkVerboseTalkCommentData : checkVerboseTalkCommentData, + checkVerboseUserData : checkVerboseUserData, + checkTrackData : checkTrackData, + checkTalkCommentData : checkTalkCommentData, + checkVerboseTalkCommentData : checkVerboseTalkCommentData, checkLanguageData : checkLanguageData } function checkEventData(ev) { - if (ev.href != null) { - expect(ev.href).toBeDefined(); - expect(typeof ev.href).toBe('string'); - if (ev.href != '') { - //expect(ev.href).toMatch(/^http/); - } - } - if (ev.icon != null) { - expect(ev.icon).toBeDefined(); - expect(typeof ev.icon).toBe('string'); - } + if (ev.href != null) { + expect(ev.href).toBeDefined(); + expect(typeof ev.href).toBe('string'); + if (ev.href != '') { + //expect(ev.href).toMatch(/^http/); + } + } + if (ev.icon != null) { + expect(ev.icon).toBeDefined(); + expect(typeof ev.icon).toBe('string'); + } - // Check required fields - expect(ev.name).toBeDefined(); - expect(ev.start_date).toBeDefined(); - expect(ev.end_date).toBeDefined(); - expect(ev.tz_continent).toBeDefined(); - expect(ev.tz_place).toBeDefined(); - expect(ev.description).toBeDefined(); - expect(ev.href).toBeDefined(); - expect(ev.icon).toBeDefined(); - expect(ev.attendee_count).toBeDefined(); - expect(ev.uri).toBeDefined(); - expect(ev.verbose_uri).toBeDefined(); + // Check required fields + expect(ev.name).toBeDefined(); + expect(ev.start_date).toBeDefined(); + expect(ev.end_date).toBeDefined(); + expect(ev.tz_continent).toBeDefined(); + expect(ev.tz_place).toBeDefined(); + expect(ev.description).toBeDefined(); + expect(ev.href).toBeDefined(); + expect(ev.icon).toBeDefined(); + expect(ev.attendee_count).toBeDefined(); + expect(ev.uri).toBeDefined(); + expect(ev.verbose_uri).toBeDefined(); if(typeof ev.average_rating != 'undefined') { expect(typeof ev.average_rating).toBe('number'); } - expect(ev.comments_uri).toBeDefined(); - expect(ev.talks_uri).toBeDefined(); - expect(ev.website_uri).toBeDefined(); - expect(ev.attending_uri).toBeDefined(); - expect(typeof ev.name).toBe('string'); - expect(ev.event_comments_count).toBeDefined(); - expect(ev.talks_count).toBeDefined(); - expect(ev.tracks_count).toBeDefined(); - checkDate(ev.start_date); - checkDate(ev.end_date); - expect(typeof ev.tz_continent).toBe('string'); - expect(typeof ev.tz_place).toBe('string'); - expect(typeof ev.description).toBe('string'); - expect(typeof ev.attendee_count).toBe('number'); - expect(typeof ev.uri).toBe('string'); - expect(typeof ev.verbose_uri).toBe('string'); - expect(typeof ev.comments_uri).toBe('string'); - expect(typeof ev.talks_uri).toBe('string'); - expect(typeof ev.website_uri).toBe('string'); + expect(ev.comments_uri).toBeDefined(); + expect(ev.talks_uri).toBeDefined(); + expect(ev.website_uri).toBeDefined(); + expect(ev.attending_uri).toBeDefined(); + expect(typeof ev.name).toBe('string'); + expect(ev.event_comments_count).toBeDefined(); + expect(ev.talks_count).toBeDefined(); + expect(ev.tracks_count).toBeDefined(); + checkDate(ev.start_date); + checkDate(ev.end_date); + expect(typeof ev.tz_continent).toBe('string'); + expect(typeof ev.tz_place).toBe('string'); + expect(typeof ev.description).toBe('string'); + expect(typeof ev.attendee_count).toBe('number'); + expect(typeof ev.uri).toBe('string'); + expect(typeof ev.verbose_uri).toBe('string'); + expect(typeof ev.comments_uri).toBe('string'); + expect(typeof ev.talks_uri).toBe('string'); + expect(typeof ev.website_uri).toBe('string'); } function checkVerboseEventData(evt) { diff --git a/tests/routers/VersionedRouterTest.php b/tests/routers/VersionedRouterTest.php deleted file mode 100644 index 2d33376c2..000000000 --- a/tests/routers/VersionedRouterTest.php +++ /dev/null @@ -1,169 +0,0 @@ - '2.1', - 'rules' => array( - array( - 'path' => '/events', - 'controller' => 'EventController', - 'action' => 'getAction' - ) - ), - 'url' => '/v2.1/events', - 'method' => Request::HTTP_GET, - 'expectedController' => 'EventController', - 'expectedAction' => 'getAction' - ), - array( // #1 - 'version' => '2.1', - 'rules' => array( - array( - 'path' => '/aevents', - 'controller' => 'AEventController', - 'action' => 'getSAction' - ), - array( - 'path' => '/events', - 'controller' => 'EventController', - 'action' => 'getAction' - ) - ), - 'url' => '/v2.1/events', - 'method' => Request::HTTP_GET, - 'expectedController' => 'EventController', - 'expectedAction' => 'getAction' - ), - array( // #2 - 'version' => '2.1', - 'rules' => array( - array( - 'path' => '/events', - 'controller' => 'EventController', - 'action' => 'getAction', - 'verbs' => array(Request::HTTP_POST) - ), - array( - 'path' => '/events', - 'controller' => 'EventController2', - 'action' => 'getAction2', - 'verbs' => array(Request::HTTP_GET, Request::HTTP_PUT) - ) - ), - 'url' => '/v2.1/events', - 'method' => Request::HTTP_GET, - 'expectedController' => 'EventController2', - 'expectedAction' => 'getAction2' - ), - array( // #3 - 'version' => '2.1', - 'rules' => array( - array( - 'path' => '/events/(?P\d+)$', - 'controller' => 'EventController', - 'action' => 'getAction' - ), - ), - 'url' => '/v2.1/events/10', - 'method' => Request::HTTP_GET, - 'expectedController' => 'EventController', - 'expectedAction' => 'getAction', - 'routeParams' => array('event_id' => 10) - ), - array( // #4 - 'version' => '2.1', - 'rules' => array( - array( - 'path' => '/aevents', - 'controller' => 'AEventController', - 'action' => 'getSAction' - ), - array( - 'path' => '/events', - 'controller' => 'EventController', - 'action' => 'getAction', - 'verbs' => array(Request::HTTP_GET) - ) - ), - 'url' => '/v2.1/events', - 'method' => Request::HTTP_POST, - 'expectedController' => 'N/A', - 'expectedAction' => 'N/A', - 'routeParams' => array(), - 'expectedExceptionCode' => 415 - ), - array( // #5 - 'version' => '2.1', - 'rules' => array( - array( - 'path' => '/aevents', - 'controller' => 'AEventController', - 'action' => 'getSAction' - ), - array( - 'path' => '/events', - 'controller' => 'EventController', - 'action' => 'getAction', - 'verbs' => array(Request::HTTP_GET) - ) - ), - 'url' => '/v2.2/events', - 'method' => Request::HTTP_GET, - 'expectedController' => 'N/A', - 'expectedAction' => 'N/A', - 'routeParams' => array(), - 'expectedExceptionCode' => 404 - ) - ); - } - - /** - * @dataProvider getRouteProvider - * @covers VersionedRouter::getRoute - * - * @param float $version - * @param array $rules - * @param string $url - * @param string $method - * @param string $expectedController - * @param string $expectedAction - * @param array $routeParams - * @param integer|false $expectedExceptionCode - */ - public function testGetRoute($version, array $rules, $url, $method, $expectedController, $expectedAction, array $routeParams = array(), $expectedExceptionCode = false) - { - $request = new Request([], ['REQUEST_URI' => $url, 'REQUEST_METHOD' => $method]); - $router = new VersionedRouter($version, [], $rules); - try { - $route = $router->getRoute($request); - } catch (Exception $ex) { - if (!$expectedExceptionCode) { - throw $ex; - } - $this->assertEquals($expectedExceptionCode, $ex->getCode()); - return; - } - $this->assertEquals($expectedController, $route->getController()); - $this->assertEquals($expectedAction, $route->getAction()); - $this->assertEquals($routeParams, $route->getParams()); - } -} diff --git a/tools/codesniffer/JoindInPSR2/ruleset.xml b/tools/codesniffer/JoindInPSR2/ruleset.xml new file mode 100644 index 000000000..e69de29bb