Skip to content

Instantly share code, notes, and snippets.

@kublermdk
Created October 28, 2019 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kublermdk/3b073b82441ff8fdd7fb5044ad5e32ef to your computer and use it in GitHub Desktop.
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
<?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:password@staging-cvs.mongodb.net/test?retryWrites=true&w=majority' => 'test',
'mongodb://staging-admin:password@staging-cvs.mongodb.net/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:password@staging-cvs.mongodb.net/test?retryWrites=true&w=majority is "test"
// ✓ As expected the DB name for mongodb://staging-admin:password@staging-cvs.mongodb.net/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