Drupal Finder provides a class to locate a Drupal installation in a given path.
$drupalFinder = new \DrupalFinder\DrupalFinder();
if ($drupalFinder->locateRoot(getcwd())) {
$drupalRoot = $drupalFinder->getDrupalRoot();
$composerRoot = $drupalFinder->getComposerRoot();
...
}
GPL-2.0+