Skip to content

Commit

Permalink
Add Orchestra\Support\Messages::extend(). Closes #22.
Browse files Browse the repository at this point in the history
Signed-off-by: crynobone <[email protected]>
  • Loading branch information
crynobone committed Jul 31, 2013
1 parent 09ac9be commit d310c34
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 7 deletions.
40 changes: 33 additions & 7 deletions src/Orchestra/Support/Messages.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
<?php namespace Orchestra\Support;

use Closure;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\MessageBag as M;

class Messages extends M {

/**
* Cached messages to be extends to current request.
*
* @var self
*/
protected $instance = null;

/**
* Retrieve Message instance from Session, the data should be in
* serialize, so we need to unserialize it first.
Expand All @@ -13,18 +21,36 @@ class Messages extends M {
*/
public function retrieve()
{
$messages = null;
$instance = null;
$messages = array();

if (Session::has('message'))
if (is_null($this->instance))
{
$messages = @unserialize(Session::get('message', ''));
if (is_array($messages)) $instance = new static($messages);
$this->instance = new static();

if (Session::has('message'))
{
$messages = @unserialize(Session::get('message', ''));
if ( ! is_array($messages)) $messages = array();
}

Session::forget('message');

$this->instance->merge($messages);
}

Session::forget('message');
return $this->instance;
}

return $instance;
/**
* Extend Messages instance from session.
*
* @param Closure $callback
* @return void
*/
public function extend(Closure $callback)
{
$instance = $this->retrieve();
call_user_func($callback, $instance);
}

/**
Expand Down
30 changes: 30 additions & 0 deletions tests/MessagesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,34 @@ public function testRetrieveMethod()
$this->assertEquals(array('Hi World'), $retrieve->get('hello'));
$this->assertEquals(array('Goodbye'), $retrieve->get('bye'));
}

/**
* Test un-serializing and extending Orchestra\Support\Messages over
* Session
*
* @test
*/
public function testExtendMethod()
{
$session = m::mock('Session');
$session->shouldReceive('has')->once()->andReturn(true)
->shouldReceive('get')->once()->andReturn('a:1:{s:5:"hello";a:1:{i:0;s:8:"Hi World";}}')
->shouldReceive('forget')->once()->andReturn(true);

\Illuminate\Support\Facades\Session::swap($session);

$callback = function ($msg)
{
$msg->add('hello', 'Hi Orchestra Platform');
};

$stub = new Messages;
$stub->extend($callback);

$retrieve = $stub->retrieve();
$retrieve->setFormat();

$this->assertInstanceOf('\Orchestra\Support\Messages', $retrieve);
$this->assertEquals(array('Hi World', 'Hi Orchestra Platform'), $retrieve->get('hello'));
}
}

0 comments on commit d310c34

Please sign in to comment.