View file upload/src/addons/AddonsLab/Core/DbMiddleware.php

File size: 1.92Kb
<?php
/** 
This software is furnished under a license and may be used and copied
only  in  accordance  with  the  terms  of such  license and with the
inclusion of the above copyright notice.  This software  or any other
copies thereof may not be provided or otherwise made available to any
other person.  No title to and  ownership of the  software is  hereby
transferred.                                                         
                                                                     
You may not reverse  engineer, decompile, defeat  license  encryption
mechanisms, or  disassemble this software product or software product
license.  AddonsLab may terminate this license if you don't comply with
any of these terms and conditions.  In such event,  licensee  agrees 
to return licensor  or destroy  all copies of software  upon termination 
of the license.
*/


namespace AddonsLab\Core;

/**
 * Class DbMiddleware
 * @package AddonsLab\Core
 * A middleware for the DB for custom handling of lock wait timeout errors
 */
class DbMiddleware
{
    protected $db;

    public function __construct($db)
    {
        $this->db = $db;
    }
    
    public function getDb()
    {
        return $this->db;
    }

    public function __call($name, $arguments)
    {
        $tryCount = 0;
        while (true) {
            $tryCount++;
            try {
                return call_user_func_array(array($this->db, $name), $arguments);
            } catch (\Zend_Db_Statement_Mysqli_Exception $exception) {
                if ($tryCount > 2) { // tried 2 times already
                    throw $exception;
                }

                if (strpos($exception->getMessage(), 'Lock wait timeout exceeded') !== false) {
                    // transaction error, trying again after some time
                    usleep(50000);
                    continue;
                }
                
                throw $exception;
            }
        }
    }
}