Skip to content

Commit

Permalink
user avatar cache to local. using cdn access. fix #107
Browse files Browse the repository at this point in the history
  • Loading branch information
nauxliu committed Mar 26, 2015
1 parent 894d2dd commit 7add6a8
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 4 deletions.
2 changes: 1 addition & 1 deletion app/Phphub/Creators/UserCreator.php
Expand Up @@ -34,7 +34,7 @@ private function createValidUserRecord($observer, $data)
if (! $user) {
return $observer->userValidationError($user->getErrors());
}

$user->cacheAvatar();
return $observer->userCreated($user);
}
}
4 changes: 1 addition & 3 deletions app/Phphub/Presenters/UserPresenter.php
Expand Up @@ -10,9 +10,7 @@ class UserPresenter extends Presenter
*/
public function gravatar($size = 80)
{
$github_id = $this->github_id;
$domainNumber = rand(0, 3);
return "https://avatars{$domainNumber}.githubusercontent.com/u/{$github_id}?v=2&s={$size}";
return cdn('uploads/avatars/' . $this->avatar) . "?imageView2/1/w/{$size}/h/{$size}";
}

public function userinfoNavActive($anchor)
Expand Down
34 changes: 34 additions & 0 deletions app/database/migrations/2015_03_25_115359_add_avatar_to_users.php
@@ -0,0 +1,34 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class AddAvatarToUsers extends Migration
{

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('avatar');
});
}


/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('avatar');
});
}

}
31 changes: 31 additions & 0 deletions app/models/User.php
Expand Up @@ -110,4 +110,35 @@ public function getRememberTokenName()
{
return 'remember_token';
}

/**
* Cache github avatar to local
* @author Xuan
*/
public function cacheAvatar()
{
//Download Image
$guzzle = new GuzzleHttp\Client();
$response = $guzzle->get($this->image_url);

//Get ext
$content_type = explode('/', $response->getHeader('Content-Type'));
$ext = array_pop($content_type);

$avatar_name = $this->id . '_' . time() . '.' . $ext;
$save_path = public_path('uploads/avatars/') . $avatar_name;

//Save File
$content = $response->getBody()->getContents();
file_put_contents($save_path, $content);

//Delete old file
if ($this->avatar) {
unlink($this->avatar);
}

//Save to database
$this->avatar = $avatar_name;
$this->save();
}
}
Empty file added public/uploads/avatars/.gitkeep
Empty file.

2 comments on commit 7add6a8

@lifesign
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@lijinma
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Please sign in to comment.