DEV Community

Benjamin Delespierre
Benjamin Delespierre

Posted on

2

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay