Created
October 28, 2019 10:21
-
-
Save kublermdk/3b073b82441ff8fdd7fb5044ad5e32ef to your computer and use it in GitHub Desktop.
A PHP command line script for checking the REGEX of the mongodb+srv support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @return string database name | |
*/ | |
function getDefaultDatabaseName($dsn) | |
{ | |
if (preg_match('/^mongodb(:|\+srv:)\\/\\/.+\\/([^?&]+)/s', $dsn, $matches)) { | |
// Updated Pattern: /^mongodb(:|\+srv:)\\/\\/.+\\/([^?&]+)/s | |
// Original Pattern: '/^mongodb:\\/\\/.+\\/([^?&]+)/s' | |
return $matches[2]; | |
} else { | |
return false; | |
} | |
} | |
$tests = [ | |
'mongodb://localhost:27017/dbname' => 'dbname', | |
'mongodb+srv://localhost:27017/dbname' => 'dbname', | |
'mongodb+srv://staging-admin:[email protected]/test?retryWrites=true&w=majority' => 'test', | |
'mongodb://staging-admin:[email protected]/test?retryWrites=true&w=majority' => 'test', | |
'invalid' => false, | |
'invalid+srv' => false, | |
]; | |
foreach ($tests as $testString => $expectedResult) { | |
$result = getDefaultDatabaseName($testString); | |
echo ($expectedResult === $result ? '✓ As expected' : '✘ ERROR INVALID') . " the DB name for {$testString} is " . json_encode($result) . "\n"; | |
} | |
// ---------------------------------- | |
// Result | |
// ---------------------------------- | |
// > php yii2-mongodb-srv-support-test.php | |
// ✓ As expected the DB name for mongodb://localhost:27017/dbname is "dbname" | |
// ✓ As expected the DB name for mongodb+srv://localhost:27017/dbname is "dbname" | |
// ✓ As expected the DB name for mongodb+srv://staging-admin:[email protected]/test?retryWrites=true&w=majority is "test" | |
// ✓ As expected the DB name for mongodb://staging-admin:[email protected]/test?retryWrites=true&w=majority is "test" | |
// ✓ As expected the DB name for invalid is false | |
// ✓ As expected the DB name for invalid+srv is false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment