PedantryTest.php 2.44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php

namespace MongoDB\Tests;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionClass;
use ReflectionMethod;
use RegexIterator;

/**
 * Pedantic tests that have nothing to do with functional correctness.
 */
14
class PedantryTest extends TestCase
15 16 17 18 19 20 21 22 23
{
    /**
     * @dataProvider provideProjectClassNames
     */
    public function testMethodsAreOrderedAlphabeticallyByVisibility($className)
    {
        $class = new ReflectionClass($className);
        $methods = $class->getMethods();

24 25 26 27 28 29 30
        $methods = array_filter(
            $methods,
            function(ReflectionMethod $method) use ($class) {
                return $method->getDeclaringClass() == $class;
            }
        );

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
        $getSortValue = function(ReflectionMethod $method) {
            if ($method->getModifiers() & ReflectionMethod::IS_PRIVATE) {
                return '2' . $method->getName();
            }
            if ($method->getModifiers() & ReflectionMethod::IS_PROTECTED) {
                return '1' . $method->getName();
            }
            if ($method->getModifiers() & ReflectionMethod::IS_PUBLIC) {
                return '0' . $method->getName();
            }
        };

        $sortedMethods = $methods;
        usort(
            $sortedMethods,
            function(ReflectionMethod $a, ReflectionMethod $b) use ($getSortValue) {
                return strcasecmp($getSortValue($a), $getSortValue($b));
            }
        );

        $methods = array_map(function(ReflectionMethod $method) { return $method->getName(); }, $methods);
        $sortedMethods = array_map(function(ReflectionMethod $method) { return $method->getName(); }, $sortedMethods);

        $this->assertEquals($sortedMethods, $methods);
    }

    public function provideProjectClassNames()
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
59
        $classNames = [];
60 61 62 63 64
        $srcDir = realpath(__DIR__ . '/../src/');

        $files = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($srcDir)), '/\.php$/i');

        foreach ($files as $file) {
65 66 67 68
            if ($file->getFilename() === 'functions.php') {
                continue;
            }

69 70 71 72 73
            /* autoload.php added downstream (e.g. Fedora) */
            if ($file->getFilename() === 'autoload.php') {
                continue;
            }

74 75 76 77 78 79
            $classNames[][] = 'MongoDB\\' . str_replace(DIRECTORY_SEPARATOR, '\\', substr($file->getRealPath(), strlen($srcDir) + 1, -4));
        }

        return $classNames;
    }
}