Socket.php
87 lines
| 1 | <?php |
| 2 | /* |
| 3 | * |
| 4 | * JetBackup @ package |
| 5 | * Created By Idan Ben-Ezra |
| 6 | * |
| 7 | * Copyrights @ JetApps |
| 8 | * https://www.jetapps.com |
| 9 | * |
| 10 | **/ |
| 11 | namespace JetBackup\SocketAPI\Socket; |
| 12 | |
| 13 | use JetBackup\SocketAPI\Exception\SocketException; |
| 14 | use JetBackup\SocketAPI\Message\MessageReader; |
| 15 | use JetBackup\SocketAPI\Message\MessageWriter; |
| 16 | |
| 17 | class Socket { |
| 18 | |
| 19 | private $_socket; |
| 20 | private $_stream; |
| 21 | private $_file; |
| 22 | |
| 23 | private $_reader; |
| 24 | private $_writer; |
| 25 | |
| 26 | /** |
| 27 | * Socket constructor. |
| 28 | * @param $socket |
| 29 | * @throws SocketException |
| 30 | */ |
| 31 | public function __construct($socket=null) { |
| 32 | $this->_socket = $socket ?: socket_create(AF_UNIX, SOCK_STREAM, 0); |
| 33 | if(!$this->getSocketResource()) throw new SocketException("Could not create socket"); |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * @param string $file |
| 38 | */ |
| 39 | public function setFile($file) { $this->_file = $file; } |
| 40 | |
| 41 | /** |
| 42 | * @return string |
| 43 | */ |
| 44 | public function getFile() { return $this->_file; } |
| 45 | |
| 46 | public function getSocketResource() { return $this->_socket; } |
| 47 | public function getStreamResource() { |
| 48 | if(!$this->_stream) $this->_stream = socket_export_stream($this->getSocketResource()); |
| 49 | return $this->_stream; |
| 50 | } |
| 51 | |
| 52 | |
| 53 | /** |
| 54 | * @return MessageReader |
| 55 | */ |
| 56 | public function getReader(): MessageReader { |
| 57 | if(!$this->_reader) $this->_reader = new MessageReader($this); |
| 58 | return $this->_reader; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * @return MessageWriter |
| 63 | */ |
| 64 | public function getWriter(): MessageWriter { |
| 65 | if(!$this->_writer) $this->_writer = new MessageWriter($this); |
| 66 | return $this->_writer; |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * @param bool $isServer |
| 71 | * |
| 72 | * @throws SocketException |
| 73 | */ |
| 74 | public function connect( bool $isServer=false) { |
| 75 | if(!$this->getFile()) throw new SocketException("There is no socket file set"); |
| 76 | if($isServer && file_exists($this->getFile())) @unlink($this->getFile()); |
| 77 | if (!file_exists($this->getFile()) || !is_readable($this->getFile())) throw new SocketException("Could not connect to socket (not exist)."); |
| 78 | if(!@socket_connect($this->getSocketResource(), $this->getFile())) throw new SocketException("Could not connect to socket (socket error)."); |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * |
| 83 | */ |
| 84 | public function close() { |
| 85 | @socket_close($this->getSocketResource()); |
| 86 | } |
| 87 | } |