HasLockProcess.php
62 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Sync\Concerns; |
| 4 | |
| 5 | /** |
| 6 | * Provides transient-based locking for sync operations. |
| 7 | */ |
| 8 | trait HasLockProcess { |
| 9 | /** |
| 10 | * The lock prefix. |
| 11 | * |
| 12 | * @var string |
| 13 | */ |
| 14 | protected $lock_prefix = 'sc_sync_lock'; |
| 15 | |
| 16 | /** |
| 17 | * Get the lock key. |
| 18 | * |
| 19 | * @param \SureCart\Models\Model $model The model. |
| 20 | * |
| 21 | * @return string |
| 22 | */ |
| 23 | protected function getLockKey( \SureCart\Models\Model $model ): string { |
| 24 | return "{$this->lock_prefix}_{$model->id}"; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Check if the lock exists. |
| 29 | * |
| 30 | * @param \SureCart\Models\Model $model The model. |
| 31 | * |
| 32 | * @return bool |
| 33 | */ |
| 34 | protected function hasLock( \SureCart\Models\Model $model ): bool { |
| 35 | return false !== get_transient( $this->getLockKey( $model ) ); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Acquire the lock. |
| 40 | * |
| 41 | * @param \SureCart\Models\Model $model The model. |
| 42 | * |
| 43 | * @return bool |
| 44 | */ |
| 45 | protected function acquireLock( \SureCart\Models\Model $model ): bool { |
| 46 | $max_execution_time = (int) ini_get( 'max_execution_time' ); |
| 47 | $expiration = $max_execution_time > 0 ? $max_execution_time : 30; |
| 48 | return set_transient( $this->getLockKey( $model ), time(), $expiration ); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Release the lock. |
| 53 | * |
| 54 | * @param \SureCart\Models\Model $model The model. |
| 55 | * |
| 56 | * @return bool |
| 57 | */ |
| 58 | protected function releaseLock( \SureCart\Models\Model $model ): bool { |
| 59 | return (bool) delete_transient( $this->getLockKey( $model ) ); |
| 60 | } |
| 61 | } |
| 62 |