3030use PhpParser \PhpVersion ;
3131use PhpParser \PrettyPrinter \Standard ;
3232use Symfony \Component \Filesystem \Filesystem ;
33+ use Webmozart \Assert \Assert ;
3334
3435final class Container
3536{
3637 private Filesystem $ filesystem ;
3738 private ConfigurationFactory $ configFactory ;
3839 private Parser $ parser ;
40+ private ?PhpVersion $ phpVersion = null ;
3941 private Reflector $ reflector ;
4042 private ScoperFactory $ scoperFactory ;
4143 private EnrichedReflectorFactory $ enrichedReflectorFactory ;
@@ -64,11 +66,11 @@ public function getConfigurationFactory(): ConfigurationFactory
6466 return $ this ->configFactory ;
6567 }
6668
67- public function getScoperFactory (): ScoperFactory
69+ public function getScoperFactory (? PhpVersion $ phpVersion = null ): ScoperFactory
6870 {
6971 if (!isset ($ this ->scoperFactory )) {
7072 $ this ->scoperFactory = new ScoperFactory (
71- $ this ->getParser (),
73+ $ this ->getParser ($ phpVersion ),
7274 $ this ->getEnrichedReflectorFactory (),
7375 $ this ->getPrinter (),
7476 );
@@ -77,21 +79,33 @@ public function getScoperFactory(): ScoperFactory
7779 return $ this ->scoperFactory ;
7880 }
7981
80- public function getParser (): Parser
82+ public function getParser (? PhpVersion $ phpVersion = null ): Parser
8183 {
8284 if (!isset ($ this ->parser )) {
83- $ this ->parser = $ this ->createParser ();
85+ $ this ->phpVersion = $ phpVersion ;
86+ $ this ->parser = $ this ->createParser ($ phpVersion );
87+ }
88+
89+ $ parserVersion = $ this ->phpVersion ;
90+
91+ $ parserMessage = 'Cannot use the existing parser: its PHP version is different than the one requested. ' ;
92+
93+ if (null === $ parserVersion ) {
94+ Assert::null ($ phpVersion , $ parserMessage );
95+ } else {
96+ Assert::notNull ($ phpVersion , $ parserMessage );
97+ Assert::true ($ parserVersion ->equals ($ phpVersion ), $ parserMessage );
8498 }
8599
86100 return $ this ->parser ;
87101 }
88102
89- private function createParser (): Parser
103+ private function createParser (? PhpVersion $ phpVersion ): Parser
90104 {
91- $ version = PhpVersion::getNewestSupported ();
105+ $ version = $ phpVersion ?? PhpVersion::getHostVersion ();
92106 $ lexer = $ version ->isHostVersion () ? new Lexer () : new Emulative ($ version );
93107
94- return $ version ->id >= 80000
108+ return $ version ->id >= 80_000
95109 ? new Php8 ($ lexer , $ version )
96110 : new Php7 ($ lexer , $ version );
97111 }
0 commit comments