Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * FireSync Observer
- *
- * Watch for changes and replicate them to the Firebase database
- *
- * PHP Version 7.1
- *
- * @category Observer
- * @package Firebase
- * @license GPLv3.0 GNU Public License v3.0
- */
- namespace App\Observers;
- use App\FireSync;
- use Kreait\Firebase\Factory;
- use Illuminate\Support\Facades\Log;
- /**
- * FireSync Observer
- *
- * Watch for changes and replicate them to the Firebase database
- *
- * @category Observer
- * @package Firebase
- * @license GPLv3.0 GNU Public License v3.0
- */
- class FireSyncObserver
- {
- private $_database;
- private $_baseReference = 'recordset/records';
- private $_reference;
- /**
- * Constructor
- */
- public function __construct()
- {
- $this->_database = (new Factory)->createDatabase();
- $this->_reference = $this->_database->getReference($this->_baseReference);
- }
- /**
- * Created event
- *
- * Takes the newly created row and adds it to the firebase record set
- *
- * @param FireSync $fireSync The Database model
- *
- * @return void
- */
- public function created(FireSync $fireSync)
- {
- $row = $fireSync->toArray();
- $pushKey = $this->_database->getReference(
- $this->_baseReference
- )
- ->push($row)->getKey();
- Log::debug('Create called for ' . $pushKey);
- $fireSync['push_key'] = $pushKey;
- // Call an update of the local table to add the push_key without
- // triggering any updated event.
- FireSync::withoutEvents(
- function () use ($fireSync) {
- $fireSync->save();
- }
- );
- }
- /**
- * Updated Event
- *
- * When a row is updated update the firebase record set to match.
- * Fairly lazy as it updates ALL columns, not just those that have changed.
- *
- * @param FireSync $fireSync Database model
- *
- * @return void
- */
- public function updated(FireSync $fireSync)
- {
- if ($fireSync['push_key'] !== null) {
- Log::debug('Update called for ' . $fireSync['push_key']);
- // Grab all the columns except push_key
- $row = $fireSync->makeHidden('push_key')->toArray();
- $this->_database->getReference(
- $this->_baseReference . '/' . $fireSync['push_key']
- )
- ->set(
- $row
- );
- }
- }
- /**
- * Deleted Event
- *
- * When a row is deleted remote the matching model from firebase.
- *
- * @param FireSync $fireSync Database model
- *
- * @return void
- */
- public function deleted(FireSync $fireSync)
- {
- if ($fireSync['push_key'] !== null) {
- Log::debug('Delete called for ' . $fireSync['push_key']);
- $this->_database->getReference(
- $this->_baseReference . '/' . $fireSync['push_key']
- )
- ->remove();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement