diff --git a/.codecov.yml b/.codecov.yml index 2d4e363c..f98f123f 100644 --- a/.codecov.yml +++ b/.codecov.yml @@ -6,7 +6,7 @@ coverage: - "runtime" - "tests" - "vendor" - - "src/PHPCensor/Migrations" - - "src/PHPCensor/Languages" + - "src/Migrations" + - "src/Languages" comment: off diff --git a/bootstrap.php b/bootstrap.php index 628eb8de..4d83682a 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -5,7 +5,7 @@ if (!defined('ROOT_DIR')) { } if (!defined('SRC_DIR')) { - define('SRC_DIR', ROOT_DIR . 'src/PHPCensor/'); + define('SRC_DIR', ROOT_DIR . 'src/'); } if (!defined('PUBLIC_DIR')) { @@ -26,13 +26,10 @@ if (!defined('RUNTIME_DIR')) { require_once(ROOT_DIR . 'vendor/autoload.php'); -// Load configuration if present: -$conf = []; -$conf['b8']['app']['namespace'] = 'PHPCensor'; -$conf['b8']['app']['default_controller'] = 'Home'; -$conf['b8']['view']['path'] = SRC_DIR . 'View/'; +use PHPCensor\Config; +use PHPCensor\Helper\Lang; -$config = new b8\Config($conf); +$config = new Config(); $configFile = APP_DIR . 'config.yml'; if (file_exists($configFile)) { @@ -43,4 +40,4 @@ if (!defined('APP_URL') && !empty($config)) { define('APP_URL', $config->get('php-censor.url', '') . '/'); } -\PHPCensor\Helper\Lang::init($config); +Lang::init($config); diff --git a/composer.json b/composer.json index 75966be4..24016281 100644 --- a/composer.json +++ b/composer.json @@ -36,14 +36,12 @@ }, "autoload": { "psr-4": { - "PHPCensor\\": "src/PHPCensor/", - "b8\\": "src/B8Framework/" + "PHPCensor\\": "src/" } }, "autoload-dev": { "psr-4": { - "Tests\\PHPCensor\\": "tests/PHPCensor/", - "Tests\\b8\\": "tests/B8Framework/" + "Tests\\PHPCensor\\": "tests/src/" } }, "require": { @@ -63,7 +61,6 @@ "symfony/browser-kit": "~3.4.0", "symfony/process": "~3.4.0", "symfony/filesystem": "~3.4.0", - "symfony/debug": "~3.4.0", "symfony/dependency-injection": "~3.4.0", "symfony/event-dispatcher": "~3.4.0", "symfony/cache": "~3.4.0", @@ -84,7 +81,9 @@ "phploc/phploc": "~4.0.0", "jakub-onderka/php-parallel-lint": "~0.9.0", "sensiolabs/security-checker": "~4.0.0", + "paragonie/random_compat": "~2.0.0", + "symfony/debug": "~3.4.0", "doctrine/instantiator": "~1.0.0", "phpunit/php-token-stream": "~1.4.0", "phpdocumentor/reflection-docblock": "~2.0.0", @@ -99,7 +98,8 @@ "bower-asset/raphael": "~2.2.0" }, "require-dev": { - "phpunit/dbunit": "~2.0.0" + "phpunit/dbunit": "~2.0.0", + "symfony/var-dumper": "~3.4.0" }, "suggest": { "maknz/slack": "For SlackNotify plugin", diff --git a/composer.lock b/composer.lock index 6999424c..11d3e97c 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "content-hash": "86960b0e8aee816f39921ca1c3e6bfc3", + "content-hash": "8c2289ac491f1f1019f88be4f375b8a9", "packages": [ { "name": "behat/gherkin", @@ -1025,16 +1025,16 @@ }, { "name": "nikic/php-parser", - "version": "v3.1.4", + "version": "v3.1.5", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "e57b3a09784f846411aa7ed664eedb73e3399078" + "reference": "bb87e28e7d7b8d9a7fda231d37457c9210faf6ce" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/e57b3a09784f846411aa7ed664eedb73e3399078", - "reference": "e57b3a09784f846411aa7ed664eedb73e3399078", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/bb87e28e7d7b8d9a7fda231d37457c9210faf6ce", + "reference": "bb87e28e7d7b8d9a7fda231d37457c9210faf6ce", "shasum": "" }, "require": { @@ -1072,7 +1072,7 @@ "parser", "php" ], - "time": "2018-01-25T21:31:33+00:00" + "time": "2018-02-28T20:30:58+00:00" }, { "name": "npm-asset/codemirror", @@ -1144,6 +1144,54 @@ "homepage": "http://www.oomphinc.com/", "time": "2017-03-31T16:57:39+00:00" }, + { + "name": "paragonie/random_compat", + "version": "v2.0.11", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "5da4d3c796c275c55f057af5a643ae297d96b4d8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/5da4d3c796c275c55f057af5a643ae297d96b4d8", + "reference": "5da4d3c796c275c55f057af5a643ae297d96b4d8", + "shasum": "" + }, + "require": { + "php": ">=5.2.0" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "type": "library", + "autoload": { + "files": [ + "lib/random.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "pseudorandom", + "random" + ], + "time": "2017-09-27T21:40:39+00:00" + }, { "name": "pda/pheanstalk", "version": "v3.1.0", @@ -2091,16 +2139,16 @@ }, { "name": "psr/simple-cache", - "version": "1.0.0", + "version": "1.0.1", "source": { "type": "git", "url": "https://github.com/php-fig/simple-cache.git", - "reference": "753fa598e8f3b9966c886fe13f370baa45ef0e24" + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/753fa598e8f3b9966c886fe13f370baa45ef0e24", - "reference": "753fa598e8f3b9966c886fe13f370baa45ef0e24", + "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", "shasum": "" }, "require": { @@ -2135,7 +2183,7 @@ "psr-16", "simple-cache" ], - "time": "2017-01-02T13:31:39+00:00" + "time": "2017-10-23T01:57:42+00:00" }, { "name": "robmorgan/phinx", @@ -3029,7 +3077,7 @@ }, { "name": "symfony/browser-kit", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/browser-kit.git", @@ -3086,16 +3134,16 @@ }, { "name": "symfony/cache", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/cache.git", - "reference": "8dee9ec2c9824c3f4039960d679a6689ee1cbdc1" + "reference": "cce49c7aa2fc82077355c8a6dfcd9e619abe6e98" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/cache/zipball/8dee9ec2c9824c3f4039960d679a6689ee1cbdc1", - "reference": "8dee9ec2c9824c3f4039960d679a6689ee1cbdc1", + "url": "https://api.github.com/repos/symfony/cache/zipball/cce49c7aa2fc82077355c8a6dfcd9e619abe6e98", + "reference": "cce49c7aa2fc82077355c8a6dfcd9e619abe6e98", "shasum": "" }, "require": { @@ -3152,20 +3200,20 @@ "caching", "psr6" ], - "time": "2018-01-18T22:16:57+00:00" + "time": "2018-02-11T14:42:07+00:00" }, { "name": "symfony/config", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "72689b934d6c6ecf73eca874e98933bf055313c9" + "reference": "05e10567b529476a006b00746c5f538f1636810e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/72689b934d6c6ecf73eca874e98933bf055313c9", - "reference": "72689b934d6c6ecf73eca874e98933bf055313c9", + "url": "https://api.github.com/repos/symfony/config/zipball/05e10567b529476a006b00746c5f538f1636810e", + "reference": "05e10567b529476a006b00746c5f538f1636810e", "shasum": "" }, "require": { @@ -3178,6 +3226,7 @@ }, "require-dev": { "symfony/dependency-injection": "~3.3|~4.0", + "symfony/event-dispatcher": "~3.3|~4.0", "symfony/finder": "~3.3|~4.0", "symfony/yaml": "~3.0|~4.0" }, @@ -3214,20 +3263,20 @@ ], "description": "Symfony Config Component", "homepage": "https://symfony.com", - "time": "2018-01-21T19:05:02+00:00" + "time": "2018-02-14T10:03:57+00:00" }, { "name": "symfony/console", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "26b6f419edda16c19775211987651cb27baea7f1" + "reference": "067339e9b8ec30d5f19f5950208893ff026b94f7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/26b6f419edda16c19775211987651cb27baea7f1", - "reference": "26b6f419edda16c19775211987651cb27baea7f1", + "url": "https://api.github.com/repos/symfony/console/zipball/067339e9b8ec30d5f19f5950208893ff026b94f7", + "reference": "067339e9b8ec30d5f19f5950208893ff026b94f7", "shasum": "" }, "require": { @@ -3283,20 +3332,20 @@ ], "description": "Symfony Console Component", "homepage": "https://symfony.com", - "time": "2018-01-29T09:03:43+00:00" + "time": "2018-02-26T15:46:28+00:00" }, { "name": "symfony/css-selector", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", - "reference": "e66394bc7610e69279bfdb3ab11b4fe65403f556" + "reference": "544655f1fc078a9cd839fdda2b7b1e64627c826a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/css-selector/zipball/e66394bc7610e69279bfdb3ab11b4fe65403f556", - "reference": "e66394bc7610e69279bfdb3ab11b4fe65403f556", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/544655f1fc078a9cd839fdda2b7b1e64627c826a", + "reference": "544655f1fc078a9cd839fdda2b7b1e64627c826a", "shasum": "" }, "require": { @@ -3336,20 +3385,20 @@ ], "description": "Symfony CssSelector Component", "homepage": "https://symfony.com", - "time": "2018-01-03T07:37:34+00:00" + "time": "2018-02-03T14:55:07+00:00" }, { "name": "symfony/debug", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/debug.git", - "reference": "53f6af2805daf52a43b393b93d2f24925d35c937" + "reference": "9b1071f86e79e1999b3d3675d2e0e7684268b9bc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/debug/zipball/53f6af2805daf52a43b393b93d2f24925d35c937", - "reference": "53f6af2805daf52a43b393b93d2f24925d35c937", + "url": "https://api.github.com/repos/symfony/debug/zipball/9b1071f86e79e1999b3d3675d2e0e7684268b9bc", + "reference": "9b1071f86e79e1999b3d3675d2e0e7684268b9bc", "shasum": "" }, "require": { @@ -3392,20 +3441,20 @@ ], "description": "Symfony Debug Component", "homepage": "https://symfony.com", - "time": "2018-01-18T22:16:57+00:00" + "time": "2018-02-28T21:49:22+00:00" }, { "name": "symfony/dependency-injection", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/dependency-injection.git", - "reference": "4b2717ee2499390e371e1fc7abaf886c1c83e83d" + "reference": "12e901abc1cb0d637a0e5abe9923471361d96b07" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/4b2717ee2499390e371e1fc7abaf886c1c83e83d", - "reference": "4b2717ee2499390e371e1fc7abaf886c1c83e83d", + "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/12e901abc1cb0d637a0e5abe9923471361d96b07", + "reference": "12e901abc1cb0d637a0e5abe9923471361d96b07", "shasum": "" }, "require": { @@ -3463,20 +3512,20 @@ ], "description": "Symfony DependencyInjection Component", "homepage": "https://symfony.com", - "time": "2018-01-29T09:16:57+00:00" + "time": "2018-03-04T03:54:53+00:00" }, { "name": "symfony/dom-crawler", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/dom-crawler.git", - "reference": "09bd97b844b3151fab82f2fdd62db9c464b3910a" + "reference": "2bb5d3101cc01f4fe580e536daf4f1959bc2d24d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/09bd97b844b3151fab82f2fdd62db9c464b3910a", - "reference": "09bd97b844b3151fab82f2fdd62db9c464b3910a", + "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/2bb5d3101cc01f4fe580e536daf4f1959bc2d24d", + "reference": "2bb5d3101cc01f4fe580e536daf4f1959bc2d24d", "shasum": "" }, "require": { @@ -3519,20 +3568,20 @@ ], "description": "Symfony DomCrawler Component", "homepage": "https://symfony.com", - "time": "2018-01-03T07:37:34+00:00" + "time": "2018-02-22T10:48:49+00:00" }, { "name": "symfony/event-dispatcher", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "26b87b6bca8f8f797331a30b76fdae5342dc26ca" + "reference": "58990682ac3fdc1f563b7e705452921372aad11d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/26b87b6bca8f8f797331a30b76fdae5342dc26ca", - "reference": "26b87b6bca8f8f797331a30b76fdae5342dc26ca", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/58990682ac3fdc1f563b7e705452921372aad11d", + "reference": "58990682ac3fdc1f563b7e705452921372aad11d", "shasum": "" }, "require": { @@ -3582,20 +3631,20 @@ ], "description": "Symfony EventDispatcher Component", "homepage": "https://symfony.com", - "time": "2018-01-03T07:37:34+00:00" + "time": "2018-02-14T10:03:57+00:00" }, { "name": "symfony/filesystem", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "e078773ad6354af38169faf31c21df0f18ace03d" + "reference": "253a4490b528597aa14d2bf5aeded6f5e5e4a541" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/e078773ad6354af38169faf31c21df0f18ace03d", - "reference": "e078773ad6354af38169faf31c21df0f18ace03d", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/253a4490b528597aa14d2bf5aeded6f5e5e4a541", + "reference": "253a4490b528597aa14d2bf5aeded6f5e5e4a541", "shasum": "" }, "require": { @@ -3631,20 +3680,20 @@ ], "description": "Symfony Filesystem Component", "homepage": "https://symfony.com", - "time": "2018-01-03T07:37:34+00:00" + "time": "2018-02-22T10:48:49+00:00" }, { "name": "symfony/finder", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "613e26310776f49a1773b6737c6bd554b8bc8c6f" + "reference": "a479817ce0a9e4adfd7d39c6407c95d97c254625" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/613e26310776f49a1773b6737c6bd554b8bc8c6f", - "reference": "613e26310776f49a1773b6737c6bd554b8bc8c6f", + "url": "https://api.github.com/repos/symfony/finder/zipball/a479817ce0a9e4adfd7d39c6407c95d97c254625", + "reference": "a479817ce0a9e4adfd7d39c6407c95d97c254625", "shasum": "" }, "require": { @@ -3680,7 +3729,7 @@ ], "description": "Symfony Finder Component", "homepage": "https://symfony.com", - "time": "2018-01-03T07:37:34+00:00" + "time": "2018-03-05T18:28:11+00:00" }, { "name": "symfony/polyfill-apcu", @@ -3799,16 +3848,16 @@ }, { "name": "symfony/process", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/process.git", - "reference": "09a5172057be8fc677840e591b17f385e58c7c0d" + "reference": "cc4aea21f619116aaf1c58016a944e4821c8e8af" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/process/zipball/09a5172057be8fc677840e591b17f385e58c7c0d", - "reference": "09a5172057be8fc677840e591b17f385e58c7c0d", + "url": "https://api.github.com/repos/symfony/process/zipball/cc4aea21f619116aaf1c58016a944e4821c8e8af", + "reference": "cc4aea21f619116aaf1c58016a944e4821c8e8af", "shasum": "" }, "require": { @@ -3844,20 +3893,20 @@ ], "description": "Symfony Process Component", "homepage": "https://symfony.com", - "time": "2018-01-29T09:03:43+00:00" + "time": "2018-02-12T17:55:00+00:00" }, { "name": "symfony/yaml", - "version": "v3.4.4", + "version": "v3.4.6", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "eab73b6c21d27ae4cd037c417618dfd4befb0bfe" + "reference": "6af42631dcf89e9c616242c900d6c52bd53bd1bb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/eab73b6c21d27ae4cd037c417618dfd4befb0bfe", - "reference": "eab73b6c21d27ae4cd037c417618dfd4befb0bfe", + "url": "https://api.github.com/repos/symfony/yaml/zipball/6af42631dcf89e9c616242c900d6c52bd53bd1bb", + "reference": "6af42631dcf89e9c616242c900d6c52bd53bd1bb", "shasum": "" }, "require": { @@ -3902,7 +3951,7 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2018-01-21T19:05:02+00:00" + "time": "2018-02-16T09:50:28+00:00" }, { "name": "theseer/fdomdocument", @@ -4000,6 +4049,75 @@ "xunit" ], "time": "2016-12-02T14:39:14+00:00" + }, + { + "name": "symfony/var-dumper", + "version": "v3.4.6", + "source": { + "type": "git", + "url": "https://github.com/symfony/var-dumper.git", + "reference": "80964679d81da3d5618519e0e4be488c3d7ecd7d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/80964679d81da3d5618519e0e4be488c3d7ecd7d", + "reference": "80964679d81da3d5618519e0e4be488c3d7ecd7d", + "shasum": "" + }, + "require": { + "php": "^5.5.9|>=7.0.8", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0" + }, + "require-dev": { + "ext-iconv": "*", + "twig/twig": "~1.34|~2.4" + }, + "suggest": { + "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", + "ext-intl": "To show region name in time zone dump", + "ext-symfony_debug": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.4-dev" + } + }, + "autoload": { + "files": [ + "Resources/functions/dump.php" + ], + "psr-4": { + "Symfony\\Component\\VarDumper\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony mechanism for exploring and dumping PHP variables", + "homepage": "https://symfony.com", + "keywords": [ + "debug", + "dump" + ], + "time": "2018-02-22T17:29:24+00:00" } ], "aliases": [], diff --git a/phpmd.xml b/phpmd.xml index e7d9aa7c..b4e6ef61 100644 --- a/phpmd.xml +++ b/phpmd.xml @@ -21,7 +21,7 @@ - + diff --git a/phpunit.xml b/phpunit.xml index bb92ca16..2974b6b8 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -20,44 +20,16 @@ - - ./tests/B8Framework - - - - ./tests/PHPCensor/Helper - - - ./tests/PHPCensor/Controller - - - ./tests/PHPCensor/Logging - - - ./tests/PHPCensor/Model - - - ./tests/PHPCensor/Plugin - - - ./tests/PHPCensor/Service - - - ./tests/PHPCensor/Command - - - ./tests/PHPCensor/ProcessControl - - - ./tests/PHPCensor/Security + + ./tests/src ./src - ./src/PHPCensor/Migrations - ./src/PHPCensor/Languages + ./src/Migrations + ./src/Languages diff --git a/public/index.php b/public/index.php index 38cf5393..753adf5e 100644 --- a/public/index.php +++ b/public/index.php @@ -4,5 +4,5 @@ session_start(); require_once(dirname(__DIR__) . '/bootstrap.php'); -$fc = new PHPCensor\Application($config, new b8\Http\Request()); +$fc = new PHPCensor\Application($config, new PHPCensor\Http\Request()); print $fc->handleRequest(); diff --git a/src/Application.php b/src/Application.php new file mode 100644 index 00000000..f726ec38 --- /dev/null +++ b/src/Application.php @@ -0,0 +1,279 @@ + + */ +class Application +{ + /** + * @var array + */ + protected $route; + + /** + * @var Controller|WebController + */ + protected $controller; + + /** + * @var Request + */ + protected $request; + + /** + * @var Config + */ + protected $config; + + /** + * @var Router + */ + protected $router; + + /** + * @param Config $config + * + * @param Request|null $request + */ + public function __construct(Config $config, Request $request = null) + { + $this->config = $config; + + if (!is_null($request)) { + $this->request = $request; + } else { + $this->request = new Request(); + } + + $this->router = new Router($this, $this->request, $this->config); + + if (method_exists($this, 'init')) { + $this->init(); + } + } + + /** + * Initialise Application - Handles session verification, routing, etc. + */ + public function init() + { + $request =& $this->request; + $route = '/:controller/:action'; + $opts = ['controller' => 'Home', 'action' => 'index']; + + // Inlined as a closure to fix "using $this when not in object context" on 5.3 + $validateSession = function () { + if (!empty($_SESSION['php-censor-user-id'])) { + $user = Factory::getStore('User')->getByPrimaryKey($_SESSION['php-censor-user-id']); + + if ($user) { + return true; + } + } + + return false; + }; + + $skipAuth = [$this, 'shouldSkipAuth']; + + // Handler for the route we're about to register, checks for a valid session where necessary: + $routeHandler = function (&$route, Response &$response) use (&$request, $validateSession, $skipAuth) { + $skipValidation = in_array($route['controller'], ['session', 'webhook', 'build-status']); + + if (!$skipValidation && !$validateSession() && (!is_callable($skipAuth) || !$skipAuth())) { + if ($request->isAjax()) { + $response->setResponseCode(401); + $response->setContent(''); + } else { + $_SESSION['php-censor-login-redirect'] = substr($request->getPath(), 1); + $response = new RedirectResponse($response); + $response->setHeader('Location', APP_URL . 'session/login'); + } + + return false; + } + + return true; + }; + + $this->router->clearRoutes(); + $this->router->register($route, $opts, $routeHandler); + } + + /** + * @return Response + * + * @throws NotFoundException + */ + protected function handleRequestInner() + { + $this->route = $this->router->dispatch(); + + if (!empty($this->route['callback'])) { + $callback = $this->route['callback']; + + $response = new Response(); + if (!$callback($this->route, $response)) { + return $response; + } + } + + if (!$this->controllerExists($this->route)) { + throw new NotFoundException('Controller ' . $this->toPhpName($this->route['controller']) . ' does not exist!'); + } + + $action = lcfirst($this->toPhpName($this->route['action'])); + if (!$this->getController()->hasAction($action)) { + throw new NotFoundException('Controller ' . $this->toPhpName($this->route['controller']) . ' does not have action ' . $action . '!'); + } + + return $this->getController()->handleAction($action, $this->route['args']); + } + + /** + * Handle an incoming web request. + * + * @return Response + */ + public function handleRequest() + { + try { + $response = $this->handleRequestInner(); + } catch (HttpException $ex) { + $this->config->set('page_title', 'Error'); + + $view = new View('exception'); + $view->exception = $ex; + + $response = new Response(); + + $response->setResponseCode($ex->getErrorCode()); + $response->setContent($view->render()); + } catch (\Exception $ex) { + $this->config->set('page_title', 'Error'); + + $view = new View('exception'); + $view->exception = $ex; + + $response = new Response(); + + $response->setResponseCode(500); + $response->setContent($view->render()); + } + + return $response; + } + + /** + * Loads a particular controller, and injects our layout view into it. + * + * @param string $class + * + * @return Controller + */ + protected function loadController($class) + { + /** @var Controller $controller */ + $controller = new $class($this->config, $this->request); + + $controller->init(); + + return $controller; + } + + /** + * Check whether we should skip auth (because it is disabled) + * + * @return boolean + */ + protected function shouldSkipAuth() + { + $config = Config::getInstance(); + $disableAuth = (bool)$config->get('php-censor.security.disable_auth', false); + $defaultUserId = (integer)$config->get('php-censor.security.default_user_id', 1); + + if ($disableAuth && $defaultUserId) { + $user = Factory::getStore('User')->getByPrimaryKey($defaultUserId); + + if ($user) { + return true; + } + } + + return false; + } + + /** + * @return Controller + */ + public function getController() + { + if (empty($this->controller)) { + $controllerClass = $this->getControllerClass($this->route); + $this->controller = $this->loadController($controllerClass); + } + + return $this->controller; + } + + /** + * @param array $route + * + * @return bool + */ + protected function controllerExists($route) + { + return class_exists($this->getControllerClass($route)); + } + + /** + * @param array $route + * + * @return string + */ + protected function getControllerClass($route) + { + $namespace = $this->toPhpName($route['namespace']); + $controller = $this->toPhpName($route['controller']); + + return 'PHPCensor\\' . $namespace . '\\' . $controller . 'Controller'; + } + + /** + * @param array $route + * + * @return boolean + */ + public function isValidRoute(array $route) + { + if ($this->controllerExists($route)) { + return true; + } + + return false; + } + + /** + * @param string $string + * + * @return string + */ + protected function toPhpName($string) + { + $string = str_replace('-', ' ', $string); + $string = ucwords($string); + $string = str_replace(' ', '', $string); + + return $string; + } +} diff --git a/src/B8Framework/Application.php b/src/B8Framework/Application.php deleted file mode 100644 index d90e8def..00000000 --- a/src/B8Framework/Application.php +++ /dev/null @@ -1,171 +0,0 @@ -config = $config; - $this->response = new Response(); - - if (!is_null($request)) { - $this->request = $request; - } else { - $this->request = new Request(); - } - - $this->router = new Router($this, $this->request, $this->config); - - if (method_exists($this, 'init')) { - $this->init(); - } - } - - /** - * @return Response - * - * @throws NotFoundException - */ - public function handleRequest() - { - $this->route = $this->router->dispatch(); - - if (!empty($this->route['callback'])) { - $callback = $this->route['callback']; - - if (!$callback($this->route, $this->response)) { - return $this->response; - } - } - - if (!$this->controllerExists($this->route)) { - throw new NotFoundException('Controller ' . $this->toPhpName($this->route['controller']) . ' does not exist!'); - } - - $action = lcfirst($this->toPhpName($this->route['action'])); - if (!$this->getController()->hasAction($action)) { - throw new NotFoundException('Controller ' . $this->toPhpName($this->route['controller']) . ' does not have action ' . $action . '!'); - } - - return $this->getController()->handleAction($action, $this->route['args']); - } - - /** - * @return Controller - */ - public function getController() - { - if (empty($this->controller)) { - $controllerClass = $this->getControllerClass($this->route); - $this->controller = $this->loadController($controllerClass); - } - - return $this->controller; - } - - /** - * @param string $class - * - * @return Controller - */ - protected function loadController($class) - { - /** @var Controller $controller */ - $controller = new $class($this->config, $this->request, $this->response); - $controller->init(); - - return $controller; - } - - /** - * @param array $route - * - * @return bool - */ - protected function controllerExists($route) - { - return class_exists($this->getControllerClass($route)); - } - - /** - * @param array $route - * - * @return string - */ - protected function getControllerClass($route) - { - $namespace = $this->toPhpName($route['namespace']); - $controller = $this->toPhpName($route['controller']); - - return $this->config->get('b8.app.namespace') . '\\' . $namespace . '\\' . $controller . 'Controller'; - } - - /** - * @param array $route - * - * @return boolean - */ - public function isValidRoute(array $route) - { - if ($this->controllerExists($route)) { - return true; - } - - return false; - } - - /** - * @param string $string - * - * @return string - */ - protected function toPhpName($string) - { - $string = str_replace('-', ' ', $string); - $string = ucwords($string); - $string = str_replace(' ', '', $string); - - return $string; - } -} diff --git a/src/B8Framework/Exception/HttpException/ServerErrorException.php b/src/B8Framework/Exception/HttpException/ServerErrorException.php deleted file mode 100644 index 34ec1e84..00000000 --- a/src/B8Framework/Exception/HttpException/ServerErrorException.php +++ /dev/null @@ -1,9 +0,0 @@ -value != $_COOKIE[$this->getName()]) { - return false; - } - - return true; - } - - /** - * @param View $view - */ - protected function onPreRender(View &$view) - { - parent::onPreRender($view); - - $csrf = md5(microtime(true)); - $view->csrf = $csrf; - - setcookie($this->getName(), $csrf); - } -} diff --git a/src/B8Framework/Form/Element/Hidden.php b/src/B8Framework/Form/Element/Hidden.php deleted file mode 100644 index ebb427e7..00000000 --- a/src/B8Framework/Form/Element/Hidden.php +++ /dev/null @@ -1,9 +0,0 @@ -data = array_merge($this->data, $initialData); - } - - $this->cache = new ArrayCache(); - } - - /** - * @return string - */ - public function getTableName() - { - return $this->tableName; - } - - /** - * @return array - */ - public function getDataArray() - { - return $this->data; - } - - /** - * @return array - */ - public function getModified() - { - return $this->modified; - } - - /** - * @param array $values - */ - public function setValues(array $values) - { - foreach ($values as $key => $value) { - if (isset($this->setters[$key])) { - $func = $this->setters[$key]; - - if ($value === 'null') { - $value = null; - } elseif ($value === 'true') { - $value = true; - } elseif ($value === 'false') { - $value = false; - } - - $this->{$func}($value); - } - } - } - - /** - * @param string $column - */ - protected function setModified($column) - { - $this->modified[$column] = $column; - } - - /** - * @param string $name - * @param mixed $value - * - * @throws HttpException\ValidationException - */ - protected function validateString($name, $value) - { - if (!is_string($value) && !is_null($value)) { - throw new HttpException\ValidationException('Column "', $name . '" must be a string.'); - } - } - - /** - * @param string $name - * @param mixed $value - * - * @throws HttpException\ValidationException - */ - protected function validateInt($name, &$value) - { - if (is_bool($value)) { - $value = $value ? 1 : 0; - } - - if (!is_numeric($value) && !is_null($value)) { - throw new HttpException\ValidationException('Column "', $name . '" must be an integer.'); - } - - if (!is_int($value) && !is_null($value)) { - $value = (int)$value; - } - } - - /** - * @param string $name - * @param mixed $value - * - * @throws HttpException\ValidationException - */ - protected function validateFloat($name, &$value) - { - if (!is_numeric($value) && !is_null($value)) { - throw new HttpException\ValidationException('Column "', $name . '" must be a float.'); - } - - if (!is_float($value) && !is_null($value)) { - $value = (float)$value; - } - } - - /** - * @param string $name - * @param mixed $value - * - * @throws HttpException\ValidationException - */ - protected function validateDate($name, &$value) - { - if (is_string($value)) { - $value = empty($value) ? null : new \DateTime($value); - } - - if ((!is_object($value) || !($value instanceof \DateTime)) && !is_null($value)) { - throw new HttpException\ValidationException('Column "', $name . '" must be a date object.'); - } - - $value = empty($value) ? null : $value->format('Y-m-d H:i:s'); - } - - /** - * @param string $name - * @param mixed $value - * - * @throws HttpException\ValidationException - */ - protected function validateNotNull($name, $value) - { - if (is_null($value)) { - throw new HttpException\ValidationException('Column "', $name . '" must not be null.'); - } - } - - /** - * @param string $key - * - * @return mixed - */ - public function __get($key) - { - if (array_key_exists($key, $this->getters)) { - $getter = $this->getters[$key]; - return $this->{$getter}(); - } - - return null; - } - - /** - * @param string $key - * @param mixed $value - * - * @return mixed - */ - public function __set($key, $value) - { - if (array_key_exists($key, $this->setters)) { - $setter = $this->setters[$key]; - return $this->{$setter}($value); - } - } -} diff --git a/src/PHPCensor/BuildFactory.php b/src/BuildFactory.php similarity index 79% rename from src/PHPCensor/BuildFactory.php rename to src/BuildFactory.php index 7ed532d4..3d66aa9c 100644 --- a/src/PHPCensor/BuildFactory.php +++ b/src/BuildFactory.php @@ -2,7 +2,8 @@ namespace PHPCensor; -use b8\Store\Factory; +use PHPCensor\Model\Project; +use PHPCensor\Store\Factory; use PHPCensor\Model\Build; /** @@ -41,31 +42,31 @@ class BuildFactory if (!empty($project)) { switch ($project->getType()) { - case 'local': + case Project::TYPE_LOCAL: $type = 'LocalBuild'; break; - case 'git': + case Project::TYPE_GIT: $type = 'GitBuild'; break; - case 'github': + case Project::TYPE_GITHUB: $type = 'GithubBuild'; break; - case 'bitbucket': + case Project::TYPE_BITBUCKET: $type = 'BitbucketBuild'; break; - case 'gitlab': + case Project::TYPE_GITLAB: $type = 'GitlabBuild'; break; - case 'gogs': + case Project::TYPE_GOGS: $type = 'GogsBuild'; break; - case 'hg': + case Project::TYPE_HG: $type = 'HgBuild'; break; - case 'bitbucket-hg': + case Project::TYPE_BITBUCKET_HG: $type = 'BitbucketHgBuild'; break; - case 'svn': + case Project::TYPE_SVN: $type = 'SvnBuild'; break; default: diff --git a/src/PHPCensor/Builder.php b/src/Builder.php similarity index 95% rename from src/PHPCensor/Builder.php rename to src/Builder.php index 5cbe6778..20b33003 100644 --- a/src/PHPCensor/Builder.php +++ b/src/Builder.php @@ -6,8 +6,7 @@ use PHPCensor\Helper\BuildInterpolator; use PHPCensor\Helper\MailerFactory; use PHPCensor\Logging\BuildLogger; use PHPCensor\Model\Build; -use b8\Config; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use PHPCensor\Store\BuildErrorWriter; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerInterface; @@ -103,7 +102,7 @@ class Builder implements LoggerAwareInterface public function __construct(Build $build, LoggerInterface $logger = null) { $this->build = $build; - $this->store = Factory::getStore('Build', 'PHPCensor'); + $this->store = Factory::getStore('Build'); $this->buildLogger = new BuildLogger($logger, $build); $pluginFactory = $this->buildPluginFactory($build); @@ -196,12 +195,11 @@ class Builder implements LoggerAwareInterface $this->build->sendStatusPostback(); $success = true; - $previous_build = $this->build->getProject()->getPreviousBuild($this->build->getBranch()); + $previousBuild = $this->build->getProject()->getPreviousBuild($this->build->getBranch()); + $previousState = Build::STATUS_PENDING; - $previous_state = Build::STATUS_PENDING; - - if ($previous_build) { - $previous_state = $previous_build->getStatus(); + if ($previousBuild) { + $previousState = $previousBuild->getStatus(); } try { @@ -233,13 +231,13 @@ class Builder implements LoggerAwareInterface if ($success) { $this->pluginExecutor->executePlugins($this->config, Build::STAGE_SUCCESS); - if ($previous_state == Build::STATUS_FAILED) { + if ($previousState == Build::STATUS_FAILED) { $this->pluginExecutor->executePlugins($this->config, Build::STAGE_FIXED); } } else { $this->pluginExecutor->executePlugins($this->config, Build::STAGE_FAILURE); - if ($previous_state == Build::STATUS_SUCCESS || $previous_state == Build::STATUS_PENDING) { + if ($previousState == Build::STATUS_SUCCESS || $previousState == Build::STATUS_PENDING) { $this->pluginExecutor->executePlugins($this->config, Build::STAGE_BROKEN); } } @@ -278,11 +276,13 @@ class Builder implements LoggerAwareInterface /** * Used by this class, and plugins, to execute shell commands. * + * @param array ...$params + * * @return boolean */ - public function executeCommand() + public function executeCommand(...$params) { - return $this->commandExecutor->executeCommand(func_get_args()); + return $this->commandExecutor->executeCommand($params); } /** diff --git a/src/PHPCensor/BuilderException.php b/src/BuilderException.php similarity index 100% rename from src/PHPCensor/BuilderException.php rename to src/BuilderException.php diff --git a/src/PHPCensor/Command/CreateAdminCommand.php b/src/Command/CreateAdminCommand.php similarity index 97% rename from src/PHPCensor/Command/CreateAdminCommand.php rename to src/Command/CreateAdminCommand.php index 113974bf..34335573 100644 --- a/src/PHPCensor/Command/CreateAdminCommand.php +++ b/src/Command/CreateAdminCommand.php @@ -85,7 +85,7 @@ class CreateAdminCommand extends Command try { $userService = new UserService($this->userStore); - $userService->createUser($adminName, $adminEmail, 'internal', json_encode(['type' => 'internal']), $adminPassword, true); + $userService->createUser($adminName, $adminEmail, 'internal', ['type' => 'internal'], $adminPassword, true); $output->writeln('User account created!'); } catch (\Exception $ex) { diff --git a/src/PHPCensor/Command/CreateBuildCommand.php b/src/Command/CreateBuildCommand.php similarity index 100% rename from src/PHPCensor/Command/CreateBuildCommand.php rename to src/Command/CreateBuildCommand.php diff --git a/src/PHPCensor/Command/InstallCommand.php b/src/Command/InstallCommand.php similarity index 99% rename from src/PHPCensor/Command/InstallCommand.php rename to src/Command/InstallCommand.php index 285749d3..dba9396b 100644 --- a/src/PHPCensor/Command/InstallCommand.php +++ b/src/Command/InstallCommand.php @@ -5,8 +5,8 @@ namespace PHPCensor\Command; use Exception; use PDO; -use b8\Config; -use b8\Store\Factory; +use PHPCensor\Config; +use PHPCensor\Store\Factory; use PHPCensor\Model\ProjectGroup; use PHPCensor\Store\UserStore; use PHPCensor\Store\ProjectGroupStore; @@ -520,7 +520,7 @@ class InstallCommand extends Command } $userService = new UserService($userStore); - $userService->createUser($admin['name'], $admin['email'], 'internal', json_encode(['type' => 'internal']), $admin['password'], true); + $userService->createUser($admin['name'], $admin['email'], 'internal', ['type' => 'internal'], $admin['password'], true); $output->writeln('User account created!'); } catch (\Exception $ex) { diff --git a/src/PHPCensor/Command/RebuildCommand.php b/src/Command/RebuildCommand.php similarity index 98% rename from src/PHPCensor/Command/RebuildCommand.php rename to src/Command/RebuildCommand.php index e62dcab0..f1e4da40 100644 --- a/src/PHPCensor/Command/RebuildCommand.php +++ b/src/Command/RebuildCommand.php @@ -2,7 +2,7 @@ namespace PHPCensor\Command; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use Monolog\Logger; use PHPCensor\Service\BuildService; use Symfony\Component\Console\Command\Command; @@ -12,7 +12,7 @@ use Symfony\Component\Console\Output\OutputInterface; /** * Re-runs the last run build. - * + * * @author Dan Cryer */ class RebuildCommand extends Command diff --git a/src/PHPCensor/Command/RebuildQueueCommand.php b/src/Command/RebuildQueueCommand.php similarity index 96% rename from src/PHPCensor/Command/RebuildQueueCommand.php rename to src/Command/RebuildQueueCommand.php index 47837021..e5e3cf44 100644 --- a/src/PHPCensor/Command/RebuildQueueCommand.php +++ b/src/Command/RebuildQueueCommand.php @@ -2,7 +2,7 @@ namespace PHPCensor\Command; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use Monolog\Logger; use PHPCensor\BuildFactory; use PHPCensor\Logging\OutputLogHandler; @@ -55,7 +55,7 @@ class RebuildQueueCommand extends Command ); } - $store = Factory::getStore('Build'); + $store = Factory::getStore('Build'); $result = $store->getByStatus(0); $this->logger->addInfo(sprintf('Found %d builds', count($result['items']))); diff --git a/src/PHPCensor/Command/RunCommand.php b/src/Command/RunCommand.php similarity index 99% rename from src/PHPCensor/Command/RunCommand.php rename to src/Command/RunCommand.php index 0f6c582a..bc613f29 100644 --- a/src/PHPCensor/Command/RunCommand.php +++ b/src/Command/RunCommand.php @@ -2,7 +2,7 @@ namespace PHPCensor\Command; -use b8\Config; +use PHPCensor\Config; use Monolog\Logger; use PHPCensor\Logging\BuildDBLogHandler; use PHPCensor\Logging\LoggedBuildContextTidier; @@ -11,7 +11,7 @@ use PHPCensor\Store\BuildStore; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use PHPCensor\Builder; use PHPCensor\BuildFactory; use PHPCensor\Model\Build; diff --git a/src/PHPCensor/Command/ScheduleBuildCommand.php b/src/Command/ScheduleBuildCommand.php similarity index 100% rename from src/PHPCensor/Command/ScheduleBuildCommand.php rename to src/Command/ScheduleBuildCommand.php diff --git a/src/PHPCensor/Command/WorkerCommand.php b/src/Command/WorkerCommand.php similarity index 99% rename from src/PHPCensor/Command/WorkerCommand.php rename to src/Command/WorkerCommand.php index 644e9394..81f25525 100644 --- a/src/PHPCensor/Command/WorkerCommand.php +++ b/src/Command/WorkerCommand.php @@ -2,7 +2,7 @@ namespace PHPCensor\Command; -use b8\Config; +use PHPCensor\Config; use Monolog\Logger; use PHPCensor\Logging\OutputLogHandler; use PHPCensor\Worker\BuildWorker; diff --git a/src/B8Framework/Config.php b/src/Config.php similarity index 81% rename from src/B8Framework/Config.php rename to src/Config.php index fa3d6c1b..b1a9482c 100644 --- a/src/B8Framework/Config.php +++ b/src/Config.php @@ -1,13 +1,9 @@ config; - $i = -1; - $last_part = count($keyParts) - 1; + $i = -1; + $lastPart = count($keyParts) - 1; while ($part = array_shift($keyParts)) { $i++; @@ -84,7 +80,7 @@ class Config return $default; } - if ($i === $last_part) { + if ($i === $lastPart) { return $selected[$part]; } else { $selected = $selected[$part]; @@ -181,25 +177,25 @@ class Config return; } - foreach ($target as $target_key => $target_value) { - if (isset($source[$target_key])) { - if (!is_array($source[$target_key]) && !is_array($target_value)) { + foreach ($target as $targetKey => $targetValue) { + if (isset($source[$targetKey])) { + if (!is_array($source[$targetKey]) && !is_array($targetValue)) { // Neither value is an array, overwrite - $source[$target_key] = $target_value; - } elseif (is_array($source[$target_key]) && is_array($target_value)) { + $source[$targetKey] = $targetValue; + } elseif (is_array($source[$targetKey]) && is_array($targetValue)) { // Both are arrays, deep merge them - self::deepMerge($source[$target_key], $target_value); - } elseif (is_array($source[$target_key])) { + self::deepMerge($source[$targetKey], $targetValue); + } elseif (is_array($source[$targetKey])) { // Source is the array, push target value - $source[$target_key][] = $target_value; + $source[$targetKey][] = $targetValue; } else { // Target is the array, push source value and copy back - $target_value[] = $source[$target_key]; - $source[$target_key] = $target_value; + $targetValue[] = $source[$targetKey]; + $source[$targetKey] = $targetValue; } } else { // No merge required, just set the value - $source[$target_key] = $target_value; + $source[$targetKey] = $targetValue; } } } diff --git a/src/PHPCensor/Console/Application.php b/src/Console/Application.php similarity index 97% rename from src/PHPCensor/Console/Application.php rename to src/Console/Application.php index f599913e..470603ac 100644 --- a/src/PHPCensor/Console/Application.php +++ b/src/Console/Application.php @@ -2,8 +2,8 @@ namespace PHPCensor\Console; -use b8\Config; -use b8\Store\Factory; +use PHPCensor\Config; +use PHPCensor\Store\Factory; use Monolog\Handler\RotatingFileHandler; use Monolog\Handler\StreamHandler; use Monolog\Logger; @@ -86,7 +86,7 @@ LOGO; if ($databaseSettings) { $phinxSettings = [ 'paths' => [ - 'migrations' => ROOT_DIR . 'src/PHPCensor/Migrations', + 'migrations' => ROOT_DIR . 'src/Migrations', ], 'environments' => [ 'default_migration_table' => 'migration', diff --git a/src/B8Framework/Controller.php b/src/Controller.php similarity index 83% rename from src/B8Framework/Controller.php rename to src/Controller.php index 325271b8..0ceb1f03 100644 --- a/src/B8Framework/Controller.php +++ b/src/Controller.php @@ -1,9 +1,9 @@ config = $config; $this->request = $request; - $this->response = $response; } + /** + * Initialise the controller. + */ + abstract public function init(); + /** * @param string $name * @@ -75,11 +63,6 @@ abstract class Controller return call_user_func_array([$this, $action], $actionParams); } - /** - * Initialise the controller. - */ - abstract public function init(); - /** * Get a hash of incoming request parameters ($_GET, $_POST) * diff --git a/src/PHPCensor/Controller/BuildController.php b/src/Controller/BuildController.php similarity index 91% rename from src/PHPCensor/Controller/BuildController.php rename to src/Controller/BuildController.php index 8de3cb43..3db8143b 100644 --- a/src/PHPCensor/Controller/BuildController.php +++ b/src/Controller/BuildController.php @@ -2,27 +2,32 @@ namespace PHPCensor\Controller; -use b8; -use b8\Exception\HttpException\NotFoundException; -use b8\Http\Response\JsonResponse; +use PHPCensor\Exception\HttpException\NotFoundException; +use PHPCensor\Http\Response\JsonResponse; use JasonGrimes\Paginator; use PHPCensor\BuildFactory; use PHPCensor\Helper\AnsiConverter; use PHPCensor\Helper\Lang; +use PHPCensor\Http\Response\RedirectResponse; use PHPCensor\Model\Build; -use PHPCensor\Model\Project; use PHPCensor\Model\User; use PHPCensor\Service\BuildService; -use PHPCensor\Controller; +use PHPCensor\WebController; use PHPCensor\View; +use PHPCensor\Store\Factory; /** * Build Controller - Allows users to run and view builds. * * @author Dan Cryer */ -class BuildController extends Controller +class BuildController extends WebController { + /** + * @var string + */ + public $layoutName = 'layout'; + /** * @var \PHPCensor\Store\BuildStore */ @@ -33,12 +38,11 @@ class BuildController extends Controller */ protected $buildService; - /** - * Initialise the controller, set up stores and services. - */ public function init() { - $this->buildStore = b8\Store\Factory::getStore('Build'); + parent::init(); + + $this->buildStore = Factory::getStore('Build'); $this->buildService = new BuildService($this->buildStore); } @@ -81,7 +85,7 @@ class BuildController extends Controller } /** @var \PHPCensor\Store\BuildErrorStore $errorStore */ - $errorStore = b8\Store\Factory::getStore('BuildError'); + $errorStore = Factory::getStore('BuildError'); $this->view->uiPlugins = $this->getUiPlugins(); $this->view->build = $build; @@ -119,13 +123,13 @@ class BuildController extends Controller break; } - $rebuild = Lang::get('rebuild_now'); + $rebuild = Lang::get('rebuild_now'); $rebuildLink = APP_URL . 'build/rebuild/' . $build->getId(); - $delete = Lang::get('delete_build'); + $delete = Lang::get('delete_build'); $deleteLink = APP_URL . 'build/delete/' . $build->getId(); - $project = b8\Store\Factory::getStore('Project')->getByPrimaryKey($build->getProjectId()); + $project = Factory::getStore('Project')->getByPrimaryKey($build->getProjectId()); $actions = ''; if (!$project->getArchived()) { @@ -146,7 +150,7 @@ class BuildController extends Controller protected function getUiPlugins() { $rtn = []; - $path = PUBLIC_DIR . 'assets' . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'build-plugins' . DIRECTORY_SEPARATOR; + $path = PUBLIC_DIR . 'assets/js/build-plugins/'; $dir = opendir($path); while ($item = readdir($dir)) { @@ -183,7 +187,7 @@ class BuildController extends Controller $data['duration'] = $build->getDuration(); /** @var \PHPCensor\Store\BuildErrorStore $errorStore */ - $errorStore = b8\Store\Factory::getStore('BuildError'); + $errorStore = Factory::getStore('BuildError'); $errors = $errorStore->getByBuildId($build->getId(), $perPage, $start, $plugin, $severity, $isNew); $errorView = new View('Build/errors'); @@ -240,7 +244,7 @@ class BuildController extends Controller public function rebuild($buildId) { $copy = BuildFactory::getBuildById($buildId); - $project = b8\Store\Factory::getStore('Project')->getByPrimaryKey($copy->getProjectId()); + $project = Factory::getStore('Project')->getByPrimaryKey($copy->getProjectId()); if (!$copy || $project->getArchived()) { throw new NotFoundException(Lang::get('build_x_not_found', $buildId)); @@ -252,7 +256,7 @@ class BuildController extends Controller $_SESSION['global_error'] = Lang::get('add_to_queue_failed'); } - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL.'build/view/' . $build->getId()); return $response; @@ -273,7 +277,7 @@ class BuildController extends Controller $this->buildService->deleteBuild($build); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL.'project/view/' . $build->getProjectId()); return $response; diff --git a/src/PHPCensor/Controller/BuildStatusController.php b/src/Controller/BuildStatusController.php similarity index 82% rename from src/PHPCensor/Controller/BuildStatusController.php rename to src/Controller/BuildStatusController.php index 3124e83c..60598c54 100644 --- a/src/PHPCensor/Controller/BuildStatusController.php +++ b/src/Controller/BuildStatusController.php @@ -2,37 +2,44 @@ namespace PHPCensor\Controller; -use b8; -use b8\Exception\HttpException\NotFoundException; -use b8\Store; +use PHPCensor\Http\Response; +use PHPCensor\Http\Response\RedirectResponse; +use PHPCensor\Exception\HttpException\NotFoundException; +use PHPCensor\Store\Factory; use PHPCensor\BuildFactory; use PHPCensor\Model\Project; use PHPCensor\Model\Build; use PHPCensor\Service\BuildStatusService; -use PHPCensor\Controller; +use PHPCensor\WebController; /** * Build Status Controller - Allows external access to build status information / images. * * @author Dan Cryer */ -class BuildStatusController extends Controller +class BuildStatusController extends WebController { - /* @var \PHPCensor\Store\ProjectStore */ - protected $projectStore; - - /* @var \PHPCensor\Store\BuildStore */ - protected $buildStore; + /** + * @var string + */ + public $layoutName = 'layoutPublic'; /** - * Initialise the controller, set up stores and services. + * @var \PHPCensor\Store\ProjectStore */ + protected $projectStore; + + /** + * @var \PHPCensor\Store\BuildStore + */ + protected $buildStore; + public function init() { - $this->response->disableLayout(); + parent::init(); - $this->buildStore = Store\Factory::getStore('Build'); - $this->projectStore = Store\Factory::getStore('Project'); + $this->buildStore = Factory::getStore('Build'); + $this->projectStore = Factory::getStore('Project'); } /** @@ -73,16 +80,15 @@ class BuildStatusController extends Controller * * @param $projectId * - * @return bool + * @return Response * * @throws \Exception - * @throws b8\Exception\HttpException */ public function ccxml($projectId) { /* @var Project $project */ $project = $this->projectStore->getById($projectId); - $xml = new \SimpleXMLElement(''); + $xml = new \SimpleXMLElement(''); if (!$project instanceof Project || !$project->getAllowPublicStatus()) { return $this->renderXml($xml); @@ -114,16 +120,16 @@ class BuildStatusController extends Controller /** * @param \SimpleXMLElement $xml * - * @return boolean + * @return Response */ protected function renderXml(\SimpleXMLElement $xml = null) { - $this->response->setHeader('Content-Type', 'text/xml'); - $this->response->setContent($xml->asXML()); - $this->response->flush(); - echo $xml->asXML(); + $response = new Response(); - return true; + $response->setHeader('Content-Type', 'text/xml'); + $response->setContent($xml->asXML()); + + return $response; } /** @@ -131,7 +137,7 @@ class BuildStatusController extends Controller * * @param $projectId * - * @return b8\Http\Response|b8\Http\Response\RedirectResponse + * @return Response */ public function image($projectId) { @@ -149,7 +155,7 @@ class BuildStatusController extends Controller $status = $this->getStatus($projectId); if (is_null($status)) { - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', '/'); return $response; @@ -179,10 +185,12 @@ class BuildStatusController extends Controller $image = file_get_contents($cacheFile); - $this->response->disableLayout(); - $this->response->setHeader('Content-Type', 'image/svg+xml'); - $this->response->setContent($image); - return $this->response; + $response = new Response(); + + $response->setHeader('Content-Type', 'image/svg+xml'); + $response->setContent($image); + + return $response; } /** @@ -192,7 +200,7 @@ class BuildStatusController extends Controller * * @return string * - * @throws \b8\Exception\HttpException\NotFoundException + * @throws NotFoundException */ public function view($projectId) { diff --git a/src/PHPCensor/Controller/GroupController.php b/src/Controller/GroupController.php similarity index 76% rename from src/PHPCensor/Controller/GroupController.php rename to src/Controller/GroupController.php index 7be5830b..6fa13bfd 100644 --- a/src/PHPCensor/Controller/GroupController.php +++ b/src/Controller/GroupController.php @@ -2,31 +2,36 @@ namespace PHPCensor\Controller; -use b8; -use b8\Form; -use PHPCensor\Controller; +use PHPCensor\Form; +use PHPCensor\WebController; +use PHPCensor\Http\Response\RedirectResponse; use PHPCensor\Model\ProjectGroup; use PHPCensor\Helper\Lang; use PHPCensor\Model\User; +use PHPCensor\Store\Factory; /** * Project Controller - Allows users to create, edit and view projects. * * @author Dan Cryer */ -class GroupController extends Controller +class GroupController extends WebController { + /** + * @var string + */ + public $layoutName = 'layout'; + /** * @var \PHPCensor\Store\ProjectGroupStore */ protected $groupStore; - /** - * Set up this controller. - */ public function init() { - $this->groupStore = b8\Store\Factory::getStore('ProjectGroup'); + parent::init(); + + $this->groupStore = Factory::getStore('ProjectGroup'); } /** @@ -44,10 +49,10 @@ class GroupController extends Controller 'title' => $group->getTitle(), 'id' => $group->getId(), ]; - $projects_active = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId(), false); - $projects_archived = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId(), true); + $projectsActive = Factory::getStore('Project')->getByGroupId($group->getId(), false); + $projectsArchived = Factory::getStore('Project')->getByGroupId($group->getId(), true); - $thisGroup['projects'] = array_merge($projects_active['items'], $projects_archived['items']); + $thisGroup['projects'] = array_merge($projectsActive['items'], $projectsArchived['items']); $groups[] = $thisGroup; } @@ -57,8 +62,10 @@ class GroupController extends Controller /** * Add or edit a project group. + * * @param null $groupId - * @return void|b8\Http\Response\RedirectResponse + * + * @return RedirectResponse */ public function edit($groupId = null) { @@ -82,16 +89,19 @@ class GroupController extends Controller $this->groupStore->save($group); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL.'group'); return $response; } $form = new Form(); + $form->setMethod('POST'); $form->setAction(APP_URL . 'group/edit' . (!is_null($groupId) ? '/' . $groupId : '')); + $form->addField(new Form\Element\Csrf('group_form')); + $title = new Form\Element\Text('title'); $title->setContainerClass('form-group'); $title->setClass('form-control'); @@ -111,7 +121,7 @@ class GroupController extends Controller /** * Delete a project group. * @param $groupId - * @return b8\Http\Response\RedirectResponse + * @return RedirectResponse */ public function delete($groupId) { @@ -119,7 +129,7 @@ class GroupController extends Controller $group = $this->groupStore->getById($groupId); $this->groupStore->delete($group); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL.'group'); return $response; } diff --git a/src/PHPCensor/Controller/HomeController.php b/src/Controller/HomeController.php similarity index 57% rename from src/PHPCensor/Controller/HomeController.php rename to src/Controller/HomeController.php index 3cfbc2dc..f65c0d6a 100644 --- a/src/PHPCensor/Controller/HomeController.php +++ b/src/Controller/HomeController.php @@ -2,15 +2,20 @@ namespace PHPCensor\Controller; -use b8; +use PHPCensor\Config; use PHPCensor\Helper\Lang; -use PHPCensor\Controller; +use PHPCensor\WebController; /** * Home Controller - Displays the Dashboard. */ -class HomeController extends Controller +class HomeController extends WebController { + /** + * @var string + */ + public $layoutName = 'layout'; + /** * Display dashboard: */ @@ -19,10 +24,11 @@ class HomeController extends Controller $this->layout->title = Lang::get('dashboard'); $widgets = [ - 'left' => [], + 'left' => [], 'right' => [], ]; - $widgets_config = b8\Config::getInstance()->get('php-censor.dashboard_widgets', [ + + $widgetsConfig = Config::getInstance()->get('php-censor.dashboard_widgets', [ 'all_projects' => [ 'side' => 'left', ], @@ -30,8 +36,11 @@ class HomeController extends Controller 'side' => 'right', ], ]); - foreach($widgets_config as $name => $params) { - $side = (isset($params['side']) and ($params['side'] == 'right')) ? 'right' : 'left'; + + foreach($widgetsConfig as $name => $params) { + $side = (isset($params['side']) && 'right' === $params['side']) + ? 'right' + : 'left'; $widgets[$side][$name] = $params; } diff --git a/src/PHPCensor/Controller/ProjectController.php b/src/Controller/ProjectController.php similarity index 88% rename from src/PHPCensor/Controller/ProjectController.php rename to src/Controller/ProjectController.php index a639311e..3d9a7d9b 100644 --- a/src/PHPCensor/Controller/ProjectController.php +++ b/src/Controller/ProjectController.php @@ -2,10 +2,8 @@ namespace PHPCensor\Controller; -use b8; -use b8\Exception\HttpException\NotFoundException; -use b8\Form; -use b8\Store; +use PHPCensor\Exception\HttpException\NotFoundException; +use PHPCensor\Form; use JasonGrimes\Paginator; use PHPCensor; use PHPCensor\BuildFactory; @@ -15,16 +13,24 @@ use PHPCensor\Helper\SshKey; use PHPCensor\Service\BuildService; use PHPCensor\Service\ProjectService; use PHPCensor\Model\Build; -use b8\Http\Response\RedirectResponse; +use PHPCensor\Http\Response\RedirectResponse; use PHPCensor\View; +use PHPCensor\Store\Factory; +use PHPCensor\Model\Project; +use PHPCensor\WebController; /** * Project Controller - Allows users to create, edit and view projects. * * @author Dan Cryer */ -class ProjectController extends PHPCensor\Controller +class ProjectController extends WebController { + /** + * @var string + */ + public $layoutName = 'layout'; + /** * @var \PHPCensor\Store\ProjectStore */ @@ -50,8 +56,10 @@ class ProjectController extends PHPCensor\Controller */ public function init() { - $this->buildStore = Store\Factory::getStore('Build'); - $this->projectStore = Store\Factory::getStore('Project'); + parent::init(); + + $this->buildStore = Factory::getStore('Build'); + $this->projectStore = Factory::getStore('Project'); $this->projectService = new ProjectService($this->projectStore); $this->buildService = new BuildService($this->buildStore); } @@ -59,7 +67,7 @@ class ProjectController extends PHPCensor\Controller /** * @param int $projectId * - * @return b8\Http\Response + * @return PHPCensor\Http\Response */ public function ajaxBuilds($projectId) { @@ -69,10 +77,10 @@ class ProjectController extends PHPCensor\Controller $perPage = (integer)$this->getParam('per_page', 10); $builds = $this->getLatestBuildsHtml($projectId, $branch, $environment, (($page - 1) * $perPage), $perPage); - $this->response->disableLayout(); - $this->response->setContent($builds[0]); + $response = new PHPCensor\Http\Response(); + $response->setContent($builds[0]); - return $this->response; + return $response; } /** @@ -327,10 +335,10 @@ class ProjectController extends PHPCensor\Controller 'ssh_private_key' => $this->getParam('key', null), 'ssh_public_key' => $this->getParam('pubkey', null), 'build_config' => $this->getParam('build_config', null), - 'allow_public_status' => $this->getParam('allow_public_status', 0), + 'allow_public_status' => (boolean)$this->getParam('allow_public_status', 0), 'branch' => $this->getParam('branch', null), - 'default_branch_only' => $this->getParam('default_branch_only', 0), - 'group' => $this->getParam('group_id', null), + 'default_branch_only' => (boolean)$this->getParam('default_branch_only', 0), + 'group' => (integer)$this->getParam('group_id', null), 'environments' => $this->getParam('environments', null), ]; @@ -380,11 +388,11 @@ class ProjectController extends PHPCensor\Controller $form = $this->projectForm($values, 'edit/' . $projectId); if ($method != 'POST' || ($method == 'POST' && !$form->validate())) { - $view = new View('Project/edit'); - $view->type = 'edit'; - $view->project = $project; - $view->form = $form; - $view->key = $values['pubkey']; + $view = new View('Project/edit'); + $view->type = 'edit'; + $view->project = $project; + $view->form = $form; + $view->key = $values['pubkey']; return $view->render(); } @@ -397,11 +405,11 @@ class ProjectController extends PHPCensor\Controller 'ssh_private_key' => $this->getParam('key', null), 'ssh_public_key' => $this->getParam('pubkey', null), 'build_config' => $this->getParam('build_config', null), - 'allow_public_status' => $this->getParam('allow_public_status', 0), - 'archived' => $this->getParam('archived', 0), + 'allow_public_status' => (boolean)$this->getParam('allow_public_status', false), + 'archived' => (boolean)$this->getParam('archived', false), 'branch' => $this->getParam('branch', null), - 'default_branch_only' => $this->getParam('default_branch_only', 0), - 'group' => $this->getParam('group_id', null), + 'default_branch_only' => (boolean)$this->getParam('default_branch_only', false), + 'group' => (integer)$this->getParam('group_id', null), 'environments' => $this->getParam('environments', null), ]; @@ -421,22 +429,22 @@ class ProjectController extends PHPCensor\Controller $form = new Form(); $form->setMethod('POST'); - $form->setAction(APP_URL.'project/' . $type); + $form->setAction(APP_URL . 'project/' . $type); - $form->addField(new Form\Element\Csrf('csrf')); + $form->addField(new Form\Element\Csrf('project_form')); $form->addField(new Form\Element\Hidden('pubkey')); $options = [ - 'choose' => Lang::get('select_repository_type'), - 'github' => 'GitHub', - 'bitbucket' => 'Bitbucket (Git)', - 'bitbucket-hg' => 'Bitbucket (Hg)', - 'gitlab' => 'GitLab', - 'gogs' => 'Gogs', - 'git' => 'Git', - 'local' => Lang::get('local'), - 'hg' => 'Hg (Mercurial)', - 'svn' => 'Svn (Subversion)', + 'choose' => Lang::get('select_repository_type'), + Project::TYPE_GITHUB => 'GitHub', + Project::TYPE_BITBUCKET => 'Bitbucket (Git)', + Project::TYPE_BITBUCKET_HG => 'Bitbucket (Hg)', + Project::TYPE_GITLAB => 'GitLab', + Project::TYPE_GOGS => 'Gogs', + Project::TYPE_GIT => 'Git', + Project::TYPE_LOCAL => Lang::get('local'), + Project::TYPE_HG => 'Hg (Mercurial)', + Project::TYPE_SVN => 'Svn (Subversion)', ]; $field = Form\Element\Select::create('type', Lang::get('where_hosted'), true); @@ -495,7 +503,7 @@ class ProjectController extends PHPCensor\Controller $field->setClass('form-control')->setContainerClass('form-group')->setValue(1); $groups = []; - $groupStore = b8\Store\Factory::getStore('ProjectGroup'); + $groupStore = Factory::getStore('ProjectGroup'); $groupList = $groupStore->getWhere([], 100, 0, ['title' => 'ASC']); foreach ($groupList['items'] as $group) { @@ -567,7 +575,7 @@ class ProjectController extends PHPCensor\Controller if (in_array($type, $validators) && !preg_match($validators[$type]['regex'], $val)) { throw new \Exception($validators[$type]['message']); - } elseif ($type == 'local' && !is_dir($val)) { + } elseif (Project::TYPE_LOCAL === $type && !is_dir($val)) { throw new \Exception(Lang::get('error_path')); } @@ -582,7 +590,7 @@ class ProjectController extends PHPCensor\Controller { $github = new Github(); - $response = new b8\Http\Response\JsonResponse(); + $response = new PHPCensor\Http\Response\JsonResponse(); $response->setContent($github->getRepositories()); return $response; diff --git a/src/PHPCensor/Controller/SessionController.php b/src/Controller/SessionController.php similarity index 78% rename from src/PHPCensor/Controller/SessionController.php rename to src/Controller/SessionController.php index 122ad509..fdc5c936 100644 --- a/src/PHPCensor/Controller/SessionController.php +++ b/src/Controller/SessionController.php @@ -2,20 +2,27 @@ namespace PHPCensor\Controller; -use b8; +use PHPCensor\Form\Element\Csrf; use PHPCensor\Helper\Email; use PHPCensor\Helper\Lang; -use PHPCensor\Controller; +use PHPCensor\WebController; +use PHPCensor\Http\Response\RedirectResponse; use PHPCensor\Security\Authentication\Service; use PHPCensor\Store\UserStore; +use PHPCensor\Store\Factory; /** * Session Controller - Handles user login / logout. * * @author Dan Cryer */ -class SessionController extends Controller +class SessionController extends WebController { + /** + * @var string + */ + public $layoutName = 'layoutSession'; + /** * @var UserStore */ @@ -31,12 +38,50 @@ class SessionController extends Controller */ public function init() { - $this->response->disableLayout(); + parent::init(); - $this->userStore = b8\Store\Factory::getStore('User'); + $this->userStore = Factory::getStore('User'); $this->authentication = Service::getInstance(); } + protected function loginForm($values) + { + $form = new \PHPCensor\Form(); + $form->setMethod('POST'); + $form->setAction(APP_URL . 'session/login'); + + $form->addField(new Csrf('login_form')); + + $email = new \PHPCensor\Form\Element\Text('email'); + $email->setLabel(Lang::get('login')); + $email->setRequired(true); + $email->setContainerClass('form-group'); + $email->setClass('form-control'); + $form->addField($email); + + $pwd = new \PHPCensor\Form\Element\Password('password'); + $pwd->setLabel(Lang::get('password')); + $pwd->setRequired(true); + $pwd->setContainerClass('form-group'); + $pwd->setClass('form-control'); + $form->addField($pwd); + + $remember = \PHPCensor\Form\Element\Checkbox::create('remember_me', Lang::get('remember_me'), false); + $remember->setContainerClass('form-group'); + $remember->setCheckedValue(1); + $remember->setValue(0); + $form->addField($remember); + + $pwd = new \PHPCensor\Form\Element\Submit(); + $pwd->setValue(Lang::get('log_in')); + $pwd->setClass('btn-success'); + $form->addField($pwd); + + $form->setValues($values); + + return $form; + } + /** * Handles user login (form and processing) */ @@ -47,22 +92,29 @@ class SessionController extends Controller if ($user) { $_SESSION['php-censor-user-id'] = $user->getId(); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', $this->getLoginRedirect()); return $response; } } + $method = $this->request->getMethod(); + + if ($method === 'POST') { + $values = $this->getParams(); + } else { + $values = []; + } + + $form = $this->loginForm($values); + $isLoginFailure = false; - if ($this->request->getMethod() == 'POST') { - $token = $this->getParam('token'); - if (!isset($token, $_SESSION['login_token']) || $token !== $_SESSION['login_token']) { + if ($this->request->getMethod() === 'POST') { + if (!$form->getChild('login_form')->validate()) { $isLoginFailure = true; } else { - unset($_SESSION['login_token']); - $email = $this->getParam('email'); $password = $this->getParam('password', ''); $rememberMe = (bool)$this->getParam('remember_me', 0); @@ -107,7 +159,7 @@ class SessionController extends Controller ); } - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', $this->getLoginRedirect()); return $response; @@ -115,42 +167,7 @@ class SessionController extends Controller } } - $form = new b8\Form(); - $form->setMethod('POST'); - $form->setAction(APP_URL . 'session/login'); - - $email = new b8\Form\Element\Text('email'); - $email->setLabel(Lang::get('login')); - $email->setRequired(true); - $email->setContainerClass('form-group'); - $email->setClass('form-control'); - $form->addField($email); - - $pwd = new b8\Form\Element\Password('password'); - $pwd->setLabel(Lang::get('password')); - $pwd->setRequired(true); - $pwd->setContainerClass('form-group'); - $pwd->setClass('form-control'); - $form->addField($pwd); - - $remember = b8\Form\Element\Checkbox::create('remember_me', Lang::get('remember_me'), false); - $remember->setContainerClass('form-group'); - $remember->setCheckedValue(1); - $remember->setValue(0); - $form->addField($remember); - - $pwd = new b8\Form\Element\Submit(); - $pwd->setValue(Lang::get('log_in')); - $pwd->setClass('btn-success'); - $form->addField($pwd); - - $tokenValue = $this->generateToken(); - $_SESSION['login_token'] = $tokenValue; - $token = new b8\Form\Element\Hidden('token'); - $token->setValue($tokenValue); - $form->addField($token); - - $this->view->form = $form->render(); + $this->view->form = $form->render(); $this->view->failed = $isLoginFailure; return $this->view->render(); @@ -175,7 +192,7 @@ class SessionController extends Controller true ); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL); return $response; } @@ -188,17 +205,15 @@ class SessionController extends Controller { if ($this->request->getMethod() == 'POST') { $email = $this->getParam('email', null); - $user = $this->userStore->getByEmail($email); + $user = $this->userStore->getByEmail($email); if (empty($user)) { $this->view->error = Lang::get('reset_no_user_exists'); return $this->view->render(); } - $key = md5(date('Y-m-d') . $user->getHash()); - $url = APP_URL; - - $message = Lang::get('reset_email_body', $user->getName(), $url, $user->getId(), $key); + $key = md5(date('Y-m-d') . $user->getHash()); + $message = Lang::get('reset_email_body', $user->getName(), APP_URL, $user->getId(), $key); $email = new Email(); $email->setEmailTo($user->getEmail(), $user->getName()); @@ -236,7 +251,7 @@ class SessionController extends Controller $_SESSION['php-censor-user-id'] = $user->getId(); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL); return $response; } @@ -262,20 +277,4 @@ class SessionController extends Controller return $rtn; } - - /** Generate a random token. - * - * @return string - */ - protected function generateToken() - { - if (function_exists('openssl_random_pseudo_bytes')) { - return bin2hex(openssl_random_pseudo_bytes(16)); - } - - return sprintf("%04x", mt_rand(0, 0xFFFF)) - . sprintf("%04x", mt_rand(0, 0xFFFF)) - . sprintf("%04x", mt_rand(0, 0xFFFF)) - . sprintf("%04x", mt_rand(0, 0xFFFF)); - } } diff --git a/src/PHPCensor/Controller/UserController.php b/src/Controller/UserController.php similarity index 85% rename from src/PHPCensor/Controller/UserController.php rename to src/Controller/UserController.php index 42e340b2..1fc0597e 100644 --- a/src/PHPCensor/Controller/UserController.php +++ b/src/Controller/UserController.php @@ -2,22 +2,29 @@ namespace PHPCensor\Controller; -use b8; -use b8\Exception\HttpException\NotFoundException; -use b8\Form; -use PHPCensor\Controller; +use PHPCensor\Config; +use PHPCensor\Exception\HttpException\NotFoundException; +use PHPCensor\Form; +use PHPCensor\WebController; use PHPCensor\Helper\Lang; +use PHPCensor\Http\Response\RedirectResponse; use PHPCensor\Model\User; use PHPCensor\Service\UserService; use PHPCensor\View; +use PHPCensor\Store\Factory; /** * User Controller - Allows an administrator to view, add, edit and delete users. * * @author Dan Cryer */ -class UserController extends Controller +class UserController extends WebController { + /** + * @var string + */ + public $layoutName = 'layout'; + /** * @var \PHPCensor\Store\UserStore */ @@ -33,7 +40,9 @@ class UserController extends Controller */ public function init() { - $this->userStore = b8\Store\Factory::getStore('User'); + parent::init(); + + $this->userStore = Factory::getStore('User'); $this->userService = new UserService($this->userStore); } @@ -68,7 +77,7 @@ class UserController extends Controller $language = null; } - $perPage = $this->getParam('per_page', null); + $perPage = (integer)$this->getParam('per_page', null); if (!$perPage) { $perPage = null; } @@ -82,9 +91,12 @@ class UserController extends Controller $this->layout->subtitle = Lang::get('edit_profile'); $form = new Form(); - $form->setAction(APP_URL.'user/profile'); + + $form->setAction(APP_URL . 'user/profile'); $form->setMethod('POST'); + $form->addField(new Form\Element\Csrf('profile_form')); + $name = new Form\Element\Text('name'); $name->setClass('form-control'); $name->setContainerClass('form-group'); @@ -115,7 +127,7 @@ class UserController extends Controller $language->setLabel(Lang::get('language')); $language->setRequired(true); $language->setOptions(array_merge( - [null => Lang::get('default') . ' (' . b8\Config::getInstance()->get('php-censor.language') . ')'], + [null => Lang::get('default') . ' (' . Config::getInstance()->get('php-censor.language') . ')'], Lang::getLanguageOptions()) ); $language->setValue($user->getLanguage()); @@ -127,7 +139,7 @@ class UserController extends Controller $perPage->setLabel(Lang::get('per_page')); $perPage->setRequired(true); $perPage->setOptions([ - null => Lang::get('default') . ' (' . b8\Config::getInstance()->get('php-censor.per_page') . ')', + null => Lang::get('default') . ' (' . Config::getInstance()->get('php-censor.per_page') . ')', 10 => 10, 25 => 25, 50 => 50, @@ -157,15 +169,15 @@ class UserController extends Controller $method = $this->request->getMethod(); - if ($method == 'POST') { + if ($method === 'POST') { $values = $this->getParams(); } else { $values = []; } - $form = $this->userForm($values); + $form = $this->userForm($values); - if ($method != 'POST' || ($method == 'POST' && !$form->validate())) { + if ($method !== 'POST' || ($method == 'POST' && !$form->validate())) { $view = new View('User/edit'); $view->type = 'add'; $view->user = null; @@ -178,11 +190,11 @@ class UserController extends Controller $name = $this->getParam('name', null); $email = $this->getParam('email', null); $password = $this->getParam('password', null); - $isAdmin = (int)$this->getParam('is_admin', 0); + $isAdmin = (boolean)$this->getParam('is_admin', 0); - $this->userService->createUser($name, $email, 'internal', json_encode(['type' => 'internal']), $password, $isAdmin); + $this->userService->createUser($name, $email, 'internal', ['type' => 'internal'], $password, $isAdmin); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL . 'user'); return $response; } @@ -195,7 +207,7 @@ class UserController extends Controller $this->requireAdmin(); $method = $this->request->getMethod(); - $user = $this->userStore->getById($userId); + $user = $this->userStore->getById($userId); if (empty($user)) { throw new NotFoundException(Lang::get('user_n_not_found', $userId)); @@ -219,11 +231,11 @@ class UserController extends Controller $name = $this->getParam('name', null); $email = $this->getParam('email', null); $password = $this->getParam('password', null); - $isAdmin = (int)$this->getParam('is_admin', 0); + $isAdmin = (boolean)$this->getParam('is_admin', 0); $this->userService->updateUser($user, $name, $email, $password, $isAdmin); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL . 'user'); return $response; } @@ -234,9 +246,11 @@ class UserController extends Controller protected function userForm($values, $type = 'add') { $form = new Form(); + $form->setMethod('POST'); - $form->setAction(APP_URL.'user/' . $type); - $form->addField(new Form\Element\Csrf('csrf')); + $form->setAction(APP_URL . 'user/' . $type); + + $form->addField(new Form\Element\Csrf('user_form')); $field = new Form\Element\Email('email'); $field->setRequired(true); @@ -279,6 +293,7 @@ class UserController extends Controller $form->addField($field); $form->setValues($values); + return $form; } @@ -289,7 +304,7 @@ class UserController extends Controller { $this->requireAdmin(); - $user = $this->userStore->getById($userId); + $user = $this->userStore->getById($userId); if (empty($user)) { throw new NotFoundException(Lang::get('user_n_not_found', $userId)); @@ -297,7 +312,7 @@ class UserController extends Controller $this->userService->deleteUser($user); - $response = new b8\Http\Response\RedirectResponse(); + $response = new RedirectResponse(); $response->setHeader('Location', APP_URL . 'user'); return $response; } diff --git a/src/PHPCensor/Controller/WebhookController.php b/src/Controller/WebhookController.php similarity index 86% rename from src/PHPCensor/Controller/WebhookController.php rename to src/Controller/WebhookController.php index 58bdd0c1..e810479c 100644 --- a/src/PHPCensor/Controller/WebhookController.php +++ b/src/Controller/WebhookController.php @@ -2,8 +2,6 @@ namespace PHPCensor\Controller; -use b8; -use b8\Store; use Exception; use GuzzleHttp\Client; use PHPCensor\Helper\Lang; @@ -12,10 +10,12 @@ use PHPCensor\Model\Project; use PHPCensor\Service\BuildService; use PHPCensor\Store\BuildStore; use PHPCensor\Store\ProjectStore; -use b8\Controller; -use b8\Config; -use b8\Exception\HttpException\NotFoundException; -use b8\Store\Factory; +use PHPCensor\Controller; +use PHPCensor\Config; +use PHPCensor\Exception\HttpException\NotFoundException; +use PHPCensor\Store\Factory; +use PHPCensor\Http\Request; +use PHPCensor\Http\Response; /** * Webhook Controller - Processes webhook pings from BitBucket, Github, Gitlab, Gogs, etc. @@ -48,21 +48,22 @@ class WebhookController extends Controller */ public function init() { - $this->buildStore = Store\Factory::getStore('Build'); - $this->projectStore = Store\Factory::getStore('Project'); + $this->buildStore = Factory::getStore('Build'); + $this->projectStore = Factory::getStore('Project'); $this->buildService = new BuildService($this->buildStore); } - /** Handle the action, Ensuring to return a JsonResponse. + /** + * Handle the action, Ensuring to return a JsonResponse. * * @param string $action - * @param mixed $actionParams + * @param array $actionParams * - * @return \b8\Http\Response + * @return Response */ public function handleAction($action, $actionParams) { - $response = new b8\Http\Response\JsonResponse(); + $response = new Response\JsonResponse(); try { $data = parent::handleAction($action, $actionParams); if (isset($data['responseCode'])) { @@ -79,10 +80,19 @@ class WebhookController extends Controller /** * Called by Bitbucket. + * + * @param integer $projectId + * + * @return array */ public function bitbucket($projectId) { - $project = $this->fetchProject($projectId, ['bitbucket', 'bitbucket-hg', 'hg', 'git']); + $project = $this->fetchProject($projectId, [ + Project::TYPE_BITBUCKET, + Project::TYPE_BITBUCKET_HG, + Project::TYPE_HG, + Project::TYPE_GIT, + ]); // Support both old services and new webhooks if ($payload = $this->getParam('payload')) { @@ -112,7 +122,7 @@ class WebhookController extends Controller * Handle the payload when Bitbucket sends a commit webhook. * * @param Project $project - * @param array $payload + * @param array $payload * * @return array */ @@ -164,7 +174,7 @@ class WebhookController extends Controller return ['status' => 'ok']; } - $username = Config::getInstance()->get('php-censor.bitbucket.username'); + $username = Config::getInstance()->get('php-censor.bitbucket.username'); $appPassword = Config::getInstance()->get('php-censor.bitbucket.app_password'); if (empty($username) || empty($appPassword)) { @@ -173,7 +183,7 @@ class WebhookController extends Controller $commitsUrl = $payload['pullrequest']['links']['commits']['href']; - $client = new Client(); + $client = new Client(); $commitsResponse = $client->get($commitsUrl, [ 'auth' => [$username, $appPassword], ]); @@ -232,11 +242,14 @@ class WebhookController extends Controller /** * Bitbucket POST service. + * + * @param array $payload + * @param Project $project + * + * @return array */ - protected function bitbucketService($payload, $project) + protected function bitbucketService(array $payload, Project $project) { - $payload = json_decode($this->getParam('payload'), true); - $results = []; $status = 'failed'; foreach ($payload['commits'] as $commit) { @@ -272,7 +285,10 @@ class WebhookController extends Controller */ public function git($projectId) { - $project = $this->fetchProject($projectId, ['local', 'git']); + $project = $this->fetchProject($projectId, [ + Project::TYPE_LOCAL, + Project::TYPE_GIT, + ]); $branch = $this->getParam('branch', $project->getBranch()); $commit = $this->getParam('commit'); $commitMessage = $this->getParam('message'); @@ -291,10 +307,17 @@ class WebhookController extends Controller /** * Called by Github Webhooks: + * + * @param integer $projectId + * + * @return array */ public function github($projectId) { - $project = $this->fetchProject($projectId, ['github', 'git']); + $project = $this->fetchProject($projectId, [ + Project::TYPE_GITHUB, + Project::TYPE_GIT, + ]); switch ($_SERVER['CONTENT_TYPE']) { case 'application/json': @@ -328,7 +351,7 @@ class WebhookController extends Controller * Handle the payload when Github sends a commit webhook. * * @param Project $project - * @param array $payload + * @param array $payload * * @return array */ @@ -411,10 +434,10 @@ class WebhookController extends Controller $url = $payload['pull_request']['commits_url']; //for large pull requests, allow grabbing more then the default number of commits - $custom_per_page = Config::getInstance()->get('php-censor.github.per_page'); - $params = []; - if ($custom_per_page) { - $params['per_page'] = $custom_per_page; + $customPerPage = Config::getInstance()->get('php-censor.github.per_page'); + $params = []; + if ($customPerPage) { + $params['per_page'] = $customPerPage; } $client = new Client(); @@ -472,18 +495,25 @@ class WebhookController extends Controller /** * Called by Gitlab Webhooks: + * + * @param integer $projectId + * + * @return array */ public function gitlab($projectId) { - $project = $this->fetchProject($projectId, ['gitlab', 'git']); + $project = $this->fetchProject($projectId, [ + Project::TYPE_GITLAB, + Project::TYPE_GIT, + ]); $payloadString = file_get_contents("php://input"); - $payload = json_decode($payloadString, true); + $payload = json_decode($payloadString, true); // build on merge request events if (isset($payload['object_kind']) && $payload['object_kind'] == 'merge_request') { $attributes = $payload['object_attributes']; - if ($attributes['state'] == 'opened' || $attributes['state'] == 'reopened') { + if ($attributes['state'] === 'opened' || $attributes['state'] === 'reopened') { $branch = $attributes['source_branch']; $commit = $attributes['last_commit']; $committer = $commit['author']['email']; @@ -508,8 +538,8 @@ class WebhookController extends Controller $status = 'failed'; foreach ($payload['commits'] as $commit) { try { - $branch = str_replace('refs/heads/', '', $payload['ref']); - $committer = $commit['author']['email']; + $branch = str_replace('refs/heads/', '', $payload['ref']); + $committer = $commit['author']['email']; $results[$commit['id']] = $this->createBuild( Build::SOURCE_WEBHOOK, $project, @@ -542,11 +572,13 @@ class WebhookController extends Controller */ public function svn($projectId) { - $project = $this->fetchProject($projectId, 'svn'); - $branch = $this->getParam('branch', $project->getBranch()); - $commit = $this->getParam('commit'); + $project = $this->fetchProject($projectId, [ + Project::TYPE_SVN + ]); + $branch = $this->getParam('branch', $project->getBranch()); + $commit = $this->getParam('commit'); $commitMessage = $this->getParam('message'); - $committer = $this->getParam('committer'); + $committer = $this->getParam('committer'); return $this->createBuild( Build::SOURCE_WEBHOOK, @@ -568,7 +600,11 @@ class WebhookController extends Controller */ public function gogs($projectId) { - $project = $this->fetchProject($projectId, ['gogs', 'git']); + $project = $this->fetchProject($projectId, [ + Project::TYPE_GOGS, + Project::TYPE_GIT, + ]); + switch ($_SERVER['CONTENT_TYPE']) { case 'application/json': $payload = json_decode(file_get_contents('php://input'), true); @@ -652,17 +688,17 @@ class WebhookController extends Controller $activeStates = ['open']; $inactiveStates = ['closed']; - if (!in_array($action, $activeActions) and !in_array($action, $inactiveActions)) { + if (!in_array($action, $activeActions) && !in_array($action, $inactiveActions)) { return ['status' => 'ignored', 'message' => 'Action ' . $action . ' ignored']; } - if (!in_array($state, $activeStates) and !in_array($state, $inactiveStates)) { + if (!in_array($state, $activeStates) && !in_array($state, $inactiveStates)) { return ['status' => 'ignored', 'message' => 'State ' . $state . ' ignored']; } $envs = []; // Get environment form labels - if (in_array($action, $activeActions) and in_array($state, $activeStates)) { + if (in_array($action, $activeActions) && in_array($state, $activeStates)) { if (isset($pullRequest['labels']) && is_array($pullRequest['labels'])) { foreach ($pullRequest['labels'] as $label) { if (strpos($label['name'], 'env:') === 0) { @@ -674,7 +710,7 @@ class WebhookController extends Controller $envsUpdated = []; $envObjects = $project->getEnvironmentsObjects(); - $store = Factory::getStore('Environment', 'PHPCensor'); + $store = Factory::getStore('Environment'); foreach ($envObjects['items'] as $environment) { $branches = $environment->getBranches(); if (in_array($environment->getName(), $envs)) { @@ -696,7 +732,7 @@ class WebhookController extends Controller } } - if (($state == 'closed') and $pullRequest['merged']) { + if ('closed' === $state && $pullRequest['merged']) { // update base branch environments $environmentNames = $project->getEnvironmentsNamesByBranch($pullRequest['base_branch']); $envsUpdated = array_merge($envsUpdated, $environmentNames); @@ -758,13 +794,13 @@ class WebhookController extends Controller // Check if a build already exists for this commit ID: $builds = $this->buildStore->getByProjectAndCommit($project->getId(), $commitId); - $ignore_environments = []; - $ignore_tags = []; + $ignoreEnvironments = []; + $ignoreTags = []; if ($builds['count']) { foreach($builds['items'] as $build) { /** @var Build $build */ - $ignore_environments[$build->getId()] = $build->getEnvironment(); - $ignore_tags[$build->getId()] = $build->getTag(); + $ignoreEnvironments[$build->getId()] = $build->getEnvironment(); + $ignoreTags[$build->getId()] = $build->getTag(); } } @@ -778,20 +814,20 @@ class WebhookController extends Controller $environments = $project->getEnvironmentsObjects(); if ($environments['count']) { - $created_builds = []; - $environment_names = $project->getEnvironmentsNamesByBranch($branch); + $createdBuilds = []; + $environmentNames = $project->getEnvironmentsNamesByBranch($branch); // use base branch from project - if (!empty($environment_names)) { + if (!empty($environmentNames)) { $duplicates = []; - foreach ($environment_names as $environment_name) { + foreach ($environmentNames as $environmentName) { if ( - !in_array($environment_name, $ignore_environments) || - ($tag && !in_array($tag, $ignore_tags, true)) + !in_array($environmentName, $ignoreEnvironments) || + ($tag && !in_array($tag, $ignoreTags, true)) ) { // If not, create a new build job for it: $build = $this->buildService->createBuild( $project, - $environment_name, + $environmentName, $commitId, $project->getBranch(), $tag, @@ -802,19 +838,19 @@ class WebhookController extends Controller $extra ); - $created_builds[] = [ + $createdBuilds[] = [ 'id' => $build->getID(), - 'environment' => $environment_name, + 'environment' => $environmentName, ]; } else { - $duplicates[] = array_search($environment_name, $ignore_environments); + $duplicates[] = array_search($environmentName, $ignoreEnvironments); } } - if (!empty($created_builds)) { + if (!empty($createdBuilds)) { if (empty($duplicates)) { - return ['status' => 'ok', 'builds' => $created_builds]; + return ['status' => 'ok', 'builds' => $createdBuilds]; } else { - return ['status' => 'ok', 'builds' => $created_builds, 'message' => sprintf('For this commit some builds already exists (%s)', implode(', ', $duplicates))]; + return ['status' => 'ok', 'builds' => $createdBuilds, 'message' => sprintf('For this commit some builds already exists (%s)', implode(', ', $duplicates))]; } } else { return ['status' => 'ignored', 'message' => sprintf('For this commit already created builds (%s)', implode(', ', $duplicates))]; @@ -823,10 +859,10 @@ class WebhookController extends Controller return ['status' => 'ignored', 'message' => 'Branch not assigned to any environment']; } } else { - $environment_name = null; + $environmentName = null; if ( - !in_array($environment_name, $ignore_environments, true) || - ($tag && !in_array($tag, $ignore_tags, true)) + !in_array($environmentName, $ignoreEnvironments, true) || + ($tag && !in_array($tag, $ignoreTags, true)) ) { $build = $this->buildService->createBuild( $project, @@ -845,7 +881,7 @@ class WebhookController extends Controller } else { return [ 'status' => 'ignored', - 'message' => sprintf('Duplicate of build #%d', array_search($environment_name, $ignore_environments)), + 'message' => sprintf('Duplicate of build #%d', array_search($environmentName, $ignoreEnvironments)), ]; } } @@ -854,14 +890,14 @@ class WebhookController extends Controller /** * Fetch a project and check its type. * - * @param int|string $projectId id or title of project - * @param array|string $expectedType + * @param integer $projectId id or title of project + * @param array $expectedType * * @return Project * * @throws Exception If the project does not exist or is not of the expected type. */ - protected function fetchProject($projectId, $expectedType) + protected function fetchProject($projectId, array $expectedType) { if (empty($projectId)) { throw new Exception('Project does not exist: ' . $projectId); @@ -880,10 +916,7 @@ class WebhookController extends Controller $project = reset($projects['items']); } - if (is_array($expectedType) - ? !in_array($project->getType(), $expectedType) - : $project->getType() !== $expectedType - ) { + if (!in_array($project->getType(), $expectedType, true)) { throw new Exception('Wrong project type: ' . $project->getType()); } diff --git a/src/PHPCensor/Controller/WidgetAllProjectsController.php b/src/Controller/WidgetAllProjectsController.php similarity index 90% rename from src/PHPCensor/Controller/WidgetAllProjectsController.php rename to src/Controller/WidgetAllProjectsController.php index b6bc5f53..48822749 100644 --- a/src/PHPCensor/Controller/WidgetAllProjectsController.php +++ b/src/Controller/WidgetAllProjectsController.php @@ -3,11 +3,11 @@ namespace PHPCensor\Controller; use PHPCensor\Model\Build; -use PHPCensor\Controller; -use b8\Store\Factory; +use PHPCensor\WebController; +use PHPCensor\Store\Factory; use PHPCensor\View; use PHPCensor\Model\Project; -use b8\Http\Response; +use PHPCensor\Http\Response; use PHPCensor\Store\BuildStore; use PHPCensor\Store\ProjectStore; use PHPCensor\Store\ProjectGroupStore; @@ -15,7 +15,7 @@ use PHPCensor\Store\ProjectGroupStore; /** * Widget All Projects Controller */ -class WidgetAllProjectsController extends Controller +class WidgetAllProjectsController extends WebController { /** * @var BuildStore @@ -37,6 +37,8 @@ class WidgetAllProjectsController extends Controller */ public function init() { + parent::init(); + $this->buildStore = Factory::getStore('Build'); $this->projectStore = Factory::getStore('Project'); $this->groupStore = Factory::getStore('ProjectGroup'); @@ -49,10 +51,10 @@ class WidgetAllProjectsController extends Controller { $this->view->groups = $this->getGroupInfo(); - $this->response->disableLayout(); - $this->response->setContent($this->view->render()); + $response = new Response(); + $response->setContent($this->view->render()); - return $this->response; + return $response; } /** @@ -142,9 +144,9 @@ class WidgetAllProjectsController extends Controller $this->view->failed = $this->buildStore->getLastBuildByStatus($projectId, Build::STATUS_FAILED); $this->view->counts = $counts; - $this->response->disableLayout(); - $this->response->setContent($this->view->render()); + $response = new Response(); + $response->setContent($this->view->render()); - return $this->response; + return $response; } } diff --git a/src/PHPCensor/Controller/WidgetBuildErrorsController.php b/src/Controller/WidgetBuildErrorsController.php similarity index 73% rename from src/PHPCensor/Controller/WidgetBuildErrorsController.php rename to src/Controller/WidgetBuildErrorsController.php index b0e1e73a..706bf601 100644 --- a/src/PHPCensor/Controller/WidgetBuildErrorsController.php +++ b/src/Controller/WidgetBuildErrorsController.php @@ -2,17 +2,17 @@ namespace PHPCensor\Controller; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use PHPCensor\View; -use b8\Http\Response; -use PHPCensor\Controller; +use PHPCensor\Http\Response; +use PHPCensor\WebController; use PHPCensor\Store\BuildStore; use PHPCensor\Store\ProjectStore; /** * Widget Build Errors Controller */ -class WidgetBuildErrorsController extends Controller +class WidgetBuildErrorsController extends WebController { /** * @var BuildStore @@ -29,6 +29,8 @@ class WidgetBuildErrorsController extends Controller */ public function init() { + parent::init(); + $this->buildStore = Factory::getStore('Build'); $this->projectStore = Factory::getStore('Project'); } @@ -42,10 +44,10 @@ class WidgetBuildErrorsController extends Controller $this->view->projects = $this->renderAllProjectsLatestBuilds($view); - $this->response->disableLayout(); - $this->response->setContent($this->view->render()); + $response = new Response(); + $response->setContent($this->view->render()); - return $this->response; + return $response; } /** @@ -53,10 +55,10 @@ class WidgetBuildErrorsController extends Controller */ public function update() { - $this->response->disableLayout(); - $this->response->setContent($this->renderAllProjectsLatestBuilds($this->view)); + $response = new Response(); + $response->setContent($this->renderAllProjectsLatestBuilds($this->view)); - return $this->response; + return $response; } /** @@ -72,15 +74,15 @@ class WidgetBuildErrorsController extends Controller $view->builds = $builds['projects']; $projects = $this->projectStore->getByIds(array_keys($builds['projects'])); - $view_projects = []; + $viewProjects = []; foreach($projects as $id => $project) { if (!$project->getArchived()) { - $view_projects[$id] = $project; + $viewProjects[$id] = $project; } else { unset($builds['projects'][$id]); } } - $view->projects = $view_projects; + $view->projects = $viewProjects; } else { $view = new View('WidgetBuildErrors/empty'); } diff --git a/src/PHPCensor/Controller/WidgetLastBuildsController.php b/src/Controller/WidgetLastBuildsController.php similarity index 73% rename from src/PHPCensor/Controller/WidgetLastBuildsController.php rename to src/Controller/WidgetLastBuildsController.php index a613a25f..a2d48e24 100644 --- a/src/PHPCensor/Controller/WidgetLastBuildsController.php +++ b/src/Controller/WidgetLastBuildsController.php @@ -2,17 +2,17 @@ namespace PHPCensor\Controller; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use PHPCensor\View; -use b8\Http\Response; +use PHPCensor\Http\Response; use PHPCensor\BuildFactory; -use PHPCensor\Controller; +use PHPCensor\WebController; use PHPCensor\Store\BuildStore; /** * Widget Last Builds Controller */ -class WidgetLastBuildsController extends Controller +class WidgetLastBuildsController extends WebController { /** * @var BuildStore @@ -24,6 +24,8 @@ class WidgetLastBuildsController extends Controller */ public function init() { + parent::init(); + $this->buildStore = Factory::getStore('Build'); } @@ -43,10 +45,10 @@ class WidgetLastBuildsController extends Controller $view->builds = $builds; $this->view->timeline = $view->render(); - $this->response->disableLayout(); - $this->response->setContent($this->view->render()); + $response = new Response(); + $response->setContent($this->view->render()); - return $this->response; + return $response; } /** @@ -62,9 +64,9 @@ class WidgetLastBuildsController extends Controller $this->view->builds = $builds; - $this->response->disableLayout(); - $this->response->setContent($this->view->render()); + $response = new Response(); + $response->setContent($this->view->render()); - return $this->response; + return $response; } } diff --git a/src/B8Framework/Database.php b/src/Database.php similarity index 96% rename from src/B8Framework/Database.php rename to src/Database.php index 996076ba..2be2993e 100644 --- a/src/B8Framework/Database.php +++ b/src/Database.php @@ -1,6 +1,6 @@ quoteNames($statement), $driver_options); + return parent::prepare($this->quoteNames($statement), $driverOptions); } } diff --git a/src/B8Framework/Exception/HttpException.php b/src/Exception/HttpException.php similarity index 95% rename from src/B8Framework/Exception/HttpException.php rename to src/Exception/HttpException.php index 4c266213..ba2637d7 100644 --- a/src/B8Framework/Exception/HttpException.php +++ b/src/Exception/HttpException.php @@ -1,6 +1,6 @@ get('b8.view.path'); - if (is_null($viewFile)) { $class = explode('\\', get_called_class()); $viewFile = end($class); } - if (file_exists($viewPath . 'Form/' . $viewFile . '.phtml')) { - $view = new View('Form/' . $viewFile); - } else { - $view = new View($viewFile, B8_PATH . 'Form/View/'); - } + $view = new View('Form/' . $viewFile); $view->name = $this->getName(); $view->id = $this->getId(); diff --git a/src/B8Framework/Form/Element/Button.php b/src/Form/Element/Button.php similarity index 84% rename from src/B8Framework/Form/Element/Button.php rename to src/Form/Element/Button.php index b3c7774b..80d9e3f5 100644 --- a/src/B8Framework/Form/Element/Button.php +++ b/src/Form/Element/Button.php @@ -1,8 +1,8 @@ getName()]) + ? $_SESSION['csrf_tokens'][$this->getName()] + : null; + + if ($this->value !== $sessionToken) { + return false; + } + + return true; + } + + /** + * @param View $view + */ + protected function onPreRender(View &$view) + { + parent::onPreRender($view); + + $this->setValue( + rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=') + ); + + $view->value = $this->getValue(); + + $_SESSION['csrf_tokens'][$this->getName()] = $this->getValue(); + } +} diff --git a/src/B8Framework/Form/Element/Email.php b/src/Form/Element/Email.php similarity index 92% rename from src/B8Framework/Form/Element/Email.php rename to src/Form/Element/Email.php index b0990eb8..f8c51fb8 100644 --- a/src/B8Framework/Form/Element/Email.php +++ b/src/Form/Element/Email.php @@ -1,6 +1,6 @@ get('php-censor.bitbucket.username'); + $username = Config::getInstance()->get('php-censor.bitbucket.username'); $appPassword = Config::getInstance()->get('php-censor.bitbucket.app_password'); if (empty($username) || empty($appPassword)) { diff --git a/src/PHPCensor/Helper/Build.php b/src/Helper/Build.php similarity index 100% rename from src/PHPCensor/Helper/Build.php rename to src/Helper/Build.php diff --git a/src/Helper/BuildInterpolator.php b/src/Helper/BuildInterpolator.php new file mode 100644 index 00000000..f113bad0 --- /dev/null +++ b/src/Helper/BuildInterpolator.php @@ -0,0 +1,85 @@ + value pairs that will be used for + * interpolation and environment variables + * @var mixed[] + * @see setupInterpolationVars() + */ + protected $interpolationVars = []; + + /** + * Sets the variables that will be used for interpolation. + * + * @param BaseBuild $build + * @param string $buildPath + * @param string $url + */ + public function setupInterpolationVars(BaseBuild $build, $buildPath, $url) + { + $this->interpolationVars = []; + $this->interpolationVars['%PHPCI%'] = 1; + $this->interpolationVars['%COMMIT%'] = $build->getCommitId(); + $this->interpolationVars['%SHORT_COMMIT%'] = substr($build->getCommitId(), 0, 7); + $this->interpolationVars['%COMMIT_EMAIL%'] = $build->getCommitterEmail(); + $this->interpolationVars['%COMMIT_MESSAGE%'] = $build->getCommitMessage(); + $this->interpolationVars['%COMMIT_URI%'] = $build->getCommitLink(); + $this->interpolationVars['%BRANCH%'] = $build->getBranch(); + $this->interpolationVars['%BRANCH_URI%'] = $build->getBranchLink(); + $this->interpolationVars['%ENVIRONMENT%'] = $build->getEnvironment(); + $this->interpolationVars['%PROJECT%'] = $build->getProjectId(); + $this->interpolationVars['%BUILD%'] = $build->getId(); + $this->interpolationVars['%PROJECT_TITLE%'] = $build->getProjectTitle(); + $this->interpolationVars['%PROJECT_URI%'] = $url . "project/view/" . $build->getProjectId(); + $this->interpolationVars['%BUILD_PATH%'] = $buildPath; + $this->interpolationVars['%BUILD_URI%'] = $url . "build/view/" . $build->getId(); + $this->interpolationVars['%PHPCI_COMMIT%'] = $this->interpolationVars['%COMMIT%']; + $this->interpolationVars['%PHPCI_SHORT_COMMIT%'] = $this->interpolationVars['%SHORT_COMMIT%']; + $this->interpolationVars['%PHPCI_COMMIT_MESSAGE%'] = $this->interpolationVars['%COMMIT_MESSAGE%']; + $this->interpolationVars['%PHPCI_COMMIT_EMAIL%'] = $this->interpolationVars['%COMMIT_EMAIL%']; + $this->interpolationVars['%PHPCI_COMMIT_URI%'] = $this->interpolationVars['%COMMIT_URI%']; + $this->interpolationVars['%PHPCI_PROJECT%'] = $this->interpolationVars['%PROJECT%']; + $this->interpolationVars['%PHPCI_BUILD%'] = $this->interpolationVars['%BUILD%']; + $this->interpolationVars['%PHPCI_PROJECT_TITLE%'] = $this->interpolationVars['%PROJECT_TITLE%']; + $this->interpolationVars['%PHPCI_PROJECT_URI%'] = $this->interpolationVars['%PROJECT_URI%']; + $this->interpolationVars['%PHPCI_BUILD_PATH%'] = $this->interpolationVars['%BUILD_PATH%']; + $this->interpolationVars['%PHPCI_BUILD_URI%'] = $this->interpolationVars['%BUILD_URI%']; + + putenv('PHPCI=1'); + putenv('PHPCI_COMMIT=' . $this->interpolationVars['%COMMIT%']); + putenv('PHPCI_SHORT_COMMIT=' . $this->interpolationVars['%SHORT_COMMIT%']); + putenv('PHPCI_COMMIT_MESSAGE=' . $this->interpolationVars['%COMMIT_MESSAGE%']); + putenv('PHPCI_COMMIT_EMAIL=' . $this->interpolationVars['%COMMIT_EMAIL%']); + putenv('PHPCI_COMMIT_URI=' . $this->interpolationVars['%COMMIT_URI%']); + putenv('PHPCI_PROJECT=' . $this->interpolationVars['%PROJECT%']); + putenv('PHPCI_BUILD=' . $this->interpolationVars['%BUILD%']); + putenv('PHPCI_PROJECT_TITLE=' . $this->interpolationVars['%PROJECT_TITLE%']); + putenv('PHPCI_BUILD_PATH=' . $this->interpolationVars['%BUILD_PATH%']); + putenv('PHPCI_BUILD_URI=' . $this->interpolationVars['%BUILD_URI%']); + putenv('PHPCI_ENVIRONMENT=' . $this->interpolationVars['%ENVIRONMENT%']); + } + + /** + * Replace every occurrence of the interpolation vars in the given string + * Example: "This is build %PHPCI_BUILD%" => "This is build 182" + * @param string $input + * @return string + */ + public function interpolate($input) + { + $keys = array_keys($this->interpolationVars); + $values = array_values($this->interpolationVars); + return str_replace($keys, $values, $input); + } +} diff --git a/src/PHPCensor/Helper/CommandExecutor.php b/src/Helper/CommandExecutor.php similarity index 95% rename from src/PHPCensor/Helper/CommandExecutor.php rename to src/Helper/CommandExecutor.php index 31ccb6b9..cbbd4243 100644 --- a/src/PHPCensor/Helper/CommandExecutor.php +++ b/src/Helper/CommandExecutor.php @@ -61,7 +61,7 @@ class CommandExecutor implements CommandExecutorInterface * @param bool $quiet * @param bool $verbose */ - public function __construct(BuildLogger $logger, $rootDir, &$quiet = false, &$verbose = false) + public function __construct(BuildLogger $logger, $rootDir, $quiet = false, $verbose = false) { $this->logger = $logger; $this->quiet = $quiet; @@ -335,14 +335,14 @@ class CommandExecutor implements CommandExecutorInterface public function getComposerBinDir($path) { if (is_dir($path)) { - $composer = $path . DIRECTORY_SEPARATOR . 'composer.json'; + $composer = $path . '/composer.json'; if (is_file($composer)) { $json = json_decode(file_get_contents($composer)); if (isset($json->config->{"bin-dir"})) { - return $path . DIRECTORY_SEPARATOR . $json->config->{"bin-dir"}; - } elseif (is_dir($path . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'bin')) { - return $path . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'bin'; + return $path . '/' . $json->config->{"bin-dir"}; + } elseif (is_dir($path . '/vendor/bin')) { + return $path . '/vendor/bin'; } } } diff --git a/src/PHPCensor/Helper/CommandExecutorInterface.php b/src/Helper/CommandExecutorInterface.php similarity index 100% rename from src/PHPCensor/Helper/CommandExecutorInterface.php rename to src/Helper/CommandExecutorInterface.php diff --git a/src/PHPCensor/Helper/Diff.php b/src/Helper/Diff.php similarity index 100% rename from src/PHPCensor/Helper/Diff.php rename to src/Helper/Diff.php diff --git a/src/PHPCensor/Helper/Email.php b/src/Helper/Email.php similarity index 98% rename from src/PHPCensor/Helper/Email.php rename to src/Helper/Email.php index dd5eb78a..b96d3265 100644 --- a/src/PHPCensor/Helper/Email.php +++ b/src/Helper/Email.php @@ -2,7 +2,7 @@ namespace PHPCensor\Helper; -use b8\Config; +use PHPCensor\Config; use PHPCensor\Builder; /** @@ -99,13 +99,13 @@ class Email 'php-censor.email_settings.from_address', self::DEFAULT_FROM ); - + if (strpos($from, '<') === false) { return (string)$from; } - + preg_match('#^(.*?)<(.*)>$#ui', $from, $fromParts); - + return [$fromParts[2] => $fromParts[1]]; } diff --git a/src/PHPCensor/Helper/Github.php b/src/Helper/Github.php similarity index 97% rename from src/PHPCensor/Helper/Github.php rename to src/Helper/Github.php index 0f8874a3..6c89ae9c 100644 --- a/src/PHPCensor/Helper/Github.php +++ b/src/Helper/Github.php @@ -2,7 +2,7 @@ namespace PHPCensor\Helper; -use b8\Config; +use PHPCensor\Config; use GuzzleHttp\Client; use Symfony\Component\Cache\Simple\FilesystemCache; @@ -34,9 +34,9 @@ class Github $results[] = $item; } - foreach ($headers as $header_name => $header) { + foreach ($headers as $headerName => $header) { if ( - 'Link' === $header_name && + 'Link' === $headerName && preg_match('/^<([^>]+)>; rel="next"/', implode(', ', $header), $r) ) { $host = parse_url($r[1]); diff --git a/src/PHPCensor/Helper/Lang.php b/src/Helper/Lang.php similarity index 76% rename from src/PHPCensor/Helper/Lang.php rename to src/Helper/Lang.php index 300ee1b4..57964d85 100644 --- a/src/PHPCensor/Helper/Lang.php +++ b/src/Helper/Lang.php @@ -2,9 +2,8 @@ namespace PHPCensor\Helper; -use b8\Config; -use b8\Store\Factory; -use PHPCensor\Model\User; +use PHPCensor\Config; +use PHPCensor\Store\Factory; use PHPCensor\Store\UserStore; /** @@ -32,24 +31,24 @@ class Lang /** * @var array */ - protected static $default_strings = []; + protected static $defaultStrings = []; /** * Get a specific string from the language file. * - * @param $string - * @return mixed|string + * @param array ...$params + * + * @return string */ - public static function get($string) + public static function get(...$params) { - $vars = func_get_args(); - + $string = $params[0]; if (array_key_exists($string, self::$strings)) { - $vars[0] = self::$strings[$string]; - return call_user_func_array('sprintf', $vars); - } elseif (self::DEFAULT_LANGUAGE !== self::$language && array_key_exists($string, self::$default_strings)) { - $vars[0] = self::$default_strings[$string]; - return call_user_func_array('sprintf', $vars); + $params[0] = self::$strings[$string]; + return call_user_func_array('sprintf', $params); + } elseif (self::DEFAULT_LANGUAGE !== self::$language && array_key_exists($string, self::$defaultStrings)) { + $params[0] = self::$defaultStrings[$string]; + return call_user_func_array('sprintf', $params); } return $string; @@ -57,10 +56,12 @@ class Lang /** * Output a specific string from the language file. + * + * @param array ...$params */ - public static function out() + public static function out(...$params) { - print call_user_func_array(['PHPCensor\Helper\Lang', 'get'], func_get_args()); + print call_user_func_array(['PHPCensor\Helper\Lang', 'get'], $params); } /** @@ -100,7 +101,7 @@ class Lang { $languages = []; foreach (self::$languages as $language) { - $strings = include(SRC_DIR . 'Languages' . DIRECTORY_SEPARATOR . 'lang.' . $language . '.php'); + $strings = include(SRC_DIR . 'Languages/lang.' . $language . '.php'); $languages[$language] = !empty($strings['language_name']) ? $strings['language_name'] . ' (' . $language . ')' : $language; @@ -123,14 +124,14 @@ class Lang * Initialise the Language helper, try load the language file for the user's browser or the configured default. * * @param Config $config - * @param string $language_force + * @param string $languageForce */ - public static function init(Config $config, $language_force = null) + public static function init(Config $config, $languageForce = null) { - self::$default_strings = self::loadLanguage(self::DEFAULT_LANGUAGE); + self::$defaultStrings = self::loadLanguage(self::DEFAULT_LANGUAGE); self::loadAvailableLanguages(); - if ($language_force && self::setLanguage($language_force)) { + if ($languageForce && self::setLanguage($languageForce)) { return; } @@ -164,8 +165,11 @@ class Lang */ protected static function loadLanguage($language = null) { - $language = $language ? $language : self::$language; - $langFile = SRC_DIR . 'Languages' . DIRECTORY_SEPARATOR . 'lang.' . $language . '.php'; + $language = $language + ? $language + : self::$language; + + $langFile = SRC_DIR . 'Languages/lang.' . $language . '.php'; if (!file_exists($langFile)) { return null; @@ -185,7 +189,7 @@ class Lang protected static function loadAvailableLanguages() { $matches = []; - foreach (glob(SRC_DIR . 'Languages' . DIRECTORY_SEPARATOR . 'lang.*.php') as $file) { + foreach (glob(SRC_DIR . 'Languages/lang.*.php') as $file) { if (preg_match('/lang\.([a-z]{2}\-?[a-z]*)\.php/', $file, $matches)) { self::$languages[] = $matches[1]; } diff --git a/src/PHPCensor/Helper/MailerFactory.php b/src/Helper/MailerFactory.php similarity index 100% rename from src/PHPCensor/Helper/MailerFactory.php rename to src/Helper/MailerFactory.php diff --git a/src/PHPCensor/Helper/SshKey.php b/src/Helper/SshKey.php similarity index 98% rename from src/PHPCensor/Helper/SshKey.php rename to src/Helper/SshKey.php index b532f181..efce7298 100644 --- a/src/PHPCensor/Helper/SshKey.php +++ b/src/Helper/SshKey.php @@ -2,7 +2,7 @@ namespace PHPCensor\Helper; -use b8\Config; +use PHPCensor\Config; /** * Helper class for dealing with SSH keys. diff --git a/src/B8Framework/Http/Request.php b/src/Http/Request.php similarity index 99% rename from src/B8Framework/Http/Request.php rename to src/Http/Request.php index c5b9782a..69a3c04a 100644 --- a/src/B8Framework/Http/Request.php +++ b/src/Http/Request.php @@ -1,6 +1,6 @@ data['layout']) ? true : $this->data['layout']; - } - - public function disableLayout() - { - $this->data['layout'] = false; - } - - public function enableLayout() - { - $this->data['layout'] = true; - } - public function getData() { return $this->data; diff --git a/src/B8Framework/Http/Response/JsonResponse.php b/src/Http/Response/JsonResponse.php similarity index 79% rename from src/B8Framework/Http/Response/JsonResponse.php rename to src/Http/Response/JsonResponse.php index ff065220..7310710a 100644 --- a/src/B8Framework/Http/Response/JsonResponse.php +++ b/src/Http/Response/JsonResponse.php @@ -1,8 +1,8 @@ setHeader('Content-Type', 'application/json'); } - public function hasLayout() - { - return false; - } - protected function flushBody() { if (isset($this->data['body'])) { diff --git a/src/B8Framework/Http/Response/RedirectResponse.php b/src/Http/Response/RedirectResponse.php similarity index 73% rename from src/B8Framework/Http/Response/RedirectResponse.php rename to src/Http/Response/RedirectResponse.php index a5c711fe..b4c8f3d5 100644 --- a/src/B8Framework/Http/Response/RedirectResponse.php +++ b/src/Http/Response/RedirectResponse.php @@ -1,8 +1,8 @@ setResponseCode(302); } - public function hasLayout() - { - return false; - } - public function flush() { parent::flush(); diff --git a/src/B8Framework/Http/Router.php b/src/Http/Router.php similarity index 95% rename from src/B8Framework/Http/Router.php rename to src/Http/Router.php index d0653241..471cac94 100644 --- a/src/B8Framework/Http/Router.php +++ b/src/Http/Router.php @@ -1,9 +1,9 @@ build->setLog($this->logValue); Factory::getStore('Build')->save($this->build); - $this->flush_timestamp = time(); + $this->flushTimestamp = time(); } /** @@ -74,7 +74,7 @@ class BuildDBLogHandler extends AbstractProcessingHandler $this->logValue .= $message . PHP_EOL; - if ($this->flush_timestamp < (time() - $this->flush_delay)) { + if ($this->flushTimestamp < (time() - $this->flushDelay)) { $this->flushData(); } } diff --git a/src/PHPCensor/Logging/BuildLogger.php b/src/Logging/BuildLogger.php similarity index 100% rename from src/PHPCensor/Logging/BuildLogger.php rename to src/Logging/BuildLogger.php diff --git a/src/PHPCensor/Logging/Handler.php b/src/Logging/Handler.php similarity index 78% rename from src/PHPCensor/Logging/Handler.php rename to src/Logging/Handler.php index e2ec1925..3c63f801 100644 --- a/src/PHPCensor/Logging/Handler.php +++ b/src/Logging/Handler.php @@ -62,10 +62,10 @@ class Handler public function handleError($level, $message, $file, $line) { if (error_reporting() & $level) { - $exception_level = isset($this->levels[$level]) ? $this->levels[$level] : $level; + $exceptionLevel = isset($this->levels[$level]) ? $this->levels[$level] : $level; throw new \ErrorException( - sprintf('%s: %s in %s line %d', $exception_level, $message, $file, $line), + sprintf('%s: %s in %s line %d', $exceptionLevel, $message, $file, $line), 0, $level, $file, @@ -79,22 +79,22 @@ class Handler */ public function handleFatalError() { - $fatal_error = error_get_last(); + $fatalError = error_get_last(); try { if (($error = error_get_last()) !== null) { $error = new \ErrorException( sprintf( '%s: %s in %s line %d', - $fatal_error['type'], - $fatal_error['message'], - $fatal_error['file'], - $fatal_error['line'] + $fatalError['type'], + $fatalError['message'], + $fatalError['file'], + $fatalError['line'] ), 0, - $fatal_error['type'], - $fatal_error['file'], - $fatal_error['line'] + $fatalError['type'], + $fatalError['file'], + $fatalError['line'] ); $this->log($error); } @@ -102,15 +102,15 @@ class Handler $error = new \ErrorException( sprintf( '%s: %s in %s line %d', - $fatal_error['type'], - $fatal_error['message'], - $fatal_error['file'], - $fatal_error['line'] + $fatalError['type'], + $fatalError['message'], + $fatalError['file'], + $fatalError['line'] ), 0, - $fatal_error['type'], - $fatal_error['file'], - $fatal_error['line'] + $fatalError['type'], + $fatalError['file'], + $fatalError['line'] ); $this->log($error); } diff --git a/src/PHPCensor/Logging/LoggedBuildContextTidier.php b/src/Logging/LoggedBuildContextTidier.php similarity index 100% rename from src/PHPCensor/Logging/LoggedBuildContextTidier.php rename to src/Logging/LoggedBuildContextTidier.php diff --git a/src/PHPCensor/Logging/OutputLogHandler.php b/src/Logging/OutputLogHandler.php similarity index 100% rename from src/PHPCensor/Logging/OutputLogHandler.php rename to src/Logging/OutputLogHandler.php diff --git a/src/PHPCensor/Migrations/20140513143726_initial_migration.php b/src/Migrations/20140513143726_initial_migration.php similarity index 100% rename from src/PHPCensor/Migrations/20140513143726_initial_migration.php rename to src/Migrations/20140513143726_initial_migration.php diff --git a/src/PHPCensor/Migrations/20140513153133_change_build_keys_migration.php b/src/Migrations/20140513153133_change_build_keys_migration.php similarity index 100% rename from src/PHPCensor/Migrations/20140513153133_change_build_keys_migration.php rename to src/Migrations/20140513153133_change_build_keys_migration.php diff --git a/src/PHPCensor/Migrations/20140611170618_choose_branch.php b/src/Migrations/20140611170618_choose_branch.php similarity index 100% rename from src/PHPCensor/Migrations/20140611170618_choose_branch.php rename to src/Migrations/20140611170618_choose_branch.php diff --git a/src/PHPCensor/Migrations/20140730143702_fix_database_columns.php b/src/Migrations/20140730143702_fix_database_columns.php similarity index 100% rename from src/PHPCensor/Migrations/20140730143702_fix_database_columns.php rename to src/Migrations/20140730143702_fix_database_columns.php diff --git a/src/PHPCensor/Migrations/20150131075425_archive_project.php b/src/Migrations/20150131075425_archive_project.php similarity index 100% rename from src/PHPCensor/Migrations/20150131075425_archive_project.php rename to src/Migrations/20150131075425_archive_project.php diff --git a/src/PHPCensor/Migrations/20150203105015_fix_column_types.php b/src/Migrations/20150203105015_fix_column_types.php similarity index 100% rename from src/PHPCensor/Migrations/20150203105015_fix_column_types.php rename to src/Migrations/20150203105015_fix_column_types.php diff --git a/src/PHPCensor/Migrations/20150308074509_add_user_providers.php b/src/Migrations/20150308074509_add_user_providers.php similarity index 100% rename from src/PHPCensor/Migrations/20150308074509_add_user_providers.php rename to src/Migrations/20150308074509_add_user_providers.php diff --git a/src/PHPCensor/Migrations/20150324174958_unique_email_and_name_user_fields.php b/src/Migrations/20150324174958_unique_email_and_name_user_fields.php similarity index 100% rename from src/PHPCensor/Migrations/20150324174958_unique_email_and_name_user_fields.php rename to src/Migrations/20150324174958_unique_email_and_name_user_fields.php diff --git a/src/PHPCensor/Migrations/20151008140800_add_project_groups.php b/src/Migrations/20151008140800_add_project_groups.php similarity index 100% rename from src/PHPCensor/Migrations/20151008140800_add_project_groups.php rename to src/Migrations/20151008140800_add_project_groups.php diff --git a/src/PHPCensor/Migrations/20151009100610_remove_unique_name_index.php b/src/Migrations/20151009100610_remove_unique_name_index.php similarity index 100% rename from src/PHPCensor/Migrations/20151009100610_remove_unique_name_index.php rename to src/Migrations/20151009100610_remove_unique_name_index.php diff --git a/src/PHPCensor/Migrations/20151014091859_errors_table.php b/src/Migrations/20151014091859_errors_table.php similarity index 100% rename from src/PHPCensor/Migrations/20151014091859_errors_table.php rename to src/Migrations/20151014091859_errors_table.php diff --git a/src/PHPCensor/Migrations/20151015124825_convert_errors.php b/src/Migrations/20151015124825_convert_errors.php similarity index 99% rename from src/PHPCensor/Migrations/20151015124825_convert_errors.php rename to src/Migrations/20151015124825_convert_errors.php index 40efd1a3..1c4d0d05 100644 --- a/src/PHPCensor/Migrations/20151015124825_convert_errors.php +++ b/src/Migrations/20151015124825_convert_errors.php @@ -3,7 +3,7 @@ use Phinx\Migration\AbstractMigration; use PHPCensor\Model\BuildMeta; use PHPCensor\Model\BuildError; -use b8\Store\Factory; +use PHPCensor\Store\Factory; class ConvertErrors extends AbstractMigration { diff --git a/src/PHPCensor/Migrations/20160425162114_branch_column_length.php b/src/Migrations/20160425162114_branch_column_length.php similarity index 100% rename from src/PHPCensor/Migrations/20160425162114_branch_column_length.php rename to src/Migrations/20160425162114_branch_column_length.php diff --git a/src/PHPCensor/Migrations/20160623100223_project_table_defaults.php b/src/Migrations/20160623100223_project_table_defaults.php similarity index 100% rename from src/PHPCensor/Migrations/20160623100223_project_table_defaults.php rename to src/Migrations/20160623100223_project_table_defaults.php diff --git a/src/PHPCensor/Migrations/20170103163312_added_language_and_per_page_for_user.php b/src/Migrations/20170103163312_added_language_and_per_page_for_user.php similarity index 100% rename from src/PHPCensor/Migrations/20170103163312_added_language_and_per_page_for_user.php rename to src/Migrations/20170103163312_added_language_and_per_page_for_user.php diff --git a/src/PHPCensor/Migrations/20170218175400_fixed_build_error_message_column.php b/src/Migrations/20170218175400_fixed_build_error_message_column.php similarity index 100% rename from src/PHPCensor/Migrations/20170218175400_fixed_build_error_message_column.php rename to src/Migrations/20170218175400_fixed_build_error_message_column.php diff --git a/src/PHPCensor/Migrations/20170223113127_fixed_build_log_column_for_mysql.php b/src/Migrations/20170223113127_fixed_build_log_column_for_mysql.php similarity index 100% rename from src/PHPCensor/Migrations/20170223113127_fixed_build_log_column_for_mysql.php rename to src/Migrations/20170223113127_fixed_build_log_column_for_mysql.php diff --git a/src/PHPCensor/Migrations/20170226132922_fixed_build_log_column_for_mysql2.php b/src/Migrations/20170226132922_fixed_build_log_column_for_mysql2.php similarity index 100% rename from src/PHPCensor/Migrations/20170226132922_fixed_build_log_column_for_mysql2.php rename to src/Migrations/20170226132922_fixed_build_log_column_for_mysql2.php diff --git a/src/PHPCensor/Migrations/20170321131931_add_environment.php b/src/Migrations/20170321131931_add_environment.php similarity index 100% rename from src/PHPCensor/Migrations/20170321131931_add_environment.php rename to src/Migrations/20170321131931_add_environment.php diff --git a/src/PHPCensor/Migrations/20170413131256_added_source_column_to_build_table.php b/src/Migrations/20170413131256_added_source_column_to_build_table.php similarity index 100% rename from src/PHPCensor/Migrations/20170413131256_added_source_column_to_build_table.php rename to src/Migrations/20170413131256_added_source_column_to_build_table.php diff --git a/src/PHPCensor/Migrations/20170416130610_fixed_environments.php b/src/Migrations/20170416130610_fixed_environments.php similarity index 100% rename from src/PHPCensor/Migrations/20170416130610_fixed_environments.php rename to src/Migrations/20170416130610_fixed_environments.php diff --git a/src/PHPCensor/Migrations/20170420142131_added_tag_column_to_build_table.php b/src/Migrations/20170420142131_added_tag_column_to_build_table.php similarity index 100% rename from src/PHPCensor/Migrations/20170420142131_added_tag_column_to_build_table.php rename to src/Migrations/20170420142131_added_tag_column_to_build_table.php diff --git a/src/PHPCensor/Migrations/20170711112805_fixed_build_meta_for_mysql.php b/src/Migrations/20170711112805_fixed_build_meta_for_mysql.php similarity index 100% rename from src/PHPCensor/Migrations/20170711112805_fixed_build_meta_for_mysql.php rename to src/Migrations/20170711112805_fixed_build_meta_for_mysql.php diff --git a/src/PHPCensor/Migrations/20170828142020_added_remember_me_login.php b/src/Migrations/20170828142020_added_remember_me_login.php similarity index 100% rename from src/PHPCensor/Migrations/20170828142020_added_remember_me_login.php rename to src/Migrations/20170828142020_added_remember_me_login.php diff --git a/src/PHPCensor/Migrations/20170913141438_added_default_branch_only.php b/src/Migrations/20170913141438_added_default_branch_only.php similarity index 100% rename from src/PHPCensor/Migrations/20170913141438_added_default_branch_only.php rename to src/Migrations/20170913141438_added_default_branch_only.php diff --git a/src/PHPCensor/Migrations/20171014173348_removed_project_id_from_build_meta.php b/src/Migrations/20171014173348_removed_project_id_from_build_meta.php similarity index 100% rename from src/PHPCensor/Migrations/20171014173348_removed_project_id_from_build_meta.php rename to src/Migrations/20171014173348_removed_project_id_from_build_meta.php diff --git a/src/PHPCensor/Migrations/20171015123827_added_additional_columns.php b/src/Migrations/20171015123827_added_additional_columns.php similarity index 100% rename from src/PHPCensor/Migrations/20171015123827_added_additional_columns.php rename to src/Migrations/20171015123827_added_additional_columns.php diff --git a/src/PHPCensor/Migrations/20171016143000_added_additional_columns2.php b/src/Migrations/20171016143000_added_additional_columns2.php similarity index 100% rename from src/PHPCensor/Migrations/20171016143000_added_additional_columns2.php rename to src/Migrations/20171016143000_added_additional_columns2.php diff --git a/src/PHPCensor/Migrations/20171019143346_added_additional_columns3.php b/src/Migrations/20171019143346_added_additional_columns3.php similarity index 100% rename from src/PHPCensor/Migrations/20171019143346_added_additional_columns3.php rename to src/Migrations/20171019143346_added_additional_columns3.php diff --git a/src/PHPCensor/Migrations/20171209135004_added_new_label_for_errors.php b/src/Migrations/20171209135004_added_new_label_for_errors.php similarity index 100% rename from src/PHPCensor/Migrations/20171209135004_added_new_label_for_errors.php rename to src/Migrations/20171209135004_added_new_label_for_errors.php diff --git a/src/PHPCensor/Migrations/20180223052715_added_request_branch_to_build.php b/src/Migrations/20180223052715_added_request_branch_to_build.php similarity index 95% rename from src/PHPCensor/Migrations/20180223052715_added_request_branch_to_build.php rename to src/Migrations/20180223052715_added_request_branch_to_build.php index edf1bdde..2c702dd6 100644 --- a/src/PHPCensor/Migrations/20180223052715_added_request_branch_to_build.php +++ b/src/Migrations/20180223052715_added_request_branch_to_build.php @@ -1,7 +1,7 @@ setExtra(json_encode($extra)); + $build->setExtra($extra); $buildStore->save($build); } unset($build); diff --git a/src/PHPCensor/Migrations/20180228024622_renamed_build_types.php b/src/Migrations/20180228024622_renamed_build_types.php similarity index 100% rename from src/PHPCensor/Migrations/20180228024622_renamed_build_types.php rename to src/Migrations/20180228024622_renamed_build_types.php diff --git a/src/Migrations/20180311165225_removed_last_commit_from_project.php b/src/Migrations/20180311165225_removed_last_commit_from_project.php new file mode 100644 index 00000000..c19f254c --- /dev/null +++ b/src/Migrations/20180311165225_removed_last_commit_from_project.php @@ -0,0 +1,32 @@ +hasTable('project')) { + $table = $this->table('project'); + + if ($table->hasColumn('last_commit')) { + $table + ->removeColumn('last_commit') + ->save(); + } + } + } + + public function down() + { + if ($this->hasTable('project')) { + $table = $this->table('project'); + + if (!$table->hasColumn('last_commit')) { + $table + ->addColumn('last_commit', 'string', ['limit' => 250, 'null' => true, 'default' => null]) + ->save(); + } + } + } +} diff --git a/src/Model.php b/src/Model.php new file mode 100644 index 00000000..292610eb --- /dev/null +++ b/src/Model.php @@ -0,0 +1,131 @@ + $item) { + if (!array_key_exists($index, $this->data)) { + throw new \InvalidArgumentException(sprintf( + 'Model "%s" doesn\'t have field "%s"', + get_called_class(), + $index + )); + } + + $this->data[$index] = $item; + } + } + } + + /** + * @return string + */ + public function getTableName() + { + return $this->tableName; + } + + /** + * @return array + */ + public function getDataArray() + { + return $this->data; + } + + /** + * @return array + */ + public function getModified() + { + return $this->modified; + } + + /** + * @param string $column + * + * @return boolean + */ + protected function setModified($column) + { + $this->modified[$column] = $column; + + return true; + } + + /** + * @param string $name + * @param mixed $value + * + * @throws ValidationException + */ + protected function validateString($name, $value) + { + if (!is_string($value) && !is_null($value)) { + throw new ValidationException('Column "' . $name . '" must be a string.'); + } + } + + /** + * @param string $name + * @param mixed $value + * + * @throws ValidationException + */ + protected function validateInt($name, $value) + { + if (!is_integer($value) && !is_null($value)) { + throw new ValidationException('Column "' . $name . '" must be an integer.'); + } + } + + /** + * @param string $name + * @param mixed $value + * + * @throws ValidationException + */ + protected function validateBoolean($name, $value) + { + if (!is_bool($value) && !is_null($value)) { + throw new ValidationException('Column "' . $name . '" must be a boolean.'); + } + } + + /** + * @param string $name + * @param mixed $value + * + * @throws ValidationException + */ + protected function validateNotNull($name, $value) + { + if (is_null($value)) { + throw new ValidationException('Column "' . $name . '" must not be null.'); + } + } +} diff --git a/src/Model/Base/Build.php b/src/Model/Base/Build.php new file mode 100644 index 00000000..c356aa2b --- /dev/null +++ b/src/Model/Base/Build.php @@ -0,0 +1,526 @@ + null, + 'project_id' => null, + 'commit_id' => null, + 'status' => null, + 'log' => null, + 'branch' => null, + 'tag' => null, + 'create_date' => null, + 'start_date' => null, + 'finish_date' => null, + 'committer_email' => null, + 'commit_message' => null, + 'extra' => null, + 'environment' => null, + 'source' => Build::SOURCE_UNKNOWN, + 'user_id' => 0, + ]; + + /** + * @var array + */ + protected $allowedStatuses = [ + self::STATUS_PENDING, + self::STATUS_RUNNING, + self::STATUS_SUCCESS, + self::STATUS_FAILED, + ]; + + /** + * @var array + */ + protected $allowedSources = [ + self::SOURCE_UNKNOWN, + self::SOURCE_MANUAL_WEB, + self::SOURCE_MANUAL_CONSOLE, + self::SOURCE_PERIODICAL, + self::SOURCE_WEBHOOK, + self::SOURCE_WEBHOOK_PULL_REQUEST, + ]; + + /** + * @return integer + */ + public function getId() + { + return (integer)$this->data['id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setId($value) + { + $this->validateNotNull('id', $value); + $this->validateInt('id', $value); + + if ($this->data['id'] === $value) { + return false; + } + + $this->data['id'] = (integer)$value; + + return $this->setModified('id'); + } + + /** + * @return integer + */ + public function getProjectId() + { + return (integer)$this->data['project_id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setProjectId($value) + { + $this->validateNotNull('project_id', $value); + $this->validateInt('project_id', $value); + + if ($this->data['project_id'] === $value) { + return false; + } + + $this->data['project_id'] = $value; + + return $this->setModified('project_id'); + } + + /** + * @return string + */ + public function getCommitId() + { + return $this->data['commit_id']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setCommitId($value) + { + $this->validateNotNull('commit_id', $value); + $this->validateString('commit_id', $value); + + if ($this->data['commit_id'] === $value) { + return false; + } + + $this->data['commit_id'] = $value; + + return $this->setModified('commit_id'); + } + + /** + * @return integer + */ + public function getStatus() + { + return (integer)$this->data['status']; + } + + /** + * @param integer $value + * + * @throws ValidationException + * + * @return boolean + */ + public function setStatus($value) + { + $this->validateNotNull('status', $value); + $this->validateInt('status', $value); + + if (!in_array($value, $this->allowedStatuses, true)) { + throw new ValidationException( + 'Column "status" must be one of: ' . join(', ', $this->allowedStatuses) . '.' + ); + } + + if ($this->data['status'] === $value) { + return false; + } + + $this->data['status'] = $value; + + return $this->setModified('status'); + } + + /** + * @return string + */ + public function getLog() + { + return $this->data['log']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setLog($value) + { + $this->validateString('log', $value); + + if ($this->data['log'] === $value) { + return false; + } + + $this->data['log'] = $value; + + return $this->setModified('log'); + } + + /** + * @return string + */ + public function getBranch() + { + return $this->data['branch']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setBranch($value) + { + $this->validateNotNull('branch', $value); + $this->validateString('branch', $value); + + if ($this->data['branch'] === $value) { + return false; + } + + $this->data['branch'] = $value; + + return $this->setModified('branch'); + } + + /** + * @return string + */ + public function getTag() + { + return $this->data['tag']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setTag($value) + { + $this->validateString('tag', $value); + + if ($this->data['tag'] === $value) { + return false; + } + + $this->data['tag'] = $value; + + return $this->setModified('tag'); + } + + /** + * @return \DateTime|null + */ + public function getCreateDate() + { + if ($this->data['create_date']) { + return new \DateTime($this->data['create_date']); + } + + return null; + } + + /** + * @param \DateTime $value + * + * @return boolean + */ + public function setCreateDate(\DateTime $value) + { + $stringValue = $value->format('Y-m-d H:i:s'); + + if ($this->data['create_date'] === $stringValue) { + return false; + } + + $this->data['create_date'] = $stringValue; + + return $this->setModified('create_date'); + } + + /** + * @return \DateTime|null + */ + public function getStartDate() + { + if ($this->data['start_date']) { + return new \DateTime($this->data['start_date']); + } + + return null; + } + + /** + * @param \DateTime $value + * + * @return boolean + */ + public function setStartDate(\DateTime $value) + { + $stringValue = $value->format('Y-m-d H:i:s'); + + if ($this->data['start_date'] === $stringValue) { + return false; + } + + $this->data['start_date'] = $stringValue; + + return $this->setModified('start_date'); + } + + /** + * @return \DateTime|null + */ + public function getFinishDate() + { + if ($this->data['finish_date']) { + return new \DateTime($this->data['finish_date']); + } + + return null; + } + + /** + * @param \DateTime $value + * + * @return boolean + */ + public function setFinishDate(\DateTime $value) + { + $stringValue = $value->format('Y-m-d H:i:s'); + + if ($this->data['finish_date'] === $stringValue) { + return false; + } + + $this->data['finish_date'] = $stringValue; + + return $this->setModified('finish_date'); + } + + /** + * @return string + */ + public function getCommitterEmail() + { + return $this->data['committer_email']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setCommitterEmail($value) + { + $this->validateString('committer_email', $value); + + if ($this->data['committer_email'] === $value) { + return false; + } + + $this->data['committer_email'] = $value; + + return $this->setModified('committer_email'); + } + + /** + * @return string + */ + public function getCommitMessage() + { + return $this->data['commit_message']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setCommitMessage($value) + { + $this->validateString('commit_message', $value); + + if ($this->data['commit_message'] === $value) { + return false; + } + + $this->data['commit_message'] = $value; + + return $this->setModified('commit_message'); + } + + /** + * @param string|null $key + * + * @return array|string|null + */ + public function getExtra($key = null) + { + $data = json_decode($this->data['extra'], true); + $extra = null; + if (is_null($key)) { + $extra = $data; + } elseif (isset($data[$key])) { + $extra = $data[$key]; + } + + return $extra; + } + + /** + * @param array $value + * + * @return boolean + */ + public function setExtra(array $value) + { + $this->validateNotNull('branches', $value); + + $extra = json_encode($value); + if ($this->data['extra'] === $extra) { + return false; + } + + $this->data['extra'] = $extra; + + return $this->setModified('extra'); + } + + /** + * @return string + */ + public function getEnvironment() + { + return $this->data['environment']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setEnvironment($value) + { + $this->validateString('environment', $value); + + if ($this->data['environment'] === $value) { + return false; + } + + $this->data['environment'] = $value; + + return $this->setModified('environment'); + } + + /** + * @return string + */ + public function getSource() + { + return (integer)$this->data['source']; + } + + /** + * @param integer $value + * + * @throws ValidationException + * + * @return boolean + */ + public function setSource($value) + { + $this->validateInt('source', $value); + + if (!in_array($value, $this->allowedSources, true)) { + throw new ValidationException( + 'Column "source" must be one of: ' . join(', ', $this->allowedSources) . '.' + ); + } + + if ($this->data['source'] === $value) { + return false; + } + + $this->data['source'] = $value; + + return $this->setModified('source'); + } + + /** + * @return string + */ + public function getUserId() + { + return (integer)$this->data['user_id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setUserId($value) + { + $this->validateNotNull('user_id', $value); + $this->validateInt('user_id', $value); + + if ($this->data['user_id'] === $value) { + return false; + } + + $this->data['user_id'] = $value; + + return $this->setModified('user_id'); + } +} diff --git a/src/Model/Base/BuildError.php b/src/Model/Base/BuildError.php new file mode 100644 index 00000000..a760e777 --- /dev/null +++ b/src/Model/Base/BuildError.php @@ -0,0 +1,334 @@ + null, + 'build_id' => null, + 'plugin' => null, + 'file' => null, + 'line_start' => null, + 'line_end' => null, + 'severity' => null, + 'message' => null, + 'create_date' => null, + 'hash' => null, + 'is_new' => null, + ]; + + /** + * @return integer + */ + public function getId() + { + return (integer)$this->data['id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setId($value) + { + $this->validateNotNull('id', $value); + $this->validateInt('id', $value); + + if ($this->data['id'] === $value) { + return false; + } + + $this->data['id'] = $value; + + return $this->setModified('id'); + } + + /** + * @return integer + */ + public function getBuildId() + { + return (integer)$this->data['build_id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setBuildId($value) + { + $this->validateNotNull('build_id', $value); + $this->validateInt('build_id', $value); + + if ($this->data['build_id'] === $value) { + return false; + } + + $this->data['build_id'] = $value; + + return $this->setModified('build_id'); + } + + /** + * @return string + */ + public function getPlugin() + { + return $this->data['plugin']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setPlugin($value) + { + $this->validateNotNull('plugin', $value); + $this->validateString('plugin', $value); + + if ($this->data['plugin'] === $value) { + return false; + } + + $this->data['plugin'] = $value; + + return $this->setModified('plugin'); + } + + /** + * @return string + */ + public function getFile() + { + return $this->data['file']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setFile($value) + { + $this->validateString('file', $value); + + if ($this->data['file'] === $value) { + return false; + } + + $this->data['file'] = $value; + + return $this->setModified('file'); + } + + /** + * @return integer + */ + public function getLineStart() + { + return (integer)$this->data['line_start']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setLineStart($value) + { + $this->validateInt('line_start', $value); + + if ($this->data['line_start'] === $value) { + return false; + } + + $this->data['line_start'] = $value; + + return $this->setModified('line_start'); + } + + /** + * @return integer + */ + public function getLineEnd() + { + return (integer)$this->data['line_end']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setLineEnd($value) + { + $this->validateInt('line_end', $value); + + if ($this->data['line_end'] === $value) { + return false; + } + + $this->data['line_end'] = $value; + + return $this->setModified('line_end'); + } + + /** + * @return integer + */ + public function getSeverity() + { + return (integer)$this->data['severity']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setSeverity($value) + { + $this->validateNotNull('severity', $value); + $this->validateInt('severity', $value); + + if ($this->data['severity'] === $value) { + return false; + } + + $this->data['severity'] = $value; + + return $this->setModified('severity'); + } + + /** + * @return string + */ + public function getMessage() + { + return $this->data['message']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setMessage($value) + { + $this->validateNotNull('message', $value); + $this->validateString('message', $value); + + if ($this->data['message'] === $value) { + return false; + } + + $this->data['message'] = $value; + + return $this->setModified('message'); + } + + /** + * @return \DateTime|null + */ + public function getCreateDate() + { + if ($this->data['create_date']) { + return new \DateTime($this->data['create_date']); + } + + return null; + } + + /** + * @param \DateTime $value + * + * @return boolean + */ + public function setCreateDate(\DateTime $value) + { + $this->validateNotNull('create_date', $value); + + $stringValue = $value->format('Y-m-d H:i:s'); + + if ($this->data['create_date'] === $stringValue) { + return false; + } + + $this->data['create_date'] = $stringValue; + + return $this->setModified('create_date'); + } + + /** + * @return string + */ + public function getHash() + { + return $this->data['hash']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setHash($value) + { + $this->validateNotNull('hash', $value); + $this->validateString('hash', $value); + + if ($this->data['hash'] === $value) { + return false; + } + + $this->data['hash'] = $value; + + return $this->setModified('hash'); + } + + /** + * @return boolean + */ + public function getIsNew() + { + return (boolean)$this->data['is_new']; + } + + /** + * @param boolean $value + * + * @return boolean + */ + public function setIsNew($value) + { + $this->validateNotNull('is_new', $value); + $this->validateBoolean('is_new', $value); + + if ($this->data['is_new'] === (integer)$value) { + return false; + } + + $this->data['is_new'] = (integer)$value; + + return $this->setModified('is_new'); + } +} diff --git a/src/Model/Base/BuildMeta.php b/src/Model/Base/BuildMeta.php new file mode 100644 index 00000000..338c2a50 --- /dev/null +++ b/src/Model/Base/BuildMeta.php @@ -0,0 +1,131 @@ + null, + 'build_id' => null, + 'meta_key' => null, + 'meta_value' => null, + ]; + + /** + * @return integer + */ + public function getId() + { + return (integer)$this->data['id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setId($value) + { + $this->validateNotNull('id', $value); + $this->validateInt('id', $value); + + if ($this->data['id'] === $value) { + return false; + } + + $this->data['id'] = $value; + + return $this->setModified('id'); + } + + /** + * @return integer + */ + public function getBuildId() + { + return (integer)$this->data['build_id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setBuildId($value) + { + $this->validateNotNull('build_id', $value); + $this->validateInt('build_id', $value); + + if ($this->data['build_id'] === $value) { + return false ; + } + + $this->data['build_id'] = $value; + + return $this->setModified('build_id'); + } + + /** + * @return string + */ + public function getMetaKey() + { + return $this->data['meta_key']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setMetaKey($value) + { + $this->validateNotNull('meta_key', $value); + $this->validateString('meta_key', $value); + + if ($this->data['meta_key'] === $value) { + return false; + } + + $this->data['meta_key'] = $value; + + return $this->setModified('meta_key'); + } + + /** + * @return string + */ + public function getMetaValue() + { + return $this->data['meta_value']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setMetaValue($value) + { + $this->validateNotNull('meta_value', $value); + $this->validateString('meta_value', $value); + + if ($this->data['meta_value'] === $value) { + return false; + } + + $this->data['meta_value'] = $value; + + return $this->setModified('meta_value'); + } +} diff --git a/src/PHPCensor/Model/Environment.php b/src/Model/Base/Environment.php similarity index 53% rename from src/PHPCensor/Model/Environment.php rename to src/Model/Base/Environment.php index 427a9be8..d160cb57 100644 --- a/src/PHPCensor/Model/Environment.php +++ b/src/Model/Base/Environment.php @@ -1,6 +1,6 @@ 'getId', - 'project_id' => 'getProjectId', - 'name' => 'getName', - 'branches' => 'getBranches', - ]; - - /** - * @var array - */ - protected $setters = [ - 'id' => 'setId', - 'project_id' => 'setProjectId', - 'name' => 'setName', - 'branches' => 'setBranches', - ]; - - /** - * @return int + * @return integer */ public function getId() { - $rtn = $this->data['id']; - - return $rtn; + return (integer)$this->data['id']; } /** - * @return int - */ - public function getProjectId() - { - $rtn = $this->data['project_id']; - - return $rtn; - } - - /** - * @return string - */ - public function getName() - { - $rtn = $this->data['name']; - - return $rtn; - } - - /** - * @return array - */ - public function getBranches() - { - $rtn = array_filter(array_map('trim', explode("\n", $this->data['branches']))); - - return $rtn; - } - - /** - * @param $value int + * @param integer $value + * + * @return boolean */ public function setId($value) { @@ -90,16 +40,26 @@ class Environment extends Model $this->validateInt('id', $value); if ($this->data['id'] === $value) { - return; + return false; } $this->data['id'] = $value; - $this->setModified('id'); + return $this->setModified('id'); } /** - * @param $value int + * @return integer + */ + public function getProjectId() + { + return (integer)$this->data['project_id']; + } + + /** + * @param integer $value + * + * @return boolean */ public function setProjectId($value) { @@ -107,16 +67,26 @@ class Environment extends Model $this->validateInt('project_id', $value); if ($this->data['project_id'] === $value) { - return; + return false; } $this->data['project_id'] = $value; - $this->setModified('project_id'); + return $this->setModified('project_id'); } /** - * @param $value string + * @return string + */ + public function getName() + { + return $this->data['name']; + } + + /** + * @param string $value + * + * @return boolean */ public function setName($value) { @@ -124,28 +94,43 @@ class Environment extends Model $this->validateString('name', $value); if ($this->data['name'] === $value) { - return; + return false; } $this->data['name'] = $value; - $this->setModified('name'); + return $this->setModified('name'); } /** - * @param $value array + * @return array */ - public function setBranches($value) + public function getBranches() + { + return array_filter( + array_map( + 'trim', + explode("\n", $this->data['branches']) + ) + ); + } + + /** + * @param array $value + * + * @return boolean + */ + public function setBranches(array $value) { $this->validateNotNull('branches', $value); - $value = implode("\n", $value); - if ($this->data['branches'] === $value) { - return; + $branches = implode("\n", $value); + if ($this->data['branches'] === $branches) { + return false; } - $this->data['branches'] = $value; + $this->data['branches'] = $branches; - $this->setModified('branches'); + return $this->setModified('branches'); } } diff --git a/src/Model/Base/Project.php b/src/Model/Base/Project.php new file mode 100644 index 00000000..15e0c250 --- /dev/null +++ b/src/Model/Base/Project.php @@ -0,0 +1,499 @@ + null, + 'title' => null, + 'reference' => null, + 'branch' => null, + 'default_branch_only' => null, + 'ssh_private_key' => null, + 'ssh_public_key' => null, + 'type' => null, + 'access_information' => null, + 'build_config' => null, + 'allow_public_status' => null, + 'archived' => null, + 'group_id' => null, + 'create_date' => null, + 'user_id' => 0, + ]; + + /** + * @var array + */ + protected $allowedTypes = [ + self::TYPE_LOCAL, + self::TYPE_GIT, + self::TYPE_GITHUB, + self::TYPE_BITBUCKET, + self::TYPE_GITLAB, + self::TYPE_GOGS, + self::TYPE_HG, + self::TYPE_BITBUCKET_HG, + self::TYPE_SVN, + ]; + + /** + * @return integer + */ + public function getId() + { + return (integer)$this->data['id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setId($value) + { + $this->validateNotNull('id', $value); + $this->validateInt('id', $value); + + if ($this->data['id'] === $value) { + return false; + } + + $this->data['id'] = $value; + + return $this->setModified('id'); + } + + /** + * @return string + */ + public function getTitle() + { + return $this->data['title']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setTitle($value) + { + $this->validateNotNull('title', $value); + $this->validateString('title', $value); + + if ($this->data['title'] === $value) { + return false; + } + + $this->data['title'] = $value; + + return $this->setModified('title'); + } + + /** + * @return string + */ + public function getReference() + { + return $this->data['reference']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setReference($value) + { + $this->validateNotNull('reference', $value); + $this->validateString('reference', $value); + + if ($this->data['reference'] === $value) { + return false; + } + + $this->data['reference'] = $value; + + return $this->setModified('reference'); + } + + /** + * @return string + */ + public function getBranch() + { + if (!$this->data['branch']) { + $projectType = $this->getType(); + switch ($projectType) { + case 'hg': + $branch = 'default'; + break; + case 'svn': + $branch = 'trunk'; + break; + default: + $branch = 'master'; + } + + return $branch; + } else { + return $this->data['branch']; + } + } + + /** + * @param string $value + * + * @return boolean + */ + public function setBranch($value) + { + $this->validateNotNull('branch', $value); + $this->validateString('branch', $value); + + if ($this->data['branch'] === $value) { + return false; + } + + $this->data['branch'] = $value; + + return $this->setModified('branch'); + } + + /** + * @return boolean + */ + public function getDefaultBranchOnly() + { + return (boolean)$this->data['default_branch_only']; + } + + /** + * @param boolean $value + * + * @return boolean + */ + public function setDefaultBranchOnly($value) + { + $this->validateNotNull('default_branch_only', $value); + $this->validateBoolean('default_branch_only', $value); + + if ($this->data['default_branch_only'] === (integer)$value) { + return false; + } + + $this->data['default_branch_only'] = (integer)$value; + + return $this->setModified('default_branch_only'); + } + + /** + * @return string + */ + public function getSshPrivateKey() + { + return $this->data['ssh_private_key']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setSshPrivateKey($value) + { + $this->validateString('ssh_private_key', $value); + + if ($this->data['ssh_private_key'] === $value) { + return false; + } + + $this->data['ssh_private_key'] = $value; + + return $this->setModified('ssh_private_key'); + } + + /** + * @return string + */ + public function getSshPublicKey() + { + return $this->data['ssh_public_key']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setSshPublicKey($value) + { + $this->validateString('ssh_public_key', $value); + + if ($this->data['ssh_public_key'] === $value) { + return false; + } + + $this->data['ssh_public_key'] = $value; + + return $this->setModified('ssh_public_key'); + } + + /** + * @return string + */ + public function getType() + { + return $this->data['type']; + } + + /** + * @param string $value + * + * @return boolean + * + * @throws ValidationException + */ + public function setType($value) + { + $this->validateNotNull('type', $value); + $this->validateString('type', $value); + + if (!in_array($value, $this->allowedTypes, true)) { + throw new ValidationException( + 'Column "type" must be one of: ' . join(', ', $this->allowedTypes) . '.' + ); + } + + if ($this->data['type'] === $value) { + return false; + } + + $this->data['type'] = $value; + + return $this->setModified('type'); + } + + /** + * @param string|null $key + * + * @return array|string|null + */ + public function getAccessInformation($key = null) + { + $data = json_decode($this->data['access_information'], true); + $accessInformation = null; + if (is_null($key)) { + $accessInformation = $data; + } elseif (isset($data[$key])) { + $accessInformation = $data[$key]; + } + + return $accessInformation; + } + + /** + * @param array $value + * + * @return boolean + */ + public function setAccessInformation(array $value) + { + $this->validateNotNull('branches', $value); + + $accessInformation = json_encode($value); + if ($this->data['access_information'] === $accessInformation) { + return false; + } + + $this->data['access_information'] = $accessInformation; + + return $this->setModified('access_information'); + } + + /** + * @return string + */ + public function getBuildConfig() + { + return $this->data['build_config']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setBuildConfig($value) + { + $this->validateString('build_config', $value); + + if ($this->data['build_config'] === $value) { + return false; + } + + $this->data['build_config'] = $value; + + return $this->setModified('build_config'); + } + + /** + * @return boolean + */ + public function getAllowPublicStatus() + { + return (boolean)$this->data['allow_public_status']; + } + + /** + * @param boolean $value + * + * @return boolean + */ + public function setAllowPublicStatus($value) + { + $this->validateNotNull('allow_public_status', $value); + $this->validateBoolean('allow_public_status', $value); + + if ($this->data['allow_public_status'] === (integer)$value) { + return false; + } + + $this->data['allow_public_status'] = (integer)$value; + + return $this->setModified('allow_public_status'); + } + + /** + * @return boolean + */ + public function getArchived() + { + return (boolean)$this->data['archived']; + } + + /** + * @param boolean $value + * + * @return boolean + */ + public function setArchived($value) + { + $this->validateNotNull('archived', $value); + $this->validateBoolean('archived', $value); + + if ($this->data['archived'] === (integer)$value) { + return false; + } + + $this->data['archived'] = (integer)$value; + + return $this->setModified('archived'); + } + + /** + * @return integer + */ + public function getGroupId() + { + return (integer)$this->data['group_id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setGroupId($value) + { + $this->validateNotNull('group_id', $value); + $this->validateInt('group_id', $value); + + if ($this->data['group_id'] === $value) { + return false; + } + + $this->data['group_id'] = $value; + + return $this->setModified('group_id'); + } + + /** + * @return \DateTime|null + */ + public function getCreateDate() + { + if ($this->data['create_date']) { + return new \DateTime($this->data['create_date']); + } + + return null; + } + + /** + * @param \DateTime $value + * + * @return boolean + */ + public function setCreateDate(\DateTime $value) + { + $stringValue = $value->format('Y-m-d H:i:s'); + + if ($this->data['create_date'] === $stringValue) { + return false; + } + + $this->data['create_date'] = $stringValue; + + return $this->setModified('create_date'); + } + + /** + * @return integer + */ + public function getUserId() + { + return (integer)$this->data['user_id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setUserId($value) + { + $this->validateNotNull('user_id', $value); + $this->validateInt('user_id', $value); + + if ($this->data['user_id'] === $value) { + return false; + } + + $this->data['user_id'] = $value; + + return $this->setModified('user_id'); + } +} diff --git a/src/Model/Base/ProjectGroup.php b/src/Model/Base/ProjectGroup.php new file mode 100644 index 00000000..c78c45a1 --- /dev/null +++ b/src/Model/Base/ProjectGroup.php @@ -0,0 +1,134 @@ + null, + 'title' => null, + 'create_date' => null, + 'user_id' => 0, + ]; + + /** + * @return integer + */ + public function getId() + { + return (integer)$this->data['id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setId($value) + { + $this->validateNotNull('id', $value); + $this->validateInt('id', $value); + + if ($this->data['id'] === $value) { + return false; + } + + $this->data['id'] = $value; + + return $this->setModified('id'); + } + + /** + * @return string + */ + public function getTitle() + { + return $this->data['title']; + } + + /** + * @param string $value + * + * @return boolean + */ + public function setTitle($value) + { + $this->validateNotNull('title', $value); + $this->validateString('title', $value); + + if ($this->data['title'] === $value) { + return false; + } + + $this->data['title'] = $value; + + return $this->setModified('title'); + } + + /** + * @return \DateTime|null + */ + public function getCreateDate() + { + if ($this->data['create_date']) { + return new \DateTime($this->data['create_date']); + } + + return null; + } + + /** + * @param \DateTime $value + * + * @return boolean + */ + public function setCreateDate(\DateTime $value) + { + $stringValue = $value->format('Y-m-d H:i:s'); + + if ($this->data['create_date'] === $stringValue) { + return false; + } + + $this->data['create_date'] = $stringValue; + + return $this->setModified('create_date'); + } + + /** + * @return string + */ + public function getUserId() + { + return (integer)$this->data['user_id']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setUserId($value) + { + $this->validateNotNull('user_id', $value); + $this->validateInt('user_id', $value); + + if ($this->data['user_id'] === $value) { + return false; + } + + $this->data['user_id'] = $value; + + return $this->setModified('user_id'); + } +} diff --git a/src/PHPCensor/Model/User.php b/src/Model/Base/User.php similarity index 50% rename from src/PHPCensor/Model/User.php rename to src/Model/Base/User.php index dd1dceb6..cd49424b 100644 --- a/src/PHPCensor/Model/User.php +++ b/src/Model/Base/User.php @@ -1,13 +1,9 @@ - */ class User extends Model { /** @@ -32,139 +28,17 @@ class User extends Model ]; /** - * @var array - */ - protected $getters = [ - 'id' => 'getId', - 'email' => 'getEmail', - 'hash' => 'getHash', - 'is_admin' => 'getIsAdmin', - 'name' => 'getName', - 'language' => 'getLanguage', - 'per_page' => 'getPerPage', - 'provider_key' => 'getProviderKey', - 'provider_data' => 'getProviderData', - 'remember_key' => 'getRememberKey', - ]; - - /** - * @var array - */ - protected $setters = [ - 'id' => 'setId', - 'email' => 'setEmail', - 'hash' => 'setHash', - 'is_admin' => 'setIsAdmin', - 'name' => 'setName', - 'language' => 'setLanguage', - 'per_page' => 'setPerPage', - 'provider_key' => 'setProviderKey', - 'provider_data' => 'setProviderData', - 'remember_key' => 'setRememberKey', - ]; - - /** - * @return int + * @return integer */ public function getId() { - $rtn = $this->data['id']; - - return $rtn; + return (integer)$this->data['id']; } /** - * @return string - */ - public function getEmail() - { - $rtn = $this->data['email']; - - return $rtn; - } - - /** - * @return string - */ - public function getHash() - { - $rtn = $this->data['hash']; - - return $rtn; - } - - /** - * @return string - */ - public function getName() - { - $rtn = $this->data['name']; - - return $rtn; - } - - /** - * @return int - */ - public function getIsAdmin() - { - $rtn = $this->data['is_admin']; - - return $rtn; - } - - /** - * @return string - */ - public function getProviderKey() - { - $rtn = $this->data['provider_key']; - - return $rtn; - } - - /** - * @return string - */ - public function getProviderData() - { - $rtn = $this->data['provider_data']; - - return $rtn; - } - - /** - * @return string - */ - public function getRememberKey() - { - $rtn = $this->data['remember_key']; - - return $rtn; - } - - /** - * @return string - */ - public function getLanguage() - { - $rtn = $this->data['language']; - - return $rtn; - } - - /** - * @return string - */ - public function getPerPage() - { - $rtn = $this->data['per_page']; - - return $rtn; - } - - /** - * @param $value int + * @param integer $value + * + * @return boolean */ public function setId($value) { @@ -172,16 +46,26 @@ class User extends Model $this->validateInt('id', $value); if ($this->data['id'] === $value) { - return; + return false; } $this->data['id'] = $value; - $this->setModified('id'); + return $this->setModified('id'); } /** - * @param $value string + * @return string + */ + public function getEmail() + { + return $this->data['email']; + } + + /** + * @param string $value + * + * @return boolean */ public function setEmail($value) { @@ -189,16 +73,26 @@ class User extends Model $this->validateString('email', $value); if ($this->data['email'] === $value) { - return; + return false; } $this->data['email'] = $value; - $this->setModified('email'); + return $this->setModified('email'); } /** - * @param $value string + * @return string + */ + public function getHash() + { + return $this->data['hash']; + } + + /** + * @param string $value + * + * @return boolean */ public function setHash($value) { @@ -206,16 +100,53 @@ class User extends Model $this->validateString('hash', $value); if ($this->data['hash'] === $value) { - return; + return false; } $this->data['hash'] = $value; - $this->setModified('hash'); + return $this->setModified('hash'); } /** - * @param $value string + * @return boolean + */ + public function getIsAdmin() + { + return (boolean)$this->data['is_admin']; + } + + /** + * @param boolean $value + * + * @return boolean + */ + public function setIsAdmin($value) + { + $this->validateNotNull('is_admin', $value); + $this->validateBoolean('is_admin', $value); + + if ($this->data['is_admin'] === (integer)$value) { + return false; + } + + $this->data['is_admin'] = (integer)$value; + + return $this->setModified('is_admin'); + } + + /** + * @return string + */ + public function getName() + { + return $this->data['name']; + } + + /** + * @param string $value + * + * @return boolean */ public function setName($value) { @@ -223,33 +154,76 @@ class User extends Model $this->validateString('name', $value); if ($this->data['name'] === $value) { - return; + return false; } $this->data['name'] = $value; - $this->setModified('name'); + return $this->setModified('name'); } /** - * @param $value int + * @return string */ - public function setIsAdmin($value) + public function getLanguage() { - $this->validateNotNull('is_admin', $value); - $this->validateInt('is_admin', $value); + return $this->data['language']; + } - if ($this->data['is_admin'] === $value) { - return; + /** + * @param string $value + * + * @return boolean + */ + public function setLanguage($value) + { + if ($this->data['language'] === $value) { + return false; } - $this->data['is_admin'] = $value; + $this->data['language'] = $value; - $this->setModified('is_admin'); + return $this->setModified('language'); } /** - * @param $value string + * @return integer + */ + public function getPerPage() + { + return (integer)$this->data['per_page']; + } + + /** + * @param integer $value + * + * @return boolean + */ + public function setPerPage($value) + { + $this->validateInt('per_page', $value); + + if ($this->data['per_page'] === $value) { + return false; + } + + $this->data['per_page'] = $value; + + return $this->setModified('per_page'); + } + + /** + * @return string + */ + public function getProviderKey() + { + return $this->data['provider_key']; + } + + /** + * @param string $value + * + * @return boolean */ public function setProviderKey($value) { @@ -257,84 +231,74 @@ class User extends Model $this->validateString('provider_key', $value); if ($this->data['provider_key'] === $value) { - return; + return false; } $this->data['provider_key'] = $value; - $this->setModified('provider_key'); + return $this->setModified('provider_key'); } /** - * @param $value string + * @param string|null $key + * + * @return array|string|null */ - public function setProviderData($value) + public function getProviderData($key = null) { - $this->validateString('provider_data', $value); - - if ($this->data['provider_data'] === $value) { - return; + $data = json_decode($this->data['provider_data'], true); + $providerData = null; + if (is_null($key)) { + $providerData = $data; + } elseif (isset($data[$key])) { + $providerData = $data[$key]; } - $this->data['provider_data'] = $value; - - $this->setModified('provider_data'); + return $providerData; } /** - * @param $value string + * @param array $value + * + * @return boolean + */ + public function setProviderData(array $value) + { + $this->validateNotNull('provider_data', $value); + + $providerData = json_encode($value); + if ($this->data['provider_data'] === $providerData) { + return false; + } + + $this->data['provider_data'] = $providerData; + + return $this->setModified('provider_data'); + } + + /** + * @return string + */ + public function getRememberKey() + { + return $this->data['remember_key']; + } + + /** + * @param string $value + * + * @return boolean */ public function setRememberKey($value) { $this->validateString('remember_key', $value); if ($this->data['remember_key'] === $value) { - return; + return false; } $this->data['remember_key'] = $value; - $this->setModified('remember_key'); - } - - /** - * @param $value string - */ - public function setLanguage($value) - { - if ($this->data['language'] === $value) { - return; - } - - $this->data['language'] = $value; - - $this->setModified('language'); - } - - /** - * @param $value string - */ - public function setPerPage($value) - { - if ($this->data['per_page'] === $value) { - return; - } - - $this->data['per_page'] = $value; - - $this->setModified('per_page'); - } - - /** - * @return integer - */ - public function getFinalPerPage() - { - $perPage = $this->getPerPage(); - if ($perPage) { - return (integer)$perPage; - } - - return (integer)Config::getInstance()->get('php-censor.per_page', 10); + return $this->setModified('remember_key'); } } diff --git a/src/Model/Build.php b/src/Model/Build.php new file mode 100644 index 00000000..207c4611 --- /dev/null +++ b/src/Model/Build.php @@ -0,0 +1,548 @@ + + */ +class Build extends BaseBuild +{ + const STAGE_SETUP = 'setup'; + const STAGE_TEST = 'test'; + const STAGE_DEPLOY = 'deploy'; + const STAGE_COMPLETE = 'complete'; + const STAGE_SUCCESS = 'success'; + const STAGE_FAILURE = 'failure'; + const STAGE_FIXED = 'fixed'; + const STAGE_BROKEN = 'broken'; + + /** + * @var integer + */ + protected $newErrorsCount = null; + + /** + * @var string + */ + protected $buildDirectory; + + /** + * @var string + */ + protected $buildBranchDirectory; + + /** + * @return Project|null + */ + public function getProject() + { + $projectId = $this->getProjectId(); + if (!$projectId) { + return null; + } + + /** @var ProjectStore $projectStore */ + $projectStore = Factory::getStore('Project'); + + return $projectStore->getById($projectId); + } + + /** + * @param string $name + * @param mixed $value + */ + public function addExtraValue($name, $value) + { + $extra = json_decode($this->data['extra'], true); + if ($extra === false) { + $extra = []; + } + $extra[$name] = $value; + $this->setExtra($extra); + } + + /** + * Set the value of status only if it synced with db. Must not be null. + * + * @param integer $value + * + * @return boolean + */ + public function setStatusSync($value) + { + $this->validateNotNull('status', $value); + $this->validateInt('status', $value); + + if ($this->data['status'] !== $value) { + $store = Factory::getStore('Build'); + if ($store->updateStatusSync($this, $value)) { + $this->data['status'] = $value; + return true; + } + } + return false; + } + + /** + * Get BuildError models by BuildId for this Build. + * + * @return \PHPCensor\Model\BuildError[] + */ + public function getBuildBuildErrors() + { + return Factory::getStore('BuildError')->getByBuildId($this->getId()); + } + + /** + * Get BuildMeta models by BuildId for this Build. + * + * @return \PHPCensor\Model\BuildMeta[] + */ + public function getBuildBuildMetas() + { + return Factory::getStore('BuildMeta')->getByBuildId($this->getId()); + } + + /** + * Get link to commit from another source (i.e. Github) + */ + public function getCommitLink() + { + return '#'; + } + + /** + * Get link to branch from another source (i.e. Github) + */ + public function getBranchLink() + { + return '#'; + } + + /** + * Get remote branch (from pull request) from another source (i.e. Github) + */ + public function getRemoteBranch() + { + return $this->getExtra('remote_branch'); + } + + /** + * Get link to remote branch (from pull request) from another source (i.e. Github) + */ + public function getRemoteBranchLink() + { + return '#'; + } + + /** + * Get link to tag from another source (i.e. Github) + */ + public function getTagLink() + { + return '#'; + } + + /** + * Return a template to use to generate a link to a specific file. + * + * @return null + */ + public function getFileLinkTemplate() + { + return null; + } + + /** + * Send status updates to any relevant third parties (i.e. Github) + */ + public function sendStatusPostback() + { + return false; + } + + /** + * @return string + */ + public function getProjectTitle() + { + $project = $this->getProject(); + return $project ? $project->getTitle() : ""; + } + + /** + * Store build metadata + * + * @param string $key + * @param string $value + */ + public function storeMeta($key, $value) + { + $value = json_encode($value); + Factory::getStore('Build')->setMeta($this->getId(), $key, $value); + } + + /** + * Is this build successful? + */ + public function isSuccessful() + { + return ($this->getStatus() === self::STATUS_SUCCESS); + } + + /** + * @param Builder $builder + * @param string $buildPath + * + * @return bool + */ + protected function handleConfig(Builder $builder, $buildPath) + { + $buildConfig = $this->getProject()->getBuildConfig(); + + if (empty($buildConfig)) { + if (file_exists($buildPath . '/.php-censor.yml')) { + $buildConfig = file_get_contents($buildPath . '/.php-censor.yml'); + } elseif (file_exists($buildPath . '/.phpci.yml')) { + $buildConfig = file_get_contents($buildPath . '/.phpci.yml'); + } elseif (file_exists($buildPath . '/phpci.yml')) { + $buildConfig = file_get_contents($buildPath . '/phpci.yml'); + } else { + $buildConfig = $this->getZeroConfigPlugins($builder); + } + } + + // for YAML configs from files/DB + if (is_string($buildConfig)) { + $yamlParser = new YamlParser(); + $buildConfig = $yamlParser->parse($buildConfig); + } + + $builder->setConfigArray($buildConfig); + + return true; + } + + /** + * Get an array of plugins to run if there's no .php-censor.yml file. + * + * @param Builder $builder + * + * @return array + */ + protected function getZeroConfigPlugins(Builder $builder) + { + $pluginDir = SRC_DIR . 'Plugin/'; + $dir = new \DirectoryIterator($pluginDir); + + $config = [ + 'build_settings' => [ + 'ignore' => [ + 'vendor', + ] + ] + ]; + + foreach ($dir as $item) { + if ($item->isDot()) { + continue; + } + + if (!$item->isFile()) { + continue; + } + + if ($item->getExtension() != 'php') { + continue; + } + + $className = '\PHPCensor\Plugin\\'.$item->getBasename('.php'); + + $reflectedPlugin = new \ReflectionClass($className); + + if (!$reflectedPlugin->implementsInterface('\PHPCensor\ZeroConfigPluginInterface')) { + continue; + } + + foreach ([Build::STAGE_SETUP, Build::STAGE_TEST] as $stage) { + if ($className::canExecute($stage, $builder, $this)) { + $config[$stage][$className::pluginName()] = [ + 'zero_config' => true + ]; + } + } + } + + return $config; + } + + /** + * Allows specific build types (e.g. Github) to report violations back to their respective services. + * + * @param Builder $builder + * @param string $plugin + * @param string $message + * @param integer $severity + * @param string $file + * @param integer $lineStart + * @param integer $lineEnd + */ + public function reportError( + Builder $builder, + $plugin, + $message, + $severity = BuildError::SEVERITY_NORMAL, + $file = null, + $lineStart = null, + $lineEnd = null + ) { + $writer = $builder->getBuildErrorWriter(); + $writer->write( + $plugin, + $message, + $severity, + $file, + $lineStart, + $lineEnd + ); + } + + /** + * @return string|null + */ + public function getBuildDirectory() + { + if (!$this->getId()) { + return null; + } + + $createDate = $this->getCreateDate(); + if (empty($this->buildDirectory)) { + $this->buildDirectory = $this->getProjectId() . '/' . $this->getId() . '_' . substr( + md5(($this->getId() . '_' . ($createDate ? $createDate->format('Y-m-d H:i:s') : null)) + ), 0, 8); + } + + return $this->buildDirectory; + } + + /** + * @return string|null + */ + public function getBuildBranchDirectory() + { + if (!$this->getId()) { + return null; + } + + $createDate = $this->getCreateDate(); + if (empty($this->buildBranchDirectory)) { + $this->buildBranchDirectory = $this->getProjectId() . '/' . $this->getBranch() . '_' . substr( + md5(($this->getBranch() . '_' . ($createDate ? $createDate->format('Y-m-d H:i:s') : null)) + ), 0, 8); + } + + return $this->buildBranchDirectory; + } + + /** + * @return string|null + */ + public function getBuildPath() + { + if (!$this->getId()) { + return null; + } + + return RUNTIME_DIR . 'builds/' . $this->getBuildDirectory() . '/'; + } + + /** + * Removes the build directory. + * + * @param boolean $withArtifacts + */ + public function removeBuildDirectory($withArtifacts = false) + { + // Get the path and remove the trailing slash as this may prompt PHP + // to see this as a directory even if it's a link. + $buildPath = rtrim($this->getBuildPath(), '/'); + + if (!$buildPath || !is_dir($buildPath)) { + return; + } + + try { + $fileSystem = new Filesystem(); + + if (is_link($buildPath)) { + // Remove the symlink without using recursive. + exec(sprintf('rm "%s"', $buildPath)); + } else { + $fileSystem->remove($buildPath); + } + + if ($withArtifacts) { + $buildDirectory = $this->getBuildDirectory(); + + $fileSystem->remove(PUBLIC_DIR . 'artifacts/pdepend/' . $buildDirectory); + $fileSystem->remove(PUBLIC_DIR . 'artifacts/phpunit/' . $buildDirectory); + } + } catch (\Exception $e) { + + } + } + + /** + * Get the number of seconds a build has been running for. + * + * @return integer + */ + public function getDuration() + { + $start = $this->getStartDate(); + + if (empty($start)) { + return 0; + } + + $end = $this->getFinishDate(); + + if (empty($end)) { + $end = new \DateTime(); + } + + return $end->getTimestamp() - $start->getTimestamp(); + } + + /** + * get time a build has been running for in hour/minute/seconds format (e.g. 1h 21m 45s) + * + * @return string + */ + public function getPrettyDuration() + { + $start = $this->getStartDate(); + if (!$start) { + $start = new \DateTime(); + } + $end = $this->getFinishDate(); + if (!$end) { + $end = new \DateTime(); + } + + $diff = date_diff($start, $end); + $parts = []; + foreach (['y', 'm', 'd', 'h', 'i', 's'] as $timePart) { + if ($diff->{$timePart} != 0) { + $parts[] = $diff->{$timePart} . ($timePart == 'i' ? 'm' : $timePart); + } + } + + return implode(" ", $parts); + } + + /** + * Create a working copy by cloning, copying, or similar. + * + * @param Builder $builder + * @param string $buildPath + * + * @return boolean + */ + public function createWorkingCopy(Builder $builder, $buildPath) + { + return false; + } + + /** + * Create an SSH key file on disk for this build. + * + * @param string $cloneTo + * + * @return string + */ + protected function writeSshKey($cloneTo) + { + $keyPath = dirname($cloneTo . '/temp'); + $keyFile = $keyPath . '.key'; + + file_put_contents($keyFile, $this->getProject()->getSshPrivateKey()); + chmod($keyFile, 0600); + + return $keyFile; + } + + /** + * Create an SSH wrapper script for Svn to use, to disable host key checking, etc. + * + * @param string $cloneTo + * @param string $keyFile + * + * @return string + */ + protected function writeSshWrapper($cloneTo, $keyFile) + { + $path = dirname($cloneTo . '/temp'); + $wrapperFile = $path . '.sh'; + + $sshFlags = '-o CheckHostIP=no -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o PasswordAuthentication=no'; + + // Write out the wrapper script for this build: + $script = <<getSource()) { + case Build::SOURCE_WEBHOOK: + return 'source_webhook'; + case Build::SOURCE_WEBHOOK_PULL_REQUEST: + return 'source_webhook_pull_request'; + case Build::SOURCE_MANUAL_WEB: + return 'source_manual_web'; + case Build::SOURCE_MANUAL_CONSOLE: + return 'source_manual_console'; + case Build::SOURCE_PERIODICAL: + return 'source_periodical'; + case Build::SOURCE_UNKNOWN: + default: + return 'source_unknown'; + } + } + + /** + * @return integer + */ + public function getNewErrorsCount() + { + if (null === $this->newErrorsCount) { + /** @var BuildErrorStore $store */ + $store = Factory::getStore('BuildError'); + + $this->newErrorsCount = $store->getNewErrorsCount($this->getId()); + } + + return $this->newErrorsCount; + } +} diff --git a/src/PHPCensor/Model/Build/BitbucketBuild.php b/src/Model/Build/BitbucketBuild.php similarity index 99% rename from src/PHPCensor/Model/Build/BitbucketBuild.php rename to src/Model/Build/BitbucketBuild.php index 3b29d38d..412e28d7 100644 --- a/src/PHPCensor/Model/Build/BitbucketBuild.php +++ b/src/Model/Build/BitbucketBuild.php @@ -6,7 +6,7 @@ use GuzzleHttp\Client; use PHPCensor\Builder; use PHPCensor\Helper\Bitbucket; use PHPCensor\Helper\Diff; -use b8\Config; +use PHPCensor\Config; use PHPCensor\Model\Build; use PHPCensor\Model\BuildError; diff --git a/src/PHPCensor/Model/Build/BitbucketHgBuild.php b/src/Model/Build/BitbucketHgBuild.php similarity index 100% rename from src/PHPCensor/Model/Build/BitbucketHgBuild.php rename to src/Model/Build/BitbucketHgBuild.php diff --git a/src/PHPCensor/Model/Build/GitBuild.php b/src/Model/Build/GitBuild.php similarity index 100% rename from src/PHPCensor/Model/Build/GitBuild.php rename to src/Model/Build/GitBuild.php diff --git a/src/PHPCensor/Model/Build/GithubBuild.php b/src/Model/Build/GithubBuild.php similarity index 99% rename from src/PHPCensor/Model/Build/GithubBuild.php rename to src/Model/Build/GithubBuild.php index b3968b93..778d11d9 100644 --- a/src/PHPCensor/Model/Build/GithubBuild.php +++ b/src/Model/Build/GithubBuild.php @@ -6,7 +6,7 @@ use GuzzleHttp\Client; use PHPCensor\Builder; use PHPCensor\Helper\Diff; use PHPCensor\Helper\Github; -use b8\Config; +use PHPCensor\Config; use PHPCensor\Model\Build; use PHPCensor\Model\BuildError; @@ -161,7 +161,7 @@ class GithubBuild extends GitBuild $project = $this->getProject(); if (!is_null($project)) { - $reference = $project->getReference(); + $reference = $project->getReference(); $commitLink = '#$1'; $rtn = preg_replace('/\#([0-9]+)/', $commitLink, $rtn); $rtn = preg_replace('/\@([a-zA-Z0-9_]+)/', '@$1', $rtn); diff --git a/src/PHPCensor/Model/Build/GitlabBuild.php b/src/Model/Build/GitlabBuild.php similarity index 92% rename from src/PHPCensor/Model/Build/GitlabBuild.php rename to src/Model/Build/GitlabBuild.php index ad5a30b9..56252e75 100644 --- a/src/PHPCensor/Model/Build/GitlabBuild.php +++ b/src/Model/Build/GitlabBuild.php @@ -49,9 +49,9 @@ class GitlabBuild extends GitBuild $key = trim($this->getProject()->getSshPrivateKey()); if (!empty($key)) { - $user = $this->getProject()->getAccessInformation("user"); + $user = $this->getProject()->getAccessInformation("user"); $domain = $this->getProject()->getAccessInformation("domain"); - $port = $this->getProject()->getAccessInformation('port'); + $port = $this->getProject()->getAccessInformation('port'); $url = $user . '@' . $domain . ':'; diff --git a/src/PHPCensor/Model/Build/GogsBuild.php b/src/Model/Build/GogsBuild.php similarity index 100% rename from src/PHPCensor/Model/Build/GogsBuild.php rename to src/Model/Build/GogsBuild.php diff --git a/src/PHPCensor/Model/Build/HgBuild.php b/src/Model/Build/HgBuild.php similarity index 100% rename from src/PHPCensor/Model/Build/HgBuild.php rename to src/Model/Build/HgBuild.php diff --git a/src/PHPCensor/Model/Build/LocalBuild.php b/src/Model/Build/LocalBuild.php similarity index 100% rename from src/PHPCensor/Model/Build/LocalBuild.php rename to src/Model/Build/LocalBuild.php diff --git a/src/PHPCensor/Model/Build/SvnBuild.php b/src/Model/Build/SvnBuild.php similarity index 100% rename from src/PHPCensor/Model/Build/SvnBuild.php rename to src/Model/Build/SvnBuild.php diff --git a/src/Model/BuildError.php b/src/Model/BuildError.php new file mode 100644 index 00000000..9c995dc4 --- /dev/null +++ b/src/Model/BuildError.php @@ -0,0 +1,109 @@ +getBuildId(); + if (empty($buildId)) { + return null; + } + + /** @var BuildStore $buildStore */ + $buildStore = Factory::getStore('Build'); + + return $buildStore->getById($buildId); + } + + /** + * Get the language string key for this error's severity level. + * + * @return string + */ + public function getSeverityString() + { + switch ($this->getSeverity()) { + case self::SEVERITY_CRITICAL: + return 'critical'; + + case self::SEVERITY_HIGH: + return 'high'; + + case self::SEVERITY_NORMAL: + return 'normal'; + + case self::SEVERITY_LOW: + return 'low'; + } + } + + /** + * Get the language string key for this error's severity level. + * + * @param integer $severity + * + * @return string + */ + public static function getSeverityName($severity) + { + switch ($severity) { + case self::SEVERITY_CRITICAL: + return 'critical'; + + case self::SEVERITY_HIGH: + return 'high'; + + case self::SEVERITY_NORMAL: + return 'normal'; + + case self::SEVERITY_LOW: + return 'low'; + } + } + + /** + * @param string $plugin + * @param string $file + * @param integer $lineStart + * @param integer $lineEnd + * @param integer $severity + * @param string $message + * + * @return string + */ + public static function generateHash($plugin, $file, $lineStart, $lineEnd, $severity, $message) + { + return md5($plugin . $file . $lineStart . $lineEnd . $severity . $message); + } + + /** + * Get the class to apply to HTML elements representing this error. + * + * @return string + */ + public function getSeverityClass() + { + switch ($this->getSeverity()) { + case self::SEVERITY_CRITICAL: + return 'danger'; + + case self::SEVERITY_HIGH: + return 'warning'; + + case self::SEVERITY_NORMAL: + return 'info'; + + case self::SEVERITY_LOW: + return 'default'; + } + } +} diff --git a/src/Model/BuildMeta.php b/src/Model/BuildMeta.php new file mode 100644 index 00000000..b6e09dd7 --- /dev/null +++ b/src/Model/BuildMeta.php @@ -0,0 +1,26 @@ +getBuildId(); + if (empty($buildId)) { + return null; + } + + /** @var BuildStore $buildStore */ + $buildStore = Factory::getStore('Build'); + + return $buildStore->getById($buildId); + } +} diff --git a/src/Model/Environment.php b/src/Model/Environment.php new file mode 100644 index 00000000..acac8908 --- /dev/null +++ b/src/Model/Environment.php @@ -0,0 +1,9 @@ + + */ +class Project extends BaseProject +{ + /** + * @return ProjectGroup|null + */ + public function getGroup() + { + $groupId = $this->getGroupId(); + if (empty($groupId)) { + return null; + } + + /** @var ProjectGroupStore $groupStore */ + $groupStore = Factory::getStore('ProjectGroup'); + + return $groupStore->getById($groupId); + } + + /** + * Get Build models by ProjectId for this Project. + * + * @return \PHPCensor\Model\Build[] + */ + public function getProjectBuilds() + { + return Factory::getStore('Build')->getByProjectId($this->getId()); + } + + /** + * Return the latest build from a specific branch, of a specific status, for this project. + * + * @param string $branch + * @param null $status + * + * @return mixed|null + */ + public function getLatestBuild($branch = 'master', $status = null) + { + $criteria = ['branch' => $branch, 'project_id' => $this->getId()]; + + if (isset($status)) { + $criteria['status'] = $status; + } + + $order = ['id' => 'DESC']; + $builds = Factory::getStore('Build')->getWhere($criteria, 1, 0, $order); + + if (is_array($builds['items']) && count($builds['items'])) { + $latest = array_shift($builds['items']); + + if (isset($latest) && $latest instanceof Build) { + return $latest; + } + } + + return null; + } + + /** + * Return the previous build from a specific branch, for this project. + * + * @param string $branch + * + * @return mixed|null + */ + public function getPreviousBuild($branch = 'master') + { + $criteria = ['branch' => $branch, 'project_id' => $this->getId()]; + $order = ['id' => 'DESC']; + $builds = Factory::getStore('Build')->getWhere($criteria, 1, 1, $order); + + if (is_array($builds['items']) && count($builds['items'])) { + $previous = array_shift($builds['items']); + + if (isset($previous) && $previous instanceof Build) { + return $previous; + } + } + + return null; + } + + /** + * Return the name of a FontAwesome icon to represent this project, depending on its type. + * + * @return string + */ + public function getIcon() + { + switch ($this->getType()) { + case 'github': + $icon = 'github'; + break; + + case 'bitbucket': + case 'bitbucket-hg': + $icon = 'bitbucket'; + break; + + case 'git': + case 'gitlab': + case 'gogs': + default: + $icon = 'code-fork'; + break; + } + + return $icon; + } + + /** + * @return EnvironmentStore + */ + protected function getEnvironmentStore() + { + /** @var EnvironmentStore $store */ + $store = Factory::getStore('Environment'); + return $store; + } + + /** + * Get Environments + * + * @return array contain items with \PHPCensor\Model\Environment + */ + public function getEnvironmentsObjects() + { + $projectId = $this->getId(); + + if (empty($projectId)) { + return null; + } + + return $this->getEnvironmentStore()->getByProjectId($projectId); + } + + /** + * Get Environments + * + * @return string[] + */ + public function getEnvironmentsNames() + { + $environments = $this->getEnvironmentsObjects(); + $environmentsNames = []; + foreach($environments['items'] as $environment) { + /** @var Environment $environment */ + $environmentsNames[] = $environment->getName(); + } + + return $environmentsNames; + } + + /** + * Get Environments + * + * @return string yaml + */ + public function getEnvironments() + { + $environments = $this->getEnvironmentsObjects(); + $environmentsConfig = []; + foreach($environments['items'] as $environment) { + /** @var Environment $environment */ + $environmentsConfig[$environment->getName()] = $environment->getBranches(); + } + + $yamlDumper = new YamlDumper(); + $value = $yamlDumper->dump($environmentsConfig, 10, 0, true, false); + + return $value; + } + + /** + * Set Environments + * + * @param string $value yaml + */ + public function setEnvironments($value) + { + $yamlParser = new YamlParser(); + $environmentsConfig = $yamlParser->parse($value); + $environmentsNames = !empty($environmentsConfig) ? array_keys($environmentsConfig) : []; + $currentEnvironments = $this->getEnvironmentsObjects(); + $store = $this->getEnvironmentStore(); + foreach ($currentEnvironments['items'] as $environment) { + /** @var Environment $environment */ + $key = array_search($environment->getName(), $environmentsNames); + if ($key !== false) { + // already exist + unset($environmentsNames[$key]); + $environment->setBranches(!empty($environmentsConfig[$environment->getName()]) ? $environmentsConfig[$environment->getName()] : []); + $store->save($environment); + } else { + // remove + $store->delete($environment); + } + } + + if (!empty($environmentsNames)) { + // add + foreach ($environmentsNames as $environmentName) { + $environment = new Environment(); + $environment->setProjectId($this->getId()); + $environment->setName($environmentName); + $environment->setBranches(!empty($environmentsConfig[$environment->getName()]) ? $environmentsConfig[$environment->getName()] : []); + $store->save($environment); + } + } + } + + /** + * @param string $branch + * + * @return string[] + */ + public function getEnvironmentsNamesByBranch($branch) + { + $environmentsNames = []; + $environments = $this->getEnvironmentsObjects(); + $defaultBranch = ($branch == $this->getBranch()); + foreach($environments['items'] as $environment) { + /** @var Environment $environment */ + if ($defaultBranch || in_array($branch, $environment->getBranches())) { + $environmentsNames[] = $environment->getName(); + } + } + + return $environmentsNames; + } + + /** + * @param string $environmentName + * + * @return string[] + */ + public function getBranchesByEnvironment($environmentName) + { + $branches = []; + $environments = $this->getEnvironmentsObjects(); + foreach($environments['items'] as $environment) { + /** @var Environment $environment */ + if ($environmentName == $environment->getName()) { + return $environment->getBranches(); + } + } + + return $branches; + } +} diff --git a/src/Model/ProjectGroup.php b/src/Model/ProjectGroup.php new file mode 100644 index 00000000..05ab3b39 --- /dev/null +++ b/src/Model/ProjectGroup.php @@ -0,0 +1,21 @@ +getByGroupId($this->getId(), false); + } +} diff --git a/src/Model/User.php b/src/Model/User.php new file mode 100644 index 00000000..bc90c9d8 --- /dev/null +++ b/src/Model/User.php @@ -0,0 +1,25 @@ + + */ +class User extends BaseUser +{ + /** + * @return integer + */ + public function getFinalPerPage() + { + $perPage = $this->getPerPage(); + if ($perPage) { + return $perPage; + } + + return (integer)Config::getInstance()->get('php-censor.per_page', 10); + } +} diff --git a/src/PHPCensor/Application.php b/src/PHPCensor/Application.php deleted file mode 100644 index 514626a6..00000000 --- a/src/PHPCensor/Application.php +++ /dev/null @@ -1,167 +0,0 @@ - - */ -class Application extends b8\Application -{ - /** - * @var \PHPCensor\Controller - */ - protected $controller; - - /** - * Initialise Application - Handles session verification, routing, etc. - */ - public function init() - { - $request =& $this->request; - $route = '/:controller/:action'; - $opts = ['controller' => 'Home', 'action' => 'index']; - - // Inlined as a closure to fix "using $this when not in object context" on 5.3 - $validateSession = function () { - if (!empty($_SESSION['php-censor-user-id'])) { - $user = b8\Store\Factory::getStore('User')->getByPrimaryKey($_SESSION['php-censor-user-id']); - - if ($user) { - return true; - } - } - - return false; - }; - - $skipAuth = [$this, 'shouldSkipAuth']; - - // Handler for the route we're about to register, checks for a valid session where necessary: - $routeHandler = function (&$route, Response &$response) use (&$request, $validateSession, $skipAuth) { - $skipValidation = in_array($route['controller'], ['session', 'webhook', 'build-status']); - - if (!$skipValidation && !$validateSession() && (!is_callable($skipAuth) || !$skipAuth())) { - if ($request->isAjax()) { - $response->setResponseCode(401); - $response->setContent(''); - } else { - $_SESSION['php-censor-login-redirect'] = substr($request->getPath(), 1); - $response = new RedirectResponse($response); - $response->setHeader('Location', APP_URL . 'session/login'); - } - - return false; - } - - return true; - }; - - $this->router->clearRoutes(); - $this->router->register($route, $opts, $routeHandler); - } - - /** - * Handle an incoming web request. - * - * @return Response - */ - public function handleRequest() - { - try { - $this->response = parent::handleRequest(); - } catch (HttpException $ex) { - $this->config->set('page_title', 'Error'); - - $view = new View('exception'); - $view->exception = $ex; - - $this->response->setResponseCode($ex->getErrorCode()); - $this->response->setContent($view->render()); - } catch (\Exception $ex) { - $this->config->set('page_title', 'Error'); - - $view = new View('exception'); - $view->exception = $ex; - - $this->response->setResponseCode(500); - $this->response->setContent($view->render()); - } - - if ($this->response->hasLayout() && $this->controller && $this->controller->layout) { - $this->setLayoutVariables($this->controller->layout); - - $this->controller->layout->content = $this->response->getContent(); - $this->response->setContent($this->controller->layout->render()); - } - - return $this->response; - } - - /** - * Loads a particular controller, and injects our layout view into it. - * - * @param string $class - * - * @return b8\Controller - */ - protected function loadController($class) - { - $controller = parent::loadController($class); - $controller->layout = new View('layout'); - $controller->layout->title = 'PHP Censor'; - $controller->layout->breadcrumb = []; - $controller->layout->version = trim(file_get_contents(ROOT_DIR . 'VERSION.md')); - - return $controller; - } - - /** - * Injects variables into the layout before rendering it. - * - * @param View $layout - */ - protected function setLayoutVariables(View &$layout) - { - $groups = []; - $groupStore = b8\Store\Factory::getStore('ProjectGroup'); - $groupList = $groupStore->getWhere([], 100, 0, ['title' => 'ASC']); - - foreach ($groupList['items'] as $group) { - $thisGroup = ['title' => $group->getTitle()]; - $projects = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId(), false); - $thisGroup['projects'] = $projects['items']; - $groups[] = $thisGroup; - } - - $archived_projects = b8\Store\Factory::getStore('Project')->getAll(true); - $layout->archived_projects = $archived_projects['items']; - $layout->groups = $groups; - } - - /** - * Check whether we should skip auth (because it is disabled) - * - * @return boolean - */ - protected function shouldSkipAuth() - { - $config = b8\Config::getInstance(); - $disableAuth = (bool)$config->get('php-censor.security.disable_auth', false); - $defaultUserId = (integer)$config->get('php-censor.security.default_user_id', 1); - - if ($disableAuth && $defaultUserId) { - $user = b8\Store\Factory::getStore('User')->getByPrimaryKey($defaultUserId); - - if ($user) { - return true; - } - } - - return false; - } -} diff --git a/src/PHPCensor/Controller.php b/src/PHPCensor/Controller.php deleted file mode 100644 index 02276580..00000000 --- a/src/PHPCensor/Controller.php +++ /dev/null @@ -1,152 +0,0 @@ -className = substr(array_pop($class), 0, -10); - $this->setControllerView(); - - unset($_SESSION['php-censor-user']); - } - - /** - * Set the view that this controller should use. - */ - protected function setControllerView() - { - if (View::exists($this->className)) { - $this->controllerView = new View($this->className); - } else { - $this->controllerView = new View('{@content}'); - } - } - - /** - * Set the view that this controller action should use. - * - * @param string $action - */ - protected function setView($action) - { - if (View::exists($this->className . '/' . $action)) { - $this->view = new View($this->className . '/' . $action); - } - } - - /** - * Handle the incoming request. - * - * @param string $action - * @param array $actionParams - * - * @return Response - */ - public function handleAction($action, $actionParams) - { - $this->setView($action); - $response = parent::handleAction($action, $actionParams); - - if ($response instanceof Response) { - return $response; - } - - if (is_string($response)) { - $this->controllerView->content = $response; - } elseif (isset($this->view)) { - $this->controllerView->content = $this->view->render(); - } - - $this->response->setContent($this->controllerView->render()); - - return $this->response; - } - - /** - * Require that the currently logged in user is an administrator. - * - * @throws ForbiddenException - */ - protected function requireAdmin() - { - if (!$this->currentUserIsAdmin()) { - throw new ForbiddenException('You do not have permission to do that.'); - } - } - - /** - * Check if the currently logged in user is an administrator. - * - * @return boolean - */ - protected function currentUserIsAdmin() - { - $user = $this->getUser(); - if (!$user) { - return false; - } - - return $this->getUser()->getIsAdmin(); - } - - /** - * @return User|null - */ - protected function getUser() - { - if (empty($_SESSION['php-censor-user-id'])) { - return null; - } - - /** @var UserStore $userStore */ - $userStore = Factory::getStore('User'); - - return $userStore->getById($_SESSION['php-censor-user-id']); - } -} diff --git a/src/PHPCensor/Helper/BuildInterpolator.php b/src/PHPCensor/Helper/BuildInterpolator.php deleted file mode 100644 index f6458051..00000000 --- a/src/PHPCensor/Helper/BuildInterpolator.php +++ /dev/null @@ -1,85 +0,0 @@ - value pairs that will be used for - * interpolation and environment variables - * @var mixed[] - * @see setupInterpolationVars() - */ - protected $interpolation_vars = []; - - /** - * Sets the variables that will be used for interpolation. - * - * @param BaseBuild $build - * @param string $buildPath - * @param string $url - */ - public function setupInterpolationVars(BaseBuild $build, $buildPath, $url) - { - $this->interpolation_vars = []; - $this->interpolation_vars['%PHPCI%'] = 1; - $this->interpolation_vars['%COMMIT%'] = $build->getCommitId(); - $this->interpolation_vars['%SHORT_COMMIT%'] = substr($build->getCommitId(), 0, 7); - $this->interpolation_vars['%COMMIT_EMAIL%'] = $build->getCommitterEmail(); - $this->interpolation_vars['%COMMIT_MESSAGE%'] = $build->getCommitMessage(); - $this->interpolation_vars['%COMMIT_URI%'] = $build->getCommitLink(); - $this->interpolation_vars['%BRANCH%'] = $build->getBranch(); - $this->interpolation_vars['%BRANCH_URI%'] = $build->getBranchLink(); - $this->interpolation_vars['%ENVIRONMENT%'] = $build->getEnvironment(); - $this->interpolation_vars['%PROJECT%'] = $build->getProjectId(); - $this->interpolation_vars['%BUILD%'] = $build->getId(); - $this->interpolation_vars['%PROJECT_TITLE%'] = $build->getProjectTitle(); - $this->interpolation_vars['%PROJECT_URI%'] = $url . "project/view/" . $build->getProjectId(); - $this->interpolation_vars['%BUILD_PATH%'] = $buildPath; - $this->interpolation_vars['%BUILD_URI%'] = $url . "build/view/" . $build->getId(); - $this->interpolation_vars['%PHPCI_COMMIT%'] = $this->interpolation_vars['%COMMIT%']; - $this->interpolation_vars['%PHPCI_SHORT_COMMIT%'] = $this->interpolation_vars['%SHORT_COMMIT%']; - $this->interpolation_vars['%PHPCI_COMMIT_MESSAGE%'] = $this->interpolation_vars['%COMMIT_MESSAGE%']; - $this->interpolation_vars['%PHPCI_COMMIT_EMAIL%'] = $this->interpolation_vars['%COMMIT_EMAIL%']; - $this->interpolation_vars['%PHPCI_COMMIT_URI%'] = $this->interpolation_vars['%COMMIT_URI%']; - $this->interpolation_vars['%PHPCI_PROJECT%'] = $this->interpolation_vars['%PROJECT%']; - $this->interpolation_vars['%PHPCI_BUILD%'] = $this->interpolation_vars['%BUILD%']; - $this->interpolation_vars['%PHPCI_PROJECT_TITLE%'] = $this->interpolation_vars['%PROJECT_TITLE%']; - $this->interpolation_vars['%PHPCI_PROJECT_URI%'] = $this->interpolation_vars['%PROJECT_URI%']; - $this->interpolation_vars['%PHPCI_BUILD_PATH%'] = $this->interpolation_vars['%BUILD_PATH%']; - $this->interpolation_vars['%PHPCI_BUILD_URI%'] = $this->interpolation_vars['%BUILD_URI%']; - - putenv('PHPCI=1'); - putenv('PHPCI_COMMIT=' . $this->interpolation_vars['%COMMIT%']); - putenv('PHPCI_SHORT_COMMIT=' . $this->interpolation_vars['%SHORT_COMMIT%']); - putenv('PHPCI_COMMIT_MESSAGE=' . $this->interpolation_vars['%COMMIT_MESSAGE%']); - putenv('PHPCI_COMMIT_EMAIL=' . $this->interpolation_vars['%COMMIT_EMAIL%']); - putenv('PHPCI_COMMIT_URI=' . $this->interpolation_vars['%COMMIT_URI%']); - putenv('PHPCI_PROJECT=' . $this->interpolation_vars['%PROJECT%']); - putenv('PHPCI_BUILD=' . $this->interpolation_vars['%BUILD%']); - putenv('PHPCI_PROJECT_TITLE=' . $this->interpolation_vars['%PROJECT_TITLE%']); - putenv('PHPCI_BUILD_PATH=' . $this->interpolation_vars['%BUILD_PATH%']); - putenv('PHPCI_BUILD_URI=' . $this->interpolation_vars['%BUILD_URI%']); - putenv('PHPCI_ENVIRONMENT=' . $this->interpolation_vars['%ENVIRONMENT%']); - } - - /** - * Replace every occurrence of the interpolation vars in the given string - * Example: "This is build %PHPCI_BUILD%" => "This is build 182" - * @param string $input - * @return string - */ - public function interpolate($input) - { - $keys = array_keys($this->interpolation_vars); - $values = array_values($this->interpolation_vars); - return str_replace($keys, $values, $input); - } -} diff --git a/src/PHPCensor/Model.php b/src/PHPCensor/Model.php deleted file mode 100644 index b11c4ada..00000000 --- a/src/PHPCensor/Model.php +++ /dev/null @@ -1,7 +0,0 @@ - - */ -class Build extends Model -{ - const STAGE_SETUP = 'setup'; - const STAGE_TEST = 'test'; - const STAGE_DEPLOY = 'deploy'; - const STAGE_COMPLETE = 'complete'; - const STAGE_SUCCESS = 'success'; - const STAGE_FAILURE = 'failure'; - const STAGE_FIXED = 'fixed'; - const STAGE_BROKEN = 'broken'; - - const STATUS_PENDING = 0; - const STATUS_RUNNING = 1; - const STATUS_SUCCESS = 2; - const STATUS_FAILED = 3; - - const SOURCE_UNKNOWN = 0; - const SOURCE_MANUAL_WEB = 1; - const SOURCE_MANUAL_CONSOLE = 2; - const SOURCE_PERIODICAL = 3; - const SOURCE_WEBHOOK = 4; - const SOURCE_WEBHOOK_PULL_REQUEST = 5; - - /** - * @var string - */ - protected $tableName = 'build'; - - /** - * @var integer - */ - protected $newErrorsCount = null; - - /** - * @var string - */ - protected $buildDirectory; - - /** - * @var string - */ - protected $buildBranchDirectory; - - /** - * @var array - */ - protected $data = [ - 'id' => null, - 'project_id' => null, - 'commit_id' => null, - 'status' => null, - 'log' => null, - 'branch' => null, - 'tag' => null, - 'create_date' => null, - 'start_date' => null, - 'finish_date' => null, - 'committer_email' => null, - 'commit_message' => null, - 'extra' => null, - 'environment' => null, - 'source' => Build::SOURCE_UNKNOWN, - 'user_id' => 0, - ]; - - /** - * @var array - */ - protected $getters = [ - // Direct property getters: - 'id' => 'getId', - 'project_id' => 'getProjectId', - 'commit_id' => 'getCommitId', - 'status' => 'getStatus', - 'log' => 'getLog', - 'branch' => 'getBranch', - 'tag' => 'getTag', - 'create_date' => 'getCreateDate', - 'start_date' => 'getStartDate', - 'finish_date' => 'getFinishDate', - 'committer_email' => 'getCommitterEmail', - 'commit_message' => 'getCommitMessage', - 'extra' => 'getExtra', - 'environment' => 'getEnvironment', - 'source' => 'getSource', - 'user_id' => 'getUserId', - - // Foreign key getters: - 'Project' => 'getProject', - ]; - - /** - * @var array - */ - protected $setters = [ - // Direct property setters: - 'id' => 'setId', - 'project_id' => 'setProjectId', - 'commit_id' => 'setCommitId', - 'status' => 'setStatus', - 'log' => 'setLog', - 'branch' => 'setBranch', - 'setTag' => 'setTag', - 'create_date' => 'setCreateDate', - 'start_date' => 'setStartDate', - 'finish_date' => 'setFinishDate', - 'committer_email' => 'setCommitterEmail', - 'commit_message' => 'setCommitMessage', - 'extra' => 'setExtra', - 'environment' => 'setEnvironment', - 'source' => 'setSource', - 'user_id' => 'setUserId', - - // Foreign key setters: - 'Project' => 'setProject', - ]; - - /** - * @return integer - */ - public function getId() - { - $rtn = $this->data['id']; - - return (integer)$rtn; - } - - /** - * @param $value int - */ - public function setId($value) - { - $this->validateNotNull('id', $value); - $this->validateInt('id', $value); - - if ($this->data['id'] === $value) { - return; - } - - $this->data['id'] = $value; - - $this->setModified('id'); - } - - /** - * @return integer - */ - public function getProjectId() - { - $rtn = $this->data['project_id']; - - return (integer)$rtn; - } - - /** - * @param $value int - */ - public function setProjectId($value) - { - $this->validateNotNull('project_id', $value); - $this->validateInt('project_id', $value); - - if ($this->data['project_id'] === $value) { - return; - } - - $this->data['project_id'] = $value; - - $this->setModified('project_id'); - } - - /** - * @return string - */ - public function getCommitId() - { - $rtn = $this->data['commit_id']; - - return $rtn; - } - - /** - * @param $value string - */ - public function setCommitId($value) - { - $this->validateNotNull('commit_id', $value); - $this->validateString('commit_id', $value); - - if ($this->data['commit_id'] === $value) { - return; - } - - $this->data['commit_id'] = $value; - - $this->setModified('commit_id'); - } - - /** - * @return integer - */ - public function getStatus() - { - $rtn = $this->data['status']; - - return (integer)$rtn; - } - - /** - * @param $value int - */ - public function setStatus($value) - { - $this->validateNotNull('status', $value); - $this->validateInt('status', $value); - - if ($this->data['status'] === $value) { - return; - } - - $this->data['status'] = $value; - - $this->setModified('status'); - } - - /** - * @return string - */ - public function getLog() - { - $rtn = $this->data['log']; - - return $rtn; - } - - /** - * @param $value string - */ - public function setLog($value) - { - $this->validateString('log', $value); - - if ($this->data['log'] === $value) { - return; - } - - $this->data['log'] = $value; - - $this->setModified('log'); - } - - /** - * @return string - */ - public function getBranch() - { - $rtn = $this->data['branch']; - - return $rtn; - } - - /** - * @param $value string - */ - public function setBranch($value) - { - $this->validateNotNull('branch', $value); - $this->validateString('branch', $value); - - if ($this->data['branch'] === $value) { - return; - } - - $this->data['branch'] = $value; - - $this->setModified('branch'); - } - - /** - * @return \DateTime - */ - public function getCreateDate() - { - $rtn = $this->data['create_date']; - - if (!empty($rtn)) { - $rtn = new \DateTime($rtn); - } - - return $rtn; - } - - /** - * @param $value \DateTime - */ - public function setCreateDate($value) - { - $this->validateDate('create_date', $value); - - if ($this->data['create_date'] === $value) { - return; - } - - $this->data['create_date'] = $value; - - $this->setModified('create_date'); - } - - /** - * @return \DateTime - */ - public function getStartDate() - { - $rtn = $this->data['start_date']; - - if (!empty($rtn)) { - $rtn = new \DateTime($rtn); - } - - return $rtn; - } - - /** - * @param $value \DateTime - */ - public function setStartDate($value) - { - $this->validateDate('start_date', $value); - - if ($this->data['start_date'] === $value) { - return; - } - - $this->data['start_date'] = $value; - - $this->setModified('start_date'); - } - - /** - * @return \DateTime - */ - public function getFinishDate() - { - $rtn = $this->data['finish_date']; - - if (!empty($rtn)) { - $rtn = new \DateTime($rtn); - } - - return $rtn; - } - - /** - * @param $value \DateTime - */ - public function setFinishDate($value) - { - $this->validateDate('finish_date', $value); - - if ($this->data['finish_date'] === $value) { - return; - } - - $this->data['finish_date'] = $value; - - $this->setModified('finish_date'); - } - - /** - * @return string - */ - public function getCommitterEmail() - { - $rtn = $this->data['committer_email']; - - return $rtn; - } - - /** - * @param $value string - */ - public function setCommitterEmail($value) - { - $this->validateString('committer_email', $value); - - if ($this->data['committer_email'] === $value) { - return; - } - - $this->data['committer_email'] = $value; - - $this->setModified('committer_email'); - } - - /** - * @return string - */ - public function getCommitMessage() - { - $rtn = htmlspecialchars($this->data['commit_message']); - - return $rtn; - } - - /** - * @param $value string - */ - public function setCommitMessage($value) - { - $this->validateString('commit_message', $value); - - if ($this->data['commit_message'] === $value) { - return; - } - - $this->data['commit_message'] = $value; - - $this->setModified('commit_message'); - } - - /** - * @return string - */ - public function getTag() - { - $rtn = $this->data['tag']; - - return $rtn; - } - - /** - * @param $value string - */ - public function setTag($value) - { - $this->validateString('tag', $value); - - if ($this->data['tag'] === $value) { - return; - } - - $this->data['tag'] = $value; - - $this->setModified('tag'); - } - - /** - * @return string - */ - public function getSource() - { - $rtn = $this->data['source']; - - return (integer)$rtn; - } - - /** - * @param $value integer - */ - public function setSource($value) - { - $this->validateInt('source', $value); - - if ($this->data['source'] === $value) { - return; - } - - $this->data['source'] = $value; - - $this->setModified('source'); - } - - /** - * @return string - */ - public function getUserId() - { - $rtn = $this->data['user_id']; - - return (integer)$rtn; - } - - /** - * @param $value integer - */ - public function setUserId($value) - { - $this->validateNotNull('user_id', $value); - $this->validateInt('user_id', $value); - - if ($this->data['user_id'] === $value) { - return; - } - - $this->data['user_id'] = $value; - - $this->setModified('user_id'); - } - - /** - * @return string - */ - public function getEnvironment() - { - $rtn = $this->data['environment']; - - return $rtn; - } - - /** - * @param $value string - */ - public function setEnvironment($value) - { - $this->validateString('environment', $value); - - if ($this->data['environment'] === $value) { - return; - } - - $this->data['environment'] = $value; - - $this->setModified('environment'); - } - - /** - * Set the value of status only if it synced with db. Must not be null. - * - * @param $value int - * @return bool - */ - public function setStatusSync($value) - { - $this->validateNotNull('status', $value); - $this->validateInt('status', $value); - - if ($this->data['status'] !== $value) { - $store = Factory::getStore('Build'); - if ($store->updateStatusSync($this, $value)) { - $this->data['status'] = $value; - return true; - } - } - return false; - } - - /** - * Return a value from the build's "extra" JSON array. - * - * @param null $key - * - * @return mixed|null|string - */ - public function getExtra($key = null) - { - $data = json_decode($this->data['extra'], true); - - if (is_null($key)) { - $rtn = $data; - } elseif (isset($data[$key])) { - $rtn = $data[$key]; - } else { - $rtn = null; - } - - return $rtn; - } - - /** - * @param $value string - */ - public function setExtra($value) - { - $this->validateString('extra', $value); - - if ($this->data['extra'] === $value) { - return; - } - - $this->data['extra'] = $value; - - $this->setModified('extra'); - } - - /** - * Set the value of extra. - * - * @param $name string - * @param $value mixed - */ - public function setExtraValue($name, $value) - { - $extra = json_decode($this->data['extra'], true); - if ($extra === false) { - $extra = []; - } - $extra[$name] = $value; - $this->setExtra(json_encode($extra)); - } - - /** - * Set the values of extra. - * - * @param $values mixed - */ - public function setExtraValues($values) - { - $extra = json_decode($this->data['extra'], true); - if ($extra === false) { - $extra = []; - } - $extra = array_replace($extra, $values); - $this->setExtra(json_encode($extra)); - } - - /** - * Get the Project model for this Build by Id. - * - * @return \PHPCensor\Model\Project - */ - public function getProject() - { - $key = $this->getProjectId(); - - if (empty($key)) { - return null; - } - - return Factory::getStore('Project', 'PHPCensor')->getById($key); - } - - /** - * Set Project - Accepts an ID, an array representing a Project or a Project model. - * - * @param $value mixed - */ - public function setProject($value) - { - // Is this an instance of Project? - if ($value instanceof Project) { - return $this->setProjectObject($value); - } - - // Is this an array representing a Project item? - if (is_array($value) && !empty($value['id'])) { - return $this->setProjectId($value['id']); - } - - // Is this a scalar value representing the ID of this foreign key? - return $this->setProjectId($value); - } - - /** - * Set Project - Accepts a Project model. - * - * @param $value Project - */ - public function setProjectObject(Project $value) - { - return $this->setProjectId($value->getId()); - } - - /** - * Get BuildError models by BuildId for this Build. - * - * @return \PHPCensor\Model\BuildError[] - */ - public function getBuildBuildErrors() - { - return Factory::getStore('BuildError', 'PHPCensor')->getByBuildId($this->getId()); - } - - /** - * Get BuildMeta models by BuildId for this Build. - * - * @return \PHPCensor\Model\BuildMeta[] - */ - public function getBuildBuildMetas() - { - return Factory::getStore('BuildMeta', 'PHPCensor')->getByBuildId($this->getId()); - } - - /** - * Get link to commit from another source (i.e. Github) - */ - public function getCommitLink() - { - return '#'; - } - - /** - * Get link to branch from another source (i.e. Github) - */ - public function getBranchLink() - { - return '#'; - } - - /** - * Get remote branch (from pull request) from another source (i.e. Github) - */ - public function getRemoteBranch() - { - return $this->getExtra('remote_branch'); - } - - /** - * Get link to remote branch (from pull request) from another source (i.e. Github) - */ - public function getRemoteBranchLink() - { - return '#'; - } - - /** - * Get link to tag from another source (i.e. Github) - */ - public function getTagLink() - { - return '#'; - } - - /** - * Return a template to use to generate a link to a specific file. - * - * @return null - */ - public function getFileLinkTemplate() - { - return null; - } - - /** - * Send status updates to any relevant third parties (i.e. Github) - */ - public function sendStatusPostback() - { - return false; - } - - /** - * @return string - */ - public function getProjectTitle() - { - $project = $this->getProject(); - return $project ? $project->getTitle() : ""; - } - - /** - * Store build metadata - */ - public function storeMeta($key, $value) - { - $value = json_encode($value); - Factory::getStore('Build')->setMeta($this->getId(), $key, $value); - } - - /** - * Is this build successful? - */ - public function isSuccessful() - { - return ($this->getStatus() === self::STATUS_SUCCESS); - } - - /** - * @param Builder $builder - * @param string $buildPath - * - * @return bool - */ - protected function handleConfig(Builder $builder, $buildPath) - { - $build_config = $this->getProject()->getBuildConfig(); - - if (empty($build_config)) { - if (file_exists($buildPath . '/.php-censor.yml')) { - $build_config = file_get_contents($buildPath . '/.php-censor.yml'); - } elseif (file_exists($buildPath . '/.phpci.yml')) { - $build_config = file_get_contents($buildPath . '/.phpci.yml'); - } elseif (file_exists($buildPath . '/phpci.yml')) { - $build_config = file_get_contents($buildPath . '/phpci.yml'); - } else { - $build_config = $this->getZeroConfigPlugins($builder); - } - } - - // for YAML configs from files/DB - if (is_string($build_config)) { - $yamlParser = new YamlParser(); - $build_config = $yamlParser->parse($build_config); - } - - $builder->setConfigArray($build_config); - - return true; - } - - /** - * Get an array of plugins to run if there's no .php-censor.yml file. - * @param Builder $builder - * @return array - */ - protected function getZeroConfigPlugins(Builder $builder) - { - $pluginDir = SRC_DIR . 'Plugin' . DIRECTORY_SEPARATOR; - $dir = new \DirectoryIterator($pluginDir); - - $config = [ - 'build_settings' => [ - 'ignore' => [ - 'vendor', - ] - ] - ]; - - foreach ($dir as $item) { - if ($item->isDot()) { - continue; - } - - if (!$item->isFile()) { - continue; - } - - if ($item->getExtension() != 'php') { - continue; - } - - $className = '\PHPCensor\Plugin\\'.$item->getBasename('.php'); - - $reflectedPlugin = new \ReflectionClass($className); - - if (!$reflectedPlugin->implementsInterface('\PHPCensor\ZeroConfigPluginInterface')) { - continue; - } - - foreach ([Build::STAGE_SETUP, Build::STAGE_TEST] as $stage) { - if ($className::canExecute($stage, $builder, $this)) { - $config[$stage][$className::pluginName()] = [ - 'zero_config' => true - ]; - } - } - } - - return $config; - } - - /** - * Allows specific build types (e.g. Github) to report violations back to their respective services. - * - * @param Builder $builder - * @param string $plugin - * @param string $message - * @param integer $severity - * @param string $file - * @param integer $lineStart - * @param integer $lineEnd - */ - public function reportError( - Builder $builder, - $plugin, - $message, - $severity = BuildError::SEVERITY_NORMAL, - $file = null, - $lineStart = null, - $lineEnd = null - ) { - $writer = $builder->getBuildErrorWriter(); - $writer->write( - $plugin, - $message, - $severity, - $file, - $lineStart, - $lineEnd - ); - } - - /** - * @return string|null - */ - public function getBuildDirectory() - { - if (!$this->getId()) { - return null; - } - - $createDate = $this->getCreateDate(); - if (empty($this->buildDirectory)) { - $this->buildDirectory = $this->getProjectId() . '/' . $this->getId() . '_' . substr( - md5(($this->getId() . '_' . ($createDate ? $createDate->format('Y-m-d H:i:s') : null)) - ), 0, 8); - } - - return $this->buildDirectory; - } - - /** - * @return string|null - */ - public function getBuildBranchDirectory() - { - if (!$this->getId()) { - return null; - } - - $createDate = $this->getCreateDate(); - if (empty($this->buildBranchDirectory)) { - $this->buildBranchDirectory = $this->getProjectId() . '/' . $this->getBranch() . '_' . substr( - md5(($this->getBranch() . '_' . ($createDate ? $createDate->format('Y-m-d H:i:s') : null)) - ), 0, 8); - } - - return $this->buildBranchDirectory; - } - - /** - * @return string|null - */ - public function getBuildPath() - { - if (!$this->getId()) { - return null; - } - - return RUNTIME_DIR . 'builds/' . $this->getBuildDirectory() . '/'; - } - - /** - * Removes the build directory. - * - * @param boolean $withArtifacts - */ - public function removeBuildDirectory($withArtifacts = false) - { - // Get the path and remove the trailing slash as this may prompt PHP - // to see this as a directory even if it's a link. - $buildPath = rtrim($this->getBuildPath(), '/'); - - if (!$buildPath || !is_dir($buildPath)) { - return; - } - - try { - $fileSystem = new Filesystem(); - - if (is_link($buildPath)) { - // Remove the symlink without using recursive. - exec(sprintf('rm "%s"', $buildPath)); - } else { - $fileSystem->remove($buildPath); - } - - if ($withArtifacts) { - $buildDirectory = $this->getBuildDirectory(); - - $fileSystem->remove(PUBLIC_DIR . 'artifacts/pdepend/' . $buildDirectory); - $fileSystem->remove(PUBLIC_DIR . 'artifacts/phpunit/' . $buildDirectory); - } - } catch (\Exception $e) { - - } - } - - /** - * Get the number of seconds a build has been running for. - * - * @return int - */ - public function getDuration() - { - $start = $this->getStartDate(); - - if (empty($start)) { - return 0; - } - - $end = $this->getFinishDate(); - - if (empty($end)) { - $end = new \DateTime(); - } - - return $end->getTimestamp() - $start->getTimestamp(); - } - - /** - * get time a build has been running for in hour/minute/seconds format (e.g. 1h 21m 45s) - * - * @return string - */ - public function getPrettyDuration() - { - $start = $this->getStartDate(); - if (!$start) { - $start = new \DateTime(); - } - $end = $this->getFinishDate(); - if (!$end) { - $end = new \DateTime(); - } - - $diff = date_diff($start, $end); - $parts = []; - foreach (['y', 'm', 'd', 'h', 'i', 's'] as $time_part) { - if ($diff->{$time_part} != 0) { - $parts[] = $diff->{$time_part} . ($time_part == 'i' ? 'm' : $time_part); - } - } - - return implode(" ", $parts); - } - - /** - * Create a working copy by cloning, copying, or similar. - * - * @param Builder $builder - * @param string $buildPath - * - * @return boolean - */ - public function createWorkingCopy(Builder $builder, $buildPath) - { - return false; - } - - /** - * Create an SSH key file on disk for this build. - * - * @param string $cloneTo - * - * @return string - */ - protected function writeSshKey($cloneTo) - { - $keyPath = dirname($cloneTo . '/temp'); - $keyFile = $keyPath . '.key'; - - file_put_contents($keyFile, $this->getProject()->getSshPrivateKey()); - chmod($keyFile, 0600); - - return $keyFile; - } - - /** - * Create an SSH wrapper script for Svn to use, to disable host key checking, etc. - * - * @param string $cloneTo - * @param string $keyFile - * - * @return string - */ - protected function writeSshWrapper($cloneTo, $keyFile) - { - $path = dirname($cloneTo . '/temp'); - $wrapperFile = $path . '.sh'; - - $sshFlags = '-o CheckHostIP=no -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o PasswordAuthentication=no'; - - // Write out the wrapper script for this build: - $script = <<getSource()) { - case Build::SOURCE_WEBHOOK: - return 'source_webhook'; - case Build::SOURCE_WEBHOOK_PULL_REQUEST: - return 'source_webhook_pull_request'; - case Build::SOURCE_MANUAL_WEB: - return 'source_manual_web'; - case Build::SOURCE_MANUAL_CONSOLE: - return 'source_manual_console'; - case Build::SOURCE_PERIODICAL: - return 'source_periodical'; - case Build::SOURCE_UNKNOWN: - default: - return 'source_unknown'; - } - } - - /** - * @return integer - */ - public function getNewErrorsCount() - { - if (null === $this->newErrorsCount) { - /** @var BuildErrorStore $store */ - $store = Factory::getStore('BuildError'); - - $this->newErrorsCount = $store->getNewErrorsCount($this->getId()); - } - - return $this->newErrorsCount; - } -} diff --git a/src/PHPCensor/Model/BuildError.php b/src/PHPCensor/Model/BuildError.php deleted file mode 100644 index a031b395..00000000 --- a/src/PHPCensor/Model/BuildError.php +++ /dev/null @@ -1,514 +0,0 @@ - null, - 'build_id' => null, - 'plugin' => null, - 'file' => null, - 'line_start' => null, - 'line_end' => null, - 'severity' => null, - 'message' => null, - 'create_date' => null, - 'hash' => null, - 'is_new' => null, - ]; - - /** - * @var array - */ - protected $getters = [ - // Direct property getters: - 'id' => 'getId', - 'build_id' => 'getBuildId', - 'plugin' => 'getPlugin', - 'file' => 'getFile', - 'line_start' => 'getLineStart', - 'line_end' => 'getLineEnd', - 'severity' => 'getSeverity', - 'message' => 'getMessage', - 'create_date' => 'getCreateDate', - 'hash' => 'getHash', - 'is_new' => 'getIsNew', - - // Foreign key getters: - 'Build' => 'getBuild', - ]; - - /** - * @var array - */ - protected $setters = [ - // Direct property setters: - 'id' => 'setId', - 'build_id' => 'setBuildId', - 'plugin' => 'setPlugin', - 'file' => 'setFile', - 'line_start' => 'setLineStart', - 'line_end' => 'setLineEnd', - 'severity' => 'setSeverity', - 'message' => 'setMessage', - 'create_date' => 'setCreateDate', - 'hash' => 'setHash', - 'is_new' => 'setIsNew', - - // Foreign key setters: - 'Build' => 'setBuild', - ]; - - /** - * @return int - */ - public function getId() - { - $rtn = $this->data['id']; - - return $rtn; - } - - /** - * @return int - */ - public function getBuildId() - { - $rtn = $this->data['build_id']; - - return $rtn; - } - - /** - * @return string - */ - public function getPlugin() - { - $rtn = $this->data['plugin']; - - return $rtn; - } - - /** - * @return string - */ - public function getFile() - { - $rtn = $this->data['file']; - - return $rtn; - } - - /** - * @return int - */ - public function getLineStart() - { - $rtn = $this->data['line_start']; - - return $rtn; - } - - /** - * @return int - */ - public function getLineEnd() - { - $rtn = $this->data['line_end']; - - return $rtn; - } - - /** - * @return int - */ - public function getSeverity() - { - $rtn = $this->data['severity']; - - return $rtn; - } - - /** - * @return string - */ - public function getMessage() - { - $rtn = $this->data['message']; - - return $rtn; - } - - /** - * @return \DateTime - */ - public function getCreateDate() - { - $rtn = $this->data['create_date']; - - if (!empty($rtn)) { - $rtn = new \DateTime($rtn); - } - - return $rtn; - } - - /** - * @return string - */ - public function getHash() - { - $rtn = (string)$this->data['hash']; - - return $rtn; - } - - /** - * @return string - */ - public function getIsNew() - { - $rtn = $this->data['is_new']; - - return $rtn; - } - - /** - * @param $value int - */ - public function setId($value) - { - $this->validateNotNull('id', $value); - $this->validateInt('id', $value); - - if ($this->data['id'] === $value) { - return; - } - - $this->data['id'] = $value; - - $this->setModified('id'); - } - - /** - * @param $value int - */ - public function setBuildId($value) - { - $this->validateNotNull('build_id', $value); - $this->validateInt('build_id', $value); - - if ($this->data['build_id'] === $value) { - return; - } - - $this->data['build_id'] = $value; - - $this->setModified('build_id'); - } - - /** - * @param $value string - */ - public function setPlugin($value) - { - $this->validateNotNull('plugin', $value); - $this->validateString('plugin', $value); - - if ($this->data['plugin'] === $value) { - return; - } - - $this->data['plugin'] = $value; - - $this->setModified('plugin'); - } - - /** - * @param $value string - */ - public function setFile($value) - { - $this->validateString('file', $value); - - if ($this->data['file'] === $value) { - return; - } - - $this->data['file'] = $value; - - $this->setModified('file'); - } - - /** - * @param $value int - */ - public function setLineStart($value) - { - $this->validateInt('line_start', $value); - - if ($this->data['line_start'] === $value) { - return; - } - - $this->data['line_start'] = $value; - - $this->setModified('line_start'); - } - - /** - * @param $value int - */ - public function setLineEnd($value) - { - $this->validateInt('line_end', $value); - - if ($this->data['line_end'] === $value) { - return; - } - - $this->data['line_end'] = $value; - - $this->setModified('line_end'); - } - - /** - * @param $value int - */ - public function setSeverity($value) - { - $this->validateNotNull('severity', $value); - $this->validateInt('severity', $value); - - if ($this->data['severity'] === $value) { - return; - } - - $this->data['severity'] = $value; - - $this->setModified('severity'); - } - - /** - * @param $value string - */ - public function setMessage($value) - { - $this->validateNotNull('message', $value); - $this->validateString('message', $value); - - if ($this->data['message'] === $value) { - return; - } - - $this->data['message'] = $value; - - $this->setModified('message'); - } - - /** - * @param $value \DateTime - */ - public function setCreateDate($value) - { - $this->validateNotNull('create_date', $value); - $this->validateDate('create_date', $value); - - if ($this->data['create_date'] === $value) { - return; - } - - $this->data['create_date'] = $value; - - $this->setModified('create_date'); - } - - /** - * @param $value string - */ - public function setHash($value) - { - $this->validateNotNull('hash', $value); - $this->validateString('hash', $value); - - if ($this->data['hash'] === $value) { - return; - } - - $this->data['hash'] = $value; - - $this->setModified('hash'); - } - - /** - * @param $value int - */ - public function setIsNew($value) - { - $this->validateNotNull('is_new', $value); - $this->validateInt('is_new', $value); - - if ($this->data['is_new'] === $value) { - return; - } - - $this->data['is_new'] = $value; - - $this->setModified('is_new'); - } - - /** - * Get the Build model for this BuildError by Id. - * - * @return \PHPCensor\Model\Build - */ - public function getBuild() - { - $key = $this->getBuildId(); - - if (empty($key)) { - return null; - } - - $cacheKey = 'php-censor.build-' . $key; - $rtn = $this->cache->get($cacheKey); - - if (empty($rtn)) { - $rtn = Factory::getStore('Build', 'PHPCensor')->getById($key); - $this->cache->set($cacheKey, $rtn); - } - - return $rtn; - } - - /** - * Set Build - Accepts an ID, an array representing a Build or a Build model. - * - * @param $value mixed - */ - public function setBuild($value) - { - // Is this an instance of Build? - if ($value instanceof Build) { - return $this->setBuildObject($value); - } - - // Is this an array representing a Build item? - if (is_array($value) && !empty($value['id'])) { - return $this->setBuildId($value['id']); - } - - // Is this a scalar value representing the ID of this foreign key? - return $this->setBuildId($value); - } - - /** - * Set Build - Accepts a Build model. - * - * @param $value Build - */ - public function setBuildObject(Build $value) - { - return $this->setBuildId($value->getId()); - } - - /** - * Get the language string key for this error's severity level. - * - * @return string - */ - public function getSeverityString() - { - switch ($this->getSeverity()) { - case self::SEVERITY_CRITICAL: - return 'critical'; - - case self::SEVERITY_HIGH: - return 'high'; - - case self::SEVERITY_NORMAL: - return 'normal'; - - case self::SEVERITY_LOW: - return 'low'; - } - } - - /** - * Get the language string key for this error's severity level. - * - * @param integer $severity - * - * @return string - */ - public static function getSeverityName($severity) - { - switch ($severity) { - case self::SEVERITY_CRITICAL: - return 'critical'; - - case self::SEVERITY_HIGH: - return 'high'; - - case self::SEVERITY_NORMAL: - return 'normal'; - - case self::SEVERITY_LOW: - return 'low'; - } - } - - /** - * @param string $plugin - * @param string $file - * @param integer $lineStart - * @param integer $lineEnd - * @param integer $severity - * @param string $message - * - * @return string - */ - public static function generateHash($plugin, $file, $lineStart, $lineEnd, $severity, $message) - { - return md5($plugin . $file . $lineStart . $lineEnd . $severity . $message); - } - - /** - * Get the class to apply to HTML elements representing this error. - * - * @return string - */ - public function getSeverityClass() - { - switch ($this->getSeverity()) { - case self::SEVERITY_CRITICAL: - return 'danger'; - - case self::SEVERITY_HIGH: - return 'warning'; - - case self::SEVERITY_NORMAL: - return 'info'; - - case self::SEVERITY_LOW: - return 'default'; - } - } -} diff --git a/src/PHPCensor/Model/BuildMeta.php b/src/PHPCensor/Model/BuildMeta.php deleted file mode 100644 index f1bd45c4..00000000 --- a/src/PHPCensor/Model/BuildMeta.php +++ /dev/null @@ -1,215 +0,0 @@ - null, - 'build_id' => null, - 'meta_key' => null, - 'meta_value' => null, - ]; - - /** - * @var array - */ - protected $getters = [ - // Direct property getters: - 'id' => 'getId', - 'build_id' => 'getBuildId', - 'meta_key' => 'getMetaKey', - 'meta_value' => 'getMetaValue', - - // Foreign key getters: - 'Build' => 'getBuild', - ]; - - /** - * @var array - */ - protected $setters = [ - // Direct property setters: - 'id' => 'setId', - 'build_id' => 'setBuildId', - 'meta_key' => 'setMetaKey', - 'meta_value' => 'setMetaValue', - - // Foreign key setters: - 'Build' => 'setBuild', - ]; - - /** - * @return int - */ - public function getId() - { - $rtn = $this->data['id']; - - return $rtn; - } - - /** - * @return int - */ - public function getBuildId() - { - $rtn = $this->data['build_id']; - - return $rtn; - } - - /** - * @return string - */ - public function getMetaKey() - { - $rtn = $this->data['meta_key']; - - return $rtn; - } - - /** - * @return string - */ - public function getMetaValue() - { - $rtn = $this->data['meta_value']; - - return $rtn; - } - - /** - * @param int $value - */ - public function setId($value) - { - $this->validateNotNull('id', $value); - $this->validateInt('id', $value); - - if ($this->data['id'] === $value) { - return; - } - - $this->data['id'] = $value; - - $this->setModified('id'); - } - - /** - * @param int $value - */ - public function setBuildId($value) - { - $this->validateNotNull('build_id', $value); - $this->validateInt('build_id', $value); - - if ($this->data['build_id'] === $value) { - return; - } - - $this->data['build_id'] = $value; - - $this->setModified('build_id'); - } - - /** - * @param $value string - */ - public function setMetaKey($value) - { - $this->validateNotNull('meta_key', $value); - $this->validateString('meta_key', $value); - - if ($this->data['meta_key'] === $value) { - return; - } - - $this->data['meta_key'] = $value; - - $this->setModified('meta_key'); - } - - /** - * @param $value string - */ - public function setMetaValue($value) - { - $this->validateNotNull('meta_value', $value); - $this->validateString('meta_value', $value); - - if ($this->data['meta_value'] === $value) { - return; - } - - $this->data['meta_value'] = $value; - - $this->setModified('meta_value'); - } - - /** - * Get the Build model for this BuildMeta by Id. - * - * @return \PHPCensor\Model\Build - */ - public function getBuild() - { - $key = $this->getBuildId(); - - if (empty($key)) { - return null; - } - - $cacheKey = 'php-censor.build-' . $key; - $rtn = $this->cache->get($cacheKey); - - if (empty($rtn)) { - $rtn = Factory::getStore('Build', 'PHPCensor')->getById($key); - $this->cache->set($cacheKey, $rtn); - } - - return $rtn; - } - - /** - * Set Build - Accepts an ID, an array representing a Build or a Build model. - * - * @param $value mixed - */ - public function setBuild($value) - { - // Is this an instance of Build? - if ($value instanceof Build) { - return $this->setBuildObject($value); - } - - // Is this an array representing a Build item? - if (is_array($value) && !empty($value['id'])) { - return $this->setBuildId($value['id']); - } - - // Is this a scalar value representing the ID of this foreign key? - return $this->setBuildId($value); - } - - /** - * Set Build - Accepts a Build model. - * - * @param $value Build - */ - public function setBuildObject(Build $value) - { - return $this->setBuildId($value->getId()); - } -} diff --git a/src/PHPCensor/Model/Project.php b/src/PHPCensor/Model/Project.php deleted file mode 100644 index 58240261..00000000 --- a/src/PHPCensor/Model/Project.php +++ /dev/null @@ -1,860 +0,0 @@ - - */ -class Project extends Model -{ - /** - * @var string - */ - protected $tableName = 'project'; - - /** - * @var array - */ - protected $data = [ - 'id' => null, - 'title' => null, - 'reference' => null, - 'branch' => null, - 'default_branch_only' => null, - 'ssh_private_key' => null, - 'type' => null, - 'access_information' => null, - 'last_commit' => null, - 'build_config' => null, - 'ssh_public_key' => null, - 'allow_public_status' => null, - 'archived' => null, - 'group_id' => null, - 'create_date' => null, - 'user_id' => 0, - ]; - - /** - * @var array - */ - protected $getters = [ - // Direct property getters: - 'id' => 'getId', - 'title' => 'getTitle', - 'reference' => 'getReference', - 'branch' => 'getBranch', - 'default_branch_only' => 'getDefaultBranchOnly', - 'ssh_private_key' => 'getSshPrivateKey', - 'type' => 'getType', - 'access_information' => 'getAccessInformation', - 'last_commit' => 'getLastCommit', - 'build_config' => 'getBuildConfig', - 'ssh_public_key' => 'getSshPublicKey', - 'allow_public_status' => 'getAllowPublicStatus', - 'archived' => 'getArchived', - 'group_id' => 'getGroupId', - 'create_date' => 'getCreateDate', - 'user_id' => 'getUserId', - - // Foreign key getters: - 'Group' => 'getGroup', - ]; - - /** - * @var array - */ - protected $setters = [ - // Direct property setters: - 'id' => 'setId', - 'title' => 'setTitle', - 'reference' => 'setReference', - 'branch' => 'setBranch', - 'default_branch_only' => 'setDefaultBranchOnly', - 'ssh_private_key' => 'setSshPrivateKey', - 'type' => 'setType', - 'access_information' => 'setAccessInformation', - 'last_commit' => 'setLastCommit', - 'build_config' => 'setBuildConfig', - 'ssh_public_key' => 'setSshPublicKey', - 'allow_public_status' => 'setAllowPublicStatus', - 'archived' => 'setArchived', - 'group_id' => 'setGroupId', - 'create_date' => 'setCreateDate', - 'user_id' => 'setUserId', - - // Foreign key setters: - 'Group' => 'setGroup', - ]; - - /** - * @return int - */ - public function getId() - { - $rtn = $this->data['id']; - - return $rtn; - } - - /** - * @return string - */ - public function getTitle() - { - $rtn = $this->data['title']; - - return $rtn; - } - - /** - * @return string - */ - public function getReference() - { - $rtn = $this->data['reference']; - - return $rtn; - } - - /** - * @return string - */ - public function getSshPrivateKey() - { - $rtn = $this->data['ssh_private_key']; - - return $rtn; - } - - /** - * @return string - */ - public function getType() - { - $rtn = $this->data['type']; - - return $rtn; - } - - /** - * @return string - */ - public function getLastCommit() - { - $rtn = $this->data['last_commit']; - - return $rtn; - } - - /** - * @return string - */ - public function getBuildConfig() - { - $rtn = $this->data['build_config']; - - return $rtn; - } - - /** - * @return string - */ - public function getSshPublicKey() - { - $rtn = $this->data['ssh_public_key']; - - return $rtn; - } - - /** - * @return int - */ - public function getAllowPublicStatus() - { - $rtn = $this->data['allow_public_status']; - - return $rtn; - } - - /** - * @return int - */ - public function getArchived() - { - $rtn = $this->data['archived']; - - return $rtn; - } - - /** - * @return int - */ - public function getGroupId() - { - $rtn = $this->data['group_id']; - - return $rtn; - } - - /** - * @return int - */ - public function getDefaultBranchOnly() - { - $rtn = $this->data['default_branch_only']; - - return $rtn; - } - - /** - * @param $value int - */ - public function setId($value) - { - $this->validateNotNull('id', $value); - $this->validateInt('id', $value); - - if ($this->data['id'] === $value) { - return; - } - - $this->data['id'] = $value; - - $this->setModified('id'); - } - - /** - * @param $value string - */ - public function setTitle($value) - { - $this->validateNotNull('title', $value); - $this->validateString('title', $value); - - if ($this->data['title'] === $value) { - return; - } - - $this->data['title'] = $value; - - $this->setModified('title'); - } - - /** - * @param $value string - */ - public function setReference($value) - { - $this->validateNotNull('reference', $value); - $this->validateString('reference', $value); - - if ($this->data['reference'] === $value) { - return; - } - - $this->data['reference'] = $value; - - $this->setModified('reference'); - } - - /** - * @param $value string - */ - public function setBranch($value) - { - $this->validateNotNull('branch', $value); - $this->validateString('branch', $value); - - if ($this->data['branch'] === $value) { - return; - } - - $this->data['branch'] = $value; - - $this->setModified('branch'); - } - - /** - * @param $value int - */ - public function setDefaultBranchOnly($value) - { - $this->validateNotNull('default_branch_only', $value); - $this->validateInt('default_branch_only', $value); - - if ($this->data['default_branch_only'] === $value) { - return; - } - - $this->data['default_branch_only'] = $value; - - $this->setModified('default_branch_only'); - } - - /** - * @param $value string - */ - public function setSshPrivateKey($value) - { - $this->validateString('ssh_private_key', $value); - - if ($this->data['ssh_private_key'] === $value) { - return; - } - - $this->data['ssh_private_key'] = $value; - - $this->setModified('ssh_private_key'); - } - - /** - * @param $value string - */ - public function setType($value) - { - $this->validateNotNull('type', $value); - $this->validateString('type', $value); - - if ($this->data['type'] === $value) { - return; - } - - $this->data['type'] = $value; - - $this->setModified('type'); - } - - /** - * @param $value string - */ - public function setLastCommit($value) - { - $this->validateString('last_commit', $value); - - if ($this->data['last_commit'] === $value) { - return; - } - - $this->data['last_commit'] = $value; - - $this->setModified('last_commit'); - } - - /** - * @param $value string - */ - public function setBuildConfig($value) - { - $this->validateString('build_config', $value); - - if ($this->data['build_config'] === $value) { - return; - } - - $this->data['build_config'] = $value; - - $this->setModified('build_config'); - } - - /** - * @param $value string - */ - public function setSshPublicKey($value) - { - $this->validateString('ssh_public_key', $value); - - if ($this->data['ssh_public_key'] === $value) { - return; - } - - $this->data['ssh_public_key'] = $value; - - $this->setModified('ssh_public_key'); - } - - /** - * @param $value int - */ - public function setAllowPublicStatus($value) - { - $this->validateNotNull('allow_public_status', $value); - $this->validateInt('allow_public_status', $value); - - if ($this->data['allow_public_status'] === $value) { - return; - } - - $this->data['allow_public_status'] = $value; - - $this->setModified('allow_public_status'); - } - - /** - * @param $value int - */ - public function setArchived($value) - { - $this->validateNotNull('archived', $value); - $this->validateInt('archived', $value); - - if ($this->data['archived'] === $value) { - return; - } - - $this->data['archived'] = $value; - - $this->setModified('archived'); - } - - /** - * @param $value int - */ - public function setGroupId($value) - { - $this->validateNotNull('group_id', $value); - $this->validateInt('group_id', $value); - - if ($this->data['group_id'] === $value) { - return; - } - - $this->data['group_id'] = $value; - - $this->setModified('group_id'); - } - - /** - * Get the ProjectGroup model for this Project by Id. - * - * @return \PHPCensor\Model\ProjectGroup - */ - public function getGroup() - { - $key = $this->getGroupId(); - - if (empty($key)) { - return null; - } - - $cacheKey = 'php-censor.project-group-' . $key; - $rtn = $this->cache->get($cacheKey); - - if (empty($rtn)) { - $rtn = Factory::getStore('ProjectGroup', 'PHPCensor')->getById($key); - $this->cache->set($cacheKey, $rtn); - } - - return $rtn; - } - - /** - * Set Group - Accepts an ID, an array representing a ProjectGroup or a ProjectGroup model. - * - * @param $value mixed - */ - public function setGroup($value) - { - // Is this an instance of ProjectGroup? - if ($value instanceof ProjectGroup) { - return $this->setGroupObject($value); - } - - // Is this an array representing a ProjectGroup item? - if (is_array($value) && !empty($value['id'])) { - return $this->setGroupId($value['id']); - } - - // Is this a scalar value representing the ID of this foreign key? - return $this->setGroupId($value); - } - - /** - * Set Group - Accepts a ProjectGroup model. - * - * @param $value ProjectGroup - */ - public function setGroupObject(ProjectGroup $value) - { - return $this->setGroupId($value->getId()); - } - - /** - * Get Build models by ProjectId for this Project. - * - * @return \PHPCensor\Model\Build[] - */ - public function getProjectBuilds() - { - return Factory::getStore('Build', 'PHPCensor')->getByProjectId($this->getId()); - } - - /** - * Return the latest build from a specific branch, of a specific status, for this project. - * - * @param string $branch - * @param null $status - * - * @return mixed|null - */ - public function getLatestBuild($branch = 'master', $status = null) - { - $criteria = ['branch' => $branch, 'project_id' => $this->getId()]; - - if (isset($status)) { - $criteria['status'] = $status; - } - - $order = ['id' => 'DESC']; - $builds = Store\Factory::getStore('Build')->getWhere($criteria, 1, 0, $order); - - if (is_array($builds['items']) && count($builds['items'])) { - $latest = array_shift($builds['items']); - - if (isset($latest) && $latest instanceof Build) { - return $latest; - } - } - - return null; - } - - /** - * Return the previous build from a specific branch, for this project. - * - * @param string $branch - * - * @return mixed|null - */ - public function getPreviousBuild($branch = 'master') - { - $criteria = ['branch' => $branch, 'project_id' => $this->getId()]; - $order = ['id' => 'DESC']; - $builds = Store\Factory::getStore('Build')->getWhere($criteria, 1, 1, $order); - - if (is_array($builds['items']) && count($builds['items'])) { - $previous = array_shift($builds['items']); - - if (isset($previous) && $previous instanceof Build) { - return $previous; - } - } - - return null; - } - - /** - * @param string|array $value - */ - public function setAccessInformation($value) - { - if (is_array($value)) { - $value = json_encode($value); - } - - $this->validateString('access_information', $value); - - if ($this->data['access_information'] === $value) { - return; - } - - $this->data['access_information'] = $value; - - $this->setModified('access_information'); - } - - /** - * Get this project's access_information data. Pass a specific key or null for all data. - * - * @param string|null $key - * - * @return mixed|null|string - */ - public function getAccessInformation($key = null) - { - $info = $this->data['access_information']; - - // Handle old-format (serialized) access information first: - if (!empty($info) && !in_array(substr($info, 0, 1), ['{', '['])) { - $data = unserialize($info); - } else { - $data = json_decode($info, true); - } - - if (is_null($key)) { - $rtn = $data; - } elseif (isset($data[$key])) { - $rtn = $data[$key]; - } else { - $rtn = null; - } - - return $rtn; - } - - /** - * @return \DateTime - */ - public function getCreateDate() - { - $rtn = $this->data['create_date']; - - if (!empty($rtn)) { - $rtn = new \DateTime($rtn); - } - - return $rtn; - } - - /** - * @param $value \DateTime - */ - public function setCreateDate($value) - { - $this->validateDate('create_date', $value); - - if ($this->data['create_date'] === $value) { - return; - } - - $this->data['create_date'] = $value; - - $this->setModified('create_date'); - } - - /** - * @return string - */ - public function getUserId() - { - $rtn = $this->data['user_id']; - - return (integer)$rtn; - } - - /** - * @param $value integer - */ - public function setUserId($value) - { - $this->validateNotNull('user_id', $value); - $this->validateInt('user_id', $value); - - if ($this->data['user_id'] === $value) { - return; - } - - $this->data['user_id'] = $value; - - $this->setModified('user_id'); - } - - /** - * Get the value of branch. - * - * @return string - */ - public function getBranch() - { - if (empty($this->data['branch'])) { - $projectType = $this->getType(); - switch ($projectType) { - case 'hg': - $branch = 'default'; - break; - case 'svn': - $branch = 'trunk'; - break; - default: - $branch = 'master'; - } - - return $branch; - } else { - return $this->data['branch']; - } - } - - /** - * Return the name of a FontAwesome icon to represent this project, depending on its type. - * - * @return string - */ - public function getIcon() - { - switch ($this->getType()) { - case 'github': - $icon = 'github'; - break; - - case 'bitbucket': - case 'bitbucket-hg': - $icon = 'bitbucket'; - break; - - case 'git': - case 'gitlab': - case 'gogs': - default: - $icon = 'code-fork'; - break; - } - - return $icon; - } - - /** - * @return EnvironmentStore - */ - protected function getEnvironmentStore() - { - /** @var EnvironmentStore $store */ - $store = Factory::getStore('Environment', 'PHPCensor'); - return $store; - } - - /** - * Get Environments - * - * @return array contain items with \PHPCensor\Model\Environment - */ - public function getEnvironmentsObjects() - { - $key = $this->getId(); - - if (empty($key)) { - return null; - } - - $cacheKey = 'php-censor.project-environments-' . $key; - $rtn = $this->cache->get($cacheKey); - - if (empty($rtn)) { - $store = $this->getEnvironmentStore(); - $rtn = $store->getByProjectId($key); - $this->cache->set($cacheKey, $rtn); - } - - return $rtn; - } - - /** - * Get Environments - * - * @return string[] - */ - public function getEnvironmentsNames() - { - $environments = $this->getEnvironmentsObjects(); - $environments_names = []; - foreach($environments['items'] as $environment) { - /** @var Environment $environment */ - $environments_names[] = $environment->getName(); - } - - return $environments_names; - } - - /** - * Get Environments - * - * @return string yaml - */ - public function getEnvironments() - { - $environments = $this->getEnvironmentsObjects(); - $environments_config = []; - foreach($environments['items'] as $environment) { - /** @var Environment $environment */ - $environments_config[$environment->getName()] = $environment->getBranches(); - } - - $yaml_dumper = new YamlDumper(); - $value = $yaml_dumper->dump($environments_config, 10, 0, true, false); - - return $value; - } - - /** - * Set Environments - * - * @param string $value yaml - */ - public function setEnvironments($value) - { - $yaml_parser = new YamlParser(); - $environments_config = $yaml_parser->parse($value); - $environments_names = !empty($environments_config) ? array_keys($environments_config) : []; - $current_environments = $this->getEnvironmentsObjects(); - $store = $this->getEnvironmentStore(); - foreach ($current_environments['items'] as $environment) { - /** @var Environment $environment */ - $key = array_search($environment->getName(), $environments_names); - if ($key !== false) { - // already exist - unset($environments_names[$key]); - $environment->setBranches(!empty($environments_config[$environment->getName()]) ? $environments_config[$environment->getName()] : []); - $store->save($environment); - } else { - // remove - $store->delete($environment); - } - } - - if (!empty($environments_names)) { - // add - foreach ($environments_names as $environment_name) { - $environment = new Environment(); - $environment->setProjectId($this->getId()); - $environment->setName($environment_name); - $environment->setBranches(!empty($environments_config[$environment->getName()]) ? $environments_config[$environment->getName()] : []); - $store->save($environment); - } - } - } - - /** - * @param string $branch - * - * @return string[] - */ - public function getEnvironmentsNamesByBranch($branch) - { - $environments_names = []; - $environments = $this->getEnvironmentsObjects(); - $default_branch = ($branch == $this->getBranch()); - foreach($environments['items'] as $environment) { - /** @var Environment $environment */ - if ($default_branch || in_array($branch, $environment->getBranches())) { - $environments_names[] = $environment->getName(); - } - } - - return $environments_names; - } - - /** - * @param string $environment_name - * - * @return string[] - */ - public function getBranchesByEnvironment($environment_name) - { - $branches = []; - $environments = $this->getEnvironmentsObjects(); - foreach($environments['items'] as $environment) { - /** @var Environment $environment */ - if ($environment_name == $environment->getName()) { - return $environment->getBranches(); - } - } - - return $branches; - } -} diff --git a/src/PHPCensor/Model/ProjectGroup.php b/src/PHPCensor/Model/ProjectGroup.php deleted file mode 100644 index 2847c8a6..00000000 --- a/src/PHPCensor/Model/ProjectGroup.php +++ /dev/null @@ -1,165 +0,0 @@ - null, - 'title' => null, - 'create_date' => null, - 'user_id' => 0, - ]; - - /** - * @var array - */ - protected $getters = [ - 'id' => 'getId', - 'title' => 'getTitle', - 'create_date' => 'getCreateDate', - 'user_id' => 'getUserId', - ]; - - /** - * @var array - */ - protected $setters = [ - 'id' => 'setId', - 'title' => 'setTitle', - 'create_date' => 'setCreateDate', - 'user_id' => 'setUserId', - ]; - - /** - * @return int - */ - public function getId() - { - $rtn = $this->data['id']; - - return $rtn; - } - - /** - * @param $value int - */ - public function setId($value) - { - $this->validateNotNull('id', $value); - $this->validateInt('id', $value); - - if ($this->data['id'] === $value) { - return; - } - - $this->data['id'] = $value; - - $this->setModified('id'); - } - - /** - * @return string - */ - public function getTitle() - { - $rtn = $this->data['title']; - - return $rtn; - } - - /** - * @param $value string - */ - public function setTitle($value) - { - $this->validateNotNull('title', $value); - $this->validateString('title', $value); - - if ($this->data['title'] === $value) { - return; - } - - $this->data['title'] = $value; - - $this->setModified('title'); - } - - /** - * @return \DateTime - */ - public function getCreateDate() - { - $rtn = $this->data['create_date']; - - if (!empty($rtn)) { - $rtn = new \DateTime($rtn); - } - - return $rtn; - } - - /** - * @param $value \DateTime - */ - public function setCreateDate($value) - { - $this->validateDate('create_date', $value); - - if ($this->data['create_date'] === $value) { - return; - } - - $this->data['create_date'] = $value; - - $this->setModified('create_date'); - } - - /** - * @return string - */ - public function getUserId() - { - $rtn = $this->data['user_id']; - - return (integer)$rtn; - } - - /** - * @param $value integer - */ - public function setUserId($value) - { - $this->validateNotNull('user_id', $value); - $this->validateInt('user_id', $value); - - if ($this->data['user_id'] === $value) { - return; - } - - $this->data['user_id'] = $value; - - $this->setModified('user_id'); - } - - /** - * Get Project models by GroupId for this ProjectGroup. - * - * @return \PHPCensor\Model\Project[] - */ - public function getGroupProjects() - { - return Factory::getStore('Project', 'PHPCensor')->getByGroupId($this->getId(), false); - } -} diff --git a/src/PHPCensor/Store.php b/src/PHPCensor/Store.php deleted file mode 100644 index 5a9ce1d6..00000000 --- a/src/PHPCensor/Store.php +++ /dev/null @@ -1,7 +0,0 @@ - - - - <?php print $project->getTitle(); ?> - PHP Censor - - - - - - - - - - - - - - - - - -
-
- -
-
-
-
- - - getStatus()) { - case 0: - $statusClass = 'blue'; - $statusText = 'Pending'; - break; - case 1: - $statusClass = 'yellow'; - $statusText = 'Running'; - break; - case 2: - $statusClass = 'green'; - $statusText = 'Success'; - break; - case 3: - $statusClass = 'red'; - $statusText = 'Failed'; - break; - } - - ?> - -
-
-

- getProject()->getTitle(); ?> #getId(); ?> () -

-

- getCommitMessage()): ?> - getCommitMessage(); ?>

- - - Branch: getBranch(); ?>
- Committer: getCommitterEmail(); ?> - - getCommitId())): ?> -
Commit: getCommitId(); ?>
- -

-
-
- -
-
-
- - -
-

Builds

- - - - - - - - - - - - - - - - - - - - - - - - getStatus()) - { - case 0: - $class = 'info'; - $status = 'Pending'; - - break; - - case 1: - $class = 'warning'; - $status = 'Running'; - break; - - case 2: - $class = 'success'; - $status = 'Success'; - break; - - case 3: - $class = 'danger'; - $status = 'Failed'; - break; - } - ?> - - - - - - - - - - - - - - -
IDStatusDateCommitBranchEnvironmentDuration
No builds yet.
#getId(), 6, '0', STR_PAD_LEFT); ?> - - getCreateDate()->format('Y-m-d H:i:s'); ?> - getCommitId())) { - print sprintf( - '%s %s', - $build->getCommitLink(), - substr($build->getCommitId(), 0, 7), - $build->getCommitterEmail() ? ('(' . $build->getCommitterEmail() . ')') : '' - ); - } else { - print '—'; - } - ?> - - getSource()): ?> - - - getRemoteBranch(); ?> : - - - - - getBranch(); ?> - - getExtra('branches'); ?> - - getTag()): ?> / - - - - - - - getEnvironment(); - echo !empty($environment) ? $environment : '—' ; - ?> - - getDuration(); ?> sec. -
-
-
-
-
- -
- - diff --git a/src/PHPCensor/View/Email/layout.phtml b/src/PHPCensor/View/Email/layout.phtml deleted file mode 100644 index a97ac991..00000000 --- a/src/PHPCensor/View/Email/layout.phtml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - -
-
-
getTitle(); ?> - Build #getId(); ?>
-
-

- Your commit getCommitId(); ?> generated a - isSuccessful() ? 'success' : 'failed'; ?> build in project - getTitle(); ?>. -

- -
- -
-
- - diff --git a/src/PHPCensor/View/Email/long.phtml b/src/PHPCensor/View/Email/long.phtml deleted file mode 100644 index daef0aa2..00000000 --- a/src/PHPCensor/View/Email/long.phtml +++ /dev/null @@ -1,2 +0,0 @@ -

getCommitMessage(); ?>

-
getLog()); ?>
diff --git a/src/PHPCensor/View/Email/short.phtml b/src/PHPCensor/View/Email/short.phtml deleted file mode 100644 index 75df4f83..00000000 --- a/src/PHPCensor/View/Email/short.phtml +++ /dev/null @@ -1 +0,0 @@ -

getCommitMessage(); ?>

diff --git a/src/PHPCensor/View/Session.phtml b/src/PHPCensor/View/Session.phtml deleted file mode 100644 index 411c2958..00000000 --- a/src/PHPCensor/View/Session.phtml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - <?php Lang::out('log_in_to_app'); ?> - - - - - - - - -
-
- -
- -
-
-
- - - - - - diff --git a/src/PHPCensor/View/pagination.phtml b/src/PHPCensor/View/pagination.phtml deleted file mode 100644 index cf6d29a3..00000000 --- a/src/PHPCensor/View/pagination.phtml +++ /dev/null @@ -1,28 +0,0 @@ - -
    - getPrevUrl()): ?> -
  • - - - getPages() as $pageArray): ?> - -
  • > - -
  • - -
  • - - - - getNextUrl()): ?> -
  • - -
diff --git a/src/PHPCensor/Plugin.php b/src/Plugin.php similarity index 91% rename from src/PHPCensor/Plugin.php rename to src/Plugin.php index 0a382dcb..cfc4658e 100644 --- a/src/PHPCensor/Plugin.php +++ b/src/Plugin.php @@ -45,7 +45,7 @@ abstract class Plugin $this->build = $build; $this->options = $options; - if (!empty($options['priority_path']) && in_array($options['priority_path'], ['global', 'system'])) { + if (!empty($options['priority_path']) && in_array($options['priority_path'], ['global', 'system'], true)) { $this->priorityPath = $options['priority_path']; } @@ -83,6 +83,14 @@ abstract class Plugin return $this->builder; } + /** + * @return string + */ + public function getPriorityPath() + { + return $this->priorityPath; + } + /** * @return boolean */ diff --git a/src/PHPCensor/Plugin/Atoum.php b/src/Plugin/Atoum.php similarity index 91% rename from src/PHPCensor/Plugin/Atoum.php rename to src/Plugin/Atoum.php index f62424b4..cd6a7b30 100644 --- a/src/PHPCensor/Plugin/Atoum.php +++ b/src/Plugin/Atoum.php @@ -47,7 +47,7 @@ class Atoum extends Plugin parent::__construct($builder, $build, $options); if (isset($options['executable'])) { - $this->executable = $this->builder->buildPath . DIRECTORY_SEPARATOR.$options['executable']; + $this->executable = $this->builder->buildPath . '/' . $options['executable']; } else { $this->executable = $this->findBinary('atoum'); } @@ -83,7 +83,7 @@ class Atoum extends Plugin } if ($this->directory !== null) { - $dirPath = $this->builder->buildPath . DIRECTORY_SEPARATOR . $this->directory; + $dirPath = $this->builder->buildPath . '/' . $this->directory; $cmd .= " -d '{$dirPath}'"; } diff --git a/src/PHPCensor/Plugin/Behat.php b/src/Plugin/Behat.php similarity index 97% rename from src/PHPCensor/Plugin/Behat.php rename to src/Plugin/Behat.php index c47be480..1825e1b5 100644 --- a/src/PHPCensor/Plugin/Behat.php +++ b/src/Plugin/Behat.php @@ -9,7 +9,7 @@ use PHPCensor\Plugin; /** * Behat BDD Plugin - * + * * @author Dan Cryer */ class Behat extends Plugin @@ -50,7 +50,7 @@ class Behat extends Plugin */ public function execute() { - $current_dir = getcwd(); + $currentDir = getcwd(); chdir($this->builder->buildPath); $behat = $this->executable; @@ -62,7 +62,7 @@ class Behat extends Plugin } $success = $this->builder->executeCommand($behat . ' %s', $this->features); - chdir($current_dir); + chdir($currentDir); list($errorCount, $data) = $this->parseBehatOutput(); diff --git a/src/PHPCensor/Plugin/Campfire.php b/src/Plugin/Campfire.php similarity index 100% rename from src/PHPCensor/Plugin/Campfire.php rename to src/Plugin/Campfire.php diff --git a/src/PHPCensor/Plugin/CleanBuild.php b/src/Plugin/CleanBuild.php similarity index 100% rename from src/PHPCensor/Plugin/CleanBuild.php rename to src/Plugin/CleanBuild.php diff --git a/src/PHPCensor/Plugin/Codeception.php b/src/Plugin/Codeception.php similarity index 100% rename from src/PHPCensor/Plugin/Codeception.php rename to src/Plugin/Codeception.php diff --git a/src/PHPCensor/Plugin/Composer.php b/src/Plugin/Composer.php similarity index 95% rename from src/PHPCensor/Plugin/Composer.php rename to src/Plugin/Composer.php index aa68f87f..093ca94c 100644 --- a/src/PHPCensor/Plugin/Composer.php +++ b/src/Plugin/Composer.php @@ -46,7 +46,7 @@ class Composer extends Plugin implements ZeroConfigPluginInterface $this->ignorePlatformReqs = false; if (array_key_exists('directory', $options)) { - $this->directory = $path . DIRECTORY_SEPARATOR . $options['directory']; + $this->directory = $path . '/' . $options['directory']; } if (array_key_exists('action', $options)) { @@ -80,7 +80,7 @@ class Composer extends Plugin implements ZeroConfigPluginInterface */ public static function canExecute($stage, Builder $builder, Build $build) { - $path = $builder->buildPath . DIRECTORY_SEPARATOR . 'composer.json'; + $path = $builder->buildPath . '/composer.json'; if (file_exists($path) && $stage == Build::STAGE_SETUP) { return true; diff --git a/src/PHPCensor/Plugin/CopyBuild.php b/src/Plugin/CopyBuild.php similarity index 100% rename from src/PHPCensor/Plugin/CopyBuild.php rename to src/Plugin/CopyBuild.php diff --git a/src/PHPCensor/Plugin/Deployer.php b/src/Plugin/Deployer.php similarity index 100% rename from src/PHPCensor/Plugin/Deployer.php rename to src/Plugin/Deployer.php diff --git a/src/PHPCensor/Plugin/Email.php b/src/Plugin/Email.php similarity index 100% rename from src/PHPCensor/Plugin/Email.php rename to src/Plugin/Email.php diff --git a/src/PHPCensor/Plugin/Env.php b/src/Plugin/Env.php similarity index 100% rename from src/PHPCensor/Plugin/Env.php rename to src/Plugin/Env.php diff --git a/src/PHPCensor/Plugin/FlowdockNotify.php b/src/Plugin/FlowdockNotify.php similarity index 97% rename from src/PHPCensor/Plugin/FlowdockNotify.php rename to src/Plugin/FlowdockNotify.php index b33ca08b..bc69d255 100644 --- a/src/PHPCensor/Plugin/FlowdockNotify.php +++ b/src/Plugin/FlowdockNotify.php @@ -56,7 +56,7 @@ class FlowdockNotify extends Plugin $message = $this->builder->interpolate($this->message); $successfulBuild = $this->build->isSuccessful() ? 'Success' : 'Failed'; $push = new Push($this->apiKey); - $flowMessage = TeamInboxMessage::create() + $flowMessage = TeamInboxMessage::create() ->setSource("PHPCensor") ->setFromAddress($this->email) ->setFromName($this->build->getProject()->getTitle()) diff --git a/src/PHPCensor/Plugin/Git.php b/src/Plugin/Git.php similarity index 100% rename from src/PHPCensor/Plugin/Git.php rename to src/Plugin/Git.php diff --git a/src/PHPCensor/Plugin/Grunt.php b/src/Plugin/Grunt.php similarity index 95% rename from src/PHPCensor/Plugin/Grunt.php rename to src/Plugin/Grunt.php index e5db5e24..cb6afb0e 100644 --- a/src/PHPCensor/Plugin/Grunt.php +++ b/src/Plugin/Grunt.php @@ -8,7 +8,7 @@ use PHPCensor\Plugin; /** * Grunt Plugin - Provides access to grunt functionality. - * + * * @author Tobias Tom */ class Grunt extends Plugin @@ -26,14 +26,14 @@ class Grunt extends Plugin { return 'grunt'; } - + /** * {@inheritdoc} */ public function __construct(Builder $builder, Build $build, array $options = []) { parent::__construct($builder, $build, $options); - + $path = $this->builder->buildPath; $this->directory = $path; $this->task = null; @@ -42,7 +42,7 @@ class Grunt extends Plugin // Handle options: if (isset($options['directory'])) { - $this->directory = $path . DIRECTORY_SEPARATOR . $options['directory']; + $this->directory = $path . '/' . $options['directory']; } if (isset($options['task'])) { diff --git a/src/PHPCensor/Plugin/Gulp.php b/src/Plugin/Gulp.php similarity index 95% rename from src/PHPCensor/Plugin/Gulp.php rename to src/Plugin/Gulp.php index 6c28cea9..3d65433b 100644 --- a/src/PHPCensor/Plugin/Gulp.php +++ b/src/Plugin/Gulp.php @@ -8,7 +8,7 @@ use PHPCensor\Plugin; /** * Gulp Plugin - Provides access to gulp functionality. - * + * * @author Dirk Heilig */ class Gulp extends Plugin @@ -26,14 +26,14 @@ class Gulp extends Plugin { return 'gulp'; } - + /** * {@inheritdoc} */ public function __construct(Builder $builder, Build $build, array $options = []) { parent::__construct($builder, $build, $options); - + $path = $this->builder->buildPath; $this->directory = $path; $this->task = null; @@ -42,7 +42,7 @@ class Gulp extends Plugin // Handle options: if (isset($options['directory'])) { - $this->directory = $path . DIRECTORY_SEPARATOR . $options['directory']; + $this->directory = $path . '/' . $options['directory']; } if (isset($options['task'])) { diff --git a/src/PHPCensor/Plugin/HipchatNotify.php b/src/Plugin/HipchatNotify.php similarity index 100% rename from src/PHPCensor/Plugin/HipchatNotify.php rename to src/Plugin/HipchatNotify.php diff --git a/src/PHPCensor/Plugin/Irc.php b/src/Plugin/Irc.php similarity index 100% rename from src/PHPCensor/Plugin/Irc.php rename to src/Plugin/Irc.php diff --git a/src/PHPCensor/Plugin/Lint.php b/src/Plugin/Lint.php similarity index 95% rename from src/PHPCensor/Plugin/Lint.php rename to src/Plugin/Lint.php index 9ef07967..35623383 100644 --- a/src/PHPCensor/Plugin/Lint.php +++ b/src/Plugin/Lint.php @@ -9,7 +9,7 @@ use PHPCensor\Plugin; /** * PHP Lint Plugin - Provides access to PHP lint functionality. - * + * * @author Dan Cryer */ class Lint extends Plugin @@ -83,7 +83,11 @@ class Lint extends Plugin if ($item->isFile() && $item->getExtension() == 'php' && !$this->lintFile($php, $itemPath)) { $success = false; - } elseif ($item->isDir() && $this->recursive && !$this->lintDirectory($php, $itemPath . DIRECTORY_SEPARATOR)) { + } elseif ( + $item->isDir() && + $this->recursive && + !$this->lintDirectory($php, ($itemPath . '/')) + ) { $success = false; } diff --git a/src/PHPCensor/Plugin/Mage.php b/src/Plugin/Mage.php similarity index 100% rename from src/PHPCensor/Plugin/Mage.php rename to src/Plugin/Mage.php diff --git a/src/PHPCensor/Plugin/Mage3.php b/src/Plugin/Mage3.php similarity index 100% rename from src/PHPCensor/Plugin/Mage3.php rename to src/Plugin/Mage3.php diff --git a/src/PHPCensor/Plugin/Mysql.php b/src/Plugin/Mysql.php similarity index 89% rename from src/PHPCensor/Plugin/Mysql.php rename to src/Plugin/Mysql.php index d80b2c78..1205aac7 100644 --- a/src/PHPCensor/Plugin/Mysql.php +++ b/src/Plugin/Mysql.php @@ -6,7 +6,7 @@ use PDO; use PHPCensor\Builder; use PHPCensor\Model\Build; use PHPCensor\Plugin; -use b8\Database; +use PHPCensor\Database; /** * MySQL Plugin - Provides access to a MySQL database. @@ -100,11 +100,13 @@ class Mysql extends Plugin } /** - * @param string $query + * @param array $query + * * @return boolean + * * @throws \Exception */ - protected function executeFile($query) + protected function executeFile(array $query) { if (!isset($query['file'])) { throw new \Exception('Import statement must contain a \'file\' key'); @@ -128,26 +130,26 @@ class Mysql extends Plugin /** * Builds the MySQL import command required to import/execute the specified file * - * @param string $import_file Path to file, relative to the build root - * @param string $database If specified, this database is selected before execution + * @param string $importFile Path to file, relative to the build root + * @param string $database If specified, this database is selected before execution * * @return string */ - protected function getImportCommand($import_file, $database = null) + protected function getImportCommand($importFile, $database = null) { $decompression = [ 'bz2' => '| bzip2 --decompress', 'gz' => '| gzip --decompress', ]; - $extension = strtolower(pathinfo($import_file, PATHINFO_EXTENSION)); + $extension = strtolower(pathinfo($importFile, PATHINFO_EXTENSION)); $decompressionCmd = ''; if (array_key_exists($extension, $decompression)) { $decompressionCmd = $decompression[$extension]; } $args = [ - ':import_file' => escapeshellarg($import_file), + ':import_file' => escapeshellarg($importFile), ':decomp_cmd' => $decompressionCmd, ':host' => escapeshellarg($this->host), ':user' => escapeshellarg($this->user), diff --git a/src/PHPCensor/Plugin/Option/PhpUnitOptions.php b/src/Plugin/Option/PhpUnitOptions.php similarity index 99% rename from src/PHPCensor/Plugin/Option/PhpUnitOptions.php rename to src/Plugin/Option/PhpUnitOptions.php index 0a49869d..0789f12f 100644 --- a/src/PHPCensor/Plugin/Option/PhpUnitOptions.php +++ b/src/Plugin/Option/PhpUnitOptions.php @@ -2,7 +2,7 @@ namespace PHPCensor\Plugin\Option; -use b8\Config; +use PHPCensor\Config; /** * Class PhpUnitOptions validates and parse the option for the PhpUnitV2 plugin diff --git a/src/PHPCensor/Plugin/PackageBuild.php b/src/Plugin/PackageBuild.php similarity index 100% rename from src/PHPCensor/Plugin/PackageBuild.php rename to src/Plugin/PackageBuild.php diff --git a/src/PHPCensor/Plugin/Pdepend.php b/src/Plugin/Pdepend.php similarity index 95% rename from src/PHPCensor/Plugin/Pdepend.php rename to src/Plugin/Pdepend.php index 39445e47..e267a260 100644 --- a/src/PHPCensor/Plugin/Pdepend.php +++ b/src/Plugin/Pdepend.php @@ -2,7 +2,7 @@ namespace PHPCensor\Plugin; -use b8\Config; +use PHPCensor\Config; use PHPCensor\Builder; use PHPCensor\Model\Build; use PHPCensor\Plugin; @@ -122,9 +122,9 @@ class Pdepend extends Plugin $success = $this->builder->executeCommand( $cmd, - $this->buildLocation . DIRECTORY_SEPARATOR . $this->summary, - $this->buildLocation . DIRECTORY_SEPARATOR . $this->chart, - $this->buildLocation . DIRECTORY_SEPARATOR . $this->pyramid, + $this->buildLocation . '/' . $this->summary, + $this->buildLocation . '/' . $this->chart, + $this->buildLocation . '/' . $this->pyramid, $ignore, $this->directory ); diff --git a/src/PHPCensor/Plugin/Pgsql.php b/src/Plugin/Pgsql.php similarity index 100% rename from src/PHPCensor/Plugin/Pgsql.php rename to src/Plugin/Pgsql.php diff --git a/src/PHPCensor/Plugin/Phar.php b/src/Plugin/Phar.php similarity index 96% rename from src/PHPCensor/Plugin/Phar.php rename to src/Plugin/Phar.php index b43b95ec..0b39d477 100644 --- a/src/PHPCensor/Plugin/Phar.php +++ b/src/Plugin/Phar.php @@ -178,7 +178,7 @@ class Phar extends Plugin $content = ''; $filename = $this->getStub(); if ($filename) { - $content = file_get_contents($this->builder->buildPath . DIRECTORY_SEPARATOR . $this->getStub()); + $content = file_get_contents($this->builder->buildPath . '/' . $this->getStub()); } return $content; } @@ -192,7 +192,7 @@ class Phar extends Plugin $success = false; try { - $file = $this->getDirectory() . DIRECTORY_SEPARATOR . $this->getFilename(); + $file = $this->getDirectory() . '/' . $this->getFilename(); $phar = new PHPPhar($file, 0, $this->getFilename()); $phar->buildFromDirectory($this->builder->buildPath, $this->getRegExp()); diff --git a/src/PHPCensor/Plugin/Phing.php b/src/Plugin/Phing.php similarity index 96% rename from src/PHPCensor/Plugin/Phing.php rename to src/Plugin/Phing.php index 5edda716..aac615d3 100644 --- a/src/PHPCensor/Plugin/Phing.php +++ b/src/Plugin/Phing.php @@ -38,7 +38,7 @@ class Phing extends Plugin * Set working directory */ if (isset($options['directory'])) { - $directory = $this->builder->buildPath . DIRECTORY_SEPARATOR . $options['directory']; + $directory = $this->builder->buildPath . '/' . $options['directory']; } else { $directory = $this->builder->buildPath; } @@ -228,7 +228,7 @@ class Phing extends Plugin */ public function setPropertyFile($propertyFile) { - if (!file_exists($this->getDirectory() . DIRECTORY_SEPARATOR . $propertyFile)) { + if (!file_exists($this->getDirectory() . '/' . $propertyFile)) { throw new \Exception('Specified property file does not exist.'); } diff --git a/src/PHPCensor/Plugin/PhpCodeSniffer.php b/src/Plugin/PhpCodeSniffer.php similarity index 100% rename from src/PHPCensor/Plugin/PhpCodeSniffer.php rename to src/Plugin/PhpCodeSniffer.php diff --git a/src/PHPCensor/Plugin/PhpCpd.php b/src/Plugin/PhpCpd.php similarity index 96% rename from src/PHPCensor/Plugin/PhpCpd.php rename to src/Plugin/PhpCpd.php index 4094d164..e4189856 100644 --- a/src/PHPCensor/Plugin/PhpCpd.php +++ b/src/Plugin/PhpCpd.php @@ -83,8 +83,8 @@ class PhpCpd extends Plugin implements ZeroConfigPluginInterface $namesExclude = ' --names-exclude '; foreach ($this->ignore as $item) { - $item = rtrim($item, DIRECTORY_SEPARATOR); - if (is_file(rtrim($this->path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $item)) { + $item = rtrim($item, '/'); + if (is_file(rtrim($this->path, '/') . '/' . $item)) { $ignoredFile = explode('/', $item); $filesToIgnore[] = array_pop($ignoredFile); } else { diff --git a/src/PHPCensor/Plugin/PhpCsFixer.php b/src/Plugin/PhpCsFixer.php similarity index 100% rename from src/PHPCensor/Plugin/PhpCsFixer.php rename to src/Plugin/PhpCsFixer.php diff --git a/src/PHPCensor/Plugin/PhpDocblockChecker.php b/src/Plugin/PhpDocblockChecker.php similarity index 100% rename from src/PHPCensor/Plugin/PhpDocblockChecker.php rename to src/Plugin/PhpDocblockChecker.php diff --git a/src/PHPCensor/Plugin/PhpLoc.php b/src/Plugin/PhpLoc.php similarity index 96% rename from src/PHPCensor/Plugin/PhpLoc.php rename to src/Plugin/PhpLoc.php index 597514a8..6ff7898f 100644 --- a/src/PHPCensor/Plugin/PhpLoc.php +++ b/src/Plugin/PhpLoc.php @@ -10,7 +10,7 @@ use PHPCensor\ZeroConfigPluginInterface; /** * PHP Loc - Allows PHP Copy / Lines of Code testing. - * + * * @author Johan van der Heide */ class PhpLoc extends Plugin implements ZeroConfigPluginInterface @@ -27,7 +27,7 @@ class PhpLoc extends Plugin implements ZeroConfigPluginInterface { return 'php_loc'; } - + /** * Check if this plugin can be executed. * @param $stage @@ -67,7 +67,7 @@ class PhpLoc extends Plugin implements ZeroConfigPluginInterface if (count($this->builder->ignore)) { $map = function ($item) { - return ' --exclude ' . rtrim($item, DIRECTORY_SEPARATOR); + return ' --exclude ' . rtrim($item, '/'); }; $ignore = array_map($map, $this->builder->ignore); diff --git a/src/PHPCensor/Plugin/PhpMessDetector.php b/src/Plugin/PhpMessDetector.php similarity index 100% rename from src/PHPCensor/Plugin/PhpMessDetector.php rename to src/Plugin/PhpMessDetector.php diff --git a/src/PHPCensor/Plugin/PhpParallelLint.php b/src/Plugin/PhpParallelLint.php similarity index 100% rename from src/PHPCensor/Plugin/PhpParallelLint.php rename to src/Plugin/PhpParallelLint.php diff --git a/src/PHPCensor/Plugin/PhpSpec.php b/src/Plugin/PhpSpec.php similarity index 97% rename from src/PHPCensor/Plugin/PhpSpec.php rename to src/Plugin/PhpSpec.php index 063235aa..3ce247dc 100644 --- a/src/PHPCensor/Plugin/PhpSpec.php +++ b/src/Plugin/PhpSpec.php @@ -97,8 +97,8 @@ class PhpSpec extends Plugin $error['message'] = (String)$attr['message']; } - foreach ($child->xpath('system-err') as $system_err) { - $error['raw'] = (String)$system_err; + foreach ($child->xpath('system-err') as $systemError) { + $error['raw'] = (String)$systemError; } $case['error'] = $error; diff --git a/src/PHPCensor/Plugin/PhpTalLint.php b/src/Plugin/PhpTalLint.php similarity index 88% rename from src/PHPCensor/Plugin/PhpTalLint.php rename to src/Plugin/PhpTalLint.php index 636df1e2..1206c6a9 100644 --- a/src/PHPCensor/Plugin/PhpTalLint.php +++ b/src/Plugin/PhpTalLint.php @@ -9,7 +9,7 @@ use PHPCensor\Plugin; /** * PHPTAL Lint Plugin - Provides access to PHPTAL lint functionality. - * + * * @author Stephen Ball */ class PhpTalLint extends Plugin @@ -35,12 +35,12 @@ class PhpTalLint extends Plugin /** * @var int */ - protected $allowed_warnings; + protected $allowedWarnings; /** * @var int */ - protected $allowed_errors; + protected $allowedErrors; /** * @var array The results of the lint scan @@ -58,8 +58,8 @@ class PhpTalLint extends Plugin $this->suffixes = ['zpt']; $this->ignore = $this->builder->ignore; - $this->allowed_warnings = 0; - $this->allowed_errors = 0; + $this->allowedWarnings = 0; + $this->allowedErrors = 0; if (!empty($options['directory'])) { $this->directories = [$options['directory']]; @@ -102,11 +102,11 @@ class PhpTalLint extends Plugin $success = true; - if ($this->allowed_warnings != -1 && $warnings > $this->allowed_warnings) { + if ($this->allowedWarnings != -1 && $warnings > $this->allowedWarnings) { $success = false; } - if ($this->allowed_errors != -1 && $errors > $this->allowed_errors) { + if ($this->allowedErrors != -1 && $errors > $this->allowedErrors) { $success = false; } @@ -127,7 +127,7 @@ class PhpTalLint extends Plugin if (!$this->lintFile($itemPath)) { $success = false; } - } elseif ($item->isDir() && $this->recursive && !$this->lintDirectory($itemPath . DIRECTORY_SEPARATOR)) { + } elseif ($item->isDir() && $this->recursive && !$this->lintDirectory($itemPath . '/')) { $success = false; } @@ -174,10 +174,10 @@ class PhpTalLint extends Plugin list($suffixes, $tales) = $this->getFlags(); - $lint = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR; - $lint .= 'vendor' . DIRECTORY_SEPARATOR . 'phptal' . DIRECTORY_SEPARATOR . 'phptal' . DIRECTORY_SEPARATOR; - $lint .= 'tools' . DIRECTORY_SEPARATOR . 'phptal_lint.php'; - $cmd = '/usr/bin/env php ' . $lint . ' %s %s "%s"'; + $lint = __DIR__ . '/'; + $lint .= 'vendor/phptal/phptal/'; + $lint .= 'tools/phptal_lint.php'; + $cmd = 'php ' . $lint . ' %s %s "%s"'; $this->builder->executeCommand($cmd, $suffixes, $tales, $this->builder->buildPath . $path); diff --git a/src/PHPCensor/Plugin/PhpUnit.php b/src/Plugin/PhpUnit.php similarity index 99% rename from src/PHPCensor/Plugin/PhpUnit.php rename to src/Plugin/PhpUnit.php index 3ce1b052..3f61f7f0 100644 --- a/src/PHPCensor/Plugin/PhpUnit.php +++ b/src/Plugin/PhpUnit.php @@ -2,7 +2,7 @@ namespace PHPCensor\Plugin; -use b8\Config; +use PHPCensor\Config; use PHPCensor; use PHPCensor\Builder; use PHPCensor\Model\Build; diff --git a/src/PHPCensor/Plugin/SecurityChecker.php b/src/Plugin/SecurityChecker.php similarity index 95% rename from src/PHPCensor/Plugin/SecurityChecker.php rename to src/Plugin/SecurityChecker.php index ba665f87..9634531d 100644 --- a/src/PHPCensor/Plugin/SecurityChecker.php +++ b/src/Plugin/SecurityChecker.php @@ -59,7 +59,7 @@ class SecurityChecker extends Plugin implements ZeroConfigPluginInterface */ public static function canExecute($stage, Builder $builder, Build $build) { - $path = $builder->buildPath . DIRECTORY_SEPARATOR . 'composer.lock'; + $path = $builder->buildPath . '/composer.lock'; if (file_exists($path) && $stage == Build::STAGE_TEST) { return true; @@ -72,7 +72,7 @@ class SecurityChecker extends Plugin implements ZeroConfigPluginInterface { $success = true; $checker = new BaseSecurityChecker(); - $warnings = $checker->check($this->builder->buildPath . DIRECTORY_SEPARATOR . 'composer.lock'); + $warnings = $checker->check($this->builder->buildPath . '/composer.lock'); if ($warnings) { foreach ($warnings as $library => $warning) { diff --git a/src/PHPCensor/Plugin/Shell.php b/src/Plugin/Shell.php similarity index 100% rename from src/PHPCensor/Plugin/Shell.php rename to src/Plugin/Shell.php diff --git a/src/PHPCensor/Plugin/SlackNotify.php b/src/Plugin/SlackNotify.php similarity index 100% rename from src/PHPCensor/Plugin/SlackNotify.php rename to src/Plugin/SlackNotify.php diff --git a/src/PHPCensor/Plugin/Sqlite.php b/src/Plugin/Sqlite.php similarity index 100% rename from src/PHPCensor/Plugin/Sqlite.php rename to src/Plugin/Sqlite.php diff --git a/src/PHPCensor/Plugin/TechnicalDebt.php b/src/Plugin/TechnicalDebt.php similarity index 100% rename from src/PHPCensor/Plugin/TechnicalDebt.php rename to src/Plugin/TechnicalDebt.php diff --git a/src/PHPCensor/Plugin/Util/Executor.php b/src/Plugin/Util/Executor.php similarity index 99% rename from src/PHPCensor/Plugin/Util/Executor.php rename to src/Plugin/Util/Executor.php index c36bf7f3..0bf44079 100644 --- a/src/PHPCensor/Plugin/Util/Executor.php +++ b/src/Plugin/Util/Executor.php @@ -2,7 +2,7 @@ namespace PHPCensor\Plugin\Util; -use b8\Store\Factory as StoreFactory; +use PHPCensor\Store\Factory as StoreFactory; use Exception; use PHPCensor\Helper\Lang; use PHPCensor\Logging\BuildLogger; @@ -162,7 +162,7 @@ class Executor $success = true; foreach ($plugins as $plugin => $options) { - $this->logger->log("\n" . + $this->logger->log("\n" . sprintf('RUNNING PLUGIN: %s', Lang::get($plugin)) . ' (' . 'Stage' . ': ' . ucfirst($stage) . ')' ); diff --git a/src/PHPCensor/Plugin/Util/Factory.php b/src/Plugin/Util/Factory.php similarity index 100% rename from src/PHPCensor/Plugin/Util/Factory.php rename to src/Plugin/Util/Factory.php diff --git a/src/PHPCensor/Plugin/Util/PhpUnitResult.php b/src/Plugin/Util/PhpUnitResult.php similarity index 100% rename from src/PHPCensor/Plugin/Util/PhpUnitResult.php rename to src/Plugin/Util/PhpUnitResult.php diff --git a/src/PHPCensor/Plugin/Util/PhpUnitResultJson.php b/src/Plugin/Util/PhpUnitResultJson.php similarity index 100% rename from src/PHPCensor/Plugin/Util/PhpUnitResultJson.php rename to src/Plugin/Util/PhpUnitResultJson.php diff --git a/src/PHPCensor/Plugin/Util/PhpUnitResultJunit.php b/src/Plugin/Util/PhpUnitResultJunit.php similarity index 100% rename from src/PHPCensor/Plugin/Util/PhpUnitResultJunit.php rename to src/Plugin/Util/PhpUnitResultJunit.php diff --git a/src/PHPCensor/Plugin/Util/TestResultParsers/Codeception.php b/src/Plugin/Util/TestResultParsers/Codeception.php similarity index 55% rename from src/PHPCensor/Plugin/Util/TestResultParsers/Codeception.php rename to src/Plugin/Util/TestResultParsers/Codeception.php index 6c2594a9..dfd97cae 100644 --- a/src/PHPCensor/Plugin/Util/TestResultParsers/Codeception.php +++ b/src/Plugin/Util/TestResultParsers/Codeception.php @@ -39,39 +39,39 @@ class Codeception implements ParserInterface $this->results = new \SimpleXMLElement($this->resultsXml); // calculate total results - foreach ($this->results->testsuite as $test_suite) { - $this->totalTests += (int)$test_suite['tests']; - $this->totalTimeTaken += (float)$test_suite['time']; - $this->totalFailures += (int)$test_suite['failures']; - $this->totalErrors += (int)$test_suite['errors']; + foreach ($this->results->testsuite as $testSuite) { + $this->totalTests += (int)$testSuite['tests']; + $this->totalTimeTaken += (float)$testSuite['time']; + $this->totalFailures += (int)$testSuite['failures']; + $this->totalErrors += (int)$testSuite['errors']; - foreach ($test_suite->testcase as $test_case) { - $test_result = [ - 'suite' => (string)$test_suite['name'], - 'file' => str_replace($this->builder->buildPath, '/', (string) $test_case['file']), - 'name' => (string)$test_case['name'], - 'feature' => (string)$test_case['feature'], - 'assertions' => (int)$test_case['assertions'], - 'time' => (float)$test_case['time'] + foreach ($testSuite->testcase as $testCase) { + $testResult = [ + 'suite' => (string)$testSuite['name'], + 'file' => str_replace($this->builder->buildPath, '/', (string) $testCase['file']), + 'name' => (string)$testCase['name'], + 'feature' => (string)$testCase['feature'], + 'assertions' => (int)$testCase['assertions'], + 'time' => (float)$testCase['time'] ]; - if (isset($test_case['class'])) { - $test_result['class'] = (string) $test_case['class']; + if (isset($testCase['class'])) { + $testResult['class'] = (string) $testCase['class']; } // PHPUnit testcases does not have feature field. Use class::method instead - if (!$test_result['feature']) { - $test_result['feature'] = sprintf('%s::%s', $test_result['class'], $test_result['name']); + if (!$testResult['feature']) { + $testResult['feature'] = sprintf('%s::%s', $testResult['class'], $testResult['name']); } - if (isset($test_case->failure) || isset($test_case->error)) { - $test_result['pass'] = false; - $test_result['message'] = isset($test_case->failure) ? (string)$test_case->failure : (string)$test_case->error; + if (isset($testCase->failure) || isset($testCase->error)) { + $testResult['pass'] = false; + $testResult['message'] = isset($testCase->failure) ? (string)$testCase->failure : (string)$testCase->error; } else { - $test_result['pass'] = true; + $testResult['pass'] = true; } - $rtn[] = $test_result; + $rtn[] = $testResult; } } diff --git a/src/PHPCensor/Plugin/Util/TestResultParsers/ParserInterface.php b/src/Plugin/Util/TestResultParsers/ParserInterface.php similarity index 100% rename from src/PHPCensor/Plugin/Util/TestResultParsers/ParserInterface.php rename to src/Plugin/Util/TestResultParsers/ParserInterface.php diff --git a/src/PHPCensor/Plugin/Wipe.php b/src/Plugin/Wipe.php similarity index 100% rename from src/PHPCensor/Plugin/Wipe.php rename to src/Plugin/Wipe.php diff --git a/src/PHPCensor/Plugin/Xmpp.php b/src/Plugin/Xmpp.php similarity index 84% rename from src/PHPCensor/Plugin/Xmpp.php rename to src/Plugin/Xmpp.php index 4c6aa8cd..0c2b7d69 100644 --- a/src/PHPCensor/Plugin/Xmpp.php +++ b/src/Plugin/Xmpp.php @@ -111,8 +111,8 @@ class XMPP extends Plugin */ public function findConfigFile() { - if (file_exists($this->builder->buildPath . DIRECTORY_SEPARATOR . '.sendxmpprc')) { - if (md5(file_get_contents($this->builder->buildPath . DIRECTORY_SEPARATOR . '.sendxmpprc')) + if (file_exists($this->builder->buildPath . '/.sendxmpprc')) { + if (md5(file_get_contents($this->builder->buildPath . '/.sendxmpprc')) !== md5($this->getConfigFormat())) { return null; } @@ -140,10 +140,10 @@ class XMPP extends Plugin /* * Try to build conf file */ - $config_file = $this->builder->buildPath . DIRECTORY_SEPARATOR . '.sendxmpprc'; + $configFile = $this->builder->buildPath . '/.sendxmpprc'; if (is_null($this->findConfigFile())) { - file_put_contents($config_file, $this->getConfigFormat()); - chmod($config_file, 0600); + file_put_contents($configFile, $this->getConfigFormat()); + chmod($configFile, 0600); } /* @@ -154,8 +154,8 @@ class XMPP extends Plugin $tls = ' -t'; } - $message_file = $this->builder->buildPath . DIRECTORY_SEPARATOR . uniqid('xmppmessage'); - if ($this->buildMessage($message_file) === false) { + $messageFile = $this->builder->buildPath . '/' . uniqid('xmppmessage'); + if ($this->buildMessage($messageFile) === false) { return false; } @@ -165,23 +165,23 @@ class XMPP extends Plugin $cmd = $sendxmpp . "%s -f %s -m %s %s"; $recipients = implode(' ', $this->recipients); - $success = $this->builder->executeCommand($cmd, $tls, $config_file, $message_file, $recipients); + $success = $this->builder->executeCommand($cmd, $tls, $configFile, $messageFile, $recipients); print $this->builder->getLastOutput(); /* * Remove temp message file */ - $this->builder->executeCommand("rm -rf ".$message_file); + $this->builder->executeCommand("rm -rf ".$messageFile); return $success; } /** - * @param $message_file + * @param $messageFile * @return int */ - protected function buildMessage($message_file) + protected function buildMessage($messageFile) { if ($this->build->isSuccessful()) { $message = "✔ [".$this->build->getProjectTitle()."] Build #" . $this->build->getId()." successful"; @@ -191,6 +191,6 @@ class XMPP extends Plugin $message .= ' ('.strftime($this->dateFormat).')'; - return file_put_contents($message_file, $message); + return file_put_contents($messageFile, $message); } } diff --git a/src/PHPCensor/ProcessControl/Factory.php b/src/ProcessControl/Factory.php similarity index 100% rename from src/PHPCensor/ProcessControl/Factory.php rename to src/ProcessControl/Factory.php diff --git a/src/PHPCensor/ProcessControl/PosixProcessControl.php b/src/ProcessControl/PosixProcessControl.php similarity index 100% rename from src/PHPCensor/ProcessControl/PosixProcessControl.php rename to src/ProcessControl/PosixProcessControl.php diff --git a/src/PHPCensor/ProcessControl/ProcessControlInterface.php b/src/ProcessControl/ProcessControlInterface.php similarity index 100% rename from src/PHPCensor/ProcessControl/ProcessControlInterface.php rename to src/ProcessControl/ProcessControlInterface.php diff --git a/src/PHPCensor/ProcessControl/UnixProcessControl.php b/src/ProcessControl/UnixProcessControl.php similarity index 100% rename from src/PHPCensor/ProcessControl/UnixProcessControl.php rename to src/ProcessControl/UnixProcessControl.php diff --git a/src/PHPCensor/Security/Authentication/LoginPasswordProviderInterface.php b/src/Security/Authentication/LoginPasswordProviderInterface.php similarity index 100% rename from src/PHPCensor/Security/Authentication/LoginPasswordProviderInterface.php rename to src/Security/Authentication/LoginPasswordProviderInterface.php diff --git a/src/PHPCensor/Security/Authentication/Service.php b/src/Security/Authentication/Service.php similarity index 99% rename from src/PHPCensor/Security/Authentication/Service.php rename to src/Security/Authentication/Service.php index 7b5aa0ef..da8e7d5a 100644 --- a/src/PHPCensor/Security/Authentication/Service.php +++ b/src/Security/Authentication/Service.php @@ -2,7 +2,7 @@ namespace PHPCensor\Security\Authentication; -use b8\Config; +use PHPCensor\Config; /** * Authentication facade. diff --git a/src/PHPCensor/Security/Authentication/UserProvider/AbstractProvider.php b/src/Security/Authentication/UserProvider/AbstractProvider.php similarity index 100% rename from src/PHPCensor/Security/Authentication/UserProvider/AbstractProvider.php rename to src/Security/Authentication/UserProvider/AbstractProvider.php diff --git a/src/PHPCensor/Security/Authentication/UserProvider/Internal.php b/src/Security/Authentication/UserProvider/Internal.php similarity index 100% rename from src/PHPCensor/Security/Authentication/UserProvider/Internal.php rename to src/Security/Authentication/UserProvider/Internal.php diff --git a/src/PHPCensor/Security/Authentication/UserProvider/Ldap.php b/src/Security/Authentication/UserProvider/Ldap.php similarity index 96% rename from src/PHPCensor/Security/Authentication/UserProvider/Ldap.php rename to src/Security/Authentication/UserProvider/Ldap.php index 6fa3470e..88a91fb0 100644 --- a/src/PHPCensor/Security/Authentication/UserProvider/Ldap.php +++ b/src/Security/Authentication/UserProvider/Ldap.php @@ -2,7 +2,7 @@ namespace PHPCensor\Security\Authentication\UserProvider; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use PHPCensor\Model\User; use PHPCensor\Security\Authentication\LoginPasswordProviderInterface; use PHPCensor\Service\UserService; @@ -79,6 +79,6 @@ class Ldap extends AbstractProvider implements LoginPasswordProviderInterface $parts = explode("@", $identifier); $username = $parts[0]; - return $userService->createUser($username, $identifier, $this->key, json_encode($this->config), '', false); + return $userService->createUser($username, $identifier, $this->key, $this->config, '', false); } } diff --git a/src/PHPCensor/Security/Authentication/UserProviderInterface.php b/src/Security/Authentication/UserProviderInterface.php similarity index 100% rename from src/PHPCensor/Security/Authentication/UserProviderInterface.php rename to src/Security/Authentication/UserProviderInterface.php diff --git a/src/PHPCensor/Service/BuildService.php b/src/Service/BuildService.php similarity index 86% rename from src/PHPCensor/Service/BuildService.php rename to src/Service/BuildService.php index 36ba2958..b8503fb7 100644 --- a/src/PHPCensor/Service/BuildService.php +++ b/src/Service/BuildService.php @@ -2,7 +2,7 @@ namespace PHPCensor\Service; -use b8\Config; +use PHPCensor\Config; use Pheanstalk\Pheanstalk; use Pheanstalk\PheanstalkInterface; use PHPCensor\BuildFactory; @@ -43,7 +43,7 @@ class BuildService * @param string|null $commitMessage * @param integer $source * @param integer $userId - * @param string|null $extra + * @param array|null $extra * * @return \PHPCensor\Model\Build */ @@ -61,12 +61,16 @@ class BuildService ) { $build = new Build(); $build->setCreateDate(new \DateTime()); - $build->setProject($project); + $build->setProjectId($project->getId()); $build->setStatus(Build::STATUS_PENDING); $build->setEnvironment($environment); + if (!is_null($extra)) { + $build->setExtra($extra); + } + $branches = $project->getBranchesByEnvironment($environment); - $build->setExtraValue('branches', $branches); + $build->addExtraValue('branches', $branches); $build->setSource($source); $build->setUserId($userId); @@ -90,10 +94,6 @@ class BuildService $build->setCommitMessage($commitMessage); } - if (!is_null($extra)) { - $build->setExtraValues($extra); - } - /** @var Build $build */ $build = $this->buildStore->save($build); $buildId = $build->getId(); @@ -116,15 +116,17 @@ class BuildService { $data = $copyFrom->getDataArray(); - // Clean up unwanted properties from the original build: - unset($data['id']); - unset($data['status']); - unset($data['log']); - unset($data['start_date']); - unset($data['finish_date']); - $build = new Build(); - $build->setValues($data); + $build->setProjectId($data['project_id']); + $build->setCommitId($data['commit_id']); + $build->setBranch($data['branch']); + $build->setTag($data['tag']); + $build->setCommitterEmail($data['committer_email']); + $build->setCommitMessage($data['commit_message']); + $build->setExtra(json_decode($data['extra'], true)); + $build->setEnvironment($data['environment']); + $build->setSource($data['source']); + $build->setUserId($data['user_id']); $build->setCreateDate(new \DateTime()); $build->setStatus(Build::STATUS_PENDING); diff --git a/src/PHPCensor/Service/BuildStatusService.php b/src/Service/BuildStatusService.php similarity index 100% rename from src/PHPCensor/Service/BuildStatusService.php rename to src/Service/BuildStatusService.php diff --git a/src/PHPCensor/Service/ProjectService.php b/src/Service/ProjectService.php similarity index 92% rename from src/PHPCensor/Service/ProjectService.php rename to src/Service/ProjectService.php index 7822f062..29cee64a 100644 --- a/src/PHPCensor/Service/ProjectService.php +++ b/src/Service/ProjectService.php @@ -63,8 +63,8 @@ class ProjectService $project->setTitle($title); $project->setType($type); $project->setReference($reference); - $project->setAllowPublicStatus(0); - $project->setDefaultBranchOnly(0); + $project->setAllowPublicStatus(false); + $project->setDefaultBranchOnly(false); // Handle extra project options: if (array_key_exists('ssh_private_key', $options)) { @@ -80,11 +80,11 @@ class ProjectService } if (array_key_exists('allow_public_status', $options)) { - $project->setAllowPublicStatus((int)$options['allow_public_status']); + $project->setAllowPublicStatus($options['allow_public_status']); } if (array_key_exists('archived', $options)) { - $project->setArchived((bool)$options['archived']); + $project->setArchived($options['archived']); } if (array_key_exists('branch', $options)) { @@ -92,11 +92,11 @@ class ProjectService } if (array_key_exists('default_branch_only', $options)) { - $project->setDefaultBranchOnly((int)$options['default_branch_only']); + $project->setDefaultBranchOnly($options['default_branch_only']); } if (array_key_exists('group', $options)) { - $project->setGroup($options['group']); + $project->setGroupId($options['group']); } // Allow certain project types to set access information: diff --git a/src/PHPCensor/Service/UserService.php b/src/Service/UserService.php similarity index 93% rename from src/PHPCensor/Service/UserService.php rename to src/Service/UserService.php index c3abd18d..efec9846 100644 --- a/src/PHPCensor/Service/UserService.php +++ b/src/Service/UserService.php @@ -29,7 +29,7 @@ class UserService * @param string $name * @param string $email * @param string $providerKey - * @param string $providerData + * @param array $providerData * @param string $password * @param boolean $isAdmin * @@ -43,7 +43,7 @@ class UserService $user->setHash(password_hash($password, PASSWORD_DEFAULT)); $user->setProviderKey($providerKey); $user->setProviderData($providerData); - $user->setIsAdmin(($isAdmin ? 1 : 0)); + $user->setIsAdmin($isAdmin); return $this->store->save($user); } @@ -71,9 +71,9 @@ class UserService } if (!is_null($isAdmin)) { - $user->setIsAdmin(($isAdmin ? 1 : 0)); + $user->setIsAdmin($isAdmin); } - + $user->setLanguage($language); $user->setPerPage($perPage); diff --git a/src/B8Framework/Store.php b/src/Store.php similarity index 95% rename from src/B8Framework/Store.php rename to src/Store.php index bef8e11a..ce218f92 100644 --- a/src/B8Framework/Store.php +++ b/src/Store.php @@ -1,6 +1,6 @@ getDataArray(); $modified = ($saveAllColumns) ? array_keys($data) : $obj->getModified(); - $updates = []; - $update_params = []; + $updates = []; + $updateParams = []; foreach ($modified as $key) { - $updates[] = $key . ' = :' . $key; - $update_params[] = [$key, $data[$key]]; + $updates[] = $key . ' = :' . $key; + $updateParams[] = [$key, $data[$key]]; } if (count($updates)) { $qs = 'UPDATE {{' . $this->tableName . '}} SET ' . implode(', ', $updates) . ' WHERE {{' . $this->primaryKey . '}} = :primaryKey'; $q = Database::getConnection('write')->prepareCommon($qs); - foreach ($update_params as $update_param) { - $q->bindValue(':' . $update_param[0], $update_param[1]); + foreach ($updateParams as $updateParam) { + $q->bindValue(':' . $updateParam[0], $updateParam[1]); } $q->bindValue(':primaryKey', $data[$this->primaryKey]); diff --git a/src/PHPCensor/Store/BuildErrorStore.php b/src/Store/BuildErrorStore.php similarity index 99% rename from src/PHPCensor/Store/BuildErrorStore.php rename to src/Store/BuildErrorStore.php index b13ede4a..c5bda60e 100644 --- a/src/PHPCensor/Store/BuildErrorStore.php +++ b/src/Store/BuildErrorStore.php @@ -2,9 +2,9 @@ namespace PHPCensor\Store; -use b8\Database; +use PHPCensor\Database; use PHPCensor\Model\BuildError; -use b8\Exception\HttpException; +use PHPCensor\Exception\HttpException; use PHPCensor\Store; class BuildErrorStore extends Store diff --git a/src/PHPCensor/Store/BuildErrorWriter.php b/src/Store/BuildErrorWriter.php similarity index 98% rename from src/PHPCensor/Store/BuildErrorWriter.php rename to src/Store/BuildErrorWriter.php index b104613a..5ec6d3d7 100644 --- a/src/PHPCensor/Store/BuildErrorWriter.php +++ b/src/Store/BuildErrorWriter.php @@ -2,10 +2,9 @@ namespace PHPCensor\Store; -use b8\Config; -use b8\Database; +use PHPCensor\Config; +use PHPCensor\Database; use PHPCensor\Model\BuildError; -use b8\Store\Factory; /** * Class BuildErrorWriter diff --git a/src/PHPCensor/Store/BuildMetaStore.php b/src/Store/BuildMetaStore.php similarity index 98% rename from src/PHPCensor/Store/BuildMetaStore.php rename to src/Store/BuildMetaStore.php index 08529889..abf75cb9 100644 --- a/src/PHPCensor/Store/BuildMetaStore.php +++ b/src/Store/BuildMetaStore.php @@ -3,9 +3,9 @@ namespace PHPCensor\Store; use PHPCensor\Store; -use b8\Database; +use PHPCensor\Database; use PHPCensor\Model\BuildMeta; -use b8\Exception\HttpException; +use PHPCensor\Exception\HttpException; class BuildMetaStore extends Store { diff --git a/src/PHPCensor/Store/BuildStore.php b/src/Store/BuildStore.php similarity index 92% rename from src/PHPCensor/Store/BuildStore.php rename to src/Store/BuildStore.php index be3ad4e8..b06aa315 100644 --- a/src/PHPCensor/Store/BuildStore.php +++ b/src/Store/BuildStore.php @@ -2,10 +2,9 @@ namespace PHPCensor\Store; -use b8\Database; -use b8\Store\Factory; +use PHPCensor\Database; use PHPCensor\Model\Build; -use b8\Exception\HttpException; +use PHPCensor\Exception\HttpException; use PHPCensor\Model\BuildMeta; use PHPCensor\Store; @@ -240,12 +239,12 @@ class BuildStore extends Store /** * Return an array of the latest builds for all projects. * - * @param integer $limit_by_project - * @param integer $limit_all + * @param integer $limitByProject + * @param integer $limitAll * * @return array */ - public function getAllProjectsLatestBuilds($limit_by_project = 5, $limit_all = 10) + public function getAllProjectsLatestBuilds($limitByProject = 5, $limitAll = 10) { // don't fetch log field - contain many data $query = ' @@ -276,40 +275,40 @@ class BuildStore extends Store $projects = []; $latest = []; foreach ($res as $item) { - $project_id = $item['project_id']; + $projectId = $item['project_id']; $environment = $item['environment']; - if (empty($projects[$project_id])) { - $projects[$project_id] = []; + if (empty($projects[$projectId])) { + $projects[$projectId] = []; } - if (empty($projects[$project_id][$environment])) { - $projects[$project_id][$environment] = [ + if (empty($projects[$projectId][$environment])) { + $projects[$projectId][$environment] = [ 'latest' => [], 'success' => null, 'failed' => null, ]; } $build = null; - if (count($projects[$project_id][$environment]['latest']) < $limit_by_project) { + if (count($projects[$projectId][$environment]['latest']) < $limitByProject) { $build = new Build($item); - $projects[$project_id][$environment]['latest'][] = $build; + $projects[$projectId][$environment]['latest'][] = $build; } - if (count($latest) < $limit_all) { + if (count($latest) < $limitAll) { if (is_null($build)) { $build = new Build($item); } $latest[] = $build; } - if (empty($projects[$project_id][$environment]['success']) and ($item['status'] == Build::STATUS_SUCCESS)) { + if (empty($projects[$projectId][$environment]['success']) && Build::STATUS_SUCCESS === $item['status']) { if (is_null($build)) { $build = new Build($item); } - $projects[$project_id][$environment]['success'] = $build; + $projects[$projectId][$environment]['success'] = $build; } - if (empty($projects[$project_id][$environment]['failed']) and ($item['status'] == Build::STATUS_FAILED)) { + if (empty($projects[$projectId][$environment]['failed']) && Build::STATUS_FAILED === $item['status']) { if (is_null($build)) { $build = new Build($item); } - $projects[$project_id][$environment]['failed'] = $build; + $projects[$projectId][$environment]['failed'] = $build; } } diff --git a/src/PHPCensor/Store/EnvironmentStore.php b/src/Store/EnvironmentStore.php similarity index 97% rename from src/PHPCensor/Store/EnvironmentStore.php rename to src/Store/EnvironmentStore.php index 8bee7f08..ec206b5b 100644 --- a/src/PHPCensor/Store/EnvironmentStore.php +++ b/src/Store/EnvironmentStore.php @@ -2,10 +2,10 @@ namespace PHPCensor\Store; -use b8\Database; +use PHPCensor\Database; use PHPCensor\Model\Environment; use PHPCensor\Store; -use b8\Exception\HttpException; +use PHPCensor\Exception\HttpException; class EnvironmentStore extends Store { diff --git a/src/B8Framework/Store/Factory.php b/src/Store/Factory.php similarity index 55% rename from src/B8Framework/Store/Factory.php rename to src/Store/Factory.php index fe9dfb21..3c516109 100644 --- a/src/B8Framework/Store/Factory.php +++ b/src/Store/Factory.php @@ -1,20 +1,20 @@ loadStore($storeName, $namespace); + return $factory->loadStore($storeName); } protected function __construct() @@ -48,19 +47,15 @@ class Factory /** * @param string $store - * @param string $namespace * - * @return \b8\Store; + * @return Store; */ - public function loadStore($store, $namespace = null) + public function loadStore($store) { if (!isset($this->loadedStores[$store])) { - $namespace = is_null($namespace) - ? Config::getInstance()->get('b8.app.namespace') - : $namespace; + $class = 'PHPCensor\\Store\\' . $store . 'Store'; + $obj = new $class(); - $class = $namespace . '\\Store\\' . $store . 'Store'; - $obj = new $class(); $this->loadedStores[$store] = $obj; } diff --git a/src/PHPCensor/Store/ProjectGroupStore.php b/src/Store/ProjectGroupStore.php similarity index 97% rename from src/PHPCensor/Store/ProjectGroupStore.php rename to src/Store/ProjectGroupStore.php index c53c8e17..2e1d4a05 100644 --- a/src/PHPCensor/Store/ProjectGroupStore.php +++ b/src/Store/ProjectGroupStore.php @@ -2,8 +2,8 @@ namespace PHPCensor\Store; -use b8\Database; -use b8\Exception\HttpException; +use PHPCensor\Database; +use PHPCensor\Exception\HttpException; use PHPCensor\Store; use PHPCensor\Model\ProjectGroup; diff --git a/src/PHPCensor/Store/ProjectStore.php b/src/Store/ProjectStore.php similarity index 99% rename from src/PHPCensor/Store/ProjectStore.php rename to src/Store/ProjectStore.php index b0473208..e2127fed 100644 --- a/src/PHPCensor/Store/ProjectStore.php +++ b/src/Store/ProjectStore.php @@ -2,10 +2,10 @@ namespace PHPCensor\Store; -use b8\Database; +use PHPCensor\Database; use PHPCensor\Model\Project; use PHPCensor\Store; -use b8\Exception\HttpException; +use PHPCensor\Exception\HttpException; /** * @author Dan Cryer diff --git a/src/PHPCensor/Store/UserStore.php b/src/Store/UserStore.php similarity index 98% rename from src/PHPCensor/Store/UserStore.php rename to src/Store/UserStore.php index 8bb75a7b..b397f090 100644 --- a/src/PHPCensor/Store/UserStore.php +++ b/src/Store/UserStore.php @@ -3,8 +3,8 @@ namespace PHPCensor\Store; use PHPCensor\Store; -use b8\Database; -use b8\Exception\HttpException; +use PHPCensor\Database; +use PHPCensor\Exception\HttpException; use PHPCensor\Model\User; /** diff --git a/src/PHPCensor/View.php b/src/View.php similarity index 94% rename from src/PHPCensor/View.php rename to src/View.php index dcb4cb38..1948b80d 100644 --- a/src/PHPCensor/View.php +++ b/src/View.php @@ -2,8 +2,7 @@ namespace PHPCensor; -use b8\Config; -use b8\Store\Factory; +use PHPCensor\Store\Factory; use PHPCensor\Model\User; use PHPCensor\Store\UserStore; @@ -29,7 +28,7 @@ class View protected static function getViewFile($file, $path = null) { - $viewPath = is_null($path) ? Config::getInstance()->get('b8.view.path') : $path; + $viewPath = is_null($path) ? (SRC_DIR . 'View/') : $path; $fullPath = $viewPath . $file . '.' . static::$extension; return $fullPath; diff --git a/src/PHPCensor/View/Build/errors.phtml b/src/View/Build/errors.phtml similarity index 100% rename from src/PHPCensor/View/Build/errors.phtml rename to src/View/Build/errors.phtml diff --git a/src/PHPCensor/View/Build/header-row.phtml b/src/View/Build/header-row.phtml similarity index 72% rename from src/PHPCensor/View/Build/header-row.phtml rename to src/View/Build/header-row.phtml index b2038c4d..126f39bf 100644 --- a/src/PHPCensor/View/Build/header-row.phtml +++ b/src/View/Build/header-row.phtml @@ -9,15 +9,15 @@ use PHPCensor\Model\Build; ?>
  • - + getCommitterEmail()): ?>
    - +

    - getProject()->getTitle(); ?> + getProject()->getTitle(); ?> getStatus() == \PHPCensor\Model\Build::STATUS_PENDING): ?> getCreateDate()->format('H:i')); ?> @@ -27,4 +27,4 @@ use PHPCensor\Model\Build;

    getBranch()); ?>

    -
  • \ No newline at end of file + diff --git a/src/PHPCensor/View/Build/view.phtml b/src/View/Build/view.phtml similarity index 95% rename from src/PHPCensor/View/Build/view.phtml rename to src/View/Build/view.phtml index da5f627a..888323e7 100644 --- a/src/PHPCensor/View/Build/view.phtml +++ b/src/View/Build/view.phtml @@ -72,7 +72,7 @@ use PHPCensor\Model\BuildError; $branches = $build->getExtra('branches'); if (!empty($branches)) { foreach($branches as $branch) { - ?> - getCommitId(), 0, 7); ?> + getCommitId(), 0, 7); ?> @@ -113,14 +113,14 @@ use PHPCensor\Model\BuildError; - getCommitterEmail(); ?> + getCommitterEmail(); ?> - getCommitMessage(); ?> + getCommitMessage()); ?> @@ -175,26 +175,26 @@ use PHPCensor\Model\BuildError;