PHP code example of sierratecnologia / gamer

1. Go to this page and download the library: Download sierratecnologia/gamer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sierratecnologia / gamer example snippets


'providers' => [
    // ...
    Gamer\GamerProvider::class,
];

// src/Traits/Pointable.php
trait Pointable
{
    public function transactions($amount = null);      // Relacionamento com transações
    public function points();                           // Relacionamento com tipos de pontos
    public function countTransactions();                // Contagem de transações
    public function currentPoints();                    // Saldo atual de pontos
    public function addPoints($amount, $message, $data = null); // Adicionar pontos
}

// Eventos registrados no GamerProvider
$this->app['events']->listen(
    'eloquent.*',
    'Gamer\Observers\ModelCallbacks'
);

$this->app['events']->listen(
    'Illuminate\Auth\Events\Login',
    'Gamer\Observers\LoginObserver'
);

// src/Repositories/PromotionRepository.php
class PromotionRepository
{
    // Lógica de acesso a dados isolada
}

// src/Services/GamerService.php
class GamerService
{
    // Lógica de negócio centralizada
}

// Qualquer modelo pode ser "Pointable"
class User extends Model implements Pointable
{
    use PointableTrait;
}

// Relacionamento polimórfico
$user->transactions()->save($transaction);

$user = User::first();
$user->addPoints(100, 'Completou tutorial');

// Com metadados personalizados
$user->addPoints(50, 'Primeira compra', [
    'ref_id' => 'ORDER-123',
    'category' => 'sales'
]);

$currentPoints = $user->currentPoints(); // 150.0

// Todas as transações
$transactions = $user->transactions;

// Últimas 5 transações
$lastTransactions = $user->transactions(5)->get();

// Contagem total
$total = $user->countTransactions();

// Estrutura planejada
$user->badges()->attach($badgeId);
$user->achievements()->where('unlocked', true)->get();

// LoginObserver.php - Pontos automáticos ao fazer login
Event::listen('Illuminate\Auth\Events\Login', function($event) {
    $event->user->addPoints(10, 'Login diário');
});

// ModelCallbacks.php - Pontos por ações em modelos
Event::listen('eloquent.created', function($model) {
    if ($model instanceof Post) {
        $model->user->addPoints(50, 'Criou um novo post');
    }
});

// Criar competição
$competition = Competition::create([
    'name' => 'Desafio de Vendas Q1',
    'start_date' => now(),
    'end_date' => now()->addMonths(3),
]);

// Adicionar jogadores
$competition->players()->attach($userId);

// Criar time
$team = Team::create(['name' => 'Time Alpha']);
$team->players()->attach($playerIds);

// Rotas de usuário
Route::get('profile/gamer/home', 'User\HomeController@index')
    ->name('profile.gamer.home');

// Rotas administrativas (RiCa)
Route::resource('rica/gamer/points', 'RiCa\PointController');
Route::resource('rica/gamer/transactions', 'RiCa\TransactionController');
Route::resource('rica/gamer/competitions', 'RiCa\CompetitionController');

// 1. Usuário realiza uma ação (ex: compra um produto)
$order = Order::create([...]);

// 2. Evento é disparado
event(new OrderCreated($order));

// 3. Observer captura e atribui pontos
// EventPointable.php ou Listener customizado
$order->user->addPoints(
    $order->total * 0.1, // 10% do valor em pontos
    'Compra no valor de R$ ' . $order->total,
    ['order_id' => $order->id]
);

// 4. Sistema verifica conquistas
if ($order->user->countTransactions() >= 10) {
    $order->user->badges()->attach($badge10Compras);
    // 5. Notificação é enviada
    $order->user->notify(new BadgeUnlocked($badge10Compras));
}

// 6. Pontos são exibidos no dashboard
return view('gamer::profile.home', [
    'currentPoints' => $order->user->currentPoints(),
    'recentTransactions' => $order->user->transactions(5)->get(),
]);



namespace App\Models;

use Gamer\Contracts\Pointable;
use Gamer\Traits\Pointable as PointableTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements Pointable
{
    use PointableTrait;

    // ... resto do modelo
}



namespace App\Listeners;

use App\Events\PostPublished;

class AwardPostPoints
{
    public function handle(PostPublished $event)
    {
        $post = $event->post;

        // Pontos base
        $post->user->addPoints(100, 'Publicou um artigo');

        // Bônus por qualidade
        if ($post->word_count >= 1000) {
            $post->user->addPoints(50, 'Artigo com mais de 1000 palavras');
        }

        // Bônus por categoria
        if ($post->category === 'tutorial') {
            $post->user->addPoints(25, 'Tutorial técnico');
        }
    }
}

// EventServiceProvider.php
protected $listen = [
    'App\Events\PostPublished' => [
        'App\Listeners\AwardPostPoints',
    ],
];

// Migration já preparada: 2020_09_18_231619_create_gamer_badges_tables.php

// Model customizado
class Badge extends Model
{
    protected $fillable = ['name', 'description', 'icon', 'points_ublic function checkAndUnlock($user, $badgeSlug)
    {
        $badge = Badge::where('slug', $badgeSlug)->first();

        if ($user->currentPoints() >= $badge->points_



namespace App\Observers;

use App\Models\Comment;

class CommentObserver
{
    public function created(Comment $comment)
    {
        // Pontos para quem comentou
        $comment->user->addPoints(5, 'Comentou em um post');

        // Pontos para o autor do post
        $comment->post->author->addPoints(2, 'Recebeu um comentário');
    }
}

// AppServiceProvider.php
public function boot()
{
    Comment::observe(CommentObserver::class);
}



namespace App\Listeners;

use Illuminate\Events\Dispatcher;

class GamificationSubscriber
{
    public function onUserLogin($event)
    {
        $event->user->addPoints(10, 'Login diário');
    }

    public function onProfileUpdate($event)
    {
        if ($event->user->profile->isComplete()) {
            $event->user->addPoints(50, 'Completou o perfil');
        }
    }

    public function subscribe(Dispatcher $events)
    {
        $events->listen(
            'Illuminate\Auth\Events\Login',
            'App\Listeners\GamificationSubscriber@onUserLogin'
        );

        $events->listen(
            'App\Events\ProfileUpdated',
            'App\Listeners\GamificationSubscriber@onProfileUpdate'
        );
    }
}

   /**
    * Pontuação de Artigos:
    * - Publicação: 100 pontos
    * - +1000 palavras: +50 pontos
    * - Categoria Tutorial: +25 pontos
    * - Primeiro artigo: +100 pontos (badge)
    */
   

   DB::transaction(function () use ($user, $order) {
       $order->save();
       $user->addPoints(100, 'Nova compra');
   });
   

   if ($user->hasVerifiedEmail() && !$user->isBanned()) {
       $user->addPoints(50, 'Ação válida');
   }
   

// Provider já registra Tracking automaticamente
public static $providers = [
    \Tracking\TrackingProvider::class,
    // ...
];

use Gamer\Notifications\BadgeUnlocked;

$user->notify(new BadgeUnlocked($badge));

// Exemplo de integração
Event::listen('Market\Events\OrderCompleted', function($event) {
    $order = $event->order;
    $points = $order->total * 0.05; // 5% cashback

    $order->customer->addPoints(
        $points,
        'Cashback da compra #' . $order->id,
        ['order_id' => $order->id]
    );
});

// config/event-sourcing.php (publicado pelo Gamer)
return [
    'stored_event_model' => \Spatie\EventSourcing\StoredEvents\Models\EloquentStoredEvent::class,
    'stored_event_repository' => \Spatie\EventSourcing\StoredEvents\Repositories\EloquentStoredEventRepository::class,
    // ...
];

use Pedreiro\Models\Base;

class Point extends Base
{
    // Herda funcionalidades comuns: slugs, UUIDs, soft deletes, etc.
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Achievement extends Model
{
    protected $fillable = [
        'name',
        'description',
        'type', // 'points', 'actions', 'streak', 'level'
        'Pivot('unlocked_at', 'progress')
            ->withTimestamps();
    }
}



namespace App\Services;

use App\Models\Achievement;

class AchievementService
{
    public function checkAchievements($user)
    {
        $achievements = Achievement::all();

        foreach ($achievements as $achievement) {
            if ($this->meetsRequirement($user, $achievement)) {
                $this->unlock($user, $achievement);
            }
        }
    }

    protected function meetsRequirement($user, $achievement)
    {
        switch ($achievement->type) {
            case 'points':
                return $user->currentPoints() >= $achievement->$achievement->id)->exists()) {
            return; // Já desbloqueada
        }

        $user->achievements()->attach($achievement, [
            'unlocked_at' => now(),
        ]);

        // Recompensa
        if ($achievement->reward_points > 0) {
            $user->addPoints(
                $achievement->reward_points,
                'Conquista desbloqueada: ' . $achievement->name
            );
        }

        // Notificar
        $user->notify(new \App\Notifications\AchievementUnlocked($achievement));
    }
}



namespace App\Services;

class LevelService
{
    protected $levels = [
        1 => ['min' => 0, 'max' => 100, 'title' => 'Novato'],
        2 => ['min' => 100, 'max' => 300, 'title' => 'Iniciante'],
        3 => ['min' => 300, 'max' => 700, 'title' => 'Intermediário'],
        4 => ['min' => 700, 'max' => 1500, 'title' => 'Avançado'],
        5 => ['min' => 1500, 'max' => 3000, 'title' => 'Expert'],
        6 => ['min' => 3000, 'max' => PHP_INT_MAX, 'title' => 'Master'],
    ];

    public function getCurrentLevel($user)
    {
        $points = $user->currentPoints();

        foreach ($this->levels as $level => $config) {
            if ($points >= $config['min'] && $points < $config['max']) {
                return [
                    'level' => $level,
                    'title' => $config['title'],
                    'current_points' => $points,
                    'next_level_at' => $config['max'],
                    'progress' => $this->calculateProgress($points, $config),
                ];
            }
        }
    }

    protected function calculateProgress($points, $config)
    {
        $range = $config['max'] - $config['min'];
        $current = $points - $config['min'];

        return min(100, ($current / $range) * 100);
    }
}

   // ❌ Evite modificar Transaction.php

   // ✅ Crie seu próprio modelo
   class CustomTransaction extends \Gamer\Models\Transaction
   {
       public function customMethod() { ... }
   }
   

   Event::listen('gamer.points.added', function($transaction) {
       // Sua lógica customizada
   });
   

   namespace App\Gamer\Extensions;

   class CustomPointType extends PointType { ... }
   

// Pontos por assistir aulas
Event::listen('Course\Events\LessonCompleted', function($event) {
    $event->user->addPoints(10, 'Completou aula: ' . $event->lesson->title);
});

// Pontos por concluir curso
Event::listen('Course\Events\CourseCompleted', function($event) {
    $points = 100 + ($event->course->lessons_count * 5);
    $event->user->addPoints($points, 'Concluiu curso: ' . $event->course->title);
});
bash
# Publicar configurações
php artisan vendor:publish --provider="Gamer\GamerProvider" --tag=config

# Publicar migrations
php artisan vendor:publish --provider="Gamer\GamerProvider" --tag=migrations

# Executar migrations
php artisan migrate
bash
# Publicar views
php artisan vendor:publish --provider="Gamer\GamerProvider" --tag=views

# Publicar traduções
php artisan vendor:publish --provider="Gamer\GamerProvider" --tag=lang