Sfoglia il codice sorgente

Rector (#19)

* Rector code quality run

* Ran Rector with coding style ruleset

* Ran Rector with the naming setlist
Belle Aerni 2 anni fa
parent
commit
ff9583bfdf

+ 7 - 2
rector.php

@@ -2,11 +2,11 @@
 
 declare(strict_types=1);
 
-use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
+use Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector;
+use Rector\CodingStyle\Rector\FuncCall\ConsistentPregDelimiterRector;
 use Rector\Config\RectorConfig;
 use Rector\Php80\Rector\FunctionLike\MixedTypeRector;
 use Rector\Php80\Rector\FunctionLike\UnionTypesRector;
-use Rector\Set\ValueObject\LevelSetList;
 use Rector\Set\ValueObject\SetList;
 
 return static function (RectorConfig $rectorConfig): void {
@@ -19,9 +19,14 @@ return static function (RectorConfig $rectorConfig): void {
         __DIR__ . '/src/Cache',
         UnionTypesRector::class,
         MixedTypeRector::class,
+        EncapsedStringsToSprintfRector::class,
+        ConsistentPregDelimiterRector::class,
     ]);
 
     $rectorConfig->sets([
         SetList::PHP_80,
+        SetList::CODE_QUALITY,
+        SetList::CODING_STYLE,
+        SetList::NAMING,
     ]);
 };

+ 4 - 6
src/AntCMS/AntCMS.php

@@ -63,9 +63,8 @@ class AntCMS
         $pageTemplate = str_replace('<!--AntCMS-Navigation-->', AntPages::generateNavigation($this->getThemeTemplate('nav_layout', $theme), $currentPage), $pageTemplate);
 
         $pageTemplate = str_replace('<!--AntCMS-SiteTitle-->', $siteInfo['siteTitle'], $pageTemplate);
-        $pageTemplate = str_replace('<!--AntCMS-SiteLink-->', '//' . AntConfig::currentConfig('baseURL'), $pageTemplate);
 
-        return $pageTemplate;
+        return str_replace('<!--AntCMS-SiteLink-->', '//' . AntConfig::currentConfig('baseURL'), $pageTemplate);
     }
 
     /**
@@ -92,11 +91,11 @@ class AntCMS
     public function getPage(string $page)
     {
         $page = strtolower($page);
-        $pagePath = AntDir . "/Content/$page";
+        $pagePath = AntDir . "/Content/{$page}";
         $pagePath = AntTools::repairFilePath($pagePath);
 
         if (is_dir($pagePath)) {
-            $pagePath = $pagePath . '/index.md';
+            $pagePath .= '/index.md';
         } else {
             $pagePath = (file_exists($pagePath)) ? $pagePath : $pagePath . '.md';
         }
@@ -107,8 +106,7 @@ class AntCMS
                 $pageHeaders = AntCMS::getPageHeaders($pageContent);
                 // Remove the AntCMS section from the content
                 $pageContent = preg_replace('/\A--AntCMS--.*?--AntCMS--/sm', '', $pageContent);
-                $result = ['content' => $pageContent, 'title' => $pageHeaders['title'], 'author' => $pageHeaders['author'], 'description' => $pageHeaders['description'], 'keywords' => $pageHeaders['keywords']];
-                return $result;
+                return ['content' => $pageContent, 'title' => $pageHeaders['title'], 'author' => $pageHeaders['author'], 'description' => $pageHeaders['description'], 'keywords' => $pageHeaders['keywords']];
             } catch (\Exception) {
                 return false;
             }

+ 4 - 5
src/AntCMS/AntCache.php

@@ -17,7 +17,7 @@ class AntCache
      */
     public function setCache(string $key, string $content)
     {
-        $cachePath = AntCachePath . DIRECTORY_SEPARATOR . "$key.cache";
+        $cachePath = AntCachePath . DIRECTORY_SEPARATOR . "{$key}.cache";
         $config = AntConfig::currentConfig();
         if ($config['enableCache']) {
             try {
@@ -40,12 +40,11 @@ class AntCache
      */
     public function getCache(string $key)
     {
-        $cachePath = AntCachePath . DIRECTORY_SEPARATOR . "$key.cache";
+        $cachePath = AntCachePath . DIRECTORY_SEPARATOR . "{$key}.cache";
         $config = AntConfig::currentConfig();
         if ($config['enableCache']) {
             try {
-                $contents = file_get_contents($cachePath);
-                return $contents;
+                return file_get_contents($cachePath);
             } catch (\Exception) {
                 return false;
             }
@@ -65,7 +64,7 @@ class AntCache
     {
         $config = AntConfig::currentConfig();
         if ($config['enableCache']) {
-            $cachePath = AntCachePath . DIRECTORY_SEPARATOR . "$key.cache";
+            $cachePath = AntCachePath . DIRECTORY_SEPARATOR . "{$key}.cache";
             return file_exists($cachePath);
         } else {
             return false;

+ 4 - 3
src/AntCMS/AntConfig.php

@@ -56,13 +56,14 @@ class AntConfig
      */
     private static function getArrayValue(array $array, array $keys)
     {
-        foreach ($keys as $k) {
-            if (isset($array[$k])) {
-                $array = $array[$k];
+        foreach ($keys as $key) {
+            if (isset($array[$key])) {
+                $array = $array[$key];
             } else {
                 return null;
             }
         }
+        
         return $array;
     }
 

+ 7 - 6
src/AntCMS/AntKeywords.php

@@ -15,15 +15,15 @@ class AntKeywords
      */
     public function generateKeywords(string $content = '', int $count = 15)
     {
-        $cache = new AntCache();
-        $cacheKey = $cache->createCacheKey($content, 'keywords');
+        $antCache = new AntCache();
+        $cacheKey = $antCache->createCacheKey($content, 'keywords');
 
         if (!AntConfig::currentConfig('generateKeywords')) {
             return '';
         }
 
-        if ($cache->isCached($cacheKey)) {
-            $cachedKeywords = $cache->getCache($cacheKey);
+        if ($antCache->isCached($cacheKey)) {
+            $cachedKeywords = $antCache->getCache($cacheKey);
 
             if ($cachedKeywords !== false && !empty($cachedKeywords)) {
                 return $cachedKeywords;
@@ -31,8 +31,9 @@ class AntKeywords
         }
 
         $keywords = RakePlus::create($content, 'en_US', $count)->keywords();
-        $keywords = implode(",", $keywords);    
-        $cache->setCache($cacheKey, $keywords);
+        $keywords = implode(",", $keywords);
+            
+        $antCache->setCache($cacheKey, $keywords);
         return $keywords;
     }
 }

+ 8 - 8
src/AntCMS/AntMarkdown.php

@@ -23,11 +23,11 @@ class AntMarkdown
      */
     public static function renderMarkdown(string $md)
     {
-        $cache = new AntCache();
-        $cacheKey = $cache->createCacheKey($md, 'markdown');
+        $antCache = new AntCache();
+        $cacheKey = $antCache->createCacheKey($md, 'markdown');
 
-        if ($cache->isCached($cacheKey)) {
-            $cachedContent = $cache->getCache($cacheKey);
+        if ($antCache->isCached($cacheKey)) {
+            $cachedContent = $antCache->getCache($cacheKey);
 
             if ($cachedContent !== false && !empty($cachedContent)) {
                 return $cachedContent;
@@ -52,11 +52,11 @@ class AntMarkdown
         $environment->addExtension(new EmojiExtension());
         $environment->addExtension(new EmbedExtension());
 
-        $converter = new MarkdownConverter($environment);
+        $markdownConverter = new MarkdownConverter($environment);
 
-        $result = $converter->convert($md);
+        $renderedContent = $markdownConverter->convert($md);
 
-        $cache->setCache($cacheKey, $result);
-        return $result;
+        $antCache->setCache($cacheKey, $renderedContent);
+        return $renderedContent;
     }
 }

+ 8 - 7
src/AntCMS/AntPages.php

@@ -30,6 +30,7 @@ class AntPages
             );
             $pageList[] = $currentPage;
         }
+        
         AntYaml::saveFile(antPagesList, $pageList);
     }
 
@@ -47,13 +48,13 @@ class AntPages
     public static function generateNavigation(string $navTemplate = '', string $currentPage = '')
     {
         $pages = AntPages::getPages();
-        $cache = new AntCache;
+        $antCache = new AntCache;
 
         $theme = AntConfig::currentConfig('activeTheme');
-        $cacheKey = $cache->createCacheKey(json_encode($pages), $theme . $currentPage);
+        $cacheKey = $antCache->createCacheKey(json_encode($pages), $theme . $currentPage);
 
-        if ($cache->isCached($cacheKey)) {
-            $cachedContent = $cache->getCache($cacheKey);
+        if ($antCache->isCached($cacheKey)) {
+            $cachedContent = $antCache->getCache($cacheKey);
 
             if ($cachedContent !== false && !empty($cachedContent)) {
                 return $cachedContent;
@@ -62,20 +63,20 @@ class AntPages
 
         $currentPage = strtolower($currentPage);
         if (str_ends_with($currentPage, '/')) {
-            $currentPage = $currentPage . 'index.md';
+            $currentPage .= 'index.md';
         }
 
         $baseURL = AntConfig::currentConfig('baseURL');
         foreach ($pages as $key => $page) {
             $url = "//" . AntTools::repairURL($baseURL . $page['functionalPagePath']);
             $pages[$key]['url'] = $url;
-            $pages[$key]['active'] = ($currentPage == strtolower($page['functionalPagePath'])) ? true : false;
+            $pages[$key]['active'] = $currentPage === strtolower($page['functionalPagePath']);
         }
 
         $antTwig = new AntTwig;
         $navHTML = $antTwig->renderWithTiwg($navTemplate, array('pages' => $pages));
 
-        $cache->setCache($cacheKey, $navHTML);
+        $antCache->setCache($cacheKey, $navHTML);
         return $navHTML;
     }
 }

+ 2 - 2
src/AntCMS/AntTools.php

@@ -20,6 +20,7 @@ class AntTools
                 $files[] = ($returnPath) ? $file->getPathname() : $file->getFilename();
             }
         }
+        
         return $files;
     }
 
@@ -50,8 +51,7 @@ class AntTools
     {
         $newURL = str_replace('\\\\', '/', $url);
         $newURL = str_replace('\\', '/', $newURL);
-        $newURL = str_replace('//', '/', $newURL);
 
-        return $newURL;
+        return str_replace('//', '/', $newURL);
     }
 }

+ 5 - 5
src/AntCMS/AntTwig.php

@@ -23,14 +23,14 @@ class AntTwig
 
         $templatePath = AntTools::repairFilePath(antThemePath . '/' . $theme . '/' . 'Templates');
 
-        $loaderFilesystem = new \Twig\Loader\FilesystemLoader($templatePath);
-        $loaderString = new \Shapecode\Twig\Loader\StringLoader();
-        $loader = new \Twig\Loader\ChainLoader([$loaderString, $loaderFilesystem]);
-        $twig = new \Twig\Environment($loader, [
+        $filesystemLoader = new \Twig\Loader\FilesystemLoader($templatePath);
+        $stringLoader = new \Shapecode\Twig\Loader\StringLoader();
+        $chainLoader = new \Twig\Loader\ChainLoader([$stringLoader, $filesystemLoader]);
+        $twigEnvironment = new \Twig\Environment($chainLoader, [
             'cache' => $twigCache,
             'debug' => AntConfig::currentConfig('debug'),
         ]);
 
-        return $twig->render($content, $params);
+        return $twigEnvironment->render($content, $params);
     }
 }

+ 1 - 1
src/Autoload.php

@@ -1,6 +1,6 @@
 <?php
 
-spl_autoload_register(function ($class) {
+spl_autoload_register(static function ($class) {
     $class = str_replace('\\', '/', $class);
     $path = __DIR__ . '/' . $class . '.php';
     if (is_readable($path)) {

+ 14 - 6
src/Plugins/Admin/AdminPlugin.php

@@ -52,7 +52,7 @@ class AdminPlugin extends AntPlugin
     }
 
     /** @return string  */
-    public function getName()
+    public function getName(): string
     {
         return 'Admin';
     }
@@ -86,10 +86,12 @@ class AdminPlugin extends AntPlugin
                 if (!$_POST['textarea']) {
                     header('Location: //' . $currentConfig['baseURL'] . "plugin/admin/config/");
                 }
+                
                 $yaml = AntYaml::parseYaml($_POST['textarea']);
                 if (is_array($yaml)) {
                     AntYaml::saveFile(antConfigFile, $yaml);
                 }
+                
                 header('Location: //' . $currentConfig['baseURL'] . "plugin/admin/config/");
                 exit;
 
@@ -99,20 +101,23 @@ class AdminPlugin extends AntPlugin
                 $HTMLTemplate .= "<ul>\n";
                 foreach ($currentConfig as $key => $value) {
                     if (is_array($value)) {
-                        $HTMLTemplate .= "<li>$key:</li>\n";
+                        $HTMLTemplate .= "<li>{$key}:</li>\n";
                         $HTMLTemplate .= "<ul>\n";
                         foreach ($value as $key => $value) {
                             $value = is_bool($value) ? $this->boolToWord($value) : $value;
-                            $HTMLTemplate .= "<li>$key: $value</li>\n";
+                            $HTMLTemplate .= "<li>{$key}: {$value}</li>\n";
                         }
+                        
                         $HTMLTemplate .= "</ul>\n";
                     } else {
                         $value = is_bool($value) ? $this->boolToWord($value) : $value;
-                        $HTMLTemplate .= "<li>$key: $value</li>\n";
+                        $HTMLTemplate .= "<li>{$key}: {$value}</li>\n";
                     }
                 }
+                
                 $HTMLTemplate .= "</ul>\n";
         }
+        
         $pageTemplate = str_replace('<!--AntCMS-Body-->', $HTMLTemplate, $pageTemplate);
         $pageTemplate = $antTwig->renderWithTiwg($pageTemplate, $params);
 
@@ -154,12 +159,13 @@ class AdminPlugin extends AntPlugin
                     if (!str_ends_with($pagePath, ".md")) {
                         $pagePath .= '.md';
                     }
+                    
                     $page = "--AntCMS--\nTitle: New Page Title\nAuthor: Author\nDescription: Description of this page.\nKeywords: Keywords\n--AntCMS--\n";
                 }
 
                 $pagePath = AntTools::repairFilePath($pagePath);
 
-                $HTMLTemplate = str_replace('<!--AntCMS-ActionURL-->', '//' . AntConfig::currentConfig('baseURL') . "plugin/admin/pages/save/$pagePath", $HTMLTemplate);
+                $HTMLTemplate = str_replace('<!--AntCMS-ActionURL-->', '//' . AntConfig::currentConfig('baseURL') . "plugin/admin/pages/save/{$pagePath}", $HTMLTemplate);
                 $HTMLTemplate = str_replace('<!--AntCMS-TextAreaContent-->', htmlspecialchars($page), $HTMLTemplate);
                 break;
 
@@ -169,6 +175,7 @@ class AdminPlugin extends AntPlugin
                 if (!isset($_POST['textarea'])) {
                     header('Location: //' . AntConfig::currentConfig('baseURL') . "plugin/admin/pages/");
                 }
+                
                 file_put_contents($pagePath, $_POST['textarea']);
                 header('Location: //' . AntConfig::currentConfig('baseURL') . "plugin/admin/pages/");
                 exit;
@@ -200,6 +207,7 @@ class AdminPlugin extends AntPlugin
                     $HTMLTemplate .= "</ul>\n";
                     $HTMLTemplate .= "</li>\n";
                 }
+                
                 $HTMLTemplate .= "</ul>\n";
         }
 
@@ -216,6 +224,6 @@ class AdminPlugin extends AntPlugin
      */
     private function boolToWord(bool $value)
     {
-        return boolval($value) ? 'true' : 'false';
+        return (bool) $value ? 'true' : 'false';
     }
 }

+ 2 - 1
src/Plugins/Robotstxt/RobotstxtPlugin.php

@@ -18,7 +18,8 @@ class RobotstxtPlugin extends AntPlugin
         echo $robotstxt;
         exit;
     }
-    public function getName()
+    
+    public function getName(): string
     {
         return 'Robotstxt';
     }

+ 12 - 11
src/Plugins/Sitemap/SitemapPlugin.php

@@ -15,12 +15,12 @@ class SitemapPlugin extends AntPlugin
         $pages = AntPages::getPages();
 
         if (extension_loaded('dom')) {
-            $doc = new DOMDocument();
-            $doc->formatOutput = true;
+            $domDocument = new DOMDocument();
+            $domDocument->formatOutput = true;
 
-            $root = $doc->createElement('urlset');
-            $root->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
-            $doc->appendChild($root);
+            $domElement = $domDocument->createElement('urlset');
+            $domElement->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
+            $domDocument->appendChild($domElement);
 
             $urls = array();
             foreach ($pages as $key => $value) {
@@ -29,25 +29,26 @@ class SitemapPlugin extends AntPlugin
             }
 
             foreach ($urls as $url) {
-                $element = $doc->createElement('url');
+                $element = $domDocument->createElement('url');
 
-                $loc = $doc->createElement('loc', $protocol . '://' . AntTools::repairURL($baseURL . $url['url']));
+                $loc = $domDocument->createElement('loc', $protocol . '://' . AntTools::repairURL($baseURL . $url['url']));
                 $element->appendChild($loc);
 
-                $lastmod = $doc->createElement('lastmod', $url['lastchange']);
+                $lastmod = $domDocument->createElement('lastmod', $url['lastchange']);
                 $element->appendChild($lastmod);
 
-                $root->appendChild($element);
+                $domElement->appendChild($element);
             }
 
             header('Content-Type: application/xml');
-            echo $doc->saveXML();
+            echo $domDocument->saveXML();
             exit;
         } else {
             die("AntCMS is unable to generate a sitemap without having the DOM extension loadded in PHP.");
         }
     }
-    public function getName()
+    
+    public function getName(): string
     {
         return 'Sitemap';
     }

+ 3 - 0
src/index.php

@@ -28,9 +28,11 @@ if (AntConfig::currentConfig('forceHTTPS') && 'cli' !== PHP_SAPI) {
     if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
         $isHTTPS = true;
     }
+    
     if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https') {
         $isHTTPS = true;
     }
+    
     if (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) !== 'off') {
         $isHTTPS = true;
     }
@@ -78,6 +80,7 @@ if ($segments[0] === 'plugin') {
             exit;
         }
     }
+    
     // plugin not found
     header("HTTP/1.0 404 Not Found");
     echo ("Error 404");

+ 3 - 3
tests/CMSTest.php

@@ -35,10 +35,10 @@ class CMSTest extends TestCase
         AntPages::generatePages();
 
         $antCMS = new AntCMS;
-        $result = $antCMS->getPageLayout();
+        $pageLayout = $antCMS->getPageLayout();
 
-        $this->assertNotEmpty($result);
-        $this->assertIsString($result);
+        $this->assertNotEmpty($pageLayout);
+        $this->assertIsString($pageLayout);
     }
 
     public function testGetPage()

+ 2 - 2
tests/ConfigTest.php

@@ -22,8 +22,8 @@ class ConfigTest extends TestCase
             'baseURL'
         );
 
-        foreach ($expectedKeys as $key) {
-            $this->assertArrayHasKey($key, $config, "Expected key '$key' not found in config array");
+        foreach ($expectedKeys as $expectedKey) {
+            $this->assertArrayHasKey($expectedKey, $config, "Expected key '{$expectedKey}' not found in config array");
         }
     }
 }

+ 7 - 7
tests/MarkdownTest.php

@@ -20,7 +20,7 @@ class MarkdownTest extends TestCase
         $markdown = file_get_contents(antContentPath . DIRECTORY_SEPARATOR . 'index.md');
         $totalTime = 0;
 
-        for ($i = 0; $i < 10; $i++) {
+        for ($i = 0; $i < 10; ++$i) {
             $start = microtime(true);
             AntMarkdown::renderMarkdown($markdown);
             $end = microtime(true);
@@ -29,11 +29,11 @@ class MarkdownTest extends TestCase
 
         $averageTime = $totalTime / 10;
 
-        $constraint = new Callback(function ($averageTime) {
+        $callback = new Callback(static function ($averageTime) {
             return $averageTime < 0.015;
         });
 
-        $this->assertThat($averageTime, $constraint, 'AntMarkdown::renderMarkdown took too long on average!');
+        $this->assertThat($averageTime, $callback, 'AntMarkdown::renderMarkdown took too long on average!');
     }
 
 
@@ -47,7 +47,7 @@ class MarkdownTest extends TestCase
         AntConfig::saveConfig($currentConfig);
 
         $totalTime = 0;
-        for ($i = 0; $i < 10; $i++) {
+        for ($i = 0; $i < 10; ++$i) {
             $start = microtime(true);
             AntMarkdown::renderMarkdown($markdown);
             $end = microtime(true);
@@ -61,7 +61,7 @@ class MarkdownTest extends TestCase
         AntConfig::saveConfig($currentConfig);
 
         $totalTime = 0;
-        for ($i = 0; $i < 10; $i++) {
+        for ($i = 0; $i < 10; ++$i) {
             $start = microtime(true);
             AntMarkdown::renderMarkdown($markdown);
             $end = microtime(true);
@@ -70,7 +70,7 @@ class MarkdownTest extends TestCase
 
         $withCache = $totalTime / 10;
         
-        echo "\n Markdown rendering speed with cache: $withCache VS without: $withoutCache \n\n";
-        $this->assertLessThan($withoutCache, $withCache, 'Cache didn\'t speed up rendering!');
+        echo "\n Markdown rendering speed with cache: {$withCache} VS without: {$withoutCache} \n\n";
+        $this->assertLessThan($withoutCache, $withCache, "Cache didn't speed up rendering!");
     }
 }

+ 2 - 2
tests/ToolsTest.php

@@ -26,7 +26,7 @@ class ToolsTest extends TestCase
 
         foreach ($badPaths as $index => $badPath) {
             $goodPath = AntTools::repairFilePath($badPath);
-            $this->assertEquals($expectedPaths[$index], $goodPath, "Expected '$expectedPaths[$index]' but got '$goodPath' for input '$badPath'");
+            $this->assertEquals($expectedPaths[$index], $goodPath, "Expected '$expectedPaths[$index]' but got '{$goodPath}' for input '{$badPath}'");
         }
     }
 
@@ -48,7 +48,7 @@ class ToolsTest extends TestCase
         $files = AntTools::getFileList($srcdir, 'md');
 
         foreach ($files as $file) {
-            $this->assertEquals('md', pathinfo($file, PATHINFO_EXTENSION), "Expected file extension to be 'md', but got '" . pathinfo($file, PATHINFO_EXTENSION) . "' for file '$file'");
+            $this->assertEquals('md', pathinfo($file, PATHINFO_EXTENSION), "Expected file extension to be 'md', but got '" . pathinfo($file, PATHINFO_EXTENSION) . "' for file '{$file}'");
         }
     }
 }