summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorDan Ungureanu <udan1107@gmail.com>2015-07-11 18:04:10 +0300
committerDan Ungureanu <udan1107@gmail.com>2015-07-11 18:07:10 +0300
commitaa865c9c941940a6c1eefb22d1d28b97809dd336 (patch)
tree577e41a182fad6b1bac71cf97042f4bfbc67e32b /src
parent08ad4807b1797459aec8de364d1fb11686d194ca (diff)
downloadsql-parser-aa865c9c941940a6c1eefb22d1d28b97809dd336.zip
sql-parser-aa865c9c941940a6c1eefb22d1d28b97809dd336.tar.gz
sql-parser-aa865c9c941940a6c1eefb22d1d28b97809dd336.tar.bz2
The closest context can be loaded for better compatibility.
Diffstat (limited to 'src')
-rw-r--r--src/Context.php48
1 files changed, 47 insertions, 1 deletions
diff --git a/src/Context.php b/src/Context.php
index b3bf4a0..7f937dc 100644
--- a/src/Context.php
+++ b/src/Context.php
@@ -422,13 +422,59 @@ abstract class Context
$context = self::$contextPrefix . $context;
}
if (!class_exists($context)) {
- throw new \Exception('Specified context ("' . $context . '") does not exist.');
+ throw new \Exception(
+ 'Specified context ("' . $context . '") does not exist.'
+ );
}
self::$loadedContext = $context;
self::$KEYWORDS = $context::$KEYWORDS;
}
/**
+ * Loads the context with the closest version to the one specified.
+ *
+ * The closest context is found by replacing last digits with zero until one
+ * is loaded succesfully.
+ *
+ * @see Context::load()
+ *
+ * @param string $context 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 = 0;
+
+ // As long as a new context can be generated, we try to laod it.
+ do {
+ $loaded = true;
+ 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;
+ }
+
+ /**
* Sets the SQL mode.
*
* @param string $mode The list of modes. If empty, the mode is reset.