Tinkerwell 4 is out now! See what's new or buy now.
Tinkerwell background image
Tinkerwell Logo Tinkerwell

Magic Comments
#

Magic comments are a powerful feature that came to Tinkerwell with version 3. They allow you to debug your code inline without changing the result of the whole script.

Setup
#

Magic Comments only work if you use buffered output – you can configure the Output Type and Magic Comments in the general settings.

Tinkerwell settings

Using Magic Comments
#

You can trigger magic comments by adding //? to the end of a line – or by using it via an inline comment/*?*/. The following example uses both and you can copy & paste this code in your default app.

collect(Http::get('https://api.github.com/orgs/beyondcode/repos')/*?->status()*/
->json())
->map(function ($repo) {
$repo["id"]; //?
return [
'full_name' => $repo["full_name"],
'stars' => $repo["stargazers_count"]
];
});

Line 1 of this example adds the status of the Http call to the editor while line 5 adds the ID of each repo to the editor with every run of the map() function.

If you run queries with simple results on your application, you might even go for a clean version of Tinkerwell that has the output and toolbars hidden and just display the result inline.

User::count() //?

Timing your code
#

If you want to quickly inspect the time that it took you to evaluate your code up to a certain point, you can use the magic comment /*?.*/. This will automatically output the amount of seconds that it took PHP to reach this line of code.

If your timing method gets evaluated multiple times, for example because it is inside of a function that gets called, or within a loop, you will see a comma separated list of all the different timings that Tinkerwell recorded for this comment.

Accessing methods and properties in magic comments
#

When trying to debug your code, it can often be helpful to quickly see the result of a method call – especially when chaining methods like on Laravel's collection helpers. Imagine that you want to:

  • Get all users
  • See the count of all users
  • Filter the users
  • Get the count of all filtered users

Without magic comments, this would involve a lot of temporary variables that you would need to dump out, only in order to see the counts at the various stages of the collection.

With magic comments, this can easily be achieved. You can use the arrow syntax inside of a magic comment, to easily dump out object properties or even method calls within your code.

use App\User;
use Illuminate\Support\Str;
 
User::all() /*?->count()*/
->filter(function ($user) {
return Str::of($user->email)->endsWith('@beyondco.de');
}); /*?->count()*/

In this example, we are dumping out the count of our collection, without interfering with the actual method chain.