repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Response.php
Response.php
<?php /** * provides named constants for * HTTP protocol status codes. * */ class REST_Response extends Zend_Controller_Response_Http { // Informational 1xx const HTTP_CONTINUE = 100; const SWITCH_PROTOCOLS = 101; // Successful 2xx const OK = 200; const CREATED = 201; const ACCEPTED = 202; const NONAUTHORITATIVE = 203; const NO_CONTENT = 204; const RESET_CONTENT = 205; const PARTIAL_CONTENT = 206; // Redirection 3xx const MULTIPLE_CHOICES = 300; const MOVED_PERMANENTLY = 301; const FOUND = 302; const SEE_OTHER = 303; const NOT_MODIFIED = 304; const USE_PROXY = 305; // 306 is deprecated but reserved const TEMP_REDIRECT = 307; // Client Error 4xx const BAD_REQUEST = 400; const UNAUTHORIZED = 401; const PAYMENT_REQUIRED = 402; const FORBIDDEN = 403; const NOT_FOUND = 404; const NOT_ALLOWED = 405; const NOT_ACCEPTABLE = 406; const PROXY_AUTH_REQUIRED = 407; const REQUEST_TIMEOUT = 408; const CONFLICT = 409; const GONE = 410; const LENGTH_REQUIRED = 411; const PRECONDITION_FAILED = 412; const LARGE_REQUEST_ENTITY = 413; const LONG_REQUEST_URI = 414; const UNSUPPORTED_TYPE = 415; const UNSATISFIABLE_RANGE = 416; const EXPECTATION_FAILED = 417; // Server Error 5xx const SERVER_ERROR = 500; const NOT_IMPLEMENTED = 501; const BAD_GATEWAY = 502; const UNAVAILABLE = 503; const GATEWAY_TIMEOUT = 504; const UNSUPPORTED_VERSION = 505; const BANDWIDTH_EXCEEDED = 509; // Informational 1xx function httpContinue() { $this->setHttpResponseCode(self::HTTP_CONTINUE); } function switchProtocols() { $this->setHttpResponseCode(self::SWITCH_PROTOCOLS); } // Successful 2xx public function Ok() { $this->setHttpResponseCode(self::OK); } public function created() { $this->setHttpResponseCode(self::CREATED); } public function accepted() { $this->setHttpResponseCode(self::ACCEPTED); } public function nonAuthoritative() { $this->setHttpResponseCode(self::NONAUTHORITATIVE); } public function noContent() { $this->setHttpResponseCode(self::NO_CONTENT); } public function resetContent() { $this->setHttpResponseCode(self::RESET_CONTENT); } public function partialContent() { $this->setHttpResponseCode(self::PARTIAL_CONTENT); } // Redirection 3xx public function multipleChoices() { $this->setHttpResponseCode(self::MULTIPLE_CHOICES); } public function movedPermanently() { $this->setHttpResponseCode(self::MOVED_PERMANENTLY); } public function found() { $this->setHttpResponseCode(self::FOUND); } public function seeOther() { $this->setHttpResponseCode(self::NO_CONTENT); } public function notModified() { $this->setHttpResponseCode(self::NOT_MODIFIED); } public function useProxy() { $this->setHttpResponseCode(self::USE_PROXY); } public function tempRedirect() { $this->setHttpResponseCode(self::TEMP_REDIRECT); } // Client Error 4xx public function badRequest() { $this->setHttpResponseCode(self::BAD_REQUEST); } public function unauthorized() { $this->setHttpResponseCode(self::UNAUTHORIZED); } public function paymentRequired() { $this->setHttpResponseCode(self::PAYMENT_REQUIRED); } public function forbidden() { $this->setHttpResponseCode(self::FORBIDDEN); } public function notFound() { $this->setHttpResponseCode(self::NOT_FOUND); } public function notAllowed() { $this->setHttpResponseCode(self::NOT_ALLOWED); } public function notAcceptable() { $this->setHttpResponseCode(self::NOT_ACCEPTABLE); } public function proxyAuthRequired() { $this->setHttpResponseCode(self::PROXY_AUTH_REQUIRED); } public function requestTimeout() { $this->setHttpResponseCode(self::REQUEST_TIMEOUT); } public function conflict() { $this->setHttpResponseCode(self::CONFLICT); } public function gone() { $this->setHttpResponseCode(self::GONE); } public function lengthRequired() { $this->setHttpResponseCode(self::NO_CONTENT); } public function preconditionFailed() { $this->setHttpResponseCode(self::PRECONDITION_FAILED); } public function largeRequestEntity() { $this->setHttpResponseCode(self::LARGE_REQUEST_ENTITY); } public function longRequestUri() { $this->setHttpResponseCode(self::LONG_REQUEST_URI); } public function unsupportedType() { $this->setHttpResponseCode(self::UNSUPPORTED_TYPE); } public function unsatisfiableRange() { $this->setHttpResponseCode(self::UNSATISFIABLE_RANGE); } public function expectationFailed() { $this->setHttpResponseCode(self::EXPECTATION_FAILED); } // Server Error 5xx public function serverError() { $this->setHttpResponseCode(self::SERVER_ERROR); } public function notImplemented() { $this->setHttpResponseCode(self::NOT_IMPLEMENTED); } public function badGateway() { $this->setHttpResponseCode(self::BAD_GATEWAY); } public function unavailable() { $this->setHttpResponseCode(self::UNAVAILABLE); } public function gatewayTimeout() { $this->setHttpResponseCode(self::GATEWAY_TIMEOUT); } public function unsupportedVersion() { $this->setHttpResponseCode(self::UNSUPPORTED_VERSION); } public function bandwidthExceeded() { $this->setHttpResponseCode(self::BANDWIDTH_EXCEEDED); } /** * Return header value (if set); see {@link $_headers} for format * * @return string | boolean */ public function getHeaderValue($name) { foreach ($this->_headers as $key => $header) { if ($name == $header['name']) { return $header['value']; } } return false; } } ?>
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Exception.php
Exception.php
<?php /** * REST_Exception * * The purpose of class is to provide posibility to work with rest errors * through exceptions and then handle it in error controller. * * Default error http code is 400 * * Example * <code> * switch ($errors->type) { * case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: * case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: * case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: * // 404 error -- controller or action not found * $this->view->errorMessages[] = 'Page not found'; * $this->getResponse()->setHttpResponseCode(404); * break; * * default: * // application error * * $message = 'Application error'; * $httpCode = 500; * * if (($exception = $this->getResponse()->getException()) * && ($exception[0] instanceof REST_Exception) * ){ * $message = $exception[0]->getMessage(); * $httpCode = $exception[0]->getHttpCode(); * } * * $this->view->errorMessages[] = $message; * $this->getResponse()->setHttpResponseCode($httpCode); * break; * } * </code> * * @author Yuriy Ishchenko <ishenkoyv@gmail.com> */ class REST_Exception extends Exception { protected $httpCode; public function __construct($message, $httpCode = REST_Response::BAD_REQUEST) { parent::__construct($message); $this->httpCode = $httpCode; } public function getHttpCode() { return $this->httpCode; } }
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Controller/Plugin/RestHandler.php
Controller/Plugin/RestHandler.php
<?php /** * Responsible for setting the HTTP Vary header, * setting the context switch based on the Accept header * and processing the incoming request formats */ class REST_Controller_Plugin_RestHandler extends Zend_Controller_Plugin_Abstract { private $dispatcher; private $defaultFormat = 'html'; private $reflectionClass = null; private $acceptableFormats = array( 'html', 'xml', 'php', 'json' ); private $responseTypes = array( 'text/html' => 'html', 'application/xhtml+xml' => 'html', 'text/xml' => 'xml', 'application/xml' => 'xml', 'application/xhtml+xml' => 'xml', 'text/php' => 'php', 'application/php' => 'php', 'application/x-httpd-php' => 'php', 'application/x-httpd-php-source' => 'php', 'text/javascript' => 'json', 'application/json' => 'json', 'application/javascript' => 'json' ); private $requestTypes = array( 'multipart/form-data', 'application/x-www-form-urlencoded', 'text/xml', 'application/xml', 'text/php', 'application/php', 'application/x-httpd-php', 'application/x-httpd-php-source', 'text/javascript', 'application/json', 'application/javascript', false ); public function __construct(Zend_Controller_Front $frontController) { $this->dispatcher = $frontController->getDispatcher(); } public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) { // send the HTTP Vary header $this->_response->setHeader('Vary', 'Accept'); // Cross-Origin Resource Sharing (CORS) // TODO: probably should be an environment setting? $this->_response->setHeader('Access-Control-Max-Age', '86400'); $this->_response->setHeader('Access-Control-Allow-Origin', '*'); $this->_response->setHeader('Access-Control-Allow-Credentials', 'true'); $this->_response->setHeader('Access-Control-Allow-Headers', 'Authorization, X-Authorization, Origin, Accept, Content-Type, X-Requested-With, X-HTTP-Method-Override'); $class = $this->getReflectionClass($request); if ($this->isRestClass($class)) { // set config settings from application.ini $this->setConfig(); // set response format $this->setResponseFormat($request); // process requested action $this->handleActions($request); // process request body $this->handleRequestBody($request); } } private function setConfig() { $frontController = Zend_Controller_Front::getInstance(); $options = new Zend_Config($frontController->getParam('bootstrap')->getOptions(), true); $rest = $options->get('rest', false); if ($rest) { $this->defaultFormat = $rest->default; $this->acceptableFormats = $rest->formats->toArray(); foreach($this->responseTypes as $mime => $format) { if (!in_array($format, $this->acceptableFormats)) { unset($this->responseTypes[$mime]); } } } } /** * sets the response format and content type * uses the "format" query string paramter and the HTTP Accept header */ private function setResponseFormat(Zend_Controller_Request_Abstract $request) { $format = false; // check query string first if (in_array($request->getParam('format', 'none'), $this->responseTypes)) { $format = $request->getParam('format'); } else { $bestMimeType = $this->negotiateContentType($request); // if there's no matching MimeType, assign default XML if (!$bestMimeType || $bestMimeType == '*/*') { $bestMimeType = 'application/xml'; } $format = $this->responseTypes[$bestMimeType]; } if ($format === false or !in_array($format, $this->acceptableFormats)) { $request->setParam('format', $this->defaultFormat); if ($request->isOptions() === false) { $request->dispatchError(REST_Response::UNSUPPORTED_TYPE, 'Unsupported Media/Format Type'); } } else { $request->setParam('format', $format); } } /** * determines whether the requested actions exists * otherwise, triggers optionsAction. */ private function handleActions(Zend_Controller_Request_Abstract $request) { $methods = $this->getReflectionClass($request)->getMethods(ReflectionMethod::IS_PUBLIC); $actions = array(); foreach ($methods as &$method) { if ($method->getDeclaringClass()->name != 'REST_Controller') { $name = strtoupper($method->name); if ($name == '__CALL' and $method->class != 'Zend_Controller_Action') { $actions[] = $request->getMethod(); } elseif (substr($name, -6) == 'ACTION' and $name != 'INDEXACTION') { $actions[] = str_replace('ACTION', null, $name); } } } if (!in_array('OPTIONS', $actions)) { $actions[] = 'OPTIONS'; } // Cross-Origin Resource Sharing (CORS) $this->_response->setHeader('Access-Control-Allow-Methods', implode(', ', $actions)); if (!in_array(strtoupper($request->getMethod()), $actions)) { $request->dispatchError(REST_Response::NOT_ALLOWED, 'Method Not Allowed'); $this->_response->setHeader('Allow', implode(', ', $actions)); } } /** * PHP only parses the body into $_POST if its a POST request * this parses the reqest body in accordance with RFC2616 spec regardless of the HTTP method */ private function handleRequestBody(Zend_Controller_Request_Abstract $request) { $header = strtolower($request->getHeader('Content-Type')); // cleanup the charset part $header = current(explode(';', $header)); // detect request body content type foreach ($this->requestTypes as $contentType) { if ($header == $contentType) { break; } } // extract the raw body $rawBody = $request->getRawBody(); // treat these two separately because of the way PHP treats POST if (in_array($contentType, array('multipart/form-data', 'application/x-www-form-urlencoded'))) { // PHP takes care of everything for us in this case lets just modify the $_FILES array if ($request->isPost() && $contentType == 'multipart/form-data') { // if there are files, lets modify the array to match what we've done below foreach ($_FILES as &$file) { if (array_key_exists('tmp_name', $file) && is_file($file['tmp_name'])) { $data = file_get_contents($file['tmp_name']); $file['content'] = base64_encode($data); } } // reset the array pointer unset($file); } else { switch ($contentType) { case 'application/x-www-form-urlencoded': parse_str($rawBody, $_POST); break; // this is wher the magic happens // creates the $_FILES array for none POST requests case 'multipart/form-data': // extract the boundary parse_str(end(explode(';', $request->getHeader('Content-Type')))); if (isset($boundary)) { // get rid of the boundary at the edges if (preg_match(sprintf('/--%s(.+)--%s--/s', $boundary, $boundary), $rawBody, $regs)) { // split into chuncks $chunks = explode('--' . $boundary, trim($regs[1])); foreach ($chunks as $chunk) { // parse each chunk if (preg_match('/Content-Disposition: form-data; name="(?P<name>.+?)"(?:; filename="(?P<filename>.+?)")?(?P<headers>(?:\\r|\\n)+?.+?(?:\\r|\\n)+?)?(?P<data>.+)/si', $chunk, $regs)) { // dedect a file upload if (!empty($regs['filename'])) { // put aside for further analysis $data = $regs['data']; $headers = $this->parseHeaders($regs['headers']); // set our params variable $_FILES[$regs['name']] = array( 'name' => $regs['filename'], 'type' => $headers['Content-Type'], 'size' => mb_strlen($data), 'content' => base64_encode($data) ); // otherwise its a regular key=value combination } else { $_POST[$regs['name']] = trim($regs['data']); } } } } } break; } } $request->setParams($_POST + $_FILES); } elseif (!empty($rawBody)) { // seems like we are dealing with an encoded request try { switch ($contentType) { case 'text/javascript': case 'application/json': case 'application/javascript': $_POST = (array) Zend_Json::decode($rawBody, Zend_Json::TYPE_OBJECT); break; case 'text/xml': case 'application/xml': $json = @Zend_Json::fromXml($rawBody); $_POST = (array) Zend_Json::decode($json, Zend_Json::TYPE_OBJECT)->request; break; case 'text/php': case 'application/x-httpd-php': case 'application/x-httpd-php-source': $_POST = (array) unserialize($rawBody); break; default: $_POST = (array) $rawBody; break; } $request->setParams($_POST); } catch (Exception $e) { $request->dispatchError(REST_Response::BAD_REQUEST, 'Invalid Payload Format'); return; } } } /** * constructs reflection class of the requested controoler **/ private function getReflectionClass(Zend_Controller_Request_Abstract $request) { if ($this->reflectionClass === null) { // get the dispatcher to load the controller class $controller = $this->dispatcher->getControllerClass($request); // if no controller present escape silently... if ($controller === false) return false; // ... load controller class $className = $this->dispatcher->loadClass($controller); // extract the actions through reflection $this->reflectionClass = new ReflectionClass($className); } return $this->reflectionClass; } /** * determines if the requested controller is a RESTful controller **/ private function isRestClass($class) { if ($class === false) { return false; } elseif (in_array($class->name, array('Zend_Rest_Controller', 'REST_Controller'))) { return true; } else { return $this->isRestClass($class->getParentClass()); } } /** * utility function to replace http_parse_headers when its not available * see: http://pecl.php.net/pecl_http **/ private function parseHeaders($header) { if (function_exists('http_parse_headers')) { return http_parse_headers($header); } $retVal = array(); $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header)); foreach( $fields as $field ) { if( preg_match('/([^:]+): (.+)/m', $field, $match) ) { $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1]))); if( isset($retVal[$match[1]]) ) { $retVal[$match[1]] = array($retVal[$match[1]], $match[2]); } else { $retVal[$match[1]] = trim($match[2]); } } } return $retVal; } /** * utility function to replace http_negotiate_content_type when its not available * see: http://pecl.php.net/pecl_http **/ private function negotiateContentType($request) { if (function_exists('http_negotiate_content_type')) { return http_negotiate_content_type(array_keys($this->responseTypes)); } $string = $request->getHeader('Accept'); $mimeTypes = array(); // Accept header is case insensitive, and whitespace isn't important $string = strtolower(str_replace(' ', '', $string)); // divide it into parts in the place of a "," $types = explode(',', $string); foreach ($types as $type) { // the default quality is 1. $quality = 1; // check if there is a different quality if (strpos($type, ';q=')) { // divide "mime/type;q=X" into two parts: "mime/type" / "X" list($type, $quality) = explode(';q=', $type); } elseif (strpos($type, ';')) { list($type, ) = explode(';', $type); } // WARNING: $q == 0 means, that mime-type isn't supported! if (array_key_exists($type, $this->responseTypes) and !array_key_exists($quality, $mimeTypes)) { $mimeTypes[$quality] = $type; } } // sort by quality descending krsort($mimeTypes); return current(array_values($mimeTypes)); } }
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Controller/Action/Helper/RestContexts.php
Controller/Action/Helper/RestContexts.php
<?php class REST_Controller_Action_Helper_RestContexts extends Zend_Controller_Action_Helper_Abstract { public function preDispatch() { $frontController = Zend_Controller_Front::getInstance(); $currentMethod = $frontController->getRequest()->getMethod(); $controller = $this->getActionController(); if ($controller instanceOf Zend_Rest_Controller or $controller instanceOf REST_Controller) { $contextSwitch = $controller->getHelper('contextSwitch'); $contextSwitch->setAutoSerialization(true); foreach ($this->getControllerActions($controller, $currentMethod) as $action) { $contextSwitch->addActionContext($action, true); } $contextSwitch->initContext(); } } private function getControllerActions($controller, $currentMethod) { $class = new ReflectionObject($controller); $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC); $actions = array(); foreach ($methods as &$method) { $name = strtolower($method->name); if ($name == '__call') { $actions[] = strtolower($currentMethod); } elseif (substr($name, -6) == 'action') { $actions[] = str_replace('action', null, $name); } } return $actions; } }
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Controller/Action/Helper/ContextSwitch.php
Controller/Action/Helper/ContextSwitch.php
<?php /** * ContextSwitch * * extends default context switch and adds AMF3, XML, PHP serialization */ class REST_Controller_Action_Helper_ContextSwitch extends Zend_Controller_Action_Helper_ContextSwitch { protected $_autoSerialization = true; // TODO: run through Zend_Serializer::factory() protected $_availableAdapters = array( 'json' => 'Zend_Serializer_Adapter_Json', 'xml' => 'REST_Serializer_Adapter_Xml', 'php' => 'Zend_Serializer_Adapter_PhpSerialize' ); protected $_rest_contexts = array( 'json' => array( 'suffix' => 'json', 'headers' => array( 'Content-Type' => 'application/json' ), 'options' => array( 'autoDisableLayout' => true, ), 'callbacks' => array( 'init' => 'initAbstractContext', 'post' => 'restContext' ), ), 'xml' => array( 'suffix' => 'xml', 'headers' => array( 'Content-Type' => 'application/xml' ), 'options' => array( 'autoDisableLayout' => true, ), 'callbacks' => array( 'init' => 'initAbstractContext', 'post' => 'restContext' ), ), 'php' => array( 'suffix' => 'php', 'headers' => array( 'Content-Type' => 'application/x-httpd-php' ), 'options' => array( 'autoDisableLayout' => true, ), 'callbacks' => array( 'init' => 'initAbstractContext', 'post' => 'restContext' ) ), 'html' => array( 'headers' => array( 'Content-Type' => 'text/html; Charset=UTF-8' ), 'options' => array( 'autoDisableLayout' => false, ) ) ); public function __construct($options = null) { if ($options instanceof Zend_Config) { $this->setConfig($options); } elseif (is_array($options)) { $this->setOptions($options); } if (empty($this->_contexts)) { $this->addContexts($this->_rest_contexts); } $this->init(); } public function getAutoDisableLayout() { $context = $this->_actionController->getRequest()->getParam($this->getContextParam()); return $this->_rest_contexts[$context]['options']['autoDisableLayout']; } public function initAbstractContext() { if (!$this->getAutoSerialization()) { return; } $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $view = $viewRenderer->view; if ($view instanceof Zend_View_Interface) { $viewRenderer->setNoRender(true); } } public function restContext() { if (!$this->getAutoSerialization()) { return; } $view = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view; if ($view instanceof Zend_View_Interface) { if (method_exists($view, 'getVars')) { $data = $view->getVars(); if (count($data) !== 0) { $serializer = new $this->_availableAdapters[$this->_currentContext]; $body = $serializer->serialize($data); if ($this->_currentContext == 'xml') { $stylesheet = $this->getRequest()->getHeader('X-XSL-Stylesheet'); if ($stylesheet !== false and !empty($stylesheet)) { $body = str_replace('<?xml version="1.0"?>', sprintf('<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="%s"?>', $stylesheet), $body); } } if ($this->_currentContext == 'json') { $callback = $this->getRequest()->getParam('jsonp-callback', false); if ($callback !== false and !empty($callback)) { $body = sprintf('%s(%s)', $callback, $body); } } $this->getResponse()->setBody($body); } } } } public function setAutoSerialization($flag) { $this->_autoSerialization = (bool) $flag; return $this; } public function getAutoSerialization() { return $this->_autoSerialization; } }
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Test/PHPUnit/ControllerTestCase.php
Test/PHPUnit/ControllerTestCase.php
<?php /** * Functional testing scaffold for MVC applications * * @uses PHPUnit_Framework_TestCase * @category Zend * @package Zend_Test * @subpackage PHPUnit */ abstract class REST_Test_PHPUnit_ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase { /** * Retrieve test case response object * * @return Zend_Controller_Response_HttpTestCase */ public function getResponse() { if (null === $this->_response) { require_once './ResponseTestCase.php'; $this->_response = new REST_ResponseTestCase(); } return $this->_response; } }
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Test/PHPUnit/ResponseTestCase.php
Test/PHPUnit/ResponseTestCase.php
<?php /** * provides named constants for * HTTP protocol status codes. * * Testing class for PHPUnit testing * @use REST_Response */ class REST_ResponseTestCase extends Zend_Controller_Response_HttpTestCase { // Informational 1xx const HTTP_CONTINUE = 100; const SWITCH_PROTOCOLS = 101; // Successful 2xx const OK = 200; const CREATED = 201; const ACCEPTED = 202; const NONAUTHORITATIVE = 203; const NO_CONTENT = 204; const RESET_CONTENT = 205; const PARTIAL_CONTENT = 206; // Redirection 3xx const MULTIPLE_CHOICES = 300; const MOVED_PERMANENTLY = 301; const FOUND = 302; const SEE_OTHER = 303; const NOT_MODIFIED = 304; const USE_PROXY = 305; // 306 is deprecated but reserved const TEMP_REDIRECT = 307; // Client Error 4xx const BAD_REQUEST = 400; const UNAUTHORIZED = 401; const PAYMENT_REQUIRED = 402; const FORBIDDEN = 403; const NOT_FOUND = 404; const NOT_ALLOWED = 405; const NOT_ACCEPTABLE = 406; const PROXY_AUTH_REQUIRED = 407; const REQUEST_TIMEOUT = 408; const CONFLICT = 409; const GONE = 410; const LENGTH_REQUIRED = 411; const PRECONDITION_FAILED = 412; const LARGE_REQUEST_ENTITY = 413; const LONG_REQUEST_URI = 414; const UNSUPPORTED_TYPE = 415; const UNSATISFIABLE_RANGE = 416; const EXPECTATION_FAILED = 417; // Server Error 5xx const SERVER_ERROR = 500; const NOT_IMPLEMENTED = 501; const BAD_GATEWAY = 502; const UNAVAILABLE = 503; const GATEWAY_TIMEOUT = 504; const UNSUPPORTED_VERSION = 505; const BANDWIDTH_EXCEEDED = 509; // Informational 1xx function httpContinue() { $this->setHttpResponseCode(self::HTTP_CONTINUE); } function switchProtocols() { $this->setHttpResponseCode(self::SWITCH_PROTOCOLS); } // Successful 2xx public function Ok() { $this->setHttpResponseCode(self::OK); } public function created() { $this->setHttpResponseCode(self::CREATED); } public function accepted() { $this->setHttpResponseCode(self::ACCEPTED); } public function nonAuthoritative() { $this->setHttpResponseCode(self::NONAUTHORITATIVE); } public function noContent() { $this->setHttpResponseCode(self::NO_CONTENT); } public function resetContent() { $this->setHttpResponseCode(self::RESET_CONTENT); } public function partialContent() { $this->setHttpResponseCode(self::PARTIAL_CONTENT); } // Redirection 3xx public function multipleChoices() { $this->setHttpResponseCode(self::MULTIPLE_CHOICES); } public function movedPermanently() { $this->setHttpResponseCode(self::MOVED_PERMANENTLY); } public function found() { $this->setHttpResponseCode(self::FOUND); } public function seeOther() { $this->setHttpResponseCode(self::NO_CONTENT); } public function notModified() { $this->setHttpResponseCode(self::NOT_MODIFIED); } public function useProxy() { $this->setHttpResponseCode(self::USE_PROXY); } public function tempRedirect() { $this->setHttpResponseCode(self::TEMP_REDIRECT); } // Client Error 4xx public function badRequest() { $this->setHttpResponseCode(self::BAD_REQUEST); } public function unauthorized() { $this->setHttpResponseCode(self::UNAUTHORIZED); } public function paymentRequired() { $this->setHttpResponseCode(self::PAYMENT_REQUIRED); } public function forbidden() { $this->setHttpResponseCode(self::FORBIDDEN); } public function notFound() { $this->setHttpResponseCode(self::NOT_FOUND); } public function notAllowed() { $this->setHttpResponseCode(self::NOT_ALLOWED); } public function notAcceptable() { $this->setHttpResponseCode(self::NOT_ACCEPTABLE); } public function proxyAuthRequired() { $this->setHttpResponseCode(self::PROXY_AUTH_REQUIRED); } public function requestTimeout() { $this->setHttpResponseCode(self::REQUEST_TIMEOUT); } public function conflict() { $this->setHttpResponseCode(self::CONFLICT); } public function gone() { $this->setHttpResponseCode(self::GONE); } public function lengthRequired() { $this->setHttpResponseCode(self::NO_CONTENT); } public function preconditionFailed() { $this->setHttpResponseCode(self::PRECONDITION_FAILED); } public function largeRequestEntity() { $this->setHttpResponseCode(self::LARGE_REQUEST_ENTITY); } public function longRequestUri() { $this->setHttpResponseCode(self::LONG_REQUEST_URI); } public function unsupportedType() { $this->setHttpResponseCode(self::UNSUPPORTED_TYPE); } public function unsatisfiableRange() { $this->setHttpResponseCode(self::UNSATISFIABLE_RANGE); } public function expectationFailed() { $this->setHttpResponseCode(self::EXPECTATION_FAILED); } // Server Error 5xx public function serverError() { $this->setHttpResponseCode(self::SERVER_ERROR); } public function notImplemented() { $this->setHttpResponseCode(self::NOT_IMPLEMENTED); } public function badGateway() { $this->setHttpResponseCode(self::BAD_GATEWAY); } public function unavailable() { $this->setHttpResponseCode(self::UNAVAILABLE); } public function gatewayTimeout() { $this->setHttpResponseCode(self::GATEWAY_TIMEOUT); } public function unsupportedVersion() { $this->setHttpResponseCode(self::UNSUPPORTED_VERSION); } public function bandwidthExceeded() { $this->setHttpResponseCode(self::BANDWIDTH_EXCEEDED); } /** * Return header value (if set); see {@link $_headers} for format * * @return string | boolean */ public function getHeaderValue($name) { foreach ($this->_headers as $key => $header) { if ($name == $header['name']) { return $header['value']; } } return false; } } ?>
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
ahmadnassri/restful-zend-framework
https://github.com/ahmadnassri/restful-zend-framework/blob/1a030f213a133336e9f8caa325ea7c002dc5ef41/Serializer/Adapter/Xml.php
Serializer/Adapter/Xml.php
<?php class REST_Serializer_Adapter_Xml extends Zend_Serializer_Adapter_AdapterAbstract { /** * @var array Default options */ protected $_options = array( 'rootNode' => 'response', ); /** * Serialize PHP value to XML * * @param mixed $value * @param array $opts * @return string * @throws Zend_Serializer_Exception on XML encoding exception */ public function serialize($value, array $opts = array()) { $opts = $opts + $this->_options; try { $dom = new DOMDocument('1.0', 'utf-8'); $root = $dom->appendChild($dom->createElement($opts['rootNode'])); $this->createNodes($dom, $value, $root, false); return $dom->saveXml(); } catch (Exception $e) { require_once 'Zend/Serializer/Exception.php'; throw new Zend_Serializer_Exception('Serialization failed', 0, $e); } } /** * Deserialize XML to PHP value * * @param string $json * @param array $opts * @return mixed */ public function unserialize($xml, array $opts = array()) { try { $json = Zend_Json::fromXml($xml); return (array) Zend_Json::decode($json, Zend_Json::TYPE_OBJECT); } catch (Exception $e) { require_once 'Zend/Serializer/Exception.php'; throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e); } } private function createNodes($dom, $data, &$parent) { switch (gettype($data)) { case 'string': case 'integer': case 'double': $parent->appendChild($dom->createTextNode($data)); break; case 'boolean': switch ($data) { case true: $value = 'true'; break; case false: $value = 'false'; break; } $parent->appendChild($dom->createTextNode($value)); break; case 'object': case 'array': foreach ($data as $key => $value) { if (is_object($value) and $value instanceOf DOMDocument and !empty($value->firstChild)) { $node = $dom->importNode($value->firstChild, true); $parent->appendChild($node); } else { $attributes = null; // SimpleXMLElements can contain key with @attribute as the key name // which indicates an associated array that should be applied to the xml element if (is_object($value) and $value instanceOf SimpleXMLElement) { $attributes = $value->attributes(); $value = (array) $value; } // don't emit @attribute as an element of it's own if ($key[0] !== '@') { if (gettype($value) == 'array' and !is_numeric($key)) { $child = $parent->appendChild($dom->createElement($key)); if ($attributes) { foreach ($attributes as $attrKey => $attrValue) { $child->setAttribute($attrKey, $attrValue); } } $this->createNodes($dom, $value, $child); } else { if (is_numeric($key)) { $key = sprintf('%s', $this->depluralize($parent->tagName)); } $child = $parent->appendChild($dom->createElement($key)); if ($attributes) { foreach ($attributes as $attrKey => $attrValue) { $child->setAttribute($attrKey, $attrValue); } } $this->createNodes($dom, $value, $child); } } } } break; } } private function depluralize($word) { $rules = array( 'ss' => false, 'os' => 'o', 'ies' => 'y', 'xes' => 'x', 'oes' => 'o', 'ies' => 'y', 'ves' => 'f', 's' => null ); // Loop through all the rules foreach(array_keys($rules) as $key) { // If the end of the word doesn't match the key, it's not a candidate for replacement. if (substr($word, (strlen($key) * -1)) != $key) { continue; } // If the value of the key is false, stop looping and return the original version of the word. if ($key === false) { return $word; } // apply the rule return substr($word, 0, strlen($word) - strlen($key)) . $rules[$key]; } return $word; } }
php
MIT
1a030f213a133336e9f8caa325ea7c002dc5ef41
2026-01-05T04:59:58.834463Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Kernel.php
src/Kernel.php
<?php namespace App; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\Routing\RouteCollectionBuilder; class Kernel extends BaseKernel { use MicroKernelTrait; const CONFIG_EXTS = '.{php,xml,yaml,yml}'; public function getCacheDir() { return $this->getProjectDir().'/var/cache/'.$this->environment; } public function getLogDir() { return $this->getProjectDir().'/var/log'; } public function registerBundles() { $contents = require $this->getProjectDir().'/config/bundles.php'; foreach ($contents as $class => $envs) { if (isset($envs['all']) || isset($envs[$this->environment])) { yield new $class(); } } } protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader) { $container->setParameter('container.autowiring.strict_mode', true); $container->setParameter('container.dumper.inline_class_loader', true); $confDir = $this->getProjectDir().'/config'; $loader->load($confDir.'/{packages}/*'.self::CONFIG_EXTS, 'glob'); $loader->load($confDir.'/{packages}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, 'glob'); $loader->load($confDir.'/{services}'.self::CONFIG_EXTS, 'glob'); $loader->load($confDir.'/{parameters}'.self::CONFIG_EXTS, 'glob'); $loader->load($confDir.'/{services}_'.$this->environment.self::CONFIG_EXTS, 'glob'); } protected function configureRoutes(RouteCollectionBuilder $routes) { $confDir = $this->getProjectDir().'/config'; $routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob'); $routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob'); $routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob'); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Event/RepoStatusChangedEvent.php
src/Event/RepoStatusChangedEvent.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Event; use App\RecipeRepo\RecipeRepo; use Symfony\Component\EventDispatcher\Event; /** * Class RepoStatusChangedEvent. * * @author moay <mv@moay.de> */ class RepoStatusChangedEvent extends Event { const NAME = 'repo.statuschange'; /** @var RecipeRepo */ private $recipeRepo; /** * RepoStatusChangedEvent constructor. * * @param RecipeRepo $recipeRepo */ public function __construct(RecipeRepo $recipeRepo) { $this->recipeRepo = $recipeRepo; } /** * @return RecipeRepo */ public function getRecipeRepo() { return $this->recipeRepo; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Entity/Recipe.php
src/Entity/Recipe.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Entity; use App\RecipeRepo\RecipeRepo; class Recipe implements \JsonSerializable { /** * @var string */ private $author; /** * @var string */ private $package; /** * @var string */ private $version; /** * @var string */ private $localPath; /** * @var RecipeRepo */ private $repo; /** @var string */ private $publicUrl; /** * @var string */ private $repoSlug; /** * @var array */ private $manifest; /** * @var bool */ private $manifestValid; /** * @return string */ public function getAuthor() { return $this->author; } /** * @param string $author */ public function setAuthor(string $author) { $this->author = $author; } /** * @return string */ public function getPackage() { return $this->package; } /** * @param string $package */ public function setPackage(string $package) { $this->package = $package; } /** * @return string */ public function getOfficialPackageName() { return implode('/', [$this->author, $this->package]); } /** * @return string */ public function getVersion() { return $this->version; } /** * @param string $version */ public function setVersion(string $version) { $this->version = $version; } /** * @return string */ public function getLocalPath() { return $this->localPath; } /** * @param string $localPath */ public function setLocalPath(string $localPath) { $this->localPath = $localPath; } /** * @return RecipeRepo */ public function getRepo() { return $this->repo; } /** * @param RecipeRepo $repo */ public function setRepo(RecipeRepo $repo) { $this->repo = $repo; } /** * @return string */ public function getRepoSlug() { return $this->repoSlug; } /** * @param string $repoSlug */ public function setRepoSlug(string $repoSlug) { $this->repoSlug = $repoSlug; } /** * @return array */ public function getManifest() { return $this->manifest; } /** * @param array $manifest */ public function setManifest(array $manifest) { $this->manifest = $manifest; } /** * @return bool */ public function isManifestValid() { return $this->manifestValid; } /** * @param bool $manifestValid */ public function setManifestValid(bool $manifestValid) { $this->manifestValid = $manifestValid; } /** * @return string */ public function getPublicUrl(): string { return $this->publicUrl; } /** * @param string $publicUrl */ public function setPublicUrl(string $publicUrl): void { $this->publicUrl = $publicUrl; } /** * @return array */ public function jsonSerialize() { return [ 'author' => $this->getAuthor(), 'package' => $this->getPackage(), 'officialPackageName' => $this->getOfficialPackageName(), 'version' => $this->getVersion(), 'manifest' => $this->getManifest(), 'manifestValid' => $this->isManifestValid(), 'repo' => $this->getRepo(), 'publicUrl' => $this->getPublicUrl(), ]; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Controller/EndpointController.php
src/Controller/EndpointController.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Controller; use App\Service\Provider\AliasesProvider; use App\Service\Provider\PackagesProvider; use App\Service\Provider\UlidProvider; use App\Service\Provider\VersionsProvider; use App\Traits\ProvidesUnescapedJsonResponsesTrait; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; /** * Class EndpointController. * * @author moay <mv@moay.de> */ class EndpointController extends AbstractController { use ProvidesUnescapedJsonResponsesTrait; /** * @Route("/aliases.json", name="endpoint_aliases") * * @param AliasesProvider $provider * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function aliases(AliasesProvider $provider): JsonResponse { return $this->unescapedSlashesJson($provider->provideAliases()); } /** * @Route("/versions.json", name="endpoint_versions") * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function versions(VersionsProvider $provider): JsonResponse { return $this->unescapedSlashesJson($provider->provideVersions()); } /** * @Route("/ulid", name="endpoint_ulid") * * @param UlidProvider $provider * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function ulid(UlidProvider $provider): JsonResponse { return $this->unescapedSlashesJson(['ulid' => $provider->provideUlid()]); } /** * @Route("/p/{packages}", name="endpoint_packages") * * @param string $packages * @param PackagesProvider $provider * * @return \Symfony\Component\HttpFoundation\JsonResponse * * @throws \Http\Client\Exception */ public function packages(string $packages, PackagesProvider $provider): JsonResponse { return $this->unescapedSlashesJson($provider->providePackages($packages)); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Controller/WebhookController.php
src/Controller/WebhookController.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Controller; use App\Service\RecipeRepoManager; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; /** * Class WebhookController. * * @author moay <mv@moay.de> */ class WebhookController extends AbstractController { /** * @Route("/webhook/update", name="webhook_update", methods={"POST"}) * * @param RecipeRepoManager $repoManager * * @return \Symfony\Component\HttpFoundation\JsonResponse * * @throws \Cz\Git\GitException */ public function update(RecipeRepoManager $repoManager): JsonResponse { foreach ($repoManager->getConfiguredRepos() as $repo) { $repo->update(); } return $this->json(['success' => true]); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Controller/FrontendController.php
src/Controller/FrontendController.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Controller; use App\Service\Compiler\LocalRecipeCompiler; use App\Service\Compiler\SystemStatusReportCompiler; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * Class FrontendController. * * @author moay <mv@moay.de> */ class FrontendController extends AbstractController { /** * @Route("/", name="frontend_dashboard") * * @return mixed|\Symfony\Component\HttpFoundation\Response */ public function dashboard(): Response { return $this->render('dashboard.html.twig'); } /** * @Route("/ui/data", name="frontend_dashboard_data") * * @param SystemStatusReportCompiler $reportGenerator * @param LocalRecipeCompiler $recipeCompiler * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function dashboardData(SystemStatusReportCompiler $reportGenerator, LocalRecipeCompiler $recipeCompiler): JsonResponse { return $this->json([ 'status' => $reportGenerator->getReport(), 'recipes' => $recipeCompiler->getLocalRecipes(), ]); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Traits/ProvidesUnescapedJsonResponsesTrait.php
src/Traits/ProvidesUnescapedJsonResponsesTrait.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Traits; use Symfony\Component\HttpFoundation\JsonResponse; /** * Class ProvidesUnescapedJsonResponsesTrait. * * @author moay <mv@moay.de> */ trait ProvidesUnescapedJsonResponsesTrait { /** * @param $data * @param int $status * @param array $headers * @param array $context * * @return static */ protected function unescapedSlashesJson($data, int $status = 200, array $headers = [], array $context = []): JsonResponse { $json = json_encode($data, JSON_UNESCAPED_SLASHES); return JsonResponse::fromJsonString($json, $status, $headers); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/RecipeRepo/OfficialRecipeRepo.php
src/RecipeRepo/OfficialRecipeRepo.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\RecipeRepo; use App\Service\Cache; use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Class OfficialRecipeRepo. * * @author moay <mv@moay.de> */ class OfficialRecipeRepo extends RecipeRepo { /** @var string */ protected $repoDirName = 'official'; /** * OfficialRecipeRepo constructor. * * @param string $officialRepoUrl * @param string $projectDir * @param Cache $cache * @param LoggerInterface $logger */ public function __construct( string $officialRepoUrl, string $projectDir, Cache $cache, LoggerInterface $logger, EventDispatcherInterface $eventDispatcher ) { parent::__construct($officialRepoUrl, $projectDir, $cache, $logger, $eventDispatcher); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/RecipeRepo/ContribRecipeRepo.php
src/RecipeRepo/ContribRecipeRepo.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\RecipeRepo; use App\Service\Cache; use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Class ContribRecipeRepo. * * @author moay <mv@moay.de> */ class ContribRecipeRepo extends RecipeRepo { /** @var string */ protected $repoDirName = 'contrib'; /** * ContribRecipeRepo constructor. * * @param string $contribRepoUrl * @param string $projectDir * @param Cache $cache * @param LoggerInterface $logger * @param EventDispatcherInterface $eventDispatcher */ public function __construct( string $contribRepoUrl, string $projectDir, Cache $cache, LoggerInterface $logger, EventDispatcherInterface $eventDispatcher ) { parent::__construct($contribRepoUrl, $projectDir, $cache, $logger, $eventDispatcher); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/RecipeRepo/GitRepo.php
src/RecipeRepo/GitRepo.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\RecipeRepo; use Cz\Git\GitException; use Cz\Git\GitRepository; /** * Class GitRepo. * * @author moay <mv@moay.de> */ class GitRepo extends GitRepository { /** * @return GitRepository * * @throws GitException */ public function forceClean() { return $this->begin() ->run('git clean -fd') ->end(); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/RecipeRepo/PrivateRecipeRepo.php
src/RecipeRepo/PrivateRecipeRepo.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\RecipeRepo; use App\Service\Cache; use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Class PrivateRecipeRepo. * * @author moay <mv@moay.de> */ class PrivateRecipeRepo extends RecipeRepo { /** @var string */ protected $repoDirName = 'private'; /** * PrivateRecipeRepo constructor. * * @param string $privateRepoUrl * @param string $projectDir * @param Cache $cache * @param LoggerInterface $logger */ public function __construct( string $privateRepoUrl, string $projectDir, Cache $cache, LoggerInterface $logger, EventDispatcherInterface $eventDispatcher ) { parent::__construct($privateRepoUrl, $projectDir, $cache, $logger, $eventDispatcher); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/RecipeRepo/RecipeRepo.php
src/RecipeRepo/RecipeRepo.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\RecipeRepo; use App\Event\RepoStatusChangedEvent; use App\Service\Cache; use Cz\Git\GitException; use InvalidArgumentException; use Psr\Log\LoggerInterface; use Symfony\Component\Cache\Simple\FilesystemCache; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; /** * Class RecipeRepo. * * @author moay <mv@moay.de> */ abstract class RecipeRepo implements \JsonSerializable { const REPO_PATH = '/var/repo/'; /** @var GitRepo */ private $repo; /** @var string */ private $repoUrl; /** @var string */ protected $repoDirName = ''; /** @var string */ private $fullRepoPath; /** @var FilesystemCache */ private $cache; /** @var LoggerInterface */ private $logger; /** @var EventDispatcherInterface */ private $eventDispatcher; /** * RecipeRepo constructor. * * @param string $repoUrl * @param string $projectDir * @param Cache $cache * @param LoggerInterface $logger * @param EventDispatcherInterface $eventDispatcher */ public function __construct( string $repoUrl, string $projectDir, Cache $cache, LoggerInterface $logger, EventDispatcherInterface $eventDispatcher ) { $this->repoUrl = $repoUrl; $this->fullRepoPath = $projectDir.self::REPO_PATH.$this->repoDirName; $this->cache = $cache(); $this->logger = $logger; $this->eventDispatcher = $eventDispatcher; } /** * Deletes all repo contents and reclones it from remote. * * @throws GitException */ public function reset() { $this->remove(); $this->initialize(); } /** * Tries to pull the repo, initalizes it if it has not been setup yet. * Tries to backup before and restore in case of failure. * * @throws GitException */ public function update() { if (!($this->repo instanceof GitRepo)) { $this->initialize(); } try { $this->backup(); $this->repo->pull(); $this->repo->forceClean(); $this->wipeBackup(); } catch (GitException $e) { $this->logger->error('Repo pull failed ('.$this->repoUrl.')'); $this->restore(); } $this->logger->info('Repo updated ('.$this->repoUrl.')'); $this->handleRepoStatusChange(); } /** * Loads the repo, clones if needed. * * @throws GitException */ public function initialize() { if (!GitRepo::isRemoteUrlReadable($this->repoUrl)) { throw new GitException('The repo url '.$this->repoUrl.' is not readable'); } if (!is_dir($this->fullRepoPath)) { try { $this->repo = GitRepo::cloneRepository($this->repoUrl, $this->fullRepoPath); $this->logger->info('Repo cloned ('.$this->repoUrl.')'); } catch (GitException $e) { $this->logger->error('Repo clone failed ('.$this->repoUrl.')'); throw $e; } } else { $this->repo = new GitRepo($this->fullRepoPath); } $this->handleRepoStatusChange(); } /** * Removes the repo directory. */ public function remove() { if (is_dir($this->fullRepoPath)) { $filesystem = new Filesystem(); $filesystem->remove($this->fullRepoPath); $this->logger->info('Repo deleted ('.$this->repoUrl.')'); $this->handleRepoStatusChange(); } } /** * Diagnose method for the system health report. * * @return array */ public function getStatus() { try { $repo = new GitRepo($this->fullRepoPath); $loaded = true; } catch (GitException $e) { $loaded = false; } return [ 'url' => $this->repoUrl, 'local_path' => $this->fullRepoPath, 'remote_readable' => GitRepo::isRemoteUrlReadable($this->repoUrl), 'downloaded' => $loaded, 'last_updated' => $this->cache->get('repo-updated-'.$this->repoDirName), 'slug' => $this->repoDirName, ]; } /** * @return iterable|SplFileInfo[] */ public function getRecipeDirectories() { if (!is_dir($this->fullRepoPath)) { return []; } try { return (new Finder()) ->ignoreUnreadableDirs() ->depth(0) ->in($this->fullRepoPath.'/*/*') ->exclude('.git') ->directories(); } catch (InvalidArgumentException $e) { return []; } } /** * Restores a backup if there was one. * * If there is no backup, existing files won't be touched. */ private function restore() { if (is_dir($this->fullRepoPath.'_backup')) { $filesystem = new Filesystem(); $filesystem->rename($this->fullRepoPath.'_backup', $this->fullRepoPath, true); $this->logger->info('Repo backup restored ('.$this->repoUrl.').'); } else { $this->logger->warning('Could not restore repo backup ('.$this->repoUrl.'). There was no backup.'); } } /** * Creates a backup of the current repo state. */ private function backup() { if (is_dir($this->fullRepoPath)) { $this->wipeBackup(); $filesystem = new Filesystem(); $filesystem->mirror($this->fullRepoPath, $this->fullRepoPath.'_backup'); $this->logger->info('Repo backup created ('.$this->repoUrl.').'); } } /** * Wipes an existing backup folder if it exists. */ private function wipeBackup() { if (is_dir($this->fullRepoPath.'_backup')) { $filesystem = new Filesystem(); $filesystem->remove($this->fullRepoPath.'_backup'); } } /** * Triggers the status changed event. */ private function handleRepoStatusChange() { $this->cache->set('repo-updated-'.$this->repoDirName, date('Y-m-d H:i:s')); $statusChangedEvent = new RepoStatusChangedEvent($this); $this->eventDispatcher->dispatch(RepoStatusChangedEvent::NAME, $statusChangedEvent); } /** * @return string */ public function getRepoUrl() { return $this->repoUrl; } /** * @return string */ public function getRepoDirName() { return $this->repoDirName; } /** * @return string */ public function getFullRepoPath() { return $this->fullRepoPath; } /** * @return array */ public function jsonSerialize() { return [ 'slug' => $this->repoDirName, 'url' => $this->repoUrl, ]; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Exception/RecipeRepoManagerException.php
src/Exception/RecipeRepoManagerException.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Exception; /** * Class RecipeRepoManagerException. * * @author moay <mv@moay.de> */ class RecipeRepoManagerException extends \Exception { }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Exception/RecipeRepoBackupException.php
src/Exception/RecipeRepoBackupException.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Exception; /** * Class RecipeRepoBackupException. * * @author moay <mv@moay.de> */ class RecipeRepoBackupException extends \Exception { }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/EventSubscriber/StatusReportEventSubscriber.php
src/EventSubscriber/StatusReportEventSubscriber.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\EventSubscriber; use App\Event\RepoStatusChangedEvent; use App\Service\Compiler\SystemStatusReportCompiler; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Class StatusReportEventSubscriber. * * @author moay <mv@moay.de> */ class StatusReportEventSubscriber implements EventSubscriberInterface { /** @var SystemStatusReportCompiler */ private $reportCompiler; /** * StatusReportEventSubscriber constructor. * * @param SystemStatusReportCompiler $reportCompiler */ public function __construct(SystemStatusReportCompiler $reportCompiler) { $this->reportCompiler = $reportCompiler; } /** * @return array */ public static function getSubscribedEvents() { return [ RepoStatusChangedEvent::NAME => 'onRepoStatusChange', ]; } /** * @param RepoStatusChangedEvent $event */ public function onRepoStatusChange(RepoStatusChangedEvent $event) { $this->reportCompiler->removeReport(); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/EventSubscriber/LocalAliasEventSubscriber.php
src/EventSubscriber/LocalAliasEventSubscriber.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\EventSubscriber; use App\Event\RepoStatusChangedEvent; use App\Service\Cache; use App\Service\Provider\AliasesProvider; use Symfony\Component\Cache\Simple\FilesystemCache; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Class LocalAliasEventSubscriber. * * @author moay <mv@moay.de> */ class LocalAliasEventSubscriber implements EventSubscriberInterface { /** @var FilesystemCache */ private $cache; /** * LocalAliasEventSubscriber constructor. * * @param Cache $cache */ public function __construct(Cache $cache) { $this->cache = $cache(); } /** * @return array */ public static function getSubscribedEvents() { return [ RepoStatusChangedEvent::NAME => 'onRepoStatusChange', ]; } /** * @param RepoStatusChangedEvent $event */ public function onRepoStatusChange(RepoStatusChangedEvent $event) { if ($this->cache->has(AliasesProvider::LOCAL_ALIASES_CACHE_KEY)) { $this->cache->delete(AliasesProvider::LOCAL_ALIASES_CACHE_KEY); } } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/RecipePublicUrlResolver.php
src/Service/RecipePublicUrlResolver.php
<?php namespace App\Service; use App\Entity\Recipe; /** * Class RecipePublicUrlResolver. * * @author Manuel Voss <manuel.voss@i22.de> */ class RecipePublicUrlResolver { const RECIPE_PREFIXES = [ 'bitbucket.org' => '/src/master/', 'default' => '/tree/master/', ]; /** * @param Recipe $recipe * * @return string */ public function resolveUrl(Recipe $recipe) { if (null === $recipe->getRepo()) { throw new \InvalidArgumentException('Recipes must have a repo in order to have their url resolved.'); } $repoUrl = $recipe->getRepo()->getRepoUrl(); $urlProtocol = parse_url($repoUrl, PHP_URL_SCHEME); switch ($urlProtocol) { case 'http': case 'https': return $this->resolveHttpUrl($repoUrl, $recipe->getOfficialPackageName()); case 'ssh': return $this->resolveSshUrl($repoUrl, $recipe->getOfficialPackageName()); case null: if ('git@' === substr($repoUrl, 0, 4)) { return $this->resolveSshUrl($repoUrl, $recipe->getOfficialPackageName()); } } return $this->buildFallbackUrl($repoUrl, $recipe->getOfficialPackageName()); } /** * @param string $repoUrl * @param string $packageName * * @return string */ private function resolveHttpUrl(string $repoUrl, string $packageName) { if (preg_match('/^(?:https?(?:\:\/\/)?)?([a-zA-Z0-9-_\.]+\.[a-z]+)(?:\:([0-9]+))?\/([a-zA-Z0-9-_]+)\/([a-zA-Z0-9-_]+)(?:\.git)?$/', $repoUrl, $urlParts)) { $host = $urlParts[1]; $port = empty($urlParts[2]) ? null : $urlParts[2]; $user = $urlParts[3]; $repo = $urlParts[4]; return $this->buildUrl($host, implode('/', [$user, $repo]), $packageName, $port); } return $this->buildFallbackUrl($repoUrl, $packageName); } /** * @param string $repoUrl * @param string $packageName * * @return string */ private function resolveSshUrl(string $repoUrl, string $packageName) { if (preg_match('/^(?:ssh(?::\/\/)?)?(?:git)?@?([a-zA-Z0-9-_\.]+\.[a-z]+)(:[0-9])?(?:[:\/]([a-zA-Z0-9-_\.]*))?(\/|:)([a-zA-Z0-9-_\.]+)\/([a-zA-Z0-9-_]+)(?:.git)?$/', $repoUrl, $urlParts)) { $host = $urlParts[1]; $port = empty($urlParts[2]) ? null : $urlParts[2]; $prefix = empty($urlParts[3]) ? null : $urlParts[3]; $user = $urlParts[4]; $repo = $urlParts[5]; if (null !== $prefix) { return $this->buildUrl($host, implode('/', [$prefix, $user, $repo]), $packageName, $port); } return $this->buildUrl($host, implode('/', [$user, $repo]), $packageName, $port); } return $this->buildFallbackUrl($repoUrl, $packageName); } /** * Returns a fallback URL based on best practices used by f.i. github or gitlab. * * @param string $repoUrl * @param string $packageName * * @return string */ private function buildFallbackUrl(string $repoUrl, string $packageName) { $host = parse_url($repoUrl, PHP_URL_HOST); $port = parse_url($repoUrl, PHP_URL_PORT); $path = parse_url($repoUrl, PHP_URL_PATH); return $this->buildUrl($host, str_replace('.git', '', $path), $packageName, $port); } /** * @param string $host * @param string $repo * @param string $packageName * @param int|null $port * @param bool $secure * * @return string */ private function buildUrl(string $host, string $repo, string $packageName, int $port = null, bool $secure = true) { $url = 'http'.($secure ? 's' : '').'://'; $url .= rtrim($host, '/'); if (null !== $port) { $url .= ':'.$port; } $url .= '/'.$repo.(self::RECIPE_PREFIXES[$host] ?? self::RECIPE_PREFIXES['default']).$packageName; return $url; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/OfficialEndpointProxy.php
src/Service/OfficialEndpointProxy.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service; use App\Service\Decoder\JsonResponseDecoder; use Nyholm\Psr7\Request; /** * Class OfficialEndpointProxy. * * @author moay <mv@moay.de> */ class OfficialEndpointProxy { /** @var string */ private $endpoint; /** @var JsonResponseDecoder */ private $decoder; /** * OfficialEndpointProxy constructor. * * @param string $officialEndpoint * @param JsonResponseDecoder $decoder */ public function __construct( string $officialEndpoint, JsonResponseDecoder $decoder ) { $this->endpoint = $officialEndpoint; $this->decoder = $decoder; } /** * Provides a proxy for the aliases.json call, which provides official Symfony aliases. * * @return array * * @throws \Exception * @throws \Http\Client\Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ public function getAliases() { $request = new Request('GET', $this->endpoint.'aliases.json'); return $this->decoder->getDecodedResponse($request); } /** * Provides a proxy for the versions.json call, which provides version information for Symfony. * * @return array * * @throws \Exception * @throws \Http\Client\Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ public function getVersions() { $request = new Request('GET', $this->endpoint.'versions.json'); return $this->decoder->getDecodedResponse($request); } /** * Provides the official response for the packages call. * * @param string $packagesRequestString * * @return array|string * * @throws \Exception * @throws \Http\Client\Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ public function getPackages(string $packagesRequestString) { $request = new Request('GET', $this->endpoint.'p/'.$packagesRequestString); return $this->decoder->getDecodedResponse($request); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/RecipeRepoManager.php
src/Service/RecipeRepoManager.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service; use App\Exception\RecipeRepoManagerException; use App\RecipeRepo\ContribRecipeRepo; use App\RecipeRepo\OfficialRecipeRepo; use App\RecipeRepo\PrivateRecipeRepo; use App\RecipeRepo\RecipeRepo; use Cz\Git\GitException; use Psr\Log\LoggerInterface; /** * Class RecipeRepoManager. * * @author moay <mv@moay.de> */ class RecipeRepoManager { /** @var RecipeRepo[] */ private $repos; /** @var LoggerInterface */ private $logger; /** * RecipeRepoManager constructor. * * @param bool $mirrorOfficialRepo * @param bool $mirrorContribRepo * @param PrivateRecipeRepo $privateRecipeRepo * @param OfficialRecipeRepo $officialRecipeRepo * @param ContribRecipeRepo $contribRecipeRepo * @param LoggerInterface $logger */ public function __construct( bool $mirrorOfficialRepo, bool $mirrorContribRepo, PrivateRecipeRepo $privateRecipeRepo, OfficialRecipeRepo $officialRecipeRepo, ContribRecipeRepo $contribRecipeRepo, LoggerInterface $logger ) { $this->repos = [ 'private' => $privateRecipeRepo, ]; if ($mirrorOfficialRepo) { $this->repos['official'] = $officialRecipeRepo; } if ($mirrorContribRepo) { $this->repos['contrib'] = $contribRecipeRepo; } $this->logger = $logger; } /** * @return RecipeRepo[] */ public function getConfiguredRepos() { return $this->repos; } /** * @param RecipeRepo $repo * * @return bool */ public function isConfigured(RecipeRepo $repo) { return isset($this->repos[$repo->getRepoDirName()]); } /** * @param string $repoDirName * * @return bool */ public function isConfiguredByDirName(string $repoDirName) { return isset($this->repos[$repoDirName]); } /** * @param string $action * @param string $repoDirName * * @throws RecipeRepoManagerException * @throws GitException */ public function executeOnRepo(string $action, string $repoDirName) { if (!isset($this->repos[$repoDirName])) { throw new RecipeRepoManagerException(sprintf('Repo \'%s\' does not exist or is not configured.', $repoDirName)); } $this->repos[$repoDirName]->{$action}(); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/CacheClear.php
src/Service/CacheClear.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service; use App\Service\Compiler\SystemStatusReportCompiler; use Symfony\Component\Cache\Simple\FilesystemCache; use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface; /** * Class CacheClear. * * @author moay <mv@moay.de> */ class CacheClear implements CacheClearerInterface { /** @var FilesystemCache */ private $cache; /** @var SystemStatusReportCompiler */ private $systemStatusReportCompiler; /** * CacheClear constructor. * * @param Cache $cache * @param SystemStatusReportCompiler $systemStatusReportCompiler */ public function __construct(Cache $cache, SystemStatusReportCompiler $systemStatusReportCompiler) { $this->cache = $cache(); $this->systemStatusReportCompiler = $systemStatusReportCompiler; } /** * Clears flex server caches. * * @param string $cacheDir The cache directory */ public function clear($cacheDir) { $this->cache->clear(); $this->systemStatusReportCompiler->removeReport(); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Cache.php
src/Service/Cache.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service; use Symfony\Component\Cache\Simple\FilesystemCache; /** * Class Cache. * * @author moay <mv@moay.de> */ class Cache { const CACHE_DIR = '/var/cache/data'; /** * @var FilesystemCache */ private $cache; /** * Cache constructor. * * @param string $projectDir */ public function __construct(string $projectDir) { $cachePath = $projectDir.self::CACHE_DIR; if (!is_dir($cachePath)) { mkdir($cachePath); } $this->cache = new FilesystemCache('flex-server', 0, $cachePath); } /** * @return FilesystemCache */ public function __invoke() { return $this->cache; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Compiler/PackagesCompiler.php
src/Service/Compiler/PackagesCompiler.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service\Compiler; use App\Entity\Recipe; use Symfony\Component\Finder\Finder; /** * Class PackagesCompiler. * * @author moay <mv@moay.de> */ class PackagesCompiler { /** * @param array $requestedPackages * @param Recipe[] $localRecipes * @param array $officialEndpointResponse * * @return array */ public function compilePackagesResponseArray(array $requestedPackages, array $localRecipes, array $officialEndpointResponse) { return [ 'locks' => $this->getPackageLocks($requestedPackages), 'manifests' => $this->getManifests($localRecipes, $officialEndpointResponse), 'vulnerabilities' => $this->getVulnerabilities($officialEndpointResponse), ]; } /** * @param array $requestedPackages * * @return array */ private function getPackageLocks(array $requestedPackages) { $locks = []; foreach ($requestedPackages as $package) { $locks[implode('/', [$package['author'], $package['package']])] = ['version' => $package['version']]; } return $locks; } /** * @param Recipe[] $localRecipes * @param array $officialResponse * * @return array */ private function getManifests(array $localRecipes, array $officialResponse) { $manifests = []; foreach ($localRecipes as $recipe) { $manifest = [ 'repository' => 'private', 'package' => $recipe->getOfficialPackageName(), 'version' => $recipe->getVersion(), 'manifest' => $this->buildManifest($recipe), 'files' => $this->getRecipeFiles($recipe), 'origin' => $recipe->getOfficialPackageName().':'.$recipe->getVersion().'@private:master', 'not_installable' => false === $recipe->isManifestValid(), 'is_contrib' => 'contrib' === $recipe->getRepoSlug(), ]; if (empty($manifest['files'])) { unset($manifest['files']); } $manifests[$recipe->getOfficialPackageName()] = $manifest; } if (is_array($officialResponse) && isset($officialResponse['manifests'])) { $manifests = array_merge($officialResponse['manifests'], $manifests); } return $manifests; } /** * @param Recipe $recipe * * @return array */ private function buildManifest(Recipe $recipe) { $manifest = $recipe->getManifest() ?? []; $postInstallPath = $recipe->getLocalPath().'/post-install.txt'; if (file_exists($postInstallPath)) { $manifest['post-install-output'] = file($postInstallPath, FILE_IGNORE_NEW_LINES); } if (empty($manifest)) { return []; } return $manifest; } /** * @param Recipe $recipe * * @return array */ private function getRecipeFiles(Recipe $recipe) { $files = []; $finder = new Finder(); $finder->ignoreUnreadableDirs() ->in($recipe->getLocalPath()) ->followLinks() ->ignoreDotFiles(false); foreach ($finder->files() as $file) { if (in_array($file->getRelativePathName(), ['manifest.json', 'post-install.txt'])) { continue; } $files[$file->getRelativePathName()] = [ 'contents' => $file->getContents(), 'executable' => is_executable($recipe->getLocalPath().$file->getRelativePathName()), ]; } return $files; } /** * @param array $officialResponse * * @return mixed */ private function getVulnerabilities(array $officialResponse) { if (is_array($officialResponse) && isset($officialResponse['vulnerabilities'])) { return $officialResponse['vulnerabilities']; } return []; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Compiler/SystemStatusReportCompiler.php
src/Service/Compiler/SystemStatusReportCompiler.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service\Compiler; use App\RecipeRepo\ContribRecipeRepo; use App\RecipeRepo\OfficialRecipeRepo; use App\RecipeRepo\PrivateRecipeRepo; /** * Class SystemStatusReportCompiler. * * @author moay <mv@moay.de> */ class SystemStatusReportCompiler { const HEALTH_REPORT_FILE = '/var/status.json'; /** @var string */ private $reportFilePath; /** @var array */ private $repos; /** @var array */ private $config; /** * SystemStatusReportCompiler constructor. * * @param string $projectDir * @param PrivateRecipeRepo $privateRecipeRepo * @param OfficialRecipeRepo $officialRecipeRepo * @param ContribRecipeRepo $contribRecipeRepo * @param bool $enableProxy * @param bool $cacheEndpoint * @param bool $mirrorOfficialRepo * @param bool $mirrorContribRepo */ public function __construct( string $projectDir, PrivateRecipeRepo $privateRecipeRepo, OfficialRecipeRepo $officialRecipeRepo, ContribRecipeRepo $contribRecipeRepo, bool $enableProxy, bool $cacheEndpoint, bool $mirrorOfficialRepo, bool $mirrorContribRepo ) { $this->reportFilePath = $projectDir.self::HEALTH_REPORT_FILE; $this->repos = [ 'private' => $privateRecipeRepo, 'official' => $officialRecipeRepo, 'contrib' => $contribRecipeRepo, ]; $this->config = [ 'enableProxy' => $enableProxy, 'enableCache' => $cacheEndpoint, 'mirrorOfficial' => $mirrorOfficialRepo, 'mirrorContrib' => $mirrorContribRepo, ]; } /** * Gets the report as array, creates the report if it doesn't exist yet. * * @return array */ public function getReport() { if (!file_exists($this->reportFilePath)) { $this->compileReport(); } return json_decode(file_get_contents($this->reportFilePath), true); } /** * Compiles system status report file. */ public function compileReport() { $report = [ 'config' => $this->config, ]; foreach ($this->repos as $key => $repo) { $report['repos'][$key] = $repo->getStatus(); } file_put_contents($this->reportFilePath, json_encode($report)); } /** * Deletes the report file. */ public function removeReport() { if (file_exists($this->reportFilePath)) { unlink($this->reportFilePath); } } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Compiler/LocalRecipeCompiler.php
src/Service/Compiler/LocalRecipeCompiler.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service\Compiler; use App\Entity\Recipe; use App\Service\RecipePublicUrlResolver; use App\Service\RecipeRepoManager; /** * Class LocalRecipeCompiler. * * @author moay <mv@moay.de> */ class LocalRecipeCompiler { /** * @var RecipeRepoManager */ private $repoManager; /** * @var RecipePublicUrlResolver */ private $urlResolver; /** * @var Recipe[] */ private $recipes = []; /** * LocalRecipeCompiler constructor. * * @param RecipeRepoManager $repoManager */ public function __construct(RecipeRepoManager $repoManager, RecipePublicUrlResolver $urlResolver) { $this->repoManager = $repoManager; $this->urlResolver = $urlResolver; } /** * @return Recipe[] */ public function getLocalRecipes() { if (0 == count($this->recipes)) { $this->loadLocalRecipes(); } return $this->recipes; } /** * @param string $author * @param string $package * @param string $version * * @return Recipe[] */ public function getLocalRecipesForPackageRequest(string $author, string $package, string $version) { if (0 == count($this->recipes)) { $this->loadLocalRecipes(); } $possibleRecipes = array_filter($this->recipes, function (Recipe $recipe) use ($author, $package, $version) { if ($recipe->getAuthor() != $author || $recipe->getPackage() != $package || 1 == version_compare($recipe->getVersion(), $version)) { return false; } return true; }); return $possibleRecipes; } /** * Loads local recipes. */ private function loadLocalRecipes() { foreach ($this->repoManager->getConfiguredRepos() as $repo) { $recipeFolders = $repo->getRecipeDirectories(); foreach ($recipeFolders as $recipeFolder) { $explodedPath = explode('/', $recipeFolder->getPathname()); [$author, $package, $version] = array_slice($explodedPath, -3); $recipe = new Recipe(); $recipe->setAuthor($author); $recipe->setPackage($package); $recipe->setVersion($version); $recipe->setRepo($repo); $recipe->setRepoSlug($repo->getRepoDirName()); $recipe->setLocalPath($recipeFolder->getPathname()); $recipe->setPublicUrl($this->urlResolver->resolveUrl($recipe)); $manifestFile = $recipeFolder->getPathname().'/manifest.json'; if (file_exists($manifestFile)) { $manifest = json_decode(file_get_contents($manifestFile), true); if (JSON_ERROR_NONE === json_last_error()) { $recipe->setManifest($manifest); $recipe->setManifestValid(true); } else { $recipe->setManifestValid(false); } } $this->recipes[] = $recipe; } } } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Decoder/JsonResponseDecoder.php
src/Service/Decoder/JsonResponseDecoder.php
<?php namespace App\Service\Decoder; use App\Service\Cache; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Nyholm\Psr7\Request; use Symfony\Component\Cache\Simple\FilesystemCache; class JsonResponseDecoder { /** @var bool */ private $cacheEndpoint; /** @var HttpClient */ private $client; /** @var FilesystemCache */ private $cache; /** * @param bool $cacheEndpoint * @param HttpClient $client * @param Cache $cache */ public function __construct(bool $cacheEndpoint, HttpClient $client, Cache $cache) { $this->cacheEndpoint = $cacheEndpoint; $this->client = $client; $this->cache = $cache(); } /** * @param Request $request * * @return array|mixed|\Psr\Http\Message\StreamInterface * * @throws \Http\Client\Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ public function getDecodedResponse(Request $request) { try { $response = $this->client->sendRequest($request); $decodedResponse = json_decode($response->getBody()->getContents(), true); if (!in_array($response->getStatusCode(), range(200, 299))) { if ($this->cacheEndpoint && $this->cache->has($this->getCacheId($request))) { return $this->cache->get($this->getCacheId($request)); } return []; } if (JSON_ERROR_NONE !== json_last_error()) { return $response->getBody()->getContents(); } if ($this->cacheEndpoint) { $this->cache->set($this->getCacheId($request), $decodedResponse); } return $decodedResponse; } catch (NetworkException $e) { if ($this->cacheEndpoint && $this->cache->has($this->getCacheId($request))) { return $this->cache->get($this->getCacheId($request)); } throw $e; } } /** * @param Request $request * * @return string */ private function getCacheId(Request $request) { return sha1( preg_replace( '/[^A-Za-z0-9\.\- ]/', '', $request->getMethod().$request->getUri() ) ); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Provider/VersionsProvider.php
src/Service/Provider/VersionsProvider.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service\Provider; use App\Service\OfficialEndpointProxy; /** * Class VersionsProvider. * * @author moay <mv@moay.de> */ class VersionsProvider { /** @var bool */ private $enableProxy; /** @var OfficialEndpointProxy */ private $proxy; /** * VersionsProvider constructor. * * @param bool $enableProxy * @param OfficialEndpointProxy $proxy */ public function __construct(bool $enableProxy, OfficialEndpointProxy $proxy) { $this->enableProxy = $enableProxy; $this->proxy = $proxy; } /** * @return array */ public function provideVersions() { if ($this->enableProxy) { return $this->proxy->getVersions(); } return []; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Provider/UlidProvider.php
src/Service/Provider/UlidProvider.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service\Provider; use Ulid\Ulid; /** * Class UlidProvider. * * @author moay <mv@moay.de> */ class UlidProvider { /** * Provides a ulid. Symfony.sh behaviour of uppercasing the ulid is imitated. * * @return string */ public function provideUlid() { return (string) Ulid::generate(); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Provider/AliasesProvider.php
src/Service/Provider/AliasesProvider.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service\Provider; use App\Entity\Recipe; use App\Service\Cache; use App\Service\Compiler\LocalRecipeCompiler; use App\Service\OfficialEndpointProxy; use Symfony\Component\Cache\Simple\FilesystemCache; /** * Class AliasesProvider. * * @author moay <mv@moay.de> */ class AliasesProvider { const LOCAL_ALIASES_CACHE_KEY = 'aliases-local'; /** @var LocalRecipeCompiler */ private $recipeCompiler; /** @var OfficialEndpointProxy */ private $officialEndpointProxy; /** @var FilesystemCache */ private $cache; /** * AliasesProvider constructor. * * @param LocalRecipeCompiler $recipeCompiler * @param bool $enableProxy * @param OfficialEndpointProxy $officialEndpointProxy * @param Cache $cache */ public function __construct( LocalRecipeCompiler $recipeCompiler, bool $enableProxy, OfficialEndpointProxy $officialEndpointProxy, Cache $cache ) { $this->recipeCompiler = $recipeCompiler; if ($enableProxy) { $this->officialEndpointProxy = $officialEndpointProxy; } $this->cache = $cache(); } /** * Provides all available aliases. Official aliases are merged if proxy is enabled. * * @return array */ public function provideAliases() { $aliases = $this->getLocalAliases(); if ($this->officialEndpointProxy instanceof OfficialEndpointProxy) { $officialAliases = $this->officialEndpointProxy->getAliases(); if (is_array($officialAliases)) { $aliases = array_merge($officialAliases, $aliases); } } ksort($aliases); return $aliases; } /** * Returns an array of all locally available aliases. * * @return array */ public function getLocalAliases() { if ($this->cache->has(self::LOCAL_ALIASES_CACHE_KEY)) { return $this->cache->get(self::LOCAL_ALIASES_CACHE_KEY); } $aliases = []; $recipes = $this->recipeCompiler->getLocalRecipes(); foreach ($recipes as $recipe) { if (null !== $recipe->getManifest() && isset($recipe->getManifest()['aliases'])) { foreach ($recipe->getManifest()['aliases'] as $alias) { if (isset($aliases[$alias])) { $recipe = $this->resolveAliasConflict($aliases[$alias], $recipe); } $aliases[$alias] = $recipe; } } } $aliases = array_map(function (Recipe $recipe) { return $recipe->getOfficialPackageName(); }, $aliases); $this->cache->set(self::LOCAL_ALIASES_CACHE_KEY, $aliases); return $aliases; } /** * If one of the recipes is local, it will be returned. * If not, the recipe with an official alias will be returned. * If there is none, $recipe1 will be returned. * * @param Recipe $recipe1 * @param Recipe $recipe2 * * @return Recipe */ private function resolveAliasConflict(Recipe $recipe1, Recipe $recipe2) { if ($recipe1->getRepoSlug() != $recipe2->getRepoSlug()) { if ('private' === $recipe1->getRepoSlug()) { return $recipe1; } if ('private' === $recipe2->getRepoSlug()) { return $recipe2; } if ('official' === $recipe1->getRepoSlug()) { return $recipe1; } return $recipe2; } return $recipe1; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Service/Provider/PackagesProvider.php
src/Service/Provider/PackagesProvider.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Service\Provider; use App\Entity\Recipe; use App\Service\Compiler\LocalRecipeCompiler; use App\Service\Compiler\PackagesCompiler; use App\Service\OfficialEndpointProxy; /** * Class AliasesProvider. * * @author moay <mv@moay.de> */ class PackagesProvider { /** @var LocalRecipeCompiler */ private $recipeCompiler; /** @var OfficialEndpointProxy */ private $officialEndpointProxy; /** @var PackagesCompiler */ private $packagesCompiler; /** * AliasesProvider constructor. * * @param LocalRecipeCompiler $recipeCompiler * @param bool $enableProxy * @param OfficialEndpointProxy $officialEndpointProxy * @param PackagesCompiler $packagesCompiler */ public function __construct( LocalRecipeCompiler $recipeCompiler, bool $enableProxy, OfficialEndpointProxy $officialEndpointProxy, PackagesCompiler $packagesCompiler ) { $this->recipeCompiler = $recipeCompiler; if ($enableProxy) { $this->officialEndpointProxy = $officialEndpointProxy; } $this->packagesCompiler = $packagesCompiler; } /** * Provides data for requested packages. * * @param string $packagesRequestString * * @return array * * @throws \Exception * @throws \Http\Client\Exception */ public function providePackages(string $packagesRequestString) { $requestedPackages = $this->parseRequestedPackages($packagesRequestString); return $this->packagesCompiler->compilePackagesResponseArray( $requestedPackages, $this->getLocalRecipes($requestedPackages), $this->getOfficialProxyResponse($packagesRequestString) ); } /** * @param array $requestedPackages * * @return Recipe[] */ private function getLocalRecipes(array $requestedPackages) { $recipes = []; foreach ($requestedPackages as $package) { $localRecipe = $this->getLocalRecipe($package); if ($localRecipe instanceof Recipe) { $recipes[implode('_', $package)] = $localRecipe; } } return $recipes; } /** * @param string $packagesRequestString * * @return array|string * * @throws \Exception * @throws \Http\Client\Exception */ private function getOfficialProxyResponse(string $packagesRequestString) { if ($this->officialEndpointProxy instanceof OfficialEndpointProxy) { return $this->officialEndpointProxy->getPackages($packagesRequestString); } return []; } /** * @param array $package * * @return Recipe|null */ private function getLocalRecipe(array $package) { $localRecipes = $this->recipeCompiler->getLocalRecipesForPackageRequest($package['author'], $package['package'], $package['version']); if (count($localRecipes) > 1) { usort($localRecipes, function (Recipe $recipe1, Recipe $recipe2) { if ($recipe1->getVersion() == $recipe2->getVersion()) { if ($recipe1->getRepoSlug() != $recipe2->getRepoSlug()) { if ('private' === $recipe1->getRepoSlug()) { return -1; } if ('private' === $recipe2->getRepoSlug()) { return 1; } if ('official' === $recipe1->getRepoSlug()) { return -1; } return 1; } return -1; } return version_compare($recipe1->getVersion(), $recipe2->getVersion()) * -1; }); } if (count($localRecipes) > 0) { return reset($localRecipes); } return null; } /** * Parses the request string and provides an array of requested packages. * * @param string $packagesRequestString * * @return array * * @throws \InvalidArgumentException */ private function parseRequestedPackages(string $packagesRequestString) { $packages = []; foreach (explode(';', rtrim($packagesRequestString, ';')) as $requestedPackage) { $packageDetails = explode(',', $requestedPackage); if (count($packageDetails) < 3) { throw new \InvalidArgumentException('Invalid package string provided'); } $packages[] = [ 'author' => $packageDetails[0], 'package' => $packageDetails[1], 'version' => preg_replace('/^[iurv]+/', '', $packageDetails[2]), ]; } return $packages; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Command/Recipes/RecipesUpdateCommand.php
src/Command/Recipes/RecipesUpdateCommand.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Command\Recipes; /** * Class RecipesUpdateCommand. * * @author moay <mv@moay.de> */ class RecipesUpdateCommand extends RecipeRepoManagerCommand { /** @var string */ protected $action = 'update'; /** @var string */ protected $description = 'Updates local recipe repos to match the current remote repo'; }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Command/Recipes/RecipesResetCommand.php
src/Command/Recipes/RecipesResetCommand.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Command\Recipes; /** * Class RecipesResetCommand. * * @author moay <mv@moay.de> */ class RecipesResetCommand extends RecipeRepoManagerCommand { /** @var string */ protected $action = 'reset'; /** @var string */ protected $description = 'Resets local recipe repos by deleting and reinitalizing from remote repo'; }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Command/Recipes/RecipeRepoManagerCommand.php
src/Command/Recipes/RecipeRepoManagerCommand.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Command\Recipes; use App\Exception\RecipeRepoManagerException; use App\Service\RecipeRepoManager; use Cz\Git\GitException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; /** * Class RecipeRepoManagerCommand. * * @author moay <mv@moay.de> */ abstract class RecipeRepoManagerCommand extends Command { const ACTION_NAMESPACE = 'recipes:'; /** @var RecipeRepoManager */ private $repoManager; /** @var string */ protected $action; /** @var string */ protected $description; /** * RecipesInitializeCommand constructor. * * @param RecipeRepoManager $repoManager */ public function __construct(RecipeRepoManager $repoManager) { $this->repoManager = $repoManager; parent::__construct(); } protected function configure() { $this ->setName(self::ACTION_NAMESPACE.$this->action) ->setDescription($this->description); $description = sprintf( '%s a single repo by selecting \'private\', \'official\' or \'contrib\'. Don\'t select any in order to %s all configured repos.', ucfirst($this->action), $this->action ); $this->addArgument('repo', InputArgument::IS_ARRAY, $description, []); } /** * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $recipeRepos = [ 'private' => 'Private recipes repo', 'official' => 'Official recipes repo', 'contrib' => 'Contrib recipes repo', ]; $repos = count($input->getArgument('repo')) > 0 ? $input->getArgument('repo') : array_keys($recipeRepos); foreach ($repos as $repo) { if (!isset($recipeRepos[$repo])) { $io->error('Repo \''.$repo.'\' does not exist. Use \'private\', \'official\' or \'contrib\'.'); } else { if ($this->repoManager->isConfiguredByDirName($repo)) { try { $this->repoManager->executeOnRepo($this->action, $repo); $actionPast = 'reset' === $this->action ? 'resetted' : $this->action.'d'; $io->success(sprintf('%s recipes repo %s.', ucfirst($repo), $actionPast)); } catch (RecipeRepoManagerException $e) { $io->error($e->getMessage()); } catch (GitException $e) { $io->error('Git error: '.$e->getMessage()); } } } } } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Command/Recipes/RecipesRemoveCommand.php
src/Command/Recipes/RecipesRemoveCommand.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Command\Recipes; /** * Class RecipesRemoveCommand. * * @author moay <mv@moay.de> */ class RecipesRemoveCommand extends RecipeRepoManagerCommand { /** @var string */ protected $action = 'remove'; /** @var string */ protected $description = 'Deletes local recipe repos'; }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Command/Recipes/RecipesInitializeCommand.php
src/Command/Recipes/RecipesInitializeCommand.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Command\Recipes; /** * Class RecipesInitializeCommand. * * @author moay <mv@moay.de> */ class RecipesInitializeCommand extends RecipeRepoManagerCommand { /** @var string */ protected $action = 'initialize'; /** @var string */ protected $description = 'Initializes local recipe repos from remote repo'; }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/src/Command/System/SystemStatusCommand.php
src/Command/System/SystemStatusCommand.php
<?php /* * This file is part of the moay server-for-symfony-flex package. * * (c) moay * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Command\System; use App\Service\Compiler\SystemStatusReportCompiler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; /** * Class SystemStatusCommand. * * @author moay <mv@moay.de> */ class SystemStatusCommand extends Command { /** @var SystemStatusReportCompiler */ private $reportCompiler; /** * SystemStatusCommand constructor. * * @param SystemStatusReportCompiler $reportCompiler */ public function __construct(SystemStatusReportCompiler $reportCompiler) { parent::__construct(); $this->reportCompiler = $reportCompiler; } public function configure() { $this ->setName('system:status') ->setDescription('Provides an overview over the system status'); } /** * @param InputInterface $input * @param OutputInterface $output */ public function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $report = $this->reportCompiler->getReport(); $io->section('Configuration'); $io->table([], [ ['Proxy for official endpoint', $report['config']['enableProxy'] ? '<fg=green>enabled</>' : '<fg=red>disabled</>'], ['Caching for official endpoint', $report['config']['enableCache'] ? '<fg=green>enabled</>' : '<fg=red>disabled</>'], ['Local mirror for official recipes', $report['config']['mirrorOfficial'] ? '<fg=green>enabled</>' : '<fg=red>disabled</>'], ['Local mirror for contrib recipes', $report['config']['mirrorContrib'] ? '<fg=green>enabled</>' : '<fg=red>disabled</>'], ]); $io->section('Repo status'); $io->table(['Repo', 'Url', 'Remote readable', 'Downloaded', 'Last Update'], array_map(function ($repo, $key) { return [ $key, $repo['url'], $repo['remote_readable'] ? '<fg=green>Yes</>' : '<fg=red>No</>', $repo['downloaded'] ? '<fg=green>Yes</>' : '<fg=red>No</>', null != $repo['last_updated'] ? $repo['last_updated'] : '', ]; }, $report['repos'], array_keys($report['repos']))); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/tests/RepoAwareTestCaseTest.php
tests/RepoAwareTestCaseTest.php
<?php namespace App\Tests; use PHPUnit\Framework\TestCase; /** * Class RepoAwareTestCaseTest. * * @author Manuel Voss <manuel.voss@i22.de> */ class RepoAwareTestCaseTest extends TestCase { public function testRepoFolderDoesntExistOutsideTestCase() { $this->assertFalse(is_dir(__DIR__.'/repo/private')); } public function testTestRepoIsSetupProperly() { RepoAwareTestCase::setUpBeforeClass(); $this->assertTrue(is_dir(__DIR__.'/repo/private')); $this->assertTrue(file_exists(__DIR__.'/repo/private/author1/withManifest/1.0/manifest.json')); $this->assertTrue(file_exists(__DIR__.'/repo/private/author1/withoutManifest/1.1/post-install.txt')); $this->assertTrue(file_exists(__DIR__.'/repo/private/author2/invalidManifest/someversion/manifest.json')); } public function testRepoIsProperlyDestroyed() { RepoAwareTestCase::tearDownAfterClass(); $this->testRepoFolderDoesntExistOutsideTestCase(); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/tests/RepoAwareTestCase.php
tests/RepoAwareTestCase.php
<?php namespace App\Tests; use App\RecipeRepo\RecipeRepo; use PHPUnit\Framework\TestCase; /** * Class RepoAwareTestCase. * * @author Manuel Voss <manuel.voss@i22.de> */ class RepoAwareTestCase extends TestCase { const TEST_REPO_DIR = '/private'; /** * Sets up the testing folder structure. */ public static function setUpBeforeClass() { $testRepoFolder = static::getTestsFolder().static::TEST_REPO_DIR; if (!is_dir($testRepoFolder)) { mkdir($testRepoFolder); } foreach (static::getTestRepoFileStructure() as $author => $packages) { mkdir($testRepoFolder.$author); foreach ($packages as $package => $versions) { mkdir($testRepoFolder.$author.$package); foreach ($versions as $version => $files) { mkdir($testRepoFolder.$author.$package.$version); foreach ($files as $name => $contents) { file_put_contents($testRepoFolder.$author.$package.$version.$name, $contents); } } } } } /** * Removes the testing folder structure. */ public static function tearDownAfterClass() { exec('rm -rf '.static::getTestsFolder().static::TEST_REPO_DIR); } /** * @return string */ protected static function getTestsFolder() { return __DIR__.'/repo'; } /** * @return array */ public static function getTestRepoFileStructure() { return [ '/author1' => [ '/withManifest' => [ '/1.0' => [ '/manifest.json' => json_encode(['some' => 'thing']), ], '/1.1' => [ '/manifest.json' => json_encode(['some' => 'thing']), ], ], '/withoutManifest' => [ '/1.0' => [ '/post-install.txt' => 'test', ], '/1.1' => [ '/post-install.txt' => 'test', '/test.yml' => 'test', ], ], ], '/author2' => [ '/invalidManifest' => [ '/someversion' => [ '/manifest.json' => '{[}', ], ], ], '/author3' => [ '/noVersions' => [], ], ]; } /** * @param string $author * @param string $package * @param string $version * * @return \PHPUnit\Framework\MockObject\MockObject|\SplFileInfo */ protected function createRecipeFolderStub(string $author, string $package, string $version) { $recipeFolderStub = $this->createMock(\SplFileInfo::class); $recipeFolderStub->method('getPathname') ->willReturn(sprintf('tests/repo/private/%s/%s/%s', $author, $package, $version)); return $recipeFolderStub; } /** * @return RecipeRepo|\PHPUnit\Framework\MockObject\MockObject */ protected function createTestRepoStub() { $repoStub = $this->createMock(RecipeRepo::class); $repoStub->method('getRecipeDirectories') ->willReturn([ $this->createRecipeFolderStub('author1', 'withManifest', '1.0'), $this->createRecipeFolderStub('author1', 'withManifest', '1.1'), $this->createRecipeFolderStub('author1', 'withoutManifest', '1.0'), $this->createRecipeFolderStub('author1', 'withoutManifest', '1.1'), $this->createRecipeFolderStub('author2', 'invalidManifest', 'someversion'), ]); $repoStub->method('getRepoDirName') ->willReturn('private'); return $repoStub; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/tests/Controller/EndpointControllerTest.php
tests/Controller/EndpointControllerTest.php
<?php namespace App\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class EndpointControllerTest extends WebTestCase { public function testUlid() { $client = self::createClient(); $client->request('GET', '/ulid'); $response = $client->getResponse(); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('application/json', $response->headers->get('Content-Type')); $data = json_decode($response->getContent(), true); $this->assertEquals(JSON_ERROR_NONE, json_last_error()); $this->assertArrayHasKey('ulid', $data); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/tests/Service/OfficialEndpointProxyTest.php
tests/Service/OfficialEndpointProxyTest.php
<?php declare(strict_types=1); namespace App\Tests\Service; use App\Service\Decoder\JsonResponseDecoder; use App\Service\OfficialEndpointProxy; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; class OfficialEndpointProxyTest extends TestCase { /** * @var OfficialEndpointProxy */ private $proxy; /** * @var JsonResponseDecoder|ObjectProphecy */ private $decoder; protected function setUp() { $this->decoder = $this->prophesize(JsonResponseDecoder::class); $this->proxy = new OfficialEndpointProxy( 'official_endpoint/', $this->decoder->reveal() ); } public function testGetAliases() { $this ->decoder ->getDecodedResponse( Argument::allOf( Argument::which('getMethod', 'GET'), Argument::which('getUri', 'official_endpoint/aliases.json') ) ) ->willReturn('decoded response'); $this->assertSame('decoded response', $this->proxy->getAliases()); } public function testGetVersions() { $this ->decoder ->getDecodedResponse( Argument::allOf( Argument::which('getMethod', 'GET'), Argument::which('getUri', 'official_endpoint/versions.json') ) ) ->willReturn('decoded response'); $this->assertSame('decoded response', $this->proxy->getVersions()); } public function testGetPackages() { $this ->decoder ->getDecodedResponse( Argument::allOf( Argument::which('getMethod', 'GET'), Argument::which('getUri', 'official_endpoint/p/package_name') ) ) ->willReturn('decoded response'); $this->assertSame('decoded response', $this->proxy->getPackages('package_name')); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/tests/Service/Compiler/LocalRecipeCompilerTest.php
tests/Service/Compiler/LocalRecipeCompilerTest.php
<?php namespace App\Tests\Service\Compiler; use App\Entity\Recipe; use App\Service\Compiler\LocalRecipeCompiler; use App\Service\RecipePublicUrlResolver; use App\Service\RecipeRepoManager; use App\Tests\RepoAwareTestCase; /** * Class LocalRecipeCompilerTest. * * @author Manuel Voss <manuel.voss@i22.de> */ class LocalRecipeCompilerTest extends RepoAwareTestCase { /** @var LocalRecipeCompiler */ private $compiler; public function setUp() { $repoStub = $this->createTestRepoStub(); $repoStub->expects($this->once())->method('getRecipeDirectories'); $repoManagerStub = $this->createMock(RecipeRepoManager::class); $repoManagerStub->method('getConfiguredRepos') ->willReturn([$repoStub]); $repoManagerStub->expects($this->once())->method('getConfiguredRepos'); $urlResolverStub = $this->createMock(RecipePublicUrlResolver::class); $urlResolverStub->method('resolveUrl') ->willReturn('testUrl'); $urlResolverStub->expects($this->exactly(5))->method('resolveUrl'); $this->compiler = new LocalRecipeCompiler($repoManagerStub, $urlResolverStub); } public function testLocalRecipesAreLoadedProperly() { foreach ($this->compiler->getLocalRecipes() as $recipe) { $this->assertInstanceOf(Recipe::class, $recipe); } $this->assertCount(5, $this->compiler->getLocalRecipes()); } public function testManifestFilesAreCheckedForValidJson() { $countInvalid = 0; $countValid = 0; foreach ($this->compiler->getLocalRecipes() as $recipe) { if ('invalidManifest' === $recipe->getPackage()) { $this->assertFalse($recipe->isManifestValid()); ++$countInvalid; } elseif ('withManifest' === $recipe->getPackage()) { $this->assertTrue($recipe->isManifestValid()); ++$countValid; } elseif ('withoutManifest' === $recipe->getPackage()) { $this->assertNull($recipe->isManifestValid()); $this->assertNull($recipe->getManifest()); } } $this->assertEquals(1, $countInvalid); $this->assertEquals(2, $countValid); } /** * @dataProvider packageResolvingTestProvider */ public function testPackageVersionsAreResolvedProperly($author, $package, $version, $expectedCount) { $recipes = $this->compiler->getLocalRecipesForPackageRequest($author, $package, $version); $this->assertCount($expectedCount, $recipes); foreach ($recipes as $recipe) { $this->assertInstanceOf(Recipe::class, $recipe); $this->assertEquals($author, $recipe->getAuthor()); $this->assertEquals($package, $recipe->getPackage()); $this->assertLessThanOrEqual(0, version_compare($recipe->getVersion(), $version)); } } public function packageResolvingTestProvider() { return [ ['author1', 'withManifest', '1.0', 1], ['author1', 'withManifest', '1.1', 2], ['author1', 'withManifest', '1', 0], ['author1', 'withManifest', '2', 2], ['author1', 'withManifest', '0.7', 0], ['author1', 'withManifest', 'dev', 0], ['author1', 'withManifest', 'master', 0], ['author1', 'withoutManifest', '1.0', 1], ['author1', 'withoutManifest', '1.1', 2], ['author2', 'withoutManifest', '1.1', 0], ['author2', 'withManifest', '1', 0], ['author2', 'invalidManifest', '1', 1], ['author3', 'noVersions', 'any', 0], ]; } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/tests/Service/Decoder/JsonResponseDecoderTest.php
tests/Service/Decoder/JsonResponseDecoderTest.php
<?php namespace App\Tests\Service\Decoder; use App\Service\Cache; use App\Service\Decoder\JsonResponseDecoder; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Nyholm\Psr7\Request; use Nyholm\Psr7\Stream; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Symfony\Component\Cache\Simple\FilesystemCache; class JsonResponseDecoderTest extends TestCase { /** * @var HttpClient|\Prophecy\Prophecy\ObjectProphecy */ private $client; /** * @var Cache|\Prophecy\Prophecy\ObjectProphecy */ private $cache; /** * @var \Prophecy\Prophecy\ObjectProphecy|FilesystemCache */ private $simpleCache; protected function setUp() { $this->client = $this->prophesize(HttpClient::class); $this->cache = $this->prophesize(Cache::class); $this->simpleCache = $this->prophesize(FilesystemCache::class); $this->cache->__invoke()->willReturn($this->simpleCache->reveal()); } public function testGetDecodedResponse() { $decoder = new JsonResponseDecoder(false, $this->client->reveal(), $this->cache->reveal()); $request = new Request('GET', 'endpoint/data.json'); $response = $this->prophesize(ResponseInterface::class); $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($this->getResponseBodyStub(json_encode(['json' => 'data']))); $this->client->sendRequest($request)->willReturn($response->reveal()); $this->assertSame( ['json' => 'data'], $decoder->getDecodedResponse($request) ); } public function testGetDecodedResponseEmptyOnRequestError() { $decoder = new JsonResponseDecoder(false, $this->client->reveal(), $this->cache->reveal()); $request = new Request('GET', 'endpoint/data.json'); $response = $this->prophesize(ResponseInterface::class); $response->getStatusCode()->willReturn(500); $response->getBody()->willReturn($this->getResponseBodyStub('')); $this->client->sendRequest($request)->willReturn($response->reveal()); $this->assertSame( [], $decoder->getDecodedResponse($request) ); } public function testGetDecodedResponseFromCacheOnRequestError() { $decoder = new JsonResponseDecoder(true, $this->client->reveal(), $this->cache->reveal()); $request = new Request('GET', 'endpoint/data.json'); $response = $this->prophesize(ResponseInterface::class); $response->getStatusCode()->willReturn(500); $response->getBody()->willReturn($this->getResponseBodyStub('')); $this->simpleCache->has('4429b090fd82239e188859ae626162e5e790b4db')->willReturn(true); $this->simpleCache->get('4429b090fd82239e188859ae626162e5e790b4db')->willReturn(['json' => 'cache']); $this->client->sendRequest($request)->willReturn($response->reveal()); $this->assertSame( ['json' => 'cache'], $decoder->getDecodedResponse($request) ); } public function testGetDecodedResponseCachesDataIfEnabled() { $decoder = new JsonResponseDecoder(true, $this->client->reveal(), $this->cache->reveal()); $request = new Request('GET', 'endpoint/data.json'); $response = $this->prophesize(ResponseInterface::class); $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($this->getResponseBodyStub(json_encode(['json' => 'cache']))); $this->simpleCache->has('4429b090fd82239e188859ae626162e5e790b4db')->willReturn(false); $this->simpleCache->set('4429b090fd82239e188859ae626162e5e790b4db', ['json' => 'cache'])->shouldBeCalledOnce(); $this->client->sendRequest($request)->willReturn($response->reveal()); $this->assertSame( ['json' => 'cache'], $decoder->getDecodedResponse($request) ); } public function testGetDecodedResponseFromCacheWhenNetworkFails() { $decoder = new JsonResponseDecoder(true, $this->client->reveal(), $this->cache->reveal()); $request = new Request('GET', 'endpoint/data.json'); $this->simpleCache->has('4429b090fd82239e188859ae626162e5e790b4db')->willReturn(true); $this->simpleCache->get('4429b090fd82239e188859ae626162e5e790b4db')->willReturn(['json' => 'cache']); $this->client->sendRequest($request)->willThrow(NetworkException::class); $this->assertSame( ['json' => 'cache'], $decoder->getDecodedResponse($request) ); } /** * @throws \Http\Client\Exception * @throws \Psr\SimpleCache\InvalidArgumentException * @expectedException \Http\Client\Exception\NetworkException */ public function testGetDecodedResponseThrowsNetworkExceptionWhenClientFailsAndNoCachedVersion() { $decoder = new JsonResponseDecoder(true, $this->client->reveal(), $this->cache->reveal()); $request = new Request('GET', 'endpoint/data.json'); $this->simpleCache->has('4429b090fd82239e188859ae626162e5e790b4db')->willReturn(false); $this->client->sendRequest($request)->willThrow(NetworkException::class); $decoder->getDecodedResponse($request); } /** * @throws \Http\Client\Exception * @throws \Psr\SimpleCache\InvalidArgumentException */ public function testGetDecodedResponseReturnsBodyWhenJsonDecodingFails() { $decoder = new JsonResponseDecoder(true, $this->client->reveal(), $this->cache->reveal()); $request = new Request('GET', 'endpoint/data.json'); $response = $this->prophesize(ResponseInterface::class); $response->getStatusCode()->willReturn(200); $response->getBody()->willReturn($this->getResponseBodyStub('{invalid_json')); $this->client->sendRequest($request)->willReturn($response->reveal()); $this->simpleCache->set('4429b090fd82239e188859ae626162e5e790b4db', '{invalid_json')->shouldNotBeCalled(); $this->assertSame( '{invalid_json', $decoder->getDecodedResponse($request) ); $this->markAsRisky(); } /** * @param $responseString * * @return Stream|object */ private function getResponseBodyStub($responseString) { $responseBody = $this->prophesize(StreamInterface::class); $responseBody->getContents()->willReturn($responseString); return $responseBody->reveal(); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/tests/Service/Provider/UlidProviderTest.php
tests/Service/Provider/UlidProviderTest.php
<?php namespace App\Tests\Service\Provider; use App\Service\Provider\UlidProvider; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; class UlidProviderTest extends KernelTestCase { public static function setUpBeforeClass() { parent::setUpBeforeClass(); self::bootKernel(); } public function testServiceIsAvailable() { $ulidProvider = self::$container->get(UlidProvider::class); $this->assertInstanceOf(UlidProvider::class, $ulidProvider); return $ulidProvider; } /** * @depends testServiceIsAvailable * * @param UlidProvider $ulidProvider */ public function testUlidLength(UlidProvider $ulidProvider) { $this->assertSame(26, strlen((string) $ulidProvider->provideUlid())); } /** * @depends testServiceIsAvailable * * @param UlidProvider $ulidProvider */ public function testUlidIsUppercased(UlidProvider $ulidProvider) { $this->assertRegExp('/[0-9][A-Z]/', (string) $ulidProvider->provideUlid()); } }
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/public/index.php
public/index.php
<?php use App\Kernel; use Symfony\Component\Debug\Debug; use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\HttpFoundation\Request; require __DIR__.'/../vendor/autoload.php'; // The check is to ensure we don't use .env in production if (!isset($_SERVER['APP_ENV'])) { if (!class_exists(Dotenv::class)) { throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.'); } (new Dotenv())->load(__DIR__.'/../.env'); } $env = $_SERVER['APP_ENV'] ?? 'dev'; $debug = $_SERVER['APP_DEBUG'] ?? ('prod' !== $env); if ($debug) { umask(0000); Debug::enable(); } if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) { Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); } if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) { Request::setTrustedHosts(explode(',', $trustedHosts)); } $kernel = new Kernel($env, $debug); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
moay/server-for-symfony-flex
https://github.com/moay/server-for-symfony-flex/blob/a495bf3dd7decc4bccd5d1d8a28e258b544920d9/config/bundles.php
config/bundles.php
<?php return [ Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true], Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true], Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true], Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true], Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true], Symfony\Bundle\WebServerBundle\WebServerBundle::class => ['dev' => true, 'test' => true], Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true], Http\HttplugBundle\HttplugBundle::class => ['all' => true], Symfony\WebpackEncoreBundle\WebpackEncoreBundle::class => ['all' => true], ];
php
MIT
a495bf3dd7decc4bccd5d1d8a28e258b544920d9
2026-01-05T05:00:08.758100Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/server.php
server.php
<?php /** * Laravel - A PHP Framework For Web Artisans * * @package Laravel * @author Taylor Otwell <taylorotwell@gmail.com> */ $uri = urldecode( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ); // This file allows us to emulate Apache's "mod_rewrite" functionality from the // built-in PHP web server. This provides a convenient way to test a Laravel // application without having installed a "real" web server software here. if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) { return false; } require_once __DIR__.'/public/index.php';
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/ItemKitItemTemp.php
app/ItemKitItemTemp.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ItemKitItemTemp extends Model { public function item() { return $this->belongsTo('App\Item'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/SaleTemp.php
app/SaleTemp.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class SaleTemp extends Model { public function item() { return $this->belongsTo('App\Item'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/ItemKit.php
app/ItemKit.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ItemKit extends Model { public function itemkititem() { return $this->hasMany('App\ItemKitItem'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/SaleItem.php
app/SaleItem.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class SaleItem extends Model { public function item() { return $this->belongsTo('App\Item'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Customer.php
app/Customer.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Customer extends Model { // }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/User.php
app/User.php
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/ItemKitItem.php
app/ItemKitItem.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ItemKitItem extends Model { // }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Sale.php
app/Sale.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Sale extends Model { public function user() { return $this->belongsTo('App\User'); } public function customer() { return $this->belongsTo('App\Customer'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Receiving.php
app/Receiving.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Receiving extends Model { public function user() { return $this->belongsTo('App\User'); } public function supplier() { return $this->belongsTo('App\Supplier'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Role.php
app/Role.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Role extends Model { // }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/ReceivingItem.php
app/ReceivingItem.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ReceivingItem extends Model { public function item() { return $this->belongsTo('App\Item'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Item.php
app/Item.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Item extends Model { public function inventory() { return $this->hasMany('App\Inventory')->orderBy('id', 'DESC'); } public function receivingtemp() { return $this->hasMany('App\ReceivingTemp')->orderBy('id', 'DESC'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/UserRole.php
app/UserRole.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserRole extends Model { // }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/ReceivingTemp.php
app/ReceivingTemp.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ReceivingTemp extends Model { public function item() { return $this->belongsTo('App\Item'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Inventory.php
app/Inventory.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Inventory extends Model { public function user() { return $this->belongsTo('App\User'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/TutaposSetting.php
app/TutaposSetting.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class TutaposSetting extends Model { // }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Supplier.php
app/Supplier.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Supplier extends Model { // }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Jobs/Job.php
app/Jobs/Job.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; abstract class Job { /* |-------------------------------------------------------------------------- | Queueable Jobs |-------------------------------------------------------------------------- | | This job base class provides a central location to place any logic that | is shared across all of your jobs. The trait included with the class | provides access to the "queueOn" and "delay" queue helper methods. | */ use Queueable; }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Exceptions/Handler.php
app/Exceptions/Handler.php
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ \Symfony\Component\HttpKernel\Exception\HttpException::class, ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { return parent::render($request, $e); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Helpers/ReportReceivingsDetailed.php
app/Helpers/ReportReceivingsDetailed.php
<?php use App\ReceivingItem; class ReportReceivingsDetailed { public static function receiving_detailed($receiving_id) { $receivingitems = ReceivingItem::where('receiving_id', $receiving_id)->get(); return $receivingitems; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Helpers/ReportSalesDetailed.php
app/Helpers/ReportSalesDetailed.php
<?php use App\SaleItem; class ReportSalesDetailed { public static function sale_detailed($sale_id) { $SaleItems = SaleItem::where('sale_id', $sale_id)->get(); return $SaleItems; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/routes.php
app/Http/routes.php
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::group(['middleware' => 'languange'], function() { Route::get('/', 'HomeController@index'); Route::get('home', 'HomeController@index'); // Authentication routes... Route::get('auth/login', 'Auth\AuthController@getLogin'); Route::post('auth/login', 'Auth\AuthController@postLogin'); Route::get('auth/logout', 'Auth\AuthController@getLogout'); // Password reset link request routes... Route::get('password/email', 'Auth\PasswordController@getEmail'); Route::post('password/email', 'Auth\PasswordController@postEmail'); // Password reset routes... Route::get('password/reset/{token}', 'Auth\PasswordController@getReset'); Route::post('password/reset', 'Auth\PasswordController@postReset'); Route::resource('customers', 'CustomerController'); Route::resource('items', 'ItemController'); Route::resource('item-kits', 'ItemKitController'); Route::resource('inventory', 'InventoryController'); Route::resource('suppliers', 'SupplierController'); Route::resource('receivings', 'ReceivingController'); Route::resource('receiving-item', 'ReceivingItemController'); Route::resource('sales', 'SaleController'); Route::resource('reports/receivings', 'ReceivingReportController'); Route::resource('reports/sales', 'SaleReportController'); Route::resource('employees', 'EmployeeController'); Route::resource('api/item', 'ReceivingApiController'); Route::resource('api/receivingtemp', 'ReceivingTempApiController'); Route::resource('api/saletemp', 'SaleTempApiController'); Route::resource('api/itemkittemp', 'ItemKitController'); Route::get('api/item-kit-temp', 'ItemKitController@itemKitApi'); Route::get('api/item-kits', 'ItemKitController@itemKits'); Route::post('store-item-kits', 'ItemKitController@storeItemKits'); Route::resource('tutapos-settings', 'TutaposSettingController'); }); /* Route::group(['middleware' => 'role'], function() { Route::get('items', function() { return 'Is admin'; }); }); Route::get('sales', [ 'middleware' => 'role', 'uses' => 'SaleController@index' ]); */
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Kernel.php
app/Http/Kernel.php
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'role' => 'App\Http\Middleware\RoleMiddleware', 'languange' => \App\Http\Middleware\LanguangeMiddleware::class, ]; }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/ItemKitRequest.php
app/Http/Requests/ItemKitRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class ItemKitRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'item_kit_name' => 'required', 'cost_price' => 'required', 'selling_price' => 'required' ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/Request.php
app/Http/Requests/Request.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; abstract class Request extends FormRequest { // }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/EmployeeStoreRequest.php
app/Http/Requests/EmployeeStoreRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class EmployeeStoreRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required|min:6|max:30|confirmed', ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/CustomerRequest.php
app/Http/Requests/CustomerRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; use \Response; class CustomerRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'email' => 'email', 'avatar' => 'mimes:jpeg,bmp,png' ]; } public function forbiddenResponse() { return Response::make('Sorry!',403); } public function messages() { return [ 'avatar.mimes' => 'Not a valid file type. Valid types include jpeg, bmp and png.' ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/SaleRequest.php
app/Http/Requests/SaleRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class SaleRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'customer_id' => 'required' ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/ReceivingRequest.php
app/Http/Requests/ReceivingRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class ReceivingRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'supplier_id' => 'required' ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/SupplierRequest.php
app/Http/Requests/SupplierRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; use \Response; class SupplierRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'company_name' => 'required', 'email' => 'email', 'avatar' => 'mimes:jpeg,bmp,png' ]; } public function forbiddenResponse() { return Response::make('Sorry!',403); } public function messages() { return [ 'avatar.mimes' => 'Not a valid file type. Valid types include jpeg, bmp and png.' ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/ItemRequest.php
app/Http/Requests/ItemRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; use \Response; class ItemRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'item_name' => 'required', 'cost_price' => 'required', 'selling_price' => 'required', 'avatar' => 'mimes:jpeg,bmp,png' ]; } public function forbiddenResponse() { return Response::make('Sorry!',403); } public function messages() { return [ 'avatar.mimes' => 'Not a valid file type. Valid types include jpeg, bmp and png.' ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Requests/InventoryRequest.php
app/Http/Requests/InventoryRequest.php
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class InventoryRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'in_out_qty' => 'required', ]; } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/SaleApiController.php
app/Http/Controllers/SaleApiController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class SaleApiController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/ReceivingApiController.php
app/Http/Controllers/ReceivingApiController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Item, App\ItemKit, App\ItemKitItem; use \Auth, \Redirect, \Validator, \Input, \Session, \Response; use Illuminate\Http\Request; class ReceivingApiController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { //$items = Item::get(); //$itemkits = ItemKit::with('itemkititem')->get(); //$array = array_merge($items->toArray(), $itemkits->toArray()); //return Response::json($array); return Response::json(Item::get()); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/ReceivingReportController.php
app/Http/Controllers/ReceivingReportController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Receiving; use \Auth, \Redirect; use Illuminate\Http\Request; class ReceivingReportController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $receivingsReport = Receiving::all(); return view('report.receiving')->with('receivingReport', $receivingsReport); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/TutaposSettingController.php
app/Http/Controllers/TutaposSettingController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\TutaposSetting; use \Auth, \Redirect, \Validator, \Input, \Session; use App\Http\Requests; use App\Http\Controllers\Controller; class TutaposSettingController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $tutapos_settings = TutaposSetting::find(1)->first(); return view('tutapos-setting.index')->with('tutapos_settings', $tutapos_settings); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $tutapos_settings = TutaposSetting::find($id); $tutapos_settings->languange = Input::get('language'); $tutapos_settings->save(); Session::flash('message', 'You have successfully saved settings'); return Redirect::to('tutapos-settings'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/Controller.php
app/Http/Controllers/Controller.php
<?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; abstract class Controller extends BaseController { use DispatchesJobs, ValidatesRequests; }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/ItemKitController.php
app/Http/Controllers/ItemKitController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\ItemKit, App\ItemKitItem, App\ItemKitItemTemp; use App\Item; use App\Http\Requests; use App\Http\Requests\ItemKitRequest; use \Auth, \Redirect, \Validator, \Input, \Session, \Response; use App\Http\Controllers\Controller; class ItemKitController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $itemkits = Item::where('type', 2)->get(); return view('itemkit.index')->with('itemkits', $itemkits); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('itemkit.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $ItemKitItemTemps = new ItemKitItemTemp; $ItemKitItemTemps->item_id = Input::get('item_id'); $ItemKitItemTemps->quantity = 1; $ItemKitItemTemps->cost_price = Input::get('cost_price'); $ItemKitItemTemps->selling_price = Input::get('selling_price'); $ItemKitItemTemps->save(); return $ItemKitItemTemps; } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $ItemKitItemTemps = ItemKitItemTemp::find($id); $ItemKitItemTemps->quantity = Input::get('quantity'); $ItemKitItemTemps->save(); return $ItemKitItemTemps; } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { ItemKitItemTemp::destroy($id); } public function itemKitApi() { return Response::json(ItemKitItemTemp::with('item')->get()); } public function itemKits() { return Response::json(Item::where('type', 1)->get()); } public function storeItemKits(ItemKitRequest $request) { $itemkits = new Item; $itemkits->item_name = Input::get('item_kit_name'); $itemkits->cost_price = Input::get('cost_price'); $itemkits->selling_price = Input::get('selling_price'); $itemkits->description = Input::get('description'); $itemkits->type = 2; $itemkits->save(); // process receiving items $item_kit_items = ItemKitItemTemp::all(); foreach ($item_kit_items as $value) { $item_kit_items_data = new ItemKitItem; $item_kit_items_data->item_kit_id = $itemkits->id; $item_kit_items_data->item_id = $value->item_id; $item_kit_items_data->quantity = $value->quantity; $item_kit_items_data->save(); } //delete all data on ReceivingTemp model ItemKitItemTemp::truncate(); Session::flash('message', 'You have successfully added Item Kits'); return Redirect::to('item-kits/create'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/EmployeeController.php
app/Http/Controllers/EmployeeController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\User; use App\Http\Requests\EmployeeStoreRequest; use App\Http\Requests\EmployeeUpdateRequest; use \Auth, \Redirect, \Validator, \Input, \Session, \Hash; use Illuminate\Http\Request; class EmployeeController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $employees = User::all(); return view('employee.index')->with('employee', $employees); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('employee.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store(EmployeeStoreRequest $request) { // store $users = new User; $users->name = Input::get('name'); $users->email = Input::get('email'); $users->password = Hash::make(Input::get('password')); $users->save(); Session::flash('message', 'You have successfully added employee'); return Redirect::to('employees'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $employees = User::find($id); return view('employee.edit') ->with('employee', $employees); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { if($id == 1) { Session::flash('message', 'You cannot edit admin on TutaPOS demo'); Session::flash('alert-class', 'alert-danger'); return Redirect::to('employees'); } else { $rules = array( 'name' => 'required', 'email' => 'required|email|unique:users,email,' . $id .'', 'password' => 'min:6|max:30|confirmed', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('employees/' . $id . '/edit') ->withErrors($validator); } else { $users = User::find($id); $users->name = Input::get('name'); $users->email = Input::get('email'); if(!empty(Input::get('password'))) { $users->password = Hash::make(Input::get('password')); } $users->save(); // redirect Session::flash('message', 'You have successfully updated employee'); return Redirect::to('employees'); } } } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { if($id == 1) { Session::flash('message', 'You cannot delete admin on TutaPOS demo'); Session::flash('alert-class', 'alert-danger'); return Redirect::to('employees'); } else { try { $users = User::find($id); $users->delete(); // redirect Session::flash('message', 'You have successfully deleted employee'); return Redirect::to('employees'); } catch(\Illuminate\Database\QueryException $e) { Session::flash('message', 'Integrity constraint violation: You Cannot delete a parent row'); Session::flash('alert-class', 'alert-danger'); return Redirect::to('employees'); } } } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/SupplierController.php
app/Http/Controllers/SupplierController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Supplier; use App\Http\Requests\SupplierRequest; use \Auth, \Redirect, \Validator, \Input, \Session; use Image; use Illuminate\Http\Request; class SupplierController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $suppliers = Supplier::all(); return view('supplier.index')->with('supplier', $suppliers); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('supplier.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store(SupplierRequest $request) { $suppliers = new Supplier; $suppliers->company_name = Input::get('company_name'); $suppliers->name = Input::get('name'); $suppliers->email = Input::get('email'); $suppliers->phone_number = Input::get('phone_number'); $suppliers->address = Input::get('address'); $suppliers->city = Input::get('city'); $suppliers->state = Input::get('state'); $suppliers->zip = Input::get('zip'); $suppliers->comments = Input::get('comments'); $suppliers->account = Input::get('account'); $suppliers->save(); // process avatar $image = $request->file('avatar'); if(!empty($image)) { $avatarName = 'sup' . $suppliers->id . '.' . $request->file('avatar')->getClientOriginalExtension(); $request->file('avatar')->move( base_path() . '/public/images/suppliers/', $avatarName ); $img = Image::make(base_path() . '/public/images/suppliers/' . $avatarName); $img->resize(100, null, function ($constraint) { $constraint->aspectRatio(); }); $img->save(); $supplierAvatar = Supplier::find($suppliers->id); $supplierAvatar->avatar = $avatarName; $supplierAvatar->save(); } Session::flash('message', 'You have successfully added supplier'); return Redirect::to('suppliers'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $suppliers = Supplier::find($id); return view('supplier.edit') ->with('supplier', $suppliers); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update(SupplierRequest $request, $id) { $suppliers = Supplier::find($id); $suppliers->company_name = Input::get('company_name'); $suppliers->name = Input::get('name'); $suppliers->email = Input::get('email'); $suppliers->phone_number = Input::get('phone_number'); $suppliers->address = Input::get('address'); $suppliers->city = Input::get('city'); $suppliers->state = Input::get('state'); $suppliers->zip = Input::get('zip'); $suppliers->comments = Input::get('comments'); $suppliers->account = Input::get('account'); $suppliers->save(); // process avatar $image = $request->file('avatar'); if(!empty($image)) { $avatarName = 'sup' . $id . '.' . $request->file('avatar')->getClientOriginalExtension(); $request->file('avatar')->move( base_path() . '/public/images/suppliers/', $avatarName ); $img = Image::make(base_path() . '/public/images/suppliers/' . $avatarName); $img->resize(100, null, function ($constraint) { $constraint->aspectRatio(); }); $img->save(); $supplierAvatar = Supplier::find($id); $supplierAvatar->avatar = $avatarName; $supplierAvatar->save(); } Session::flash('message', 'You have successfully updated supplier'); return Redirect::to('suppliers'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { try { $suppliers = Supplier::find($id); $suppliers->delete(); Session::flash('message', 'You have successfully deleted supplier'); return Redirect::to('suppliers'); } catch(\Illuminate\Database\QueryException $e) { Session::flash('message', 'Integrity constraint violation: You Cannot delete a parent row'); Session::flash('alert-class', 'alert-danger'); return Redirect::to('suppliers'); } } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/ItemController.php
app/Http/Controllers/ItemController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Item; use App\Inventory; use App\Http\Requests\ItemRequest; use \Auth, \Redirect, \Validator, \Input, \Session; use Image; use Illuminate\Http\Request; class ItemController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $items = Item::where('type', 1)->get(); return view('item.index')->with('item', $items); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('item.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store(ItemRequest $request) { $items = new Item; $items->upc_ean_isbn = Input::get('upc_ean_isbn'); $items->item_name = Input::get('item_name'); $items->size = Input::get('size'); $items->description = Input::get('description'); $items->cost_price = Input::get('cost_price'); $items->selling_price = Input::get('selling_price'); $items->quantity = Input::get('quantity'); $items->save(); // process inventory if(!empty(Input::get('quantity'))) { $inventories = new Inventory; $inventories->item_id = $items->id; $inventories->user_id = Auth::user()->id; $inventories->in_out_qty = Input::get('quantity'); $inventories->remarks = 'Manual Edit of Quantity'; $inventories->save(); } // process avatar $image = $request->file('avatar'); if(!empty($image)) { $avatarName = 'item' . $items->id . '.' . $request->file('avatar')->getClientOriginalExtension(); $request->file('avatar')->move( base_path() . '/public/images/items/', $avatarName ); $img = Image::make(base_path() . '/public/images/items/' . $avatarName); $img->resize(100, null, function ($constraint) { $constraint->aspectRatio(); }); $img->save(); $itemAvatar = Item::find($items->id); $itemAvatar->avatar = $avatarName; $itemAvatar->save(); } Session::flash('message', 'You have successfully added item'); return Redirect::to('items/create'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $items = Item::find($id); return view('item.edit') ->with('item', $items); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update(ItemRequest $request, $id) { $items = Item::find($id); // process inventory $inventories = new Inventory; $inventories->item_id = $id; $inventories->user_id = Auth::user()->id; $inventories->in_out_qty = Input::get('quantity')- $items->quantity; $inventories->remarks = 'Manual Edit of Quantity'; $inventories->save(); // save update $items->upc_ean_isbn = Input::get('upc_ean_isbn'); $items->item_name = Input::get('item_name'); $items->size = Input::get('size'); $items->description = Input::get('description'); $items->cost_price = Input::get('cost_price'); $items->selling_price = Input::get('selling_price'); $items->quantity = Input::get('quantity'); $items->save(); // process avatar $image = $request->file('avatar'); if(!empty($image)) { $avatarName = 'item' . $id . '.' . $request->file('avatar')->getClientOriginalExtension(); $request->file('avatar')->move( base_path() . '/public/images/items/', $avatarName ); $img = Image::make(base_path() . '/public/images/items/' . $avatarName); $img->resize(100, null, function ($constraint) { $constraint->aspectRatio(); }); $img->save(); $itemAvatar = Item::find($id); $itemAvatar->avatar = $avatarName; $itemAvatar->save(); } Session::flash('message', 'You have successfully updated item'); return Redirect::to('items'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { $items = Item::find($id); $items->delete(); Session::flash('message', 'You have successfully deleted item'); return Redirect::to('items'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/SaleTempApiController.php
app/Http/Controllers/SaleTempApiController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\SaleTemp; use App\Item; use \Auth, \Redirect, \Validator, \Input, \Session, \Response; use Illuminate\Http\Request; class SaleTempApiController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { return Response::json(SaleTemp::with('item')->get()); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('sale.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $SaleTemps = new SaleTemp; $SaleTemps->item_id = Input::get('item_id'); $SaleTemps->cost_price = Input::get('cost_price'); $SaleTemps->selling_price = Input::get('selling_price'); $SaleTemps->quantity = 1; $SaleTemps->total_cost = Input::get('cost_price'); $SaleTemps->total_selling = Input::get('selling_price'); $SaleTemps->save(); return $SaleTemps; } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $SaleTemps = SaleTemp::find($id); $SaleTemps->quantity = Input::get('quantity'); $SaleTemps->total_cost = Input::get('total_cost'); $SaleTemps->total_selling = Input::get('total_selling'); $SaleTemps->save(); return $SaleTemps; } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { SaleTemp::destroy($id); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/WelcomeController.php
app/Http/Controllers/WelcomeController.php
<?php namespace App\Http\Controllers; class WelcomeController extends Controller { /* |-------------------------------------------------------------------------- | Welcome Controller |-------------------------------------------------------------------------- | | This controller renders the "marketing page" for the application and | is configured to only allow guests. Like most of the other sample | controllers, you are free to modify or remove it as you desire. | */ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } /** * Show the application welcome screen to the user. * * @return Response */ public function index() { return view('welcome'); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/HomeController.php
app/Http/Controllers/HomeController.php
<?php namespace App\Http\Controllers; use App\Item, App\Customer, App\Sale; use App\Supplier, App\Receiving, App\User; use App; class HomeController extends Controller { /* |-------------------------------------------------------------------------- | Home Controller |-------------------------------------------------------------------------- | | This controller renders your application's "dashboard" for users that | are authenticated. Of course, you are free to change or remove the | controller as you wish. It is just here to get your app started! | */ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard to the user. * * @return Response */ public function index() { $items = Item::where('type', 1)->count(); $item_kits = Item::where('type', 2)->count(); $customers = Customer::count(); $suppliers = Supplier::count(); $receivings = Receiving::count(); $sales = Sale::count(); $employees = User::count(); return view('home') ->with('items', $items) ->with('item_kits', $item_kits) ->with('customers', $customers) ->with('suppliers', $suppliers) ->with('receivings', $receivings) ->with('sales', $sales) ->with('employees', $employees); } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/SaleReportController.php
app/Http/Controllers/SaleReportController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Sale; use \Auth, \Redirect; use Illuminate\Http\Request; class SaleReportController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $salesReport = Sale::all(); return view('report.sale')->with('saleReport', $salesReport); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/InventoryController.php
app/Http/Controllers/InventoryController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Item; use App\Inventory; use App\Http\Requests\InventoryRequest; use \Auth, \Redirect, \Validator, \Input, \Session; use Illuminate\Http\Request; class InventoryController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $items = Item::find($id); $inventories = Inventory::all(); return view('inventory.edit') ->with('item', $items) ->with('inventory', $inventories); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update(InventoryRequest $request, $id) { $items = Item::find($id); $items->quantity = $items->quantity + Input::get('in_out_qty'); $items->save(); $inventories = new Inventory; $inventories->item_id = $id; $inventories->user_id = Auth::user()->id; $inventories->in_out_qty = Input::get('in_out_qty'); $inventories->remarks = Input::get('remarks'); $inventories->save(); Session::flash('message', 'You have successfully updated item'); return Redirect::to('inventory/' . $id . '/edit'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false
tutacare/tutapos
https://github.com/tutacare/tutapos/blob/2e07e73ad355162caacf2e5509125894001b84a5/app/Http/Controllers/CustomerController.php
app/Http/Controllers/CustomerController.php
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Customer; use App\Http\Requests\CustomerRequest; use \Auth, \Redirect, \Validator, \Input, \Session; use Image; use Illuminate\Http\Request; class CustomerController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { $customers = Customer::all(); return view('customer.index')->with('customer', $customers); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('customer.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store(CustomerRequest $request) { // store $customers = new Customer; $customers->name = Input::get('name'); $customers->email = Input::get('email'); $customers->phone_number = Input::get('phone_number'); $customers->address = Input::get('address'); $customers->city = Input::get('city'); $customers->state = Input::get('state'); $customers->zip = Input::get('zip'); $customers->company_name = Input::get('company_name'); $customers->account = Input::get('account'); $customers->save(); // process avatar $image = $request->file('avatar'); if(!empty($image)) { $avatarName = 'cus' . $customers->id . '.' . $request->file('avatar')->getClientOriginalExtension(); $request->file('avatar')->move( base_path() . '/public/images/customers/', $avatarName ); $img = Image::make(base_path() . '/public/images/customers/' . $avatarName); $img->resize(100, null, function ($constraint) { $constraint->aspectRatio(); }); $img->save(); $customerAvatar = Customer::find($customers->id); $customerAvatar->avatar = $avatarName; $customerAvatar->save(); } Session::flash('message', 'You have successfully added customer'); return Redirect::to('customers'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $customers = Customer::find($id); return view('customer.edit') ->with('customer', $customers); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update(CustomerRequest $request, $id) { $customers = Customer::find($id); $customers->name = Input::get('name'); $customers->email = Input::get('email'); $customers->phone_number = Input::get('phone_number'); $customers->address = Input::get('address'); $customers->city = Input::get('city'); $customers->state = Input::get('state'); $customers->zip = Input::get('zip'); $customers->company_name = Input::get('company_name'); $customers->account = Input::get('account'); $customers->save(); // process avatar $image = $request->file('avatar'); if(!empty($image)) { $avatarName = 'cus' . $id . '.' . $request->file('avatar')->getClientOriginalExtension(); $request->file('avatar')->move( base_path() . '/public/images/customers/', $avatarName ); $img = Image::make(base_path() . '/public/images/customers/' . $avatarName); $img->resize(100, null, function ($constraint) { $constraint->aspectRatio(); }); $img->save(); $customerAvatar = Customer::find($id); $customerAvatar->avatar = $avatarName; $customerAvatar->save(); } // redirect Session::flash('message', 'You have successfully updated customer'); return Redirect::to('customers'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { try { $customers = Customer::find($id); $customers->delete(); // redirect Session::flash('message', 'You have successfully deleted customer'); return Redirect::to('customers'); } catch(\Illuminate\Database\QueryException $e) { Session::flash('message', 'Integrity constraint violation: You Cannot delete a parent row'); Session::flash('alert-class', 'alert-danger'); return Redirect::to('customers'); } } }
php
MIT
2e07e73ad355162caacf2e5509125894001b84a5
2026-01-05T05:00:20.248800Z
false