Skip to content

Commit

Permalink
Merge pull request #10 from urbanindo/add-routing-behavior
Browse files Browse the repository at this point in the history
Add routing behavior
  • Loading branch information
petrabarus committed Jun 30, 2015
2 parents e515070 + 7a318b0 commit 9895f75
Show file tree
Hide file tree
Showing 8 changed files with 330 additions and 178 deletions.
183 changes: 17 additions & 166 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/Behaviors/ActiveRecordDeferredEventBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,10 @@ public function postDeferredEvent($event) {
$this->queue->post(new \UrbanIndo\Yii2\Queue\Job([
'route' => function() use ($class, $pk, $handlers, $eventName, $serializer, $scenario) {
$object = $class::findOne($pk);
$object->scenario = $scenario;
if ($object === null) {
throw new \Exception("Model is not found");
throw new \Exception("Model #{$pk} is not found");
}
$object->scenario = $scenario;
if ($handlers) {
$handler = $handlers[$eventName];
if ($serializer !== null) {
Expand Down
60 changes: 60 additions & 0 deletions src/Behaviors/ActiveRecordDeferredEventRoutingBehavior.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

/**
* ActiveRecordDeferredRoutingBehavior extends
* @author Petra Barus <[email protected]>
* @since 2015.02.25
*/

namespace UrbanIndo\Yii2\Queue\Behaviors;

use yii\db\ActiveRecord;

/**
* ActiveRecordDeferredRoutingBehavior provides matching between controller in
* task worker with the appropriate event.
*
* @property-read ActiveRecord $owner the owner.
*
* @author Petra Barus <[email protected]>
* @since 2015.02.25
*/
class ActiveRecordDeferredEventRoutingBehavior extends DeferredEventRoutingBehavior {

/**
* The attribute name.
* @var type
*/
public $pkAttribute = 'id';

/**
* Whether to add the primary key to the data.
* @var boolean
*/
public $addPkToData = true;

public function routeEvent($event) {
/* @var $owner ActiveRecord */

$eventName = $event->name;
$handler = $this->events[$eventName];
if (is_callable($handler)) {
$handler = call_user_func($handler, $this->owner);
} else if ($this->addPkToData) {
$pk = $this->owner->getPrimaryKey();
if (is_array($pk)) {
$handler = array_merge($handler, $pk);
} else {
$handler[$this->pkAttribute] = $pk;
}
}
$route = $handler[0];
unset($handler[0]);
$handler['scenario'] = $this->owner->getScenario();
$data = $handler;
$this->queue->post(new \UrbanIndo\Yii2\Queue\Job([
'route' => $route,
'data' => $data
]));
}
}
Loading

0 comments on commit 9895f75

Please sign in to comment.