22
33namespace Elegantly \Translator \Services \SearchCode ;
44
5+ use Closure ;
6+ use Elegantly \Translator \Caches \SearchCodeCache ;
7+ use Illuminate \Contracts \Filesystem \Filesystem ;
58use Illuminate \Support \Facades \Blade ;
69use PhpParser \Node ;
710use PhpParser \Node \Expr \FuncCall ;
1417
1518class PhpParserService implements SearchCodeServiceInterface
1619{
20+ public ?SearchCodeCache $ cache = null ;
21+
1722 public function __construct (
1823 public array $ paths ,
1924 public array $ excludedPaths = [],
25+ ?Filesystem $ cacheStorage = null ,
2026 ) {
21- //
27+ if ($ cacheStorage ) {
28+ $ this ->cache = new SearchCodeCache ($ cacheStorage );
29+ }
2230 }
2331
2432 public function finder (): Finder
2533 {
2634 return Finder::create ()
2735 ->in ($ this ->paths )
28- // ->exclude($this->excludedPaths)
2936 ->notPath ($ this ->excludedPaths )
3037 ->exclude ('vendor ' )
3138 ->exclude ('node_modules ' )
@@ -39,7 +46,7 @@ public function finder(): Finder
3946 }
4047
4148 /**
42- * @return string[]
49+ * @return string[] All translations keys used in the code
4350 */
4451 public static function scanCode (string $ code ): array
4552 {
@@ -72,24 +79,45 @@ public static function scanCode(string $code): array
7279 ->toArray ();
7380 }
7481
75- public function translationsByFiles (): array
76- {
82+ public function translationsByFiles (
83+ ?Closure $ progress = null ,
84+ ): array {
7785 return collect ($ this ->finder ())
78- ->map (function (SplFileInfo $ file ) {
79- $ content = str ($ file ->getFilename ())->endsWith ('.blade.php ' )
80- ? Blade::compileString ($ file ->getContents ())
81- : $ file ->getContents ();
86+ ->map (function (SplFileInfo $ file , string $ key ) use ($ progress ) {
87+
88+ $ lastModified = $ file ->getMTime ();
89+ $ cachedResult = $ this ->cache ?->get($ key );
90+
91+ if (
92+ $ lastModified && $ cachedResult &&
93+ $ lastModified < $ cachedResult ['created_at ' ]
94+ ) {
95+ $ translations = $ cachedResult ['translations ' ];
96+ } else {
97+ $ content = str ($ file ->getFilename ())->endsWith ('.blade.php ' )
98+ ? Blade::compileString ($ file ->getContents ())
99+ : $ file ->getContents ();
82100
83- return static ::scanCode ($ content );
101+ $ translations = static ::scanCode ($ content );
102+
103+ $ this ->cache ?->put($ key , $ translations );
104+ }
105+
106+ if ($ progress ) {
107+ $ progress ($ file );
108+ }
109+
110+ return $ translations ;
84111 })
85112 ->filter ()
86113 ->sortKeys (SORT_NATURAL )
87114 ->toArray ();
88115 }
89116
90- public function filesByTranslations (): array
91- {
92- $ translations = $ this ->translationsByFiles ();
117+ public function filesByTranslations (
118+ ?Closure $ progress = null ,
119+ ): array {
120+ $ translations = $ this ->translationsByFiles ($ progress );
93121
94122 $ results = [];
95123
0 commit comments