Drupal Finder provides a class to locate a Drupal installation based on Composer metadata.
$drupalFinder = new \DrupalFinder\DrupalFinderComposerRuntime();
$drupalRoot = $drupalFinder->getDrupalRoot();
$composerRoot = $drupalFinder->getComposerRoot();
$vendorDir = $drupalFinder->getVendorDir();
GPL-2.0+