REBELinBLUE\Deployer\Console\Commands\ClearOrphanAvatars::purgeOldAvatars PHP Method

purgeOldAvatars() private method

Remove unused avatar files from disk.
private purgeOldAvatars ( )
    private function purgeOldAvatars()
    {
        // Build up a list of all avatar images
        $avatars = glob(public_path() . '/upload/*/*.*');
        // Remove the public_path() from the path so that they match values in the DB
        array_walk($avatars, function (&$avatar) {
            $avatar = str_replace(public_path(), '', $avatar);
        });
        $all_avatars = collect($avatars);
        // Get all avatars currently assigned
        $current_avatars = DB::table('users')->whereNotNull('avatar')->lists('avatar');
        // Compare the 2 collections get a list of avatars which are no longer assigned
        $orphan_avatars = $all_avatars->diff($current_avatars);
        $this->info('Found ' . $orphan_avatars->count() . ' orphaned avatars');
        // Now loop through the avatars and delete them from storage
        foreach ($orphan_avatars as $avatar) {
            $avatarPath = public_path() . $avatar;
            // Don't delete recently created files as they could be temp files from the uploader
            if (filemtime($avatarPath) > strtotime('-15 minutes')) {
                $this->info('Skipping ' . $avatar);
                continue;
            }
            if (!unlink($avatarPath)) {
                $this->error('Failed to delete ' . $avatar);
            } else {
                $this->info('Deleted ' . $avatar);
            }
        }
    }
ClearOrphanAvatars