action.class for current user - php

i learn Symfony 1.4 with Jobeet. I made Jobeet and system login for user. Now i would like add possibility edit own affiliate.
<?php
class jobActions extends sfActions
{
public function executeIndex(sfWebRequest $request)
{
$this->jobeet_job_list = Doctrine::getTable('JobeetJob')
->createQuery('a')
->execute();
}
public function executeShow(sfWebRequest $request)
{
$this->jobeet_job = Doctrine::getTable('JobeetJob')->find($request->getParameter('id'));
$this->forward404Unless($this->jobeet_job);
}
public function executeNew(sfWebRequest $request)
{
$this->form = new JobeetJobForm();
}
public function executeCreate(sfWebRequest $request)
{
$this->forward404Unless($request->isMethod('post'));
$this->form = new JobeetJobForm();
$this->processForm($request, $this->form);
$this->setTemplate('new');
}
public function executeEdit(sfWebRequest $request)
{
$this->forward404Unless($jobeet_job = Doctrine::getTable('JobeetJob')->find($request->getParameter('id')), sprintf('Object jobeet_job does not exist (%s).', $request->getParameter('id')));
$this->form = new JobeetJobForm($jobeet_job);
}
public function executeUpdate(sfWebRequest $request)
{
$this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
$this->forward404Unless($jobeet_job = Doctrine::getTable('JobeetJob')->find($request->getParameter('id')), sprintf('Object jobeet_job does not exist (%s).', $request->getParameter('id')));
$this->form = new JobeetJobForm($jobeet_job);
$this->processForm($request, $this->form);
$this->setTemplate('edit');
}
public function executeDelete(sfWebRequest $request)
{
$request->checkCSRFProtection();
$this->forward404Unless($jobeet_job = Doctrine::getTable('JobeetJob')->find($request->getParameter('id')), sprintf('Object jobeet_job does not exist (%s).', $request->getParameter('id')));
$jobeet_job->delete();
$this->redirect('job/index');
}
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()));
if ($form->isValid())
{
$jobeet_job = $form->save();
$this->redirect('job/edit?id='.$jobeet_job['id']);
}
}
}
In actions.class executeIndex i can add where:
public function executeIndex(sfWebRequest $request)
{
$this->jobeet_job_list = Doctrine::getTable('JobeetJob')
->createQuery('a')
->where('id = ?', $id) //$id i have in session, this working OK
->execute();
}
how can i make similarly with executeEdit? in database i have field user_id, which added a news. I would like to edit can only author this news. thanks for help!

If its editing the job what you are trying to do, you have to find the job you want to edit and create a form initialized with the object. Something like (i'm skipping all the parameter checking bits, obviously you have to make sure that the id is in the request, the user is logged and the job retrieved exists and is owned by the user):
$user_id = $this->getUser()->getId(); // if you are logged and getId is defined in your myUser class
$job_id = $request->getParameter('id', false);
$job = Doctrine::getTable('JobeetJob')->find($job_id);
if ($job['owner_id'] == $user_id)
{
$this->form = new JobeetJobForm($job);
}

Related

Is it necessary creating a function in model when updating database

I have a controller like this
use App\Model\User;
class UserController extends BaseController
{
protected $model;
public function __construct(User $user)
{
$this->model = $user;
}
public function updatePhone(Request $request)
{
//user id
$id = $request->id;
//new phone number
$phone = $request->phone;
}
}
The function updatePhone is used to update the phone number of the user.So I can code like this
$res = $this->model->where('id',$id)->update('phone',$phone)
In this way, I do nothing in the user model.But I get used to like this
$res = $this->model->updatePhone($id, $phone);
And I must create function updatePhone in user model
public function updatePhone($id,$phone)
{
return $this->where('id',$id)->update('phone',$phone);
}
who is the better way to update a single model? Any answers or suggestions are excepted.

Yii2 save() creating DB row with default values

I am trying to implement a login method using OpenID, and the $_SESSION var's are posting correctly - and through those I am simply trying to register users in MySQL. For some reason, when passing through the 'login' action in my controller ::
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
include ('../views/user-record/steamauth/userInfo.php');
$steamid = $_SESSION['steam_steamid'];
$username = $_SESSION['steam_personaname'];
$profileurl = $_SESSION['steam_profileurl'];
$avatar = $_SESSION['steam_avatar'];
$avatarmedium = $_SESSION['steam_avatarmedium'];
$avatarfull = $_SESSION['steam_avatarfull'];
$user = UserRecord::findBySteamId($steamid);
if ($user === null)
{
$user = new UserRecord();
$user->steamid = $steamid;
$user->username = $username;
$user->profileurl = $profileurl;
$user->avatar = $avatar;
$user->avatarmedium = $avatarmedium;
$user->avatarfull = $avatarfull;
$user->verified = 0;
$user->banned = 0;
$user->save();
}
Yii::$app->user->login($user, 604800);
return $this->redirect(Yii::$app->user->returnUrl);
}
EDIT: Here is the UserRecord class, forgot to add it in.
<?php
namespace app\models;
class UserRecord extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $steamid;
public $username;
public $profileurl;
public $avatar;
public $avatarmedium;
public $avatarfull;
public $verified;
public $banned;
public $rank;
public $authKey;
// public $password;
// public $accessToken;
public static function tableName()
{
return 'users';
}
public function getAuthKey()
{
return $this->authKey;
}
public function getId()
{
return $this->id;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
public static function findIdentity($id)
{
return self::findOne($id);
}
public function validateSteamID($steamid)
{
return $this->steamid === $steamid;
}
public static function findIdentityByAccessToken($token, $type = null)
{
throw new \yii\base\NotSupportedException;
}
public static function findBySteamId($steamid)
{
return self::findOne(['steamid' => $steamid]);
}
}
The result is simply a posted row, with none of the data entered.
Any help would be greatly appreciated, thank you.
If you have redefine the same columns name using public vars these override the vars for activeRecord and then are saved only empty value ..
if this you must remove the (redifined) public vars in your model
otherwise if you have no rules then
Try adding safe at the attribute in you model rules
public function rules()
{
return [
[['steamid', 'username', 'profileurl', 'avatar', 'avatarmedium',
'avatarfull', 'verified', 'banned', 'rank', 'authKey',], 'safe'],
];
}
Declaring 'public' variables made the save() ignore the data being posted. Thanks.

Arguement 1 must be instance of Illuminate\Http\Request integer given

When I am trying to send mail, everytime a new member is added to the user table, so that they can get a setup password link. I have been trying to get this to work but seem not to be.
public function store(AddUser $request)
{
$user = $request->all();
$user['activate'] = $this->active();
$user['guid'] = $this->guid();
$user['accountno'] = $this->generateAndValidateAccountno();
$check = User::find($user['phone']);
if(!$check) {
$id = User::create($user);
$this->sendEmail($user['accountno']);
}
return redirect('employee');
}
public function sendEmail(Request $request, $id)
{
$user = User::find($id);
Beautymail::send('emails.welcome', [], function($message)
{
$message
->to('$id->email', '$id->fname')
->subject('Welcome!');
});
}
}
Not sure what am doing wrong
Just use the same request class in the controller and the model. In your user model, add use Illuminate\Http\Request at the top of the class to tell it which Request class to use.
Just change:
public function sendEmail(Request $request, $id){...}
to
public function sendEmail($id){...}

Model observer in Laravel 4, restore() triggering both restored() and updated()

I'm using an observer on models in Laravel 4 for the purposes of keeping historical records of changes made by each user. The code I'm currently using is as follows:
class BaseObserver {
public function __construct(){}
public function saving(Eloquent $model){}
public function saved(Eloquent $model){}
public function updating(Eloquent $model){}
public function updated(Eloquent $model)
{
$this->storeAuditData($model, 'update');
}
public function creating(Eloquent $model){}
public function created(Eloquent $model)
{
$this->storeAuditData($model, 'create');
}
public function deleting(Eloquent $model){}
public function deleted(Eloquent $model)
{
$this->storeAuditData($model, 'delete');
}
public function restoring(Eloquent $model){}
public function restored(Eloquent $model)
{
$this->storeAuditData($model, 'restore');
}
public function storeAuditData(Eloquent $model, $action)
{
$snapshot = array();
foreach ($model->fillable as $fieldName) {
$snapshot[$fieldName] = $model->$fieldName;
}
$auditData = new AuditData;
$auditData->model = get_class($model);
$auditData->rowId = $model->id;
$auditData->action = $action;
$auditData->user = Auth::user()->username;
$auditData->moment = date('Y-m-d H:i:s');
$auditData->snapshot = json_encode($snapshot);
$auditData->save();
}
}
This works fine, except when a restore() is performed, both the restored and updated methods get run, so I end up with two rows in the AuditData database table, when I only want one (the "restore").
Is there any way I can tell within the updated method whether the update is a restore or not, and only store the audit data if it is a stand-alone update and not a restore?
You could check if only the deleted_at column has been modified (is dirty)
public function updated(Eloquent $model)
{
if($model->isDirty($model->getDeletedAtColumn()) && count($model->getDirty()) == 1){
// only soft deleting column changed
}
else {
$this->storeAuditData($model, 'update');
}
}
While restoring, and using Laravel auto timestamps, the column updated_at will be modified along with deleted_at. To differentiate between 'restored' and 'updated' observer event, within updated method I use:
public function updated(Eloquent $model)
{
if ($model->isDirty($model->getDeletedAtColumn())
&& $model->{$model->getDeletedAtColumn()} === null
&& $model->getOriginal($model->getDeletedAtColumn()) !== null) {
// model was restored
}
}

Laravel partial mocked model not invoked

I'm using laravel (4.2) framework to develop a web application (PHP 5.4.25). I've create a repository-interface that was implemented with eloquent-repository, I use that repository inside a UserController:
# app/controllers/UsersController.php
use Gas\Storage\User\UserRepositoryInterface as User;
class UsersController extends \BaseController {
protected $user;
public function __construct(User $user) {
$this->user = $user;
}
public function store() {
$input = Input::all();
$validator = Validator::make(Input::all(), $this->user->getRoles());
if ( $validator->passes() ) {
$this->user->getUser()->username = Input::get('username');
$this->user->getUser()->password = Hash::make(Input::get('password'));
$this->user->getUser()->first_name = Input::get('first_name');
$this->user->getUser()->last_name = Input::get('last_name');
$this->user->getUser()->email = Input::get('email');
$this->user->save();
return false;
} else {
return true;
}
}
}
My Repository implementation:
namespace Gas\Storage\User;
# app/lib/Gas/Storage/User/EloquentUserRepository.php
use User;
class EloquentUserRepository implements UserRepositoryInterface {
public $_eloquentUser;
public function __construct(User $user) {
$this->_eloquentUser = $user;
}
public function all()
{
return User::all();
}
public function find($id)
{
return User::find($id);
}
public function create($input)
{
return User::create($input);
}
public function save()
{
$this->_eloquentUser->save();
}
public function getRoles()
{
return User::$rules;
}
public function getUser()
{
return $this->_eloquentUser;
}
}
I've also create a UsersControllerTest to testing the controller and all works fine, the user was added to the DB. After I mocked my UserRepositoryInterface because I don't need to test the DB insert, but I just want to test the controller
class UsersControllerTest extends TestCase {
private $mock;
public function setUp() {
parent::setUp();
}
public function tearDown() {
Mockery::close();
}
public function mock($class) {
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
public function testStore() {
$this->mock = $this->mock('Gas\Storage\User\UserRepositoryInterface[save]');
$this->mock
->shouldReceive('save')
->once();
$data['username'] = 'xxxxxx';
$data['first_name'] = 'xxxx';
$data['last_name'] = 'xxxx';
$data['email'] = 'prova#gmail.com';
$data['password'] = 'password';
$data['password_confirmation'] = 'password';
$response = $this->call('POST', 'users', $data);
var_dump($response->getContent());
}
}
My ruote file:
Route::resource('users', 'UsersController');
When I run the test I get the following error:
Mockery\Exception\InvalidCountException : Method save() from Mockery_0_Gas_Storage_User_UserRepositoryInterface should be called
exactly 1 times but called 0 times.
Why the mocked method save has not be called?
What is wrong?
EDIT: without partial mock all works fine, now the question is: why with partial mock it doesn't work?
Thanks
Looking back at your code, it seems like you should be able to use partial mocks just by changing your mock function to something like this:
public function mock($class) {
$mock = Mockery::mock($class);
$ioc_binding = preg_replace('/\[.*\]/', '', $class);
$this->app->instance($ioc_binding, $mock);
return $mock;
}
You are telling the mock to expect the save() method, but the save() is on the Eloquent model inside the Repository, not the Repository you are mocking.
Your code is currently leaking details of the implementation of the Repository.
Instead of calling:
$this->user->getUser()->username = Input::get('username');
You need to pass an instance of the User into the Repository:
$this->user->add(User::create(Input::all());
Or you pass the array of Input into the Repository and allow the Repository to create a new User instance internally:
$this->user->add(Input::all());
You would then mock the add() method in your test:
$this->mock->shouldReceive('add')->once();
The comments about Laravel not being suited for mocking or unit testing are wrong.

Categories