bensampo

Experience

46,230

0 Best Reply Awards

  • Member Since 1 Year Ago
  • 459 Lessons Completed
  • 0 Favorites

6th July, 2018

bensampo left a reply on Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?) • 2 weeks ago

@click This is pretty much what I have ended up with. I have a test which loops over all of the files in the resource folder and makes sure that a corresponding test files exists.

Thanks for the suggestions all!

bensampo left a reply on Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?) • 2 weeks ago

If anyone is interested, this is my solution:

public function test_resource_tests_exist_test()
    {
        // Get all of the resource test files
        $resourceTestFiles = array_map(function(SplFileInfo $file) {
            return $file->getFilename();
        }, array_filter(File::allFiles('tests/Unit'), function(SplFileInfo $file) {
            $filename = $file->getFilename();
            if (substr($filename, -strlen('ResourceTest.php'))==='ResourceTest.php') {
                return true;
            }
        }));

        // Loop over each of the resource files and assert that a test file exists for them
        $resourceFiles = array_map(function(SplFileInfo $file) use ($resourceTestFiles) {
            $resourceFilename = $file->getFilename();
            $expectedTestFile = str_replace('.php', 'Test.php', $resourceFilename);

            $this->assertContains($expectedTestFile, $resourceTestFiles);

        }, File::allFiles('app/Http/Resources'));
    }

This relies on the naming convention of: ModelResource.php for your model ModelResourceTest.php for your test

bensampo left a reply on Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?) • 2 weeks ago

Thanks @martinbean, to clarify: I want to check that the output contains the data I expect, rather than that it conforms to a standard.

bensampo started a new conversation Ensuring That There Are Tests For A Given Set Of Classes (static Analysis?) • 2 weeks ago

I'm building an API using Laravel's resources. I want to make sure that the output of each one conforms to my expectations, so for each resource class I have a corresponding unit test.

What I'd ideally like to do is have a test which grabs a list of all of my resource classes and makes sure there is a corresponding unit test.

Essentially I want to test that there are tests.

Is there a sensible/standard way to do this?

bensampo left a reply on Counting A Related Model Using Lazy Eager Loading • 2 weeks ago

Turns out this was all fine, I just hadn't set up the likes relation on the Comment model. Doh!

bensampo started a new conversation Counting A Related Model Using Lazy Eager Loading • 2 weeks ago

Hi,

I have a model for Houses. Each house can have many Comments. Comments can be liked by users. I want to include the number of likes alongside each of the comments.

I'm using route model binding and lazy eager loading on my controller action for [email protected]:

public function show(House $house)
    {
        $house->load([
            'comments' => function($query) {
                $query->withCount('likes');
            },
            'comments.user'
        ]);

        return new HouseResource($house);
    }
        

This doesn't work and I get the error:

Method Illuminate\Database\Query\Builder::likes does not exist.

Anyone know how I might be able to achieve this without re-querying the model?

30th May, 2018

bensampo left a reply on Flagged Enum • 1 month ago

I wrote a package which simulates enums but actually uses class constants.

https://github.com/BenSampo/laravel-enum

You could set up an enum like this:

// DaysEnum.php
namespace DummyNamespace;

use BenSampo\Enum\Enum;

final class Days extends Enum
{
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;
}

Your type in the DB column would be an int and you'd store the values 0-6 depending on the day.

You could then use the enum like this:

if ($day == Days::Tuesday) {
    // Do Tuesday stuff
}

11th September, 2017

bensampo left a reply on Laravel Enum • 10 months ago

I was looking for a similar solution recently and ended up building an abstract enum class pulled together from lots of different resources.

I've split it out into a package in case it's of use to anyone in future: https://github.com/BenSampo/laravel-enum

As an example you can do:

final class UserType extends Enum
{
    const Administrator = 0;
    const Moderator = 1;
    const Subscriber = 2;
    const SuperAdministrator = 3;
}

And grab the value back like:

UserType::Administrator // 0

Of course, you can then store this in the DB as an int.

22nd August, 2017

bensampo left a reply on Sanity Check On My Deployment, Staging, Production Plan. Is It Good? • 11 months ago

I believe that the environment variables should be added in Forge for production and staging and the .env should only be read on dev/local.

See: https://scotch.io/tutorials/understanding-laravel-environment-variables

I would be interested to hear others feedback on the rest, as I'm in a similar position and had a very similar idea on infrastructure to you.

14th August, 2017

bensampo left a reply on A Clean Way For Users To Opt Out Of Emails • 11 months ago

In the end I found an event which is fired just before sending a message. I've set up a listener for this event which grabs the users from the to address on the message and checks for a setting on the user model. Depending on if the users has emails enabled the event is either stopped or it continues. Code below:

EventServiceProvider.php

protected $listen = [
    'Illuminate\Mail\Events\MessageSending' => [
        'App\Listeners\MessageBeforeSendListener',
    ],
];

MessageBeforeSendListener.php

<?php

namespace App\Listeners;

use App\Repositories\IUserRepository;
use Illuminate\Mail\Events\MessageSending;

class MessageBeforeSendListener
{
    private $userRepo;

    /**
     * Create the event listener.
     */
    public function __construct(IUserRepository $userRepo)
    {
        $this->userRepo = $userRepo;
    }

    /**
     * Handle the event.
     *
     * @param MessageSending $event
     */
    public function handle(MessageSending $event)
    {
        $toAddress = key($event->message->getTo());
        $user = $this->userRepo->findWhere([
            'email' => $toAddress,
        ])->first();

        return $user->send_notification_emails ? $event : false;
    }
}

13th August, 2017

bensampo left a reply on A Clean Way For Users To Opt Out Of Emails • 11 months ago

@IgorBabko - thanks for the response. I could do that, but if I have 100 calls to different notifications, I'm going to need to do that for every one.

Ideally I'd like to say "only send emails to users who have opted in" globally.

bensampo started a new conversation A Clean Way For Users To Opt Out Of Emails • 11 months ago

I have a flag on my user model which allows people to opt out of emails. I want to use this flag to only send notification emails to users who have opted in. Is there a way to do this in one place rather than wrapping every call to Mail in a condition?

Thanks, Ben

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.