SqlParser\Context::loadClosest PHP Method

loadClosest() public static method

The closest context is found by replacing last digits with zero until one is loaded successfully.
See also: Context::load()
public static loadClosest ( string $context = '' ) : string
$context string Name of the context or full class name that defines the context.
return string The loaded context. `null` if no context was loaded.
    public static function loadClosest($context = '')
    {
        /**
         * The number of replaces done by `preg_replace`.
         * This actually represents whether a new context was generated or not.
         *
         * @var int $count
         */
        $count = 0;
        // As long as a new context can be generated, we try to load it.
        do {
            try {
                // Trying to load the new context.
                static::load($context);
            } catch (\Exception $e) {
                // If it didn't work, we are looking for a new one and skipping
                // over to the next generation that will try the new context.
                $context = preg_replace('/[1-9](0*)$/', '0$1', $context, -1, $count);
                continue;
            }
            // Last generated context was valid (did not throw any exceptions).
            // So we return it, to let the user know what context was loaded.
            return $context;
        } while ($count !== 0);
        return null;
    }

Usage Example

Example #1
0
 public function testLoad()
 {
     // Default context is 5.7.0.
     $this->assertEquals('\\SqlParser\\Contexts\\ContextMySql50700', Context::$loadedContext);
     $this->assertTrue(isset(Context::$KEYWORDS['STORED']));
     $this->assertFalse(isset(Context::$KEYWORDS['AUTHORS']));
     Context::load('MySql50600');
     $this->assertEquals('\\SqlParser\\Contexts\\ContextMySql50600', Context::$loadedContext);
     $this->assertFalse(isset(Context::$KEYWORDS['STORED']));
     $this->assertTrue(isset(Context::$KEYWORDS['AUTHORS']));
     Context::loadClosest('MySql50712');
     $this->assertEquals('\\SqlParser\\Contexts\\ContextMySql50700', Context::$loadedContext);
     $this->assertEquals(null, Context::loadClosest('Sql'));
     // Restoring context.
     Context::load('');
     $this->assertEquals('\\SqlParser\\Contexts\\ContextMySql50700', Context::$defaultContext);
     $this->assertTrue(isset(Context::$KEYWORDS['STORED']));
     $this->assertFalse(isset(Context::$KEYWORDS['AUTHORS']));
 }