DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

How to locate all usages of a method in PHP code with Bash and Git

Using Git grep you can locate code fragment very, very fast. Much faster than any IDE. So I made a very simple script to help me refactor my code.

Code

Create a file find-usage.sh with the following content

#!/bin/bash
git grep -C2 -p -E "(-[>]|::)$1\("
Enter fullscreen mode Exit fullscreen mode

make it executable with

chmod +x find-usage.sh
Enter fullscreen mode Exit fullscreen mode

It will locate usage like $object->method() as well as Object::staticMethod().

Usage

find-usage.sh methodName
Enter fullscreen mode Exit fullscreen mode

Output:

>_bin/find-usage.sh getName
app/Models/Addworking/User/Concerns/User/HasLogs.php=trait HasLogs
--
app/Models/Addworking/User/Concerns/User/HasLogs.php-    {
app/Models/Addworking/User/Concerns/User/HasLogs.php-        $this->log()->create([
app/Models/Addworking/User/Concerns/User/HasLogs.php:            'route'         => optional($request->route())->getName() ?? 'n/a',
app/Models/Addworking/User/Concerns/User/HasLogs.php-            'url'           => substr($request->fullUrl(), 0, 254),
app/Models/Addworking/User/Concerns/User/HasLogs.php-            'http_method'   => $request->getMethod(),
--
Enter fullscreen mode Exit fullscreen mode

Leave a like and a comment if you need help using it.

Top comments (0)