repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
awurth/SlimValidationREST
Validator.php
Validator.validate
public function validate(Request $request, array $rules, array $messages = []) { foreach ($rules as $param => $options) { $value = $request->getParam($param); $this->data[$param] = $value; $isRule = $options instanceof V; try { if ($isRule) { $options->assert($value); } else { if (!isset($options['rules']) || !($options['rules'] instanceof V)) { throw new InvalidArgumentException('Validation rules are missing'); } $options['rules']->assert($value); } } catch (NestedValidationException $e) { $paramRules = $isRule ? $options->getRules() : $options['rules']->getRules(); // Get the names of all rules used for this param $rulesNames = []; foreach ($paramRules as $rule) { $rulesNames[] = lcfirst((new ReflectionClass($rule))->getShortName()); } // If the 'message' key exists, set it as only message for this param if (!$isRule && isset($options['message']) && is_string($options['message'])) { $this->errors[$param] = [$options['message']]; return $this; } else { // If the 'messages' key exists, override global messages $params = [ $e->findMessages($rulesNames) ]; // If default messages are defined if (!empty($this->defaultMessages)) { $params[] = $e->findMessages($this->defaultMessages); } // If global messages are defined if (!empty($messages)) { $params[] = $e->findMessages($messages); } // If individual messages are defined if (!$isRule && isset($options['messages'])) { $params[] = $e->findMessages($options['messages']); } $this->errors[$param] = array_values(array_filter(call_user_func_array('array_merge', $params))); } } } return $this; }
php
public function validate(Request $request, array $rules, array $messages = []) { foreach ($rules as $param => $options) { $value = $request->getParam($param); $this->data[$param] = $value; $isRule = $options instanceof V; try { if ($isRule) { $options->assert($value); } else { if (!isset($options['rules']) || !($options['rules'] instanceof V)) { throw new InvalidArgumentException('Validation rules are missing'); } $options['rules']->assert($value); } } catch (NestedValidationException $e) { $paramRules = $isRule ? $options->getRules() : $options['rules']->getRules(); // Get the names of all rules used for this param $rulesNames = []; foreach ($paramRules as $rule) { $rulesNames[] = lcfirst((new ReflectionClass($rule))->getShortName()); } // If the 'message' key exists, set it as only message for this param if (!$isRule && isset($options['message']) && is_string($options['message'])) { $this->errors[$param] = [$options['message']]; return $this; } else { // If the 'messages' key exists, override global messages $params = [ $e->findMessages($rulesNames) ]; // If default messages are defined if (!empty($this->defaultMessages)) { $params[] = $e->findMessages($this->defaultMessages); } // If global messages are defined if (!empty($messages)) { $params[] = $e->findMessages($messages); } // If individual messages are defined if (!$isRule && isset($options['messages'])) { $params[] = $e->findMessages($options['messages']); } $this->errors[$param] = array_values(array_filter(call_user_func_array('array_merge', $params))); } } } return $this; }
Validate request params with the given rules @param Request $request @param array $rules @param array $messages @return $this
https://github.com/awurth/SlimValidationREST/blob/e1e715b880acc43b963d2bad660a00f68499dfea/Validator.php#L56-L112
awurth/SlimValidationREST
Validator.php
Validator.addErrors
public function addErrors($param, array $messages) { foreach ($messages as $message) { $this->errors[$param][] = $message; } return $this; }
php
public function addErrors($param, array $messages) { foreach ($messages as $message) { $this->errors[$param][] = $message; } return $this; }
Add errors for param @param string $param @param array $messages @return $this
https://github.com/awurth/SlimValidationREST/blob/e1e715b880acc43b963d2bad660a00f68499dfea/Validator.php#L134-L141
chilimatic/chilimatic-framework
lib/datastructure/graph/AbstractNode.php
AbstractNode.delete
public function delete($key = '') { $node = $this->mainNode->getByKey($key); if (empty($node)) return $this->mainNode; $this->mainNode->children->removeNode($node); unset($node); return $this->mainNode; }
php
public function delete($key = '') { $node = $this->mainNode->getByKey($key); if (empty($node)) return $this->mainNode; $this->mainNode->children->removeNode($node); unset($node); return $this->mainNode; }
deletes a config @param string $key @return mixed
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/datastructure/graph/AbstractNode.php#L53-L61
chilimatic/chilimatic-framework
lib/datastructure/graph/AbstractNode.php
AbstractNode.get
public function get($var) { $node = $this->mainNode->getByKey($var); if (empty($node)) return null; return $node->getData(); }
php
public function get($var) { $node = $this->mainNode->getByKey($var); if (empty($node)) return null; return $node->getData(); }
gets a specific parameter @param $var @return mixed
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/datastructure/graph/AbstractNode.php#L70-L76
chilimatic/chilimatic-framework
lib/datastructure/graph/AbstractNode.php
AbstractNode.setById
public function setById($id, $val) { // set the variable if (empty($id)) return $this; $node = new Node($this->mainNode, $id, $val); $this->mainNode->addChild($node); return $this; }
php
public function setById($id, $val) { // set the variable if (empty($id)) return $this; $node = new Node($this->mainNode, $id, $val); $this->mainNode->addChild($node); return $this; }
sets a specific parameter @param $id @param $val @return mixed
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/datastructure/graph/AbstractNode.php#L101-L111
chilimatic/chilimatic-framework
lib/datastructure/graph/AbstractNode.php
AbstractNode.set
public function set($key, $val) { // set the variable if (empty($key)) return $this; $node = new Node($this->mainNode, $key, $val); $this->mainNode->addChild($node); return $this; }
php
public function set($key, $val) { // set the variable if (empty($key)) return $this; $node = new Node($this->mainNode, $key, $val); $this->mainNode->addChild($node); return $this; }
sets a specific parameter @param $key @param $val @return mixed
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/datastructure/graph/AbstractNode.php#L121-L130
andrelohmann/silverstripe-geoform
code/forms/BackendGeoLocationField.php
BackendGeoLocationField.validate
public function validate($validator){ $name = $this->name; $addressField = $this->fieldAddress; $latitudeField = $this->fieldLatitude; $longditudeField = $this->fieldLongditude; $addressField->setValue($_POST[$name]['Address']); $latitudeField->setValue($_POST[$name]['Latitude']); $longditudeField->setValue($_POST[$name]['Longditude']); // Result was unique if($latitudeField->Value() != '' && is_numeric($latitudeField->Value()) && $longditudeField->Value() != '' && is_numeric($longditudeField->Value())){ return true; } if(trim($addressField->Value()) == ''){ if(!$validator->fieldIsRequired($this->name)){ return true; } else { $validator->validationError($name, _t('GeoLocationField.VALIDATION', 'Please enter an accurate address!'), "validation"); return false; } } // fetch result from google (serverside) $myAddress = trim($addressField->Value()); // Update to v3 API $googleUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($myAddress).'&language='.i18n::get_tinymce_lang(); if(GoogleMaps::getApiKey()) $googleUrl.= '&key='.GoogleMaps::getApiKey(); $result = json_decode(file_get_contents($googleUrl), true); // if result unique if($result['status'] == 'OK' && count($result['results']) == 1){ $latitudeField->setValue($result['results'][0]['geometry']['location']['lat']); $longditudeField->setValue($result['results'][0]['geometry']['location']['lng']); return true; }else{ $tmpCounter = 0; $tmpLocality = null; for($i=0; $i<count($result['results']); $i++){ // check if type is locality political if($result['results'][$i]['types'][0] == 'locality' && $result['results'][$i]['types'][1] == 'political'){ $tmpLocality = $i; $tmpCounter++; } } if($tmpCounter == 1){ $latitudeField->setValue($result['results'][$tmpLocality]['geometry']['location']['lat']); $longditudeField->setValue($result['results'][$tmpLocality]['geometry']['location']['lng']); return true; }else{ // result not unique $validator->validationError($name, _t('GeoLocationField.VALIDATIONUNIQUE', 'The address is not unique, please specify.'), "validation"); return false; } } }
php
public function validate($validator){ $name = $this->name; $addressField = $this->fieldAddress; $latitudeField = $this->fieldLatitude; $longditudeField = $this->fieldLongditude; $addressField->setValue($_POST[$name]['Address']); $latitudeField->setValue($_POST[$name]['Latitude']); $longditudeField->setValue($_POST[$name]['Longditude']); // Result was unique if($latitudeField->Value() != '' && is_numeric($latitudeField->Value()) && $longditudeField->Value() != '' && is_numeric($longditudeField->Value())){ return true; } if(trim($addressField->Value()) == ''){ if(!$validator->fieldIsRequired($this->name)){ return true; } else { $validator->validationError($name, _t('GeoLocationField.VALIDATION', 'Please enter an accurate address!'), "validation"); return false; } } // fetch result from google (serverside) $myAddress = trim($addressField->Value()); // Update to v3 API $googleUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($myAddress).'&language='.i18n::get_tinymce_lang(); if(GoogleMaps::getApiKey()) $googleUrl.= '&key='.GoogleMaps::getApiKey(); $result = json_decode(file_get_contents($googleUrl), true); // if result unique if($result['status'] == 'OK' && count($result['results']) == 1){ $latitudeField->setValue($result['results'][0]['geometry']['location']['lat']); $longditudeField->setValue($result['results'][0]['geometry']['location']['lng']); return true; }else{ $tmpCounter = 0; $tmpLocality = null; for($i=0; $i<count($result['results']); $i++){ // check if type is locality political if($result['results'][$i]['types'][0] == 'locality' && $result['results'][$i]['types'][1] == 'political'){ $tmpLocality = $i; $tmpCounter++; } } if($tmpCounter == 1){ $latitudeField->setValue($result['results'][$tmpLocality]['geometry']['location']['lat']); $longditudeField->setValue($result['results'][$tmpLocality]['geometry']['location']['lng']); return true; }else{ // result not unique $validator->validationError($name, _t('GeoLocationField.VALIDATIONUNIQUE', 'The address is not unique, please specify.'), "validation"); return false; } } }
Validates PostCodeLocation against GoogleMaps Serverside @return String
https://github.com/andrelohmann/silverstripe-geoform/blob/4b8ca69d094dca985c059fb35a159673c39af8d3/code/forms/BackendGeoLocationField.php#L188-L247
harmony-project/modular-bundle
source/DependencyInjection/HarmonyModularExtension.php
HarmonyModularExtension.load
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); // Disable the bundle if no module class is specified if (!$config['module_class']) { return; } // Load services $loader = new XmlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); $loader->load('services.xml'); // Set parameters $container->setParameter('harmony_modular.module_class', $config['module_class']); $container->setParameter('harmony_modular.module_identifier', $config['module_identifier']); $container->setParameter('harmony_modular.router.resource', $config['router']['resource']); $container->setParameter('harmony_modular.router.resource_type', $config['router']['resource_type'] ?: 'yaml'); $this->setupRoutePrefix($config, $container); $this->setupServices($config, $container); }
php
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); // Disable the bundle if no module class is specified if (!$config['module_class']) { return; } // Load services $loader = new XmlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); $loader->load('services.xml'); // Set parameters $container->setParameter('harmony_modular.module_class', $config['module_class']); $container->setParameter('harmony_modular.module_identifier', $config['module_identifier']); $container->setParameter('harmony_modular.router.resource', $config['router']['resource']); $container->setParameter('harmony_modular.router.resource_type', $config['router']['resource_type'] ?: 'yaml'); $this->setupRoutePrefix($config, $container); $this->setupServices($config, $container); }
{@inheritdoc}
https://github.com/harmony-project/modular-bundle/blob/2813f7285eb5ae18d2ebe7dd1623fd0e032cfab7/source/DependencyInjection/HarmonyModularExtension.php#L34-L59
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.setDelay
public function setDelay($delay) { if (is_string($delay) && ctype_digit($delay)) { $delay = (int) $delay; } elseif (!is_int($delay)) { throw new \RuntimeException('Delay should be an integer in MS.'); } $this->delay = $delay; return $this; }
php
public function setDelay($delay) { if (is_string($delay) && ctype_digit($delay)) { $delay = (int) $delay; } elseif (!is_int($delay)) { throw new \RuntimeException('Delay should be an integer in MS.'); } $this->delay = $delay; return $this; }
Defines how long the client should wait for the AlphaRPC instances to respond. If the time is reached the next AlphaRPC instance will be asked to execute the request. @param integer $delay @return Client @throws \RuntimeException
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L132-L143
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.setTimeout
public function setTimeout($timeout) { if (is_string($timeout) && ctype_digit($timeout)) { $timeout = (int) $timeout; } elseif (!is_int($timeout)) { throw new \RuntimeException('Unable to set timeout.'); } $this->timeout = $timeout; return $this; }
php
public function setTimeout($timeout) { if (is_string($timeout) && ctype_digit($timeout)) { $timeout = (int) $timeout; } elseif (!is_int($timeout)) { throw new \RuntimeException('Unable to set timeout.'); } $this->timeout = $timeout; return $this; }
Sets the timeout in MS. @param int $timeout @return Client @throws \RuntimeException
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L197-L207
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.addManager
public function addManager($manager) { if (is_array($manager)) { foreach ($manager as $item) { $this->managerList->add($item); } return $this; } $this->managerList->add($manager); return $this; }
php
public function addManager($manager) { if (is_array($manager)) { foreach ($manager as $item) { $this->managerList->add($item); } return $this; } $this->managerList->add($manager); return $this; }
Adds an address to a AlphaRPC daemon. @param string|array $manager @return Client @throws \InvalidArgumentException
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L217-L230
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.startRequest
public function startRequest($function, array $params = array(), $cache = null) { if ($cache !== null && !is_string($cache)) { throw new \RuntimeException('$cache is an id for the request and should be a string or null.'); } $request = new Request($function, $params); $prioritizedManagerList = $this->managerList->toPrioritizedArray(); foreach ($prioritizedManagerList as $manager) { try { $response = $this->sendExecuteRequest($manager, $request, $cache); $request->setManager($manager); $request->setRequestId($response->getRequestId()); $this->managerList->flag($manager, ManagerList::FLAG_AVAILABLE); $this->getLogger()->debug($manager.' accepted request '.$response->getRequestId().' '.$request->getFunction()); return $request; } catch (TimeoutException $ex) { $this->managerList->flag($manager, ManagerList::FLAG_UNAVAILABLE); $this->getLogger()->notice($manager.': '.$ex->getMessage()); } } throw new RuntimeException('AlphaRPC ('.implode(', ', $prioritizedManagerList).') did not respond in time.'); }
php
public function startRequest($function, array $params = array(), $cache = null) { if ($cache !== null && !is_string($cache)) { throw new \RuntimeException('$cache is an id for the request and should be a string or null.'); } $request = new Request($function, $params); $prioritizedManagerList = $this->managerList->toPrioritizedArray(); foreach ($prioritizedManagerList as $manager) { try { $response = $this->sendExecuteRequest($manager, $request, $cache); $request->setManager($manager); $request->setRequestId($response->getRequestId()); $this->managerList->flag($manager, ManagerList::FLAG_AVAILABLE); $this->getLogger()->debug($manager.' accepted request '.$response->getRequestId().' '.$request->getFunction()); return $request; } catch (TimeoutException $ex) { $this->managerList->flag($manager, ManagerList::FLAG_UNAVAILABLE); $this->getLogger()->notice($manager.': '.$ex->getMessage()); } } throw new RuntimeException('AlphaRPC ('.implode(', ', $prioritizedManagerList).') did not respond in time.'); }
Starts a request. @param string $function @param array $params @param string $cache @return Request @throws \RuntimeException
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L242-L270
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.request
public function request($function, array $params = array(), $cache = null) { $request = $this->startRequest($function, $params, $cache); return $this->fetchResponse($request); }
php
public function request($function, array $params = array(), $cache = null) { $request = $this->startRequest($function, $params, $cache); return $this->fetchResponse($request); }
Does a full request and returns the result. @param string $function @param array $params @param string $cache @return mixed
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L281-L286
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.getSocket
protected function getSocket($server) { if (isset($this->socket[$server])) { return $this->socket[$server]; } $context = new ZMQContext(); $socket = Socket::create($context, ZMQ::SOCKET_REQ, $this->logger); $socket->connect($server); $this->socket[$server] = $socket; return $socket; }
php
protected function getSocket($server) { if (isset($this->socket[$server])) { return $this->socket[$server]; } $context = new ZMQContext(); $socket = Socket::create($context, ZMQ::SOCKET_REQ, $this->logger); $socket->connect($server); $this->socket[$server] = $socket; return $socket; }
Returns a socket for the given server. If the socket does not yet exist, it is created. @param string $server @return Socket
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L297-L310
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.serializeParams
protected function serializeParams(array $params) { $serialized = array(); foreach ($params as $param) { $serialized[] = $this->serializer->serialize($param); } return $serialized; }
php
protected function serializeParams(array $params) { $serialized = array(); foreach ($params as $param) { $serialized[] = $this->serializer->serialize($param); } return $serialized; }
Serializes parameters. @param array $params @return array
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L333-L341
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.sendExecuteRequest
protected function sendExecuteRequest($manager, Request $request, $cache = null) { $serialized = $this->serializeParams($request->getParams()); $msg = new ExecuteRequest($cache, $request->getFunction(), $serialized); $socket = $this->getSocket($manager); $stream = $socket->getStream(); $stream->send($msg); try { $response = $stream->read(new TimeoutTimer($this->delay)); } catch (TimeoutException $ex) { $this->invalidateSocket($manager); throw $ex; } if (!$response instanceof ExecuteResponse) { $msg = $manager.': Invalid response '.get_class($response).'.'; $this->getLogger()->notice($msg); throw new InvalidResponseException($msg); } if ('' != $response->getResult()) { $this->handleFetchResponse($response, $request); } return $response; }
php
protected function sendExecuteRequest($manager, Request $request, $cache = null) { $serialized = $this->serializeParams($request->getParams()); $msg = new ExecuteRequest($cache, $request->getFunction(), $serialized); $socket = $this->getSocket($manager); $stream = $socket->getStream(); $stream->send($msg); try { $response = $stream->read(new TimeoutTimer($this->delay)); } catch (TimeoutException $ex) { $this->invalidateSocket($manager); throw $ex; } if (!$response instanceof ExecuteResponse) { $msg = $manager.': Invalid response '.get_class($response).'.'; $this->getLogger()->notice($msg); throw new InvalidResponseException($msg); } if ('' != $response->getResult()) { $this->handleFetchResponse($response, $request); } return $response; }
Send a request to the ClientHandler. @param string $manager @param Request $request @param string $cache @return ExecuteResponse @throws TimeoutException @throws InvalidResponseException
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L354-L382
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.fetchResponse
public function fetchResponse(Request $request, $waitForResult = true) { if ($request->hasResponse()) { return $request->getResponse(); } $timer = $this->getFetchTimer($waitForResult); $req = new FetchRequest($request->getRequestId(), $waitForResult); do { try { $response = $this->sendFetchRequest($this->getManagerForRequest($request), $req); $result = $this->handleFetchResponse($response, $request); return $result; } catch (TimeoutException $ex) { $this->getLogger()->debug($request->getRequestId().': '.$ex->getMessage()); } } while (!$timer->isExpired()); throw new TimeoutException('Request '.$request->getRequestId().' timed out.'); }
php
public function fetchResponse(Request $request, $waitForResult = true) { if ($request->hasResponse()) { return $request->getResponse(); } $timer = $this->getFetchTimer($waitForResult); $req = new FetchRequest($request->getRequestId(), $waitForResult); do { try { $response = $this->sendFetchRequest($this->getManagerForRequest($request), $req); $result = $this->handleFetchResponse($response, $request); return $result; } catch (TimeoutException $ex) { $this->getLogger()->debug($request->getRequestId().': '.$ex->getMessage()); } } while (!$timer->isExpired()); throw new TimeoutException('Request '.$request->getRequestId().' timed out.'); }
Fetches the response for a request. Throws a RuntimeException if there is no response (yet) and the timeout is reached. @param \AlphaRPC\Client\Request $request @param boolean $waitForResult @return mixed @throws \RuntimeException
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L396-L417
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.handleFetchResponse
private function handleFetchResponse(FetchResponse $response, Request $request) { $rawResult = $response->getResult(); $this->getLogger()->info('Received result: '.$rawResult.' for request: '.$request->getRequestId().'.'); $result = $this->serializer->unserialize($rawResult); $request->setResponse($result); return $result; }
php
private function handleFetchResponse(FetchResponse $response, Request $request) { $rawResult = $response->getResult(); $this->getLogger()->info('Received result: '.$rawResult.' for request: '.$request->getRequestId().'.'); $result = $this->serializer->unserialize($rawResult); $request->setResponse($result); return $result; }
@param FetchResponse $response @param Request $request @return mixed
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L425-L433
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.getFetchTimer
protected function getFetchTimer($waitForResult) { if (!$waitForResult) { return new TimeoutTimer($this->delay); } if ($this->timeout == -1) { return new UnlimitedTimer(); } return new TimeoutTimer($this->timeout); }
php
protected function getFetchTimer($waitForResult) { if (!$waitForResult) { return new TimeoutTimer($this->delay); } if ($this->timeout == -1) { return new UnlimitedTimer(); } return new TimeoutTimer($this->timeout); }
@param boolean $waitForResult @return TimerInterface
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L440-L451
alphacomm/alpharpc
src/AlphaRPC/Client/Client.php
Client.getManagerForRequest
private function getManagerForRequest(Request $request) { if (!$request->getManager()) { $request->setManager($this->managerList->get()); } return $request->getManager(); }
php
private function getManagerForRequest(Request $request) { if (!$request->getManager()) { $request->setManager($this->managerList->get()); } return $request->getManager(); }
Returns a manager for the Request. It prefers the manager that is already set, but if it is not, then it adds a random manager from the manager list. @param Request $request @return string
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Client.php#L534-L541
rackberg/para
src/Plugin/PluginManager.php
PluginManager.fetchPluginsAvailable
public function fetchPluginsAvailable(): array { $plugins = []; $packages = $this->packagist->findPackagesByType('para-plugin'); foreach ($packages as $package) { $plugin = $this->pluginFactory->getPlugin($package->getName()); $plugin->setVersion($package->getVersion()); $plugin->setDescription($package->getDescription()); $plugins[] = $plugin; } return $plugins; }
php
public function fetchPluginsAvailable(): array { $plugins = []; $packages = $this->packagist->findPackagesByType('para-plugin'); foreach ($packages as $package) { $plugin = $this->pluginFactory->getPlugin($package->getName()); $plugin->setVersion($package->getVersion()); $plugin->setDescription($package->getDescription()); $plugins[] = $plugin; } return $plugins; }
{@inheritdoc}
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Plugin/PluginManager.php#L92-L106
rackberg/para
src/Plugin/PluginManager.php
PluginManager.installPlugin
public function installPlugin(string $name, string &$version = ''): string { if ($this->isInstalled($name)) { throw new PluginAlreadyInstalledException($name); } if (empty($version)) { $versions = $this->packagist->getPackageVersions($name); $version = $this->packagist->getHighestVersion($versions); } $process = $this->processFactory->getProcess(sprintf( 'composer require %s %s', $name, $version ), $this->rootDirectory); $process->run(); if (!$process->isSuccessful()) { throw new PluginNotFoundException($name); } $output = $process->getOutput(); if (empty($output)) { $output = $process->getErrorOutput(); } return $output; }
php
public function installPlugin(string $name, string &$version = ''): string { if ($this->isInstalled($name)) { throw new PluginAlreadyInstalledException($name); } if (empty($version)) { $versions = $this->packagist->getPackageVersions($name); $version = $this->packagist->getHighestVersion($versions); } $process = $this->processFactory->getProcess(sprintf( 'composer require %s %s', $name, $version ), $this->rootDirectory); $process->run(); if (!$process->isSuccessful()) { throw new PluginNotFoundException($name); } $output = $process->getOutput(); if (empty($output)) { $output = $process->getErrorOutput(); } return $output; }
{@inheritdoc}
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Plugin/PluginManager.php#L111-L139
rackberg/para
src/Plugin/PluginManager.php
PluginManager.uninstallPlugin
public function uninstallPlugin(string $pluginName): void { if (!$this->isInstalled($pluginName)) { throw new PluginNotFoundException($pluginName); } $process = $this->processFactory->getProcess(sprintf( 'composer remove %s', $pluginName ), $this->rootDirectory); $process->run(); if (!$process->isSuccessful()) { throw new \Exception('Failed to uninstall the plugin.', 1); } }
php
public function uninstallPlugin(string $pluginName): void { if (!$this->isInstalled($pluginName)) { throw new PluginNotFoundException($pluginName); } $process = $this->processFactory->getProcess(sprintf( 'composer remove %s', $pluginName ), $this->rootDirectory); $process->run(); if (!$process->isSuccessful()) { throw new \Exception('Failed to uninstall the plugin.', 1); } }
{@inheritdoc}
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Plugin/PluginManager.php#L144-L159
rackberg/para
src/Plugin/PluginManager.php
PluginManager.isInstalled
public function isInstalled(string $pluginName): bool { $data = $this->decodeLockFile(); if (!empty($data['packages'])) { foreach ($data['packages'] as $package) { if ($this->isParaPlugin($package) && $package['name'] === $pluginName) { return true; } } } return false; }
php
public function isInstalled(string $pluginName): bool { $data = $this->decodeLockFile(); if (!empty($data['packages'])) { foreach ($data['packages'] as $package) { if ($this->isParaPlugin($package) && $package['name'] === $pluginName) { return true; } } } return false; }
{@inheritdoc}
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Plugin/PluginManager.php#L164-L176
rackberg/para
src/Plugin/PluginManager.php
PluginManager.getInstalledPlugins
public function getInstalledPlugins(): array { $plugins = []; $data = $this->decodeLockFile(); if (!empty($data['packages'])) { foreach ($data['packages'] as $package) { if ($this->isParaPlugin($package)) { $plugin = $this->pluginFactory->getPlugin($package['name']); $plugin->setDescription(isset($package['description']) ? $package['description'] : ''); $plugin->setVersion(isset($package['version']) ? $package['version'] : ''); $plugins[] = $plugin; } } } return $plugins; }
php
public function getInstalledPlugins(): array { $plugins = []; $data = $this->decodeLockFile(); if (!empty($data['packages'])) { foreach ($data['packages'] as $package) { if ($this->isParaPlugin($package)) { $plugin = $this->pluginFactory->getPlugin($package['name']); $plugin->setDescription(isset($package['description']) ? $package['description'] : ''); $plugin->setVersion(isset($package['version']) ? $package['version'] : ''); $plugins[] = $plugin; } } } return $plugins; }
{@inheritdoc}
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Plugin/PluginManager.php#L181-L199
rackberg/para
src/Plugin/PluginManager.php
PluginManager.decodeLockFile
private function decodeLockFile(): array { $data = []; $encoder = $this->jsonEncoderFactory->getEncoder(); if (file_exists($this->rootDirectory . 'composer.lock')) { $data = $encoder->decode( file_get_contents($this->rootDirectory.'composer.lock'), JsonEncoder::FORMAT ); } return $data; }
php
private function decodeLockFile(): array { $data = []; $encoder = $this->jsonEncoderFactory->getEncoder(); if (file_exists($this->rootDirectory . 'composer.lock')) { $data = $encoder->decode( file_get_contents($this->rootDirectory.'composer.lock'), JsonEncoder::FORMAT ); } return $data; }
Returns the decoded lock file data. @return array
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Plugin/PluginManager.php#L206-L219
yii2lab/yii2-rbac
src/domain/services/RuleService.php
RuleService.executeRule
public function executeRule($user, $item, $params) { if ($item->ruleName === null) { return true; } $rule = $this->domain->rule->getRule($item->ruleName); if ($rule instanceof Rule) { return $rule->execute($user, $item, $params); } throw new InvalidConfigException("Rule not found: {$item->ruleName}"); }
php
public function executeRule($user, $item, $params) { if ($item->ruleName === null) { return true; } $rule = $this->domain->rule->getRule($item->ruleName); if ($rule instanceof Rule) { return $rule->execute($user, $item, $params); } throw new InvalidConfigException("Rule not found: {$item->ruleName}"); }
Executes the rule associated with the specified auth item. If the item does not specify a rule, this method will return true. Otherwise, it will return the value of [[Rule::execute()]]. @param string|int $user the user ID. This should be either an integer or a string representing the unique identifier of a user. See [[\yii\web\User::id]]. @param Item $item the auth item that needs to execute its rule @param array $params parameters passed to [[CheckAccessInterface::checkAccess()]] and will be passed to the rule @return bool the return value of [[Rule::execute()]]. If the auth item does not specify a rule, true will be returned. @throws InvalidConfigException if the auth item has an invalid rule.
https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/services/RuleService.php#L84-L95
gplcart/base
handlers/Install.php
Install.install
public function install(array $data, $db) { $this->db = $db; $this->data = $data; $this->data['step'] = 0; if (GC_CLI) { $this->installCli(); return array(); } return $this->installHttp(); }
php
public function install(array $data, $db) { $this->db = $db; $this->data = $data; $this->data['step'] = 0; if (GC_CLI) { $this->installCli(); return array(); } return $this->installHttp(); }
Performs initial system installation. Step 0 @param array $data @param \gplcart\core\Database $db @return array
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L54-L66
gplcart/base
handlers/Install.php
Install.installHttp
protected function installHttp() { $result = array( 'message' => '', 'severity' => 'success', 'redirect' => 'install/' . ($this->data['step'] + 1) ); try { $this->start(); $this->process(); } catch (Exception $ex) { $result = array( 'redirect' => '', 'severity' => 'warning', 'message' => $ex->getMessage() ); } return $result; }
php
protected function installHttp() { $result = array( 'message' => '', 'severity' => 'success', 'redirect' => 'install/' . ($this->data['step'] + 1) ); try { $this->start(); $this->process(); } catch (Exception $ex) { $result = array( 'redirect' => '', 'severity' => 'warning', 'message' => $ex->getMessage() ); } return $result; }
Performs installation via classic web UI @return array
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L72-L94
gplcart/base
handlers/Install.php
Install.installCli
protected function installCli() { try { $this->process(); $this->installCliStep1(); $this->installCliStep2(); $this->installCliStep3(); $this->cli->line($this->getSuccessMessage()); } catch (Exception $ex) { $this->cli->error($ex->getMessage()); } }
php
protected function installCli() { try { $this->process(); $this->installCliStep1(); $this->installCliStep2(); $this->installCliStep3(); $this->cli->line($this->getSuccessMessage()); } catch (Exception $ex) { $this->cli->error($ex->getMessage()); } }
Install in CLI mode
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L99-L110
gplcart/base
handlers/Install.php
Install.installCliStep1
protected function installCliStep1() { $this->data['step'] = 1; $this->setCliMessage('Configuring modules...'); $result = $this->installModules($this->data, $this->db); if ($result['severity'] !== 'success') { throw new UnexpectedValueException($result['message']); } }
php
protected function installCliStep1() { $this->data['step'] = 1; $this->setCliMessage('Configuring modules...'); $result = $this->installModules($this->data, $this->db); if ($result['severity'] !== 'success') { throw new UnexpectedValueException($result['message']); } }
Process step 1 in CLI mode @throws UnexpectedValueException
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L116-L125
gplcart/base
handlers/Install.php
Install.installCliStep2
protected function installCliStep2() { $title = $this->translation->text('Please select a demo content package (enter a number)'); $this->data['demo_handler_id'] = $this->cli->menu($this->getDemoOptions(), '', $title); if (!empty($this->data['demo_handler_id'])) { $this->data['step'] = 2; $this->setCliMessage('Installing demo content...'); $result = $this->installDemo($this->data, $this->db); if ($result['severity'] !== 'success') { throw new UnexpectedValueException($result['message']); } $this->setContext('demo_handler_id', $this->data['demo_handler_id']); } }
php
protected function installCliStep2() { $title = $this->translation->text('Please select a demo content package (enter a number)'); $this->data['demo_handler_id'] = $this->cli->menu($this->getDemoOptions(), '', $title); if (!empty($this->data['demo_handler_id'])) { $this->data['step'] = 2; $this->setCliMessage('Installing demo content...'); $result = $this->installDemo($this->data, $this->db); if ($result['severity'] !== 'success') { throw new UnexpectedValueException($result['message']); } $this->setContext('demo_handler_id', $this->data['demo_handler_id']); } }
Process step 2 in CLI mode @throws UnexpectedValueException
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L131-L148
gplcart/base
handlers/Install.php
Install.installCliStep3
protected function installCliStep3() { $this->data['step'] = 3; $result = $this->installFinish($this->data, $this->db); if ($result['severity'] !== 'success') { throw new UnexpectedValueException($result['message']); } }
php
protected function installCliStep3() { $this->data['step'] = 3; $result = $this->installFinish($this->data, $this->db); if ($result['severity'] !== 'success') { throw new UnexpectedValueException($result['message']); } }
Precess step 3 in CLI mode @throws UnexpectedValueException
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L154-L162
gplcart/base
handlers/Install.php
Install.installModules
public function installModules(array $data, $db) { $this->db = $db; $this->data = $data; try { $this->install_model->installModules(); $this->configureModules(); return array( 'message' => '', 'severity' => 'success', 'redirect' => 'install/' . ($this->data['step'] + 1) ); } catch (Exception $ex) { $this->setContextError($this->data['step'], $ex->getMessage()); return array( 'redirect' => '', 'severity' => 'danger', 'message' => $ex->getMessage() ); } }
php
public function installModules(array $data, $db) { $this->db = $db; $this->data = $data; try { $this->install_model->installModules(); $this->configureModules(); return array( 'message' => '', 'severity' => 'success', 'redirect' => 'install/' . ($this->data['step'] + 1) ); } catch (Exception $ex) { $this->setContextError($this->data['step'], $ex->getMessage()); return array( 'redirect' => '', 'severity' => 'danger', 'message' => $ex->getMessage() ); } }
Installs required modules. Step 1 @param array $data @param \gplcart\core\Database $db @return array
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L170-L196
gplcart/base
handlers/Install.php
Install.installDemo
public function installDemo(array $data, $db) { set_time_limit(0); $this->db = $db; $this->data = $data; $success_result = array( 'message' => '', 'severity' => 'success', 'redirect' => 'install/' . ($this->data['step'] + 1) ); if (empty($data['demo_handler_id'])) { return $success_result; } $result = $this->install_model->getDemoModule()->create($this->getContext('store_id'), $data['demo_handler_id']); if ($result !== true) { $this->setContextError($this->data['step'], $result); } return $success_result; }
php
public function installDemo(array $data, $db) { set_time_limit(0); $this->db = $db; $this->data = $data; $success_result = array( 'message' => '', 'severity' => 'success', 'redirect' => 'install/' . ($this->data['step'] + 1) ); if (empty($data['demo_handler_id'])) { return $success_result; } $result = $this->install_model->getDemoModule()->create($this->getContext('store_id'), $data['demo_handler_id']); if ($result !== true) { $this->setContextError($this->data['step'], $result); } return $success_result; }
Install a demo-content. Step 2 @param array $data @param \gplcart\core\Database $db @return array
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L204-L228
gplcart/base
handlers/Install.php
Install.installFinish
public function installFinish(array $data, $db) { $this->db = $db; $this->data = $data; $result = $this->finish(); $errors = $this->getContextErrors(); if (empty($errors)) { if ($this->getContext('demo_handler_id')) { $store_id = $this->getContext('store_id'); $this->getStoreModel()->update($store_id, array('status' => 1)); } } else { $result['severity'] = 'warning'; $result['message'] = implode(PHP_EOL, $errors); } return $result; }
php
public function installFinish(array $data, $db) { $this->db = $db; $this->data = $data; $result = $this->finish(); $errors = $this->getContextErrors(); if (empty($errors)) { if ($this->getContext('demo_handler_id')) { $store_id = $this->getContext('store_id'); $this->getStoreModel()->update($store_id, array('status' => 1)); } } else { $result['severity'] = 'warning'; $result['message'] = implode(PHP_EOL, $errors); } return $result; }
Performs final tasks. Step 3 @param array $data @param \gplcart\core\Database $db @return array
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L236-L255
gplcart/base
handlers/Install.php
Install.getDemoOptions
protected function getDemoOptions() { $options = array('' => $this->translation->text('No demo')); foreach ($this->install_model->getDemoHandlers() as $id => $handler) { $options[$id] = $handler['title']; } return $options; }
php
protected function getDemoOptions() { $options = array('' => $this->translation->text('No demo')); foreach ($this->install_model->getDemoHandlers() as $id => $handler) { $options[$id] = $handler['title']; } return $options; }
Returns an array of demo content options @return array
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L261-L270
gplcart/base
handlers/Install.php
Install.configureModuleDevice
protected function configureModuleDevice() { $store_id = $this->getContext('store_id'); $settings = array(); $settings['theme'][$store_id]['mobile'] = 'mobile'; $settings['theme'][$store_id]['tablet'] = 'mobile'; $this->module->setSettings('device', $settings); }
php
protected function configureModuleDevice() { $store_id = $this->getContext('store_id'); $settings = array(); $settings['theme'][$store_id]['mobile'] = 'mobile'; $settings['theme'][$store_id]['tablet'] = 'mobile'; $this->module->setSettings('device', $settings); }
Configure Device module settings
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L284-L293
gplcart/base
handlers/Install.php
Install.configureModuleGaReport
protected function configureModuleGaReport() { $info = $this->module->getInfo('ga_report'); $info['settings']['dashboard'] = array( 'visit_date', 'pageview_date', 'content_statistic', 'top_pages', 'source', 'keyword', 'audience' ); $this->module->setSettings('ga_report', $info['settings']); }
php
protected function configureModuleGaReport() { $info = $this->module->getInfo('ga_report'); $info['settings']['dashboard'] = array( 'visit_date', 'pageview_date', 'content_statistic', 'top_pages', 'source', 'keyword', 'audience' ); $this->module->setSettings('ga_report', $info['settings']); }
Configure Google Analytics Report module settings
https://github.com/gplcart/base/blob/bbcd87604d25333a0a1b84d79299fa06ec5dd39e/handlers/Install.php#L298-L313
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.initialize
public function initialize($url, $reset = true) { if ((bool)$reset) $this->reset(); $this->currentRequestUrl = $url; $this->state = self::STATE_INITIALIZED; return $this; }
php
public function initialize($url, $reset = true) { if ((bool)$reset) $this->reset(); $this->currentRequestUrl = $url; $this->state = self::STATE_INITIALIZED; return $this; }
Create a new CURL resource @param string $url @param bool $reset @return $this
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L82-L92
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.setRequestHeader
public function setRequestHeader($name, $value) { if (!is_string($name)) throw new \InvalidArgumentException('Argument 1 expected to be string, '.gettype($name).' seen.'); if (!is_string($value)) throw new \InvalidArgumentException('Argument 2 expected to be string, '.gettype($value).' seen.'); if (($name = trim($name)) === '') throw new \RuntimeException('Argument 1 cannot be empty string.'); $this->requestHeaders[$name] = $value; return $this; }
php
public function setRequestHeader($name, $value) { if (!is_string($name)) throw new \InvalidArgumentException('Argument 1 expected to be string, '.gettype($name).' seen.'); if (!is_string($value)) throw new \InvalidArgumentException('Argument 2 expected to be string, '.gettype($value).' seen.'); if (($name = trim($name)) === '') throw new \RuntimeException('Argument 1 cannot be empty string.'); $this->requestHeaders[$name] = $value; return $this; }
Add a header string to the request @param string $name @param string $value @throws \RuntimeException @throws \InvalidArgumentException @return $this
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L111-L125
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.setCurlOpt
public function setCurlOpt($opt, $val) { if (!is_int($opt)) { throw new \InvalidArgumentException(sprintf( '%s::setCurlOpt - Argument 1 expected to be integer, %s seen.', get_class($this), gettype($opt) )); } $this->curlOpts[$opt] = $val; return $this; }
php
public function setCurlOpt($opt, $val) { if (!is_int($opt)) { throw new \InvalidArgumentException(sprintf( '%s::setCurlOpt - Argument 1 expected to be integer, %s seen.', get_class($this), gettype($opt) )); } $this->curlOpts[$opt] = $val; return $this; }
Set CURL option @link http://www.php.net/manual/en/function.curl-setopt.php @param int $opt curl option @param mixed $val curl option value @throws \InvalidArgumentException @return $this
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L189-L202
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.close
public function close() { if ('resource' === gettype($this->ch)) curl_close($this->ch); $this->state = self::STATE_CLOSED; return $this; }
php
public function close() { if ('resource' === gettype($this->ch)) curl_close($this->ch); $this->state = self::STATE_CLOSED; return $this; }
Close the curl resource, if exists
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L249-L257
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.reset
public function reset() { $this->close(); $this->curlOpts = array(); $this->requestHeaders = array(); $this->currentRequestUrl = null; $this->state = self::STATE_NEW; return $this; }
php
public function reset() { $this->close(); $this->curlOpts = array(); $this->requestHeaders = array(); $this->currentRequestUrl = null; $this->state = self::STATE_NEW; return $this; }
Reset to new state @return $this
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L264-L274
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.curlOptSet
public function curlOptSet($opt) { return isset($this->curlOpts[$opt]) || array_key_exists($opt, $this->curlOpts); }
php
public function curlOptSet($opt) { return isset($this->curlOpts[$opt]) || array_key_exists($opt, $this->curlOpts); }
Returns true if passed in curl option has a value @param int $opt @return bool
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L282-L285
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.execute
public function execute($resetAfterExecution = false) { $this->buildRequest(); $response = new CurlPlusResponse( curl_exec($this->ch), curl_getinfo($this->ch), curl_error($this->ch), $this->getCurlOpts() ); if ($resetAfterExecution) $this->reset(); return $response; }
php
public function execute($resetAfterExecution = false) { $this->buildRequest(); $response = new CurlPlusResponse( curl_exec($this->ch), curl_getinfo($this->ch), curl_error($this->ch), $this->getCurlOpts() ); if ($resetAfterExecution) $this->reset(); return $response; }
Execute CURL command @param bool $resetAfterExecution @throws \RuntimeException @return \DCarbone\CurlPlus\CurlPlusResponse
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L308-L323
dcarbone/curl-plus
src/CurlPlusClient.php
CurlPlusClient.buildRequest
protected function buildRequest() { if (self::STATE_NEW === $this->state) { throw new \RuntimeException(sprintf( '%s::execute - Could not execute request, curl has not been initialized.', get_class($this) )); } if (self::STATE_EXECUTED === $this->state) $this->close(); if (self::STATE_CLOSED === $this->state) $this->initialize($this->currentRequestUrl, false); // Create curl handle resource $this->ch = curl_init($this->currentRequestUrl); if (false === $this->ch) { throw new \RuntimeException(sprintf( 'Unable to initialize curl with url: %s', $this->getRequestUrl() )); } // Set the Header array (if any) if (count($this->requestHeaders) > 0) { $headers = array(); foreach($this->requestHeaders as $k=>$v) { $headers[] = vsprintf('%s: %s', array($k, $v)); } $this->setCurlOpt(CURLOPT_HTTPHEADER, $headers); } // Return the Request Header as part of the curl_info array unless they specify otherwise if (!$this->curlOptSet(CURLINFO_HEADER_OUT)) $this->setCurlOpt(CURLINFO_HEADER_OUT, true); // If the user has opted to return the data, rather than save to file or output directly, // attempt to get headers back in the response for later use if they have not specified // otherwise. if ($this->getCurlOptValue(CURLOPT_RETURNTRANSFER) && !$this->curlOptSet(CURLOPT_HEADER)) $this->setCurlOpt(CURLOPT_HEADER, true); // Set the CURLOPTS if (false === curl_setopt_array($this->ch, $this->curlOpts)) { throw new \RuntimeException(sprintf( 'Unable to specify curl options, please ensure you\'re passing in valid constants. Specified opts: %s', json_encode($this->getCurlOpts()) )); } }
php
protected function buildRequest() { if (self::STATE_NEW === $this->state) { throw new \RuntimeException(sprintf( '%s::execute - Could not execute request, curl has not been initialized.', get_class($this) )); } if (self::STATE_EXECUTED === $this->state) $this->close(); if (self::STATE_CLOSED === $this->state) $this->initialize($this->currentRequestUrl, false); // Create curl handle resource $this->ch = curl_init($this->currentRequestUrl); if (false === $this->ch) { throw new \RuntimeException(sprintf( 'Unable to initialize curl with url: %s', $this->getRequestUrl() )); } // Set the Header array (if any) if (count($this->requestHeaders) > 0) { $headers = array(); foreach($this->requestHeaders as $k=>$v) { $headers[] = vsprintf('%s: %s', array($k, $v)); } $this->setCurlOpt(CURLOPT_HTTPHEADER, $headers); } // Return the Request Header as part of the curl_info array unless they specify otherwise if (!$this->curlOptSet(CURLINFO_HEADER_OUT)) $this->setCurlOpt(CURLINFO_HEADER_OUT, true); // If the user has opted to return the data, rather than save to file or output directly, // attempt to get headers back in the response for later use if they have not specified // otherwise. if ($this->getCurlOptValue(CURLOPT_RETURNTRANSFER) && !$this->curlOptSet(CURLOPT_HEADER)) $this->setCurlOpt(CURLOPT_HEADER, true); // Set the CURLOPTS if (false === curl_setopt_array($this->ch, $this->curlOpts)) { throw new \RuntimeException(sprintf( 'Unable to specify curl options, please ensure you\'re passing in valid constants. Specified opts: %s', json_encode($this->getCurlOpts()) )); } }
Attempts to set up the client for a request, throws an exception if it cannot
https://github.com/dcarbone/curl-plus/blob/7f6b8269c3045eee6e5ade0bff2ca91cb4f58d52/src/CurlPlusClient.php#L328-L383
internetofvoice/libvoice
src/Alexa/Response/Directives/AudioPlayer/ClearQueue.php
ClearQueue.setClearBehavior
public function setClearBehavior($clearBehavior) { if(!in_array($clearBehavior, self::CLEAR_BEHAVIORS)) { throw new InvalidArgumentException('ClearBehavior must be one of ' . implode(', ', self::CLEAR_BEHAVIORS)); } $this->clearBehavior = $clearBehavior; return $this; }
php
public function setClearBehavior($clearBehavior) { if(!in_array($clearBehavior, self::CLEAR_BEHAVIORS)) { throw new InvalidArgumentException('ClearBehavior must be one of ' . implode(', ', self::CLEAR_BEHAVIORS)); } $this->clearBehavior = $clearBehavior; return $this; }
@param string $clearBehavior @return ClearQueue @throws InvalidArgumentException
https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Response/Directives/AudioPlayer/ClearQueue.php#L47-L55
digipolisgent/robo-digipolis-deploy
src/BackupManager/Factory/BackupManagerFactory.php
BackupManagerFactory.create
public static function create($filesystemConfig, $dbConfig) { // Add all default filesystems. $filesystemProvider = FilesystemProviderFactory::create($filesystemConfig); // Add all default databases. $databaseProvider = DatabaseProviderFactory::create($dbConfig); // Add all default compressors. $compressorProvider = CompressorProviderFactory::create(); return new BackupManagerAdapter(new Manager($filesystemProvider, $databaseProvider, $compressorProvider)); }
php
public static function create($filesystemConfig, $dbConfig) { // Add all default filesystems. $filesystemProvider = FilesystemProviderFactory::create($filesystemConfig); // Add all default databases. $databaseProvider = DatabaseProviderFactory::create($dbConfig); // Add all default compressors. $compressorProvider = CompressorProviderFactory::create(); return new BackupManagerAdapter(new Manager($filesystemProvider, $databaseProvider, $compressorProvider)); }
{@inheritdoc}
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/BackupManager/Factory/BackupManagerFactory.php#L14-L26
traderinteractive/filter-bools-php
src/Booleans.php
Booleans.filter
public static function filter( $value, bool $allowNull = false, array $trueValues = ['true'], array $falseValues = ['false'] ) { if (self::valueIsNullAndValid($allowNull, $value)) { return null; } if (is_bool($value)) { return $value; } self::validateAsString($value); $value = trim($value); $value = strtolower($value); return self::validateTrueValuesArray($value, $trueValues, $falseValues); }
php
public static function filter( $value, bool $allowNull = false, array $trueValues = ['true'], array $falseValues = ['false'] ) { if (self::valueIsNullAndValid($allowNull, $value)) { return null; } if (is_bool($value)) { return $value; } self::validateAsString($value); $value = trim($value); $value = strtolower($value); return self::validateTrueValuesArray($value, $trueValues, $falseValues); }
Filters $value to a boolean strictly. $value must be a bool or 'true' or 'false' disregarding case and whitespace. The return value is the bool, as expected by the \TraderInteractive\Filterer class. @param mixed $value the value to filter to a boolean @param bool $allowNull Set to true if NULL values are allowed. The filtered result of a NULL value is NULL @param array $trueValues Array of values which represent the boolean true value. Values should be lower cased @param array $falseValues Array of values which represent the boolean false value. Values should be lower cased @return bool|null the filtered $value @throws FilterException
https://github.com/traderinteractive/filter-bools-php/blob/167002e3c59e85f4bd928c5a85c17aea58a8738f/src/Booleans.php#L31-L51
widoz/template-loader
src/Sanitizer.php
Sanitizer.sanitizePath
public static function sanitizePath($path) { while (false !== strpos($path, '..')) { $path = str_replace('..', '', $path); } $path = ('/' !== $path) ? $path : ''; return $path; }
php
public static function sanitizePath($path) { while (false !== strpos($path, '..')) { $path = str_replace('..', '', $path); } $path = ('/' !== $path) ? $path : ''; return $path; }
Sanitize path @since 2.0.0 @param string $path The path to sanitize @return string The sanitized path.
https://github.com/widoz/template-loader/blob/6fa0f74047505fe7f2f37c76b61f4e2058e22868/src/Sanitizer.php#L47-L56
courtney-miles/schnoop-schema
src/MySQL/DataType/AbstractIntType.php
AbstractIntType.getDDL
public function getDDL() { return implode( ' ', array_filter( [ strtoupper($this->getType()) . ($this->displayWidth > 0 ? '(' . $this->displayWidth .')' : null), !$this->isSigned() ? 'UNSIGNED' : null ] ) ); }
php
public function getDDL() { return implode( ' ', array_filter( [ strtoupper($this->getType()) . ($this->displayWidth > 0 ? '(' . $this->displayWidth .')' : null), !$this->isSigned() ? 'UNSIGNED' : null ] ) ); }
{@inheritdoc}
https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/DataType/AbstractIntType.php#L44-L55
crisu83/yii-consoletools
helpers/ConfigHelper.php
ConfigHelper.merge
public static function merge(array $array) { $result = array(); foreach ($array as $config) { if (is_string($config)) { if (!file_exists($config)) { continue; } $config = require($config); } if (!is_array($config)) { continue; } $result = self::mergeArray($result, $config); } return $result; }
php
public static function merge(array $array) { $result = array(); foreach ($array as $config) { if (is_string($config)) { if (!file_exists($config)) { continue; } $config = require($config); } if (!is_array($config)) { continue; } $result = self::mergeArray($result, $config); } return $result; }
Merges the given configurations into a single configuration array. @param array $array the configurations to merge. @return array the merged configuration.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/helpers/ConfigHelper.php#L20-L36
znframework/package-helpers
Debugger.php
Debugger.parent
public function parent(Int $index = 1) : stdClass { return $this->_layer($this->debug, $index, $index + 1); }
php
public function parent(Int $index = 1) : stdClass { return $this->_layer($this->debug, $index, $index + 1); }
Parent Debug Data @param int $index = 1 @return object
https://github.com/znframework/package-helpers/blob/c78502263cdda5c14626a1abf7fc7e02dd2bd57d/Debugger.php#L52-L55
znframework/package-helpers
Debugger.php
Debugger.output
public function output($type = 'array') { $debug = Arrays\RemoveElement::first($this->debug, 2); $debug = array_merge([(array) $this->current()], $debug); if( is_numeric($type) ) { return (object) ( $debug[$type] ?? $this->_default() ); } elseif( $type === 'array' ) { return $debug; } elseif( $type === 'string' ) { return output($debug, [], true); } else { return $this->_default(); } }
php
public function output($type = 'array') { $debug = Arrays\RemoveElement::first($this->debug, 2); $debug = array_merge([(array) $this->current()], $debug); if( is_numeric($type) ) { return (object) ( $debug[$type] ?? $this->_default() ); } elseif( $type === 'array' ) { return $debug; } elseif( $type === 'string' ) { return output($debug, [], true); } else { return $this->_default(); } }
Output Debug @param mixed $type = 'array' - options[array|string|int value] @return mixed
https://github.com/znframework/package-helpers/blob/c78502263cdda5c14626a1abf7fc7e02dd2bd57d/Debugger.php#L64-L85
znframework/package-helpers
Debugger.php
Debugger._layer
protected function _layer($debug, $layer1 = 0, $layer2 = 1) { $file = $debug[$layer1]['file'] ?? NULL; $line = $debug[$layer1]['line'] ?? NULL; $function = $debug[$layer2]['function'] ?? NULL; $class = $debug[$layer2]['class'] ?? NULL; $args = $debug[$layer2]['args'] ?? NULL; $type = $debug[$layer1]['type'] ?? NULL; $type = str_replace('->', '::', $type); $classSuffix = $type.$function.'()'; $method = $class.$classSuffix; $internalMethod = Classes::onlyName((string) $class).$classSuffix; return (object) [ 'file' => $file, 'line' => $line, 'args' => $args, 'function' => $function, 'class' => $class, 'type' => $type, 'method' => $method, 'internalMethod' => $internalMethod ]; }
php
protected function _layer($debug, $layer1 = 0, $layer2 = 1) { $file = $debug[$layer1]['file'] ?? NULL; $line = $debug[$layer1]['line'] ?? NULL; $function = $debug[$layer2]['function'] ?? NULL; $class = $debug[$layer2]['class'] ?? NULL; $args = $debug[$layer2]['args'] ?? NULL; $type = $debug[$layer1]['type'] ?? NULL; $type = str_replace('->', '::', $type); $classSuffix = $type.$function.'()'; $method = $class.$classSuffix; $internalMethod = Classes::onlyName((string) $class).$classSuffix; return (object) [ 'file' => $file, 'line' => $line, 'args' => $args, 'function' => $function, 'class' => $class, 'type' => $type, 'method' => $method, 'internalMethod' => $internalMethod ]; }
Protected Layer
https://github.com/znframework/package-helpers/blob/c78502263cdda5c14626a1abf7fc7e02dd2bd57d/Debugger.php#L90-L114
crisu83/yii-consoletools
commands/MysqldumpCommand.php
MysqldumpCommand.init
public function init() { parent::init(); $db = $this->getDb(); if (!isset($this->options['user'])) { $this->options['user'] = $db->username; } if (!isset($this->options['password'])) { $this->options['password'] = $db->password; } $parsed = $this->parseConnectionString($db->connectionString); if (!isset($this->options['host'])) { $this->options['host'] = $parsed['hostName']; } if (!isset($this->options['port']) && isset($parsed['port'])) { $this->options['port'] = $parsed['port']; } }
php
public function init() { parent::init(); $db = $this->getDb(); if (!isset($this->options['user'])) { $this->options['user'] = $db->username; } if (!isset($this->options['password'])) { $this->options['password'] = $db->password; } $parsed = $this->parseConnectionString($db->connectionString); if (!isset($this->options['host'])) { $this->options['host'] = $parsed['hostName']; } if (!isset($this->options['port']) && isset($parsed['port'])) { $this->options['port'] = $parsed['port']; } }
Initializes the command.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/MysqldumpCommand.php#L42-L59
crisu83/yii-consoletools
commands/MysqldumpCommand.php
MysqldumpCommand.parseConnectionString
protected function parseConnectionString($connectionString) { $parsed = array(); $_ = explode(":", $connectionString, 2); $parsed["driverName"] = $_[0]; $__ = explode(";", $_[1]); foreach ($__ as $v) { $___ = explode("=", $v); $parsed[$___[0]] = $___[1]; } // For staying true to the original variable names $parsed["hostName"] = $parsed["host"]; $parsed["dbName"] = $parsed["dbname"]; return $parsed; }
php
protected function parseConnectionString($connectionString) { $parsed = array(); $_ = explode(":", $connectionString, 2); $parsed["driverName"] = $_[0]; $__ = explode(";", $_[1]); foreach ($__ as $v) { $___ = explode("=", $v); $parsed[$___[0]] = $___[1]; } // For staying true to the original variable names $parsed["hostName"] = $parsed["host"]; $parsed["dbName"] = $parsed["dbname"]; return $parsed; }
Reversing $this->connectionString = $this->driverName.':host='.$this->hostName.';dbname='.$this->dbName; Ugly but will have to do in short of better options (http://www.yiiframework.com/forum/index.php/topic/7984-where-to-get-the-name-of-the-database/) @param $connectionString
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/MysqldumpCommand.php#L66-L80
crisu83/yii-consoletools
commands/MysqldumpCommand.php
MysqldumpCommand.run
public function run($args) { list($action, $options, $args) = $this->resolveRequest($args); foreach ($options as $key => $value) { if (property_exists($this, $key)) { $this->$key = $value; } } $binPath = $this->resolveBinPath(); $options = $this->normalizeOptions($this->options); $database = $this->resolveDatabaseName(); $dumpPath = $this->resolveDumpPath(); return $this->process( "$binPath $options $database", array( self::DESCRIPTOR_STDIN => array('pipe', 'r'), self::DESCRIPTOR_STDOUT => array('file', $dumpPath, 'w'), self::DESCRIPTOR_STDERR => array('pipe', 'w'), ) ); }
php
public function run($args) { list($action, $options, $args) = $this->resolveRequest($args); foreach ($options as $key => $value) { if (property_exists($this, $key)) { $this->$key = $value; } } $binPath = $this->resolveBinPath(); $options = $this->normalizeOptions($this->options); $database = $this->resolveDatabaseName(); $dumpPath = $this->resolveDumpPath(); return $this->process( "$binPath $options $database", array( self::DESCRIPTOR_STDIN => array('pipe', 'r'), self::DESCRIPTOR_STDOUT => array('file', $dumpPath, 'w'), self::DESCRIPTOR_STDERR => array('pipe', 'w'), ) ); }
Runs the command. @param array $args the command-line arguments. @return integer the return code. @throws CException if the mysqldump binary cannot be located or if the actual dump fails.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/MysqldumpCommand.php#L88-L111
crisu83/yii-consoletools
commands/MysqldumpCommand.php
MysqldumpCommand.resolveDumpPath
protected function resolveDumpPath() { $path = $this->basePath . '/' . $this->dumpPath; $this->ensureDirectory($path); return realpath($path) . '/' . $this->dumpFile; }
php
protected function resolveDumpPath() { $path = $this->basePath . '/' . $this->dumpPath; $this->ensureDirectory($path); return realpath($path) . '/' . $this->dumpFile; }
Returns the path to the dump-file. @return string the path.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/MysqldumpCommand.php#L135-L140
crisu83/yii-consoletools
commands/MysqldumpCommand.php
MysqldumpCommand.normalizeOptions
protected function normalizeOptions($options) { $result = array(); foreach ($options as $name => $value) { $result[] = "--$name=\"$value\""; } return implode(' ', $result); }
php
protected function normalizeOptions($options) { $result = array(); foreach ($options as $name => $value) { $result[] = "--$name=\"$value\""; } return implode(' ', $result); }
Normalizes the given options to a string @param array $options the options. @return string the options.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/MysqldumpCommand.php#L147-L154
crisu83/yii-consoletools
commands/MysqldumpCommand.php
MysqldumpCommand.getDb
protected function getDb() { if (isset($this->_db)) { return $this->_db; } else { if (($db = Yii::app()->getComponent($this->connectionID)) === null) { throw new CException(sprintf( 'Failed to get database connection. Component %s not found.', $this->connectionID )); } return $this->_db = $db; } }
php
protected function getDb() { if (isset($this->_db)) { return $this->_db; } else { if (($db = Yii::app()->getComponent($this->connectionID)) === null) { throw new CException(sprintf( 'Failed to get database connection. Component %s not found.', $this->connectionID )); } return $this->_db = $db; } }
Returns the database connection component. @return CDbConnection the component. @throws CException if the component is not found.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/MysqldumpCommand.php#L161-L174
andyburton/Sonic-Framework
src/Model.php
Model.get
public function get ($name) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If attribute getter isn't set or is disabled if (!$this->attributeGet ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute get is disabled!'); } // If no attribute value is set if (!$this->attributeHasValue ($name)) { // If there is a default set to value if (array_key_exists ('default', static::$attributes[$name])) { $this->iset ($name, static::$attributes[$name]['default'], FALSE); } // Else there is no value and no default else { throw new Exception (get_called_class () . '->' . $name . ' attribute isn\'t set and has no default value!'); } } // Return value return $this->attributeValues[$name]; }
php
public function get ($name) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If attribute getter isn't set or is disabled if (!$this->attributeGet ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute get is disabled!'); } // If no attribute value is set if (!$this->attributeHasValue ($name)) { // If there is a default set to value if (array_key_exists ('default', static::$attributes[$name])) { $this->iset ($name, static::$attributes[$name]['default'], FALSE); } // Else there is no value and no default else { throw new Exception (get_called_class () . '->' . $name . ' attribute isn\'t set and has no default value!'); } } // Return value return $this->attributeValues[$name]; }
Return an attribute value if allowed by attribute getter @param string $name Attribute name @throws Exception @return mixed
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L328-L370
andyburton/Sonic-Framework
src/Model.php
Model.set
public function set ($name, $val, $validate = TRUE) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If attribute setter isn't set or is disabled if (!$this->attributeSet ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute set is disabled!'); } // If we're validating the value if ($validate) { // Set friendly name if one exists $friendlyName = isset (static::$attributes[$name]['name'])? static::$attributes[$name]['name'] : $name; // Validate it using the parser method $this->parser->Validate ($friendlyName, static::$attributes[$name], $val); } // Set the attribute value $this->attributeValues[$name] = $val; }
php
public function set ($name, $val, $validate = TRUE) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If attribute setter isn't set or is disabled if (!$this->attributeSet ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute set is disabled!'); } // If we're validating the value if ($validate) { // Set friendly name if one exists $friendlyName = isset (static::$attributes[$name]['name'])? static::$attributes[$name]['name'] : $name; // Validate it using the parser method $this->parser->Validate ($friendlyName, static::$attributes[$name], $val); } // Set the attribute value $this->attributeValues[$name] = $val; }
Set an attribute value if allowed by attribute setter @param string $name Attribute name @param mixed $val Attribute value @param boolean $validate Whether to validate the value @throws Exception|Parser\Exception @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L382-L418
andyburton/Sonic-Framework
src/Model.php
Model.iget
protected function iget ($name) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If no attribute value is set if (!$this->attributeHasValue ($name)) { // If there is a default set to value if (array_key_exists ('default', static::$attributes[$name])) { $this->iset ($name, static::$attributes[$name]['default'], FALSE); } // Else there is no value and no default else { throw new Exception (get_called_class () . '->' . $name . ' attribute isn\'t set and has no default value!'); } } // Return value return $this->attributeValues[$name]; }
php
protected function iget ($name) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If no attribute value is set if (!$this->attributeHasValue ($name)) { // If there is a default set to value if (array_key_exists ('default', static::$attributes[$name])) { $this->iset ($name, static::$attributes[$name]['default'], FALSE); } // Else there is no value and no default else { throw new Exception (get_called_class () . '->' . $name . ' attribute isn\'t set and has no default value!'); } } // Return value return $this->attributeValues[$name]; }
Return an attribute value (internal) @param string $name Attribute name @throws Exception @return mixed
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L428-L463
andyburton/Sonic-Framework
src/Model.php
Model.iset
protected function iset ($name, $val, $validate = TRUE, $cast = FALSE) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If we're validating the value if ($validate) { // Set friendly name if one exists $friendlyName = isset (static::$attributes[$name]['name'])? static::$attributes[$name]['name'] : $name; // Validate it using the parser method $this->parser->Validate ($friendlyName, static::$attributes[$name], $val); } // Cast the value if ($cast) { $val = $this->cast ($name, $val); } // Set the attribute value $this->attributeValues[$name] = $val; }
php
protected function iset ($name, $val, $validate = TRUE, $cast = FALSE) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If we're validating the value if ($validate) { // Set friendly name if one exists $friendlyName = isset (static::$attributes[$name]['name'])? static::$attributes[$name]['name'] : $name; // Validate it using the parser method $this->parser->Validate ($friendlyName, static::$attributes[$name], $val); } // Cast the value if ($cast) { $val = $this->cast ($name, $val); } // Set the attribute value $this->attributeValues[$name] = $val; }
Set an attribute value (internal) @param string $name Attribute name @param mixed $val Attribute value @param boolean $validate Whether to validate the value @param boolean $cast Whether to cast the value to the attribute datatype @throws Exception|Parser\Exception @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L476-L512
andyburton/Sonic-Framework
src/Model.php
Model.reset
public function reset ($name) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If attribute reset is disabled if (!$this->attributeReset ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute reset is disabled!'); } // If there is no default attribute value remove the value if (!array_key_exists ('default', static::$attributes[$name])) { unset ($this->attributeValues[$name]); } // Else there is a default attribute value so set it else { $this->iset ($name, static::$attributes[$name]['default'], FALSE); } }
php
public function reset ($name) { // If the attribute doesn't exists if (!$this->attributeExists ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute does not exist!'); } // If attribute reset is disabled if (!$this->attributeReset ($name)) { throw new Exception (get_called_class () . '->' . $name . ' attribute reset is disabled!'); } // If there is no default attribute value remove the value if (!array_key_exists ('default', static::$attributes[$name])) { unset ($this->attributeValues[$name]); } // Else there is a default attribute value so set it else { $this->iset ($name, static::$attributes[$name]['default'], FALSE); } }
Reset an attribute value to its default @param string $name Attribute name @throws Exception @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L522-L553
andyburton/Sonic-Framework
src/Model.php
Model.resetPK
public function resetPK ($val = FALSE) { if ($val === FALSE) { $this->reset (static::$pk); } else { $this->attributeValues[static::$pk] = $val; } }
php
public function resetPK ($val = FALSE) { if ($val === FALSE) { $this->reset (static::$pk); } else { $this->attributeValues[static::$pk] = $val; } }
Reset the primary key to default or set to a specific value @param mixed $val Value
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L561-L573
andyburton/Sonic-Framework
src/Model.php
Model.cast
public function cast ($name, $val) { // Ignore if value is null if (is_null ($val)) { return $val; } // Cast value based upon attribute datatype switch (@static::$attributes[$name]['type']) { case self::TYPE_INT: $val = (int)$val; break; case self::TYPE_STRING: $val = (string)$val; break; case self::TYPE_BOOL: $val = (bool)$val; break; case self::TYPE_DECIMAL: $val = (float)$val; break; case self::TYPE_BINARY: $val = (binary)$val; break; } // Return casted value return $val; }
php
public function cast ($name, $val) { // Ignore if value is null if (is_null ($val)) { return $val; } // Cast value based upon attribute datatype switch (@static::$attributes[$name]['type']) { case self::TYPE_INT: $val = (int)$val; break; case self::TYPE_STRING: $val = (string)$val; break; case self::TYPE_BOOL: $val = (bool)$val; break; case self::TYPE_DECIMAL: $val = (float)$val; break; case self::TYPE_BINARY: $val = (binary)$val; break; } // Return casted value return $val; }
Cast a value for an attribute datatype @param string $name Attribute name @param mixed $val Value to cast @return mixed
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L583-L624
andyburton/Sonic-Framework
src/Model.php
Model.create
public function create ($exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') '); // Bind attributes $this->bindAttributes ($query, $exclude); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // Changelog if ($this->changelog ('create')) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('create', static::_Read ($this->iget (static::$pk), $db)); } // return TRUE return TRUE; }
php
public function create ($exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') '); // Bind attributes $this->bindAttributes ($query, $exclude); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // Changelog if ($this->changelog ('create')) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('create', static::_Read ($this->iget (static::$pk), $db)); } // return TRUE return TRUE; }
Create object in the database @param array $exclude Attributes not to set @param \PDO $db Database connection to use, default to master resource @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L634-L686
andyburton/Sonic-Framework
src/Model.php
Model.createOrUpdate
public function createOrUpdate ($update, $exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Generate update values $updateVals = NULL; foreach ($update as $column => $value) { // Add column $updateVals .= ', `' . $column . '` = '; // If the updated value is an array treat first item // as literal query insert and the second a params to bind $updateVals .= is_array ($value)? $value[0] : $value; } // Trim the first character (,) from the update $updateVals = substr ($updateVals, 2); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(' . static::$pk . '), ' . $updateVals . ' '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind update parameters foreach ($update as $value) { if (is_array ($value) && isset ($value[1]) && is_array ($value[1])) { foreach ($value[1] as $column => $newVal) { $query->bindValue ($column, $newVal); } } } // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // return TRUE return TRUE; }
php
public function createOrUpdate ($update, $exclude = array (), &$db = FALSE) { // Get columns and values $create = $this->createColumnsAndValues ($exclude); // Generate update values $updateVals = NULL; foreach ($update as $column => $value) { // Add column $updateVals .= ', `' . $column . '` = '; // If the updated value is an array treat first item // as literal query insert and the second a params to bind $updateVals .= is_array ($value)? $value[0] : $value; } // Trim the first character (,) from the update $updateVals = substr ($updateVals, 2); // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Prepare query $query = $db->prepare (' INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ') VALUES ( ' . $create['values'] . ') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(' . static::$pk . '), ' . $updateVals . ' '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind update parameters foreach ($update as $value) { if (is_array ($value) && isset ($value[1]) && is_array ($value[1])) { foreach ($value[1] as $column => $newVal) { $query->bindValue ($column, $newVal); } } } // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Set the pk if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk)) { $this->iset (static::$pk, $db->lastInsertID ()); } // return TRUE return TRUE; }
Create or update an object in the database if it already exists @param array $update Values to update @param array $exclude Attributes not to set in create @param \PDO $db Database connection to use, default to master resource @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L697-L776
andyburton/Sonic-Framework
src/Model.php
Model.createColumnsAndValues
private function createColumnsAndValues (&$exclude) { // If there is no primary key value exclude it (i.e assume auto increment) if (!$this->attributeHasValue (static::$pk)) { $exclude[] = static::$pk; } // Set column and value variables $columns = NULL; $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute is not set if (!$this->attributeIsset ($name)) { // If there is a default set it if (array_key_exists ('default', $attribute)) { $this->iset ($name, $attribute['default'], FALSE); } // Else if the attribute can be set to NULL then do so else if (isset ($attribute['null']) && $attribute['null']) { $this->iset ($name, NULL, FALSE); } // Else set a blank value else { $this->iset ($name, '', FALSE); } } // Add the column and values $columns .= ', `' . $name . '`'; $values .= ', ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the column and values $columns = substr ($columns, 2); $values = substr ($values, 2); // Return columns and values return array ( 'columns' => $columns, 'values' => $values ); }
php
private function createColumnsAndValues (&$exclude) { // If there is no primary key value exclude it (i.e assume auto increment) if (!$this->attributeHasValue (static::$pk)) { $exclude[] = static::$pk; } // Set column and value variables $columns = NULL; $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute is not set if (!$this->attributeIsset ($name)) { // If there is a default set it if (array_key_exists ('default', $attribute)) { $this->iset ($name, $attribute['default'], FALSE); } // Else if the attribute can be set to NULL then do so else if (isset ($attribute['null']) && $attribute['null']) { $this->iset ($name, NULL, FALSE); } // Else set a blank value else { $this->iset ($name, '', FALSE); } } // Add the column and values $columns .= ', `' . $name . '`'; $values .= ', ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the column and values $columns = substr ($columns, 2); $values = substr ($values, 2); // Return columns and values return array ( 'columns' => $columns, 'values' => $values ); }
Generate create query columns and values @param array $exclude Attribute exclusion array @return array ('columns', 'values')
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L785-L859
andyburton/Sonic-Framework
src/Model.php
Model.transformValue
private function transformValue ($name, $attribute, &$exclude) { // If an attribute can accept NULL and it's value is '' then NULL will be set $value = $this->iget ($name); if (is_null ($value) || (isset ($attribute['null']) && $attribute['null'] && $value === '')) { $this->iset ($name, NULL); $value = 'NULL'; $exclude[] = $name; } else { // Switch special values switch ((string)$value) { case "CURRENT_TIMESTAMP": $value = 'CURRENT_TIMESTAMP'; $exclude[] = $name; break; case 'CURRENT_UTC_DATE': $value = "'" . $this->parser->utcDate () . "'"; $exclude[] = $name; break; default: $value = ':' . $name; break; } } // Return transformed value return $value; }
php
private function transformValue ($name, $attribute, &$exclude) { // If an attribute can accept NULL and it's value is '' then NULL will be set $value = $this->iget ($name); if (is_null ($value) || (isset ($attribute['null']) && $attribute['null'] && $value === '')) { $this->iset ($name, NULL); $value = 'NULL'; $exclude[] = $name; } else { // Switch special values switch ((string)$value) { case "CURRENT_TIMESTAMP": $value = 'CURRENT_TIMESTAMP'; $exclude[] = $name; break; case 'CURRENT_UTC_DATE': $value = "'" . $this->parser->utcDate () . "'"; $exclude[] = $name; break; default: $value = ':' . $name; break; } } // Return transformed value return $value; }
Apply any attribute value transformations for SQL query @param string $name Attribute name @param array $attribute Attribute property array @param array $exclude Attribute exclusion array @return mixed
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L870-L916
andyburton/Sonic-Framework
src/Model.php
Model.bindAttributes
private function bindAttributes (&$query, $exclude = array ()) { // Loop through attributes foreach (array_keys (static::$attributes) as $name) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // Bind paramater $query->bindValue (':' . $name, $this->iget ($name)); } }
php
private function bindAttributes (&$query, $exclude = array ()) { // Loop through attributes foreach (array_keys (static::$attributes) as $name) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // Bind paramater $query->bindValue (':' . $name, $this->iget ($name)); } }
Bind object attribute values to the query @param \PDOStatement $query Query object to bind values to @param array $exclude Attributes to exclude @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L926-L947
andyburton/Sonic-Framework
src/Model.php
Model.executeCreateUpdateQuery
private function executeCreateUpdateQuery (&$query) { // Execute try { $query->execute (); return TRUE; } catch (\PDOException $e) { // Catch some errors switch ($e->getCode ()) { // Duplicate Key case 23000: // Get attribute name and set error if (preg_match ('/Duplicate entry \'(.*?)\' for key \'(.*?)\'/', $e->getMessage (), $match)) { $name = $this->attributeExists ($match[2]) && isset (static::$attributes[$match[2]]['name'])? static::$attributes[$match[2]]['name'] : $match[2]; new Message ('error', 'Please choose another ' . ucwords ($name) . ' `' . $match[1] . '` already exists!'); return FALSE; } // Else unrecognised message so throw the error again else { throw $e; } break; // Throw error by default default: throw $e; } } }
php
private function executeCreateUpdateQuery (&$query) { // Execute try { $query->execute (); return TRUE; } catch (\PDOException $e) { // Catch some errors switch ($e->getCode ()) { // Duplicate Key case 23000: // Get attribute name and set error if (preg_match ('/Duplicate entry \'(.*?)\' for key \'(.*?)\'/', $e->getMessage (), $match)) { $name = $this->attributeExists ($match[2]) && isset (static::$attributes[$match[2]]['name'])? static::$attributes[$match[2]]['name'] : $match[2]; new Message ('error', 'Please choose another ' . ucwords ($name) . ' `' . $match[1] . '` already exists!'); return FALSE; } // Else unrecognised message so throw the error again else { throw $e; } break; // Throw error by default default: throw $e; } } }
Execute create or update query and cope with an exception @param \PDOStatement $query Query object to bind values to @return boolean @throws PDOException
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L957-L1007
andyburton/Sonic-Framework
src/Model.php
Model.read
public function read ($pkValue = FALSE, &$db = FALSE) { try { // If there is a key value passed set it if ($pkValue !== FALSE) { $this->iset (static::$pk, $pkValue); } // Get database slave for read if ($db === FALSE) { $db =& $this->getDbSlave (); } // Prepare query $query = $db->prepare (' SELECT * FROM `' . static::$dbTable . '` WHERE ' . static::$pk . ' = :pk '); // Bind paramater $query->bindValue (':pk', $this->iget (static::$pk)); // Execute $query->execute (); // Set row $row = $query->fetch (\PDO::FETCH_ASSOC); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($this->attributeExists ($name)) { $this->iset ($name, $val, FALSE, TRUE); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); return FALSE; } // Return TRUE return TRUE; }
php
public function read ($pkValue = FALSE, &$db = FALSE) { try { // If there is a key value passed set it if ($pkValue !== FALSE) { $this->iset (static::$pk, $pkValue); } // Get database slave for read if ($db === FALSE) { $db =& $this->getDbSlave (); } // Prepare query $query = $db->prepare (' SELECT * FROM `' . static::$dbTable . '` WHERE ' . static::$pk . ' = :pk '); // Bind paramater $query->bindValue (':pk', $this->iget (static::$pk)); // Execute $query->execute (); // Set row $row = $query->fetch (\PDO::FETCH_ASSOC); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($this->attributeExists ($name)) { $this->iset ($name, $val, FALSE, TRUE); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); return FALSE; } // Return TRUE return TRUE; }
Read an object from the database, populating the object attributes @param mixed $pkValue Primary key value @param \PDO $db Database connection to use, default to slave resource @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1017-L1089
andyburton/Sonic-Framework
src/Model.php
Model.readAttribute
public function readAttribute ($name) { $this->iset ($name, $this->getValue (array ( 'select' => $name, 'where' => array (array (static::$pk, $this->iget (static::$pk))) ))); }
php
public function readAttribute ($name) { $this->iset ($name, $this->getValue (array ( 'select' => $name, 'where' => array (array (static::$pk, $this->iget (static::$pk))) ))); }
Read and set a single object attribute from the database @param string $name Attribute name @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1098-L1104
andyburton/Sonic-Framework
src/Model.php
Model.update
public function update ($exclude = array (), &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Changelog $old = FALSE; if ($this->changelog ('update')) { $old = static::_Read ($this->get (static::$pk), $db); } // Exclude the primary key $exclude[] = static::$pk; // Set value variable $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute has derefresh enabled the refresh value to default for the update if (isset ($attribute['deupdate']) && $attribute['deupdate']) { $this->reset ($name); } // Else if the attribute is not set or is creation only else if (!$this->attributeIsset ($name) || (isset ($attribute['creation']) && $attribute['creation'])) { // Exclude it and move on $exclude[] = $name; continue; } // Add the value $values .= ',`' . $name . '` = ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the values $values = substr ($values, 1); // Prepare query $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $values . ' WHERE ' . static::$pk . ' = :pk '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind pk $query->bindValue (':pk', $this->iget (static::$pk)); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Changelog if ($old) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('update', $old, $this); } // return TRUE return TRUE; }
php
public function update ($exclude = array (), &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Changelog $old = FALSE; if ($this->changelog ('update')) { $old = static::_Read ($this->get (static::$pk), $db); } // Exclude the primary key $exclude[] = static::$pk; // Set value variable $values = NULL; // Loop through attributes foreach (static::$attributes as $name => $attribute) { // If we're excluding the attribute then move on if (in_array ($name, $exclude)) { continue; } // If the attribute has derefresh enabled the refresh value to default for the update if (isset ($attribute['deupdate']) && $attribute['deupdate']) { $this->reset ($name); } // Else if the attribute is not set or is creation only else if (!$this->attributeIsset ($name) || (isset ($attribute['creation']) && $attribute['creation'])) { // Exclude it and move on $exclude[] = $name; continue; } // Add the value $values .= ',`' . $name . '` = ' . $this->transformValue ($name, $attribute, $exclude); } // Trim the first character (,) from the values $values = substr ($values, 1); // Prepare query $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $values . ' WHERE ' . static::$pk . ' = :pk '); // Bind attributes $this->bindAttributes ($query, $exclude); // Bind pk $query->bindValue (':pk', $this->iget (static::$pk)); // Execute if (!$this->executeCreateUpdateQuery ($query)) { return FALSE; } // Changelog if ($old) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('update', $old, $this); } // return TRUE return TRUE; }
Update an object in the database @param array $exclude Attributes not to update @param \PDO $db Database connection to use, default to master resource @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1114-L1219
andyburton/Sonic-Framework
src/Model.php
Model.updateAttribute
public function updateAttribute ($name, $value, &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Changelog $old = FALSE; if ($this->changelog ('update')) { $old = static::_Read ($this->iget (static::$pk), $db); } $this->iset ($name, $value); // Prepare query $exclude = []; $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $name . ' = ' . $this->transformValue ($name, $value, $exclude) . ' WHERE ' . static::$pk . ' = :pk '); // Bind values if (!in_array($name, $exclude)) { $query->bindValue (':' . $name, $this->iget ($name)); } $query->bindValue (':pk', $this->iget (static::$pk)); // Execute if (!$query->execute ()) { return FALSE; } // Changelog if ($old) { // Only update attribute thats changed $exclude = $this->toArray (); unset ($exclude[$name]); $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('update', $old, $this, array_keys ($exclude)); } // Return TRUE return TRUE; }
php
public function updateAttribute ($name, $value, &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // Changelog $old = FALSE; if ($this->changelog ('update')) { $old = static::_Read ($this->iget (static::$pk), $db); } $this->iset ($name, $value); // Prepare query $exclude = []; $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $name . ' = ' . $this->transformValue ($name, $value, $exclude) . ' WHERE ' . static::$pk . ' = :pk '); // Bind values if (!in_array($name, $exclude)) { $query->bindValue (':' . $name, $this->iget ($name)); } $query->bindValue (':pk', $this->iget (static::$pk)); // Execute if (!$query->execute ()) { return FALSE; } // Changelog if ($old) { // Only update attribute thats changed $exclude = $this->toArray (); unset ($exclude[$name]); $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); $log::_Log ('update', $old, $this, array_keys ($exclude)); } // Return TRUE return TRUE; }
Set and update a single object attribute in the database @param string $name Attribute name @param string $value Attribute value @param \PDO $db Database connection to use, default to master resource @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1230-L1295
andyburton/Sonic-Framework
src/Model.php
Model._setValue
public static function _setValue ($pk, $name, $value, &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& self::_getDbMaster (); } if (!($db instanceof \PDO)) { throw new Exception ('Invalid or no database resource set'); } // Prepare query $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $name . ' = :val WHERE ' . static::$pk . ' = :pk '); // Bind values $query->bindValue (':val', $value); $query->bindValue (':pk', $pk); // Execute return $query->execute (); }
php
public static function _setValue ($pk, $name, $value, &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& self::_getDbMaster (); } if (!($db instanceof \PDO)) { throw new Exception ('Invalid or no database resource set'); } // Prepare query $query = $db->prepare (' UPDATE `' . static::$dbTable . '` SET ' . $name . ' = :val WHERE ' . static::$pk . ' = :pk '); // Bind values $query->bindValue (':val', $value); $query->bindValue (':pk', $pk); // Execute return $query->execute (); }
Set and update a single object attribute in the database @param integer $pk Primary key @param string $name Attribute name @param string $value Attribute value @param \PDO $db Database connection to use, default to master resource @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1307-L1339
andyburton/Sonic-Framework
src/Model.php
Model.delete
public function delete ($params = FALSE, &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // If there is no key value passed set to the object id if ($params === FALSE) { $params = array ( 'where' => array ( array (static::$pk, $this->iget (static::$pk)) ) ); } // If the params are not an array assume the variable // is an object pk, and set the parameter array if (!is_array ($params)) { $params = array ( 'where' => array ( array (static::$pk, $params) ) ); } // If there is no where clause if (!isset ($params['where'])) { throw new Exception ('No where clause for ' . get_called_class () . '->delete'); } // Changelog $arrRemove = FALSE; // Get all objects being removed if ($this->changelog ('delete')) { $arrRemove = static::_getObjects (array ('where' => $params['where']), FALSE, $db); } // Prepare query $query = $db->prepare (' DELETE FROM `' . static::$dbTable . '` ' . $db->genClause ('WHERE', $db->genWHERE ($params['where'])) ); // Bind values $db->genBindValues ($query, $params['where']); // Execute $query->execute (); // Changelog if ($arrRemove) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); // Log all removed entries foreach ($arrRemove as $obj) { $log::_Log ('delete', $obj); } } // return TRUE return TRUE; }
php
public function delete ($params = FALSE, &$db = FALSE) { // Get database master for write if ($db === FALSE) { $db =& $this->getDbMaster (); } // If there is no key value passed set to the object id if ($params === FALSE) { $params = array ( 'where' => array ( array (static::$pk, $this->iget (static::$pk)) ) ); } // If the params are not an array assume the variable // is an object pk, and set the parameter array if (!is_array ($params)) { $params = array ( 'where' => array ( array (static::$pk, $params) ) ); } // If there is no where clause if (!isset ($params['where'])) { throw new Exception ('No where clause for ' . get_called_class () . '->delete'); } // Changelog $arrRemove = FALSE; // Get all objects being removed if ($this->changelog ('delete')) { $arrRemove = static::_getObjects (array ('where' => $params['where']), FALSE, $db); } // Prepare query $query = $db->prepare (' DELETE FROM `' . static::$dbTable . '` ' . $db->genClause ('WHERE', $db->genWHERE ($params['where'])) ); // Bind values $db->genBindValues ($query, $params['where']); // Execute $query->execute (); // Changelog if ($arrRemove) { $log =& $this->getResource ('changelog'); $log->hookTransactions ($db); // Log all removed entries foreach ($arrRemove as $obj) { $log::_Log ('delete', $obj); } } // return TRUE return TRUE; }
Delete an object in the database @param array|integer $params Primary key value or parameter array @param \PDO $db Database connection to use, default to master resource @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1349-L1436
andyburton/Sonic-Framework
src/Model.php
Model.hookTransactions
public function hookTransactions (Resource\Db &$parent, Resource\Db &$child = NULL) { // Use default object database resource if none is specified if (!$child) { $child =& $this->getResource ('db'); } /** * We only want to create the hook and begin a transaction on the database * if a transaction has already begun on the database we're hooking onto. */ if ($parent->getTransactionCount () > 0 && $parent->addTransactionHook ($child)) { $child->beginTransaction (); } }
php
public function hookTransactions (Resource\Db &$parent, Resource\Db &$child = NULL) { // Use default object database resource if none is specified if (!$child) { $child =& $this->getResource ('db'); } /** * We only want to create the hook and begin a transaction on the database * if a transaction has already begun on the database we're hooking onto. */ if ($parent->getTransactionCount () > 0 && $parent->addTransactionHook ($child)) { $child->beginTransaction (); } }
Hook any database queries into another database transaction so that the queries are commited and rolled back at the same point @param \Sonic\Resource\Db $parent Parent database This is the database resource that is hooked and passes transaction state to the child database @param \Sonic\Resource\Db $child Child database This is the datababase resource that hooks onto the parent and has its transaction state copied from the parent Defaults to object 'db' connection resource
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1449-L1469
andyburton/Sonic-Framework
src/Model.php
Model.toXML
public function toXML ($attributes = FALSE) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); // Create DOMDocument $doc = new \DOMDocument ('1.0', 'UTF-8'); // Create root node $node = $doc->createElement ($class); $doc->appendChild ($node); // Get array $arr = $this->toArray ($attributes); // Set each attribute foreach ($arr as $name => $val) { $node->appendChild ($doc->createElement (strtolower ($name), htmlentities ($val))); } // Return doc return $doc; }
php
public function toXML ($attributes = FALSE) { // Set class name for the elements // Remove the Sonic\Model prefix and convert namespace \ to _ $class = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); // Create DOMDocument $doc = new \DOMDocument ('1.0', 'UTF-8'); // Create root node $node = $doc->createElement ($class); $doc->appendChild ($node); // Get array $arr = $this->toArray ($attributes); // Set each attribute foreach ($arr as $name => $val) { $node->appendChild ($doc->createElement (strtolower ($name), htmlentities ($val))); } // Return doc return $doc; }
Return a DOM tree with object attributes @param array|boolean $attributes Attributes to include, default to false i.e all attributes @return \DOMDocument|boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1478-L1510
andyburton/Sonic-Framework
src/Model.php
Model.toJSON
public function toJSON ($attributes = FALSE, $addClass = FALSE) { // Get array $arr = $this->toArray ($attributes); // Add the class name if required if ($addClass) { $arr['class'] = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); } // Return json encoded return json_encode ($arr); }
php
public function toJSON ($attributes = FALSE, $addClass = FALSE) { // Get array $arr = $this->toArray ($attributes); // Add the class name if required if ($addClass) { $arr['class'] = str_replace ('\\', '_', str_replace ('sonic\\model\\', '', strtolower (get_called_class ()))); } // Return json encoded return json_encode ($arr); }
Return a JSON encoded string with object attributes @param array|boolean $attributes Attributes to include, default to false i.e all attributes @param boolean $addClass Whether to add the class name to each exported object @return object|boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1520-L1538
andyburton/Sonic-Framework
src/Model.php
Model.toArray
public function toArray ($attributes = FALSE, $relations = array (), $recursive = FALSE) { // If no attributes are set to display, get all object attributes with get allowed if ($attributes === FALSE) { $attributes = array (); foreach (array_keys (static::$attributes) as $name) { if ($this->attributeGet ($name)) { $attributes[] = $name; } } } // Set array $arr = array (); // Set each attribute foreach ($attributes as $name) { try { $arr[$name] = $this->get ($name); } catch (Exception $e) { $arr[$name] = NULL; } } // Get any related attributes if ($relations) { foreach ($relations as $name => $relation) { // Remove first \ from class if ($relation[0][0] == '\\') { $relation[0] = substr ($relation[0], 1); } // If the first value exists as a class name // Get object and attribute value if (class_exists ($relation[0])) { $obj = $this->getRelated ($relation[0]); $arr[$name] = $obj? $obj->get ($relation[1]) : ''; } // Else switch first item of relation array else { switch ($relation[0]) { // Object method case '$this': $args = isset ($relation[2])? $relation[2] : array (); $arr[$name] = call_user_func_array (array ($this, $relation[1]), $args); break; // Related object case 'related': $args = isset ($relation[2])? $relation[2] : FALSE; $obj = $this->getRelated ($relation[1]); $arr[$name] = $obj? $obj->toArray ($args) : ''; break; // Child objects case 'children': $args = isset ($relation[2])? $relation[2] : FALSE; $obj = isset ($relation[3])? $this->getChildren ($relation[1], FALSE, FALSE, $relation[3]) : $this->getChildren ($relation[1]); $arr[$name] = $obj? $obj->toArray ($args) : ''; break; // Anything else // Pass directly to call_user_func_array default: $args = isset ($relation[2])? $relation[2] : array (); $arr[$name] = call_user_func_array (array ($relation[0], $relation[1]), $args); break; } } } } // Output recursively if ($recursive) { if (isset ($this->children)) { $arr['children'] = $this->children->toArray ($attributes, $relations, $recursive); } else { $arr['children'] = array (); } } // Return array return $arr; }
php
public function toArray ($attributes = FALSE, $relations = array (), $recursive = FALSE) { // If no attributes are set to display, get all object attributes with get allowed if ($attributes === FALSE) { $attributes = array (); foreach (array_keys (static::$attributes) as $name) { if ($this->attributeGet ($name)) { $attributes[] = $name; } } } // Set array $arr = array (); // Set each attribute foreach ($attributes as $name) { try { $arr[$name] = $this->get ($name); } catch (Exception $e) { $arr[$name] = NULL; } } // Get any related attributes if ($relations) { foreach ($relations as $name => $relation) { // Remove first \ from class if ($relation[0][0] == '\\') { $relation[0] = substr ($relation[0], 1); } // If the first value exists as a class name // Get object and attribute value if (class_exists ($relation[0])) { $obj = $this->getRelated ($relation[0]); $arr[$name] = $obj? $obj->get ($relation[1]) : ''; } // Else switch first item of relation array else { switch ($relation[0]) { // Object method case '$this': $args = isset ($relation[2])? $relation[2] : array (); $arr[$name] = call_user_func_array (array ($this, $relation[1]), $args); break; // Related object case 'related': $args = isset ($relation[2])? $relation[2] : FALSE; $obj = $this->getRelated ($relation[1]); $arr[$name] = $obj? $obj->toArray ($args) : ''; break; // Child objects case 'children': $args = isset ($relation[2])? $relation[2] : FALSE; $obj = isset ($relation[3])? $this->getChildren ($relation[1], FALSE, FALSE, $relation[3]) : $this->getChildren ($relation[1]); $arr[$name] = $obj? $obj->toArray ($args) : ''; break; // Anything else // Pass directly to call_user_func_array default: $args = isset ($relation[2])? $relation[2] : array (); $arr[$name] = call_user_func_array (array ($relation[0], $relation[1]), $args); break; } } } } // Output recursively if ($recursive) { if (isset ($this->children)) { $arr['children'] = $this->children->toArray ($attributes, $relations, $recursive); } else { $arr['children'] = array (); } } // Return array return $arr; }
Return an array with object attributes @param array|boolean $attributes Attributes to include, default to false i.e all attributes @param array $relations Array of related object attributes or tranformed method attributes to return e.g. related value - 'key' => array ('\Sonic\Model\User\Group', 'name') e.g. related object - 'key' => array ('related', '\Sonic\Model\User\Group', array (toArray params)) e.g. related children - 'key' => array ('children', '\Sonic\Model\User\Group', array (toArray params)) e.g. object tranformed value - 'key' => array ('$this', 'getStringValue', array (args)) e.g. class tranformed value - 'key' => array ('self', '_getStringValue', array (args)) e.g. static tranformed value - 'key' => array ('static', '_getStringValue', array (args)) e.g. parent tranformed value - 'key' => array ('parent', '_getStringValue', array (args)) @param integer $recursive Output array recursively, so any $this->children also get output @return object|boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1556-L1697
andyburton/Sonic-Framework
src/Model.php
Model.fromPost
public function fromPost ($validate = TRUE, $required = array (), $valid = array ()) { // By default allow all attributes except pk if (!$valid) { $valid = array_keys (static::$attributes); if (($key = array_search (static::$pk, $valid)) !== FALSE) { unset ($valid[$key]); } } $this->fromArray ($_POST, TRUE, $validate, $required, $valid); }
php
public function fromPost ($validate = TRUE, $required = array (), $valid = array ()) { // By default allow all attributes except pk if (!$valid) { $valid = array_keys (static::$attributes); if (($key = array_search (static::$pk, $valid)) !== FALSE) { unset ($valid[$key]); } } $this->fromArray ($_POST, TRUE, $validate, $required, $valid); }
Populate object attributes from a post array Attribute names need to be in the format ClassName_AttributeName in $_POST @param boolean $validate Validate attributes during set @param array $required Required attributes @param array $valid Valid attributes to set @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1709-L1725
andyburton/Sonic-Framework
src/Model.php
Model.fromArray
public function fromArray ($attributes, $removeClass = FALSE, $validate = TRUE, $required = array (), $valid = array ()) { // Remove class prefix if ($removeClass) { // Set attributes to set $arr = array (); // Get class name $class = strtolower ($this->getClass ()); // Loop through attributes and add any that exist with the class name foreach (array_keys (static::$attributes) as $name) { if (isset ($attributes[$class . '_' . strtolower ($name)])) { $arr[$name] = $attributes[$class . '_' . $name]; } } // Set attributes $attributes = $arr; } // If we have an array of valid attributes to set // Remove any that arent valid if ($valid) { foreach (array_keys ($attributes) as $name) { if (!in_array ($name, $valid, TRUE)) { unset ($attributes[$name]); } } } // Set each attribute try { foreach ($attributes as $name => $val) { if ($this->attributeExists ($name) && $this->attributeSet ($name)) { $this->set ($name, $val, $validate); } if (($key = array_search ($name, $required, TRUE)) !== FALSE) { unset ($required[$key]); } } // Error if there are required fields that have not been set if (count ($required) > 0) { foreach ($required as $name) { if ($this->attributeExists ($name) && isset (static::$attributes[$name]['name'])) { $name = static::$attributes[$name]['name']; } $word = in_array (strtoupper ($name[0]), array ('A', 'E', 'I', 'O'))? 'an' : 'a'; new Message ('error', 'You have not entered ' . $word . ' ' . ucwords ($name)); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); } }
php
public function fromArray ($attributes, $removeClass = FALSE, $validate = TRUE, $required = array (), $valid = array ()) { // Remove class prefix if ($removeClass) { // Set attributes to set $arr = array (); // Get class name $class = strtolower ($this->getClass ()); // Loop through attributes and add any that exist with the class name foreach (array_keys (static::$attributes) as $name) { if (isset ($attributes[$class . '_' . strtolower ($name)])) { $arr[$name] = $attributes[$class . '_' . $name]; } } // Set attributes $attributes = $arr; } // If we have an array of valid attributes to set // Remove any that arent valid if ($valid) { foreach (array_keys ($attributes) as $name) { if (!in_array ($name, $valid, TRUE)) { unset ($attributes[$name]); } } } // Set each attribute try { foreach ($attributes as $name => $val) { if ($this->attributeExists ($name) && $this->attributeSet ($name)) { $this->set ($name, $val, $validate); } if (($key = array_search ($name, $required, TRUE)) !== FALSE) { unset ($required[$key]); } } // Error if there are required fields that have not been set if (count ($required) > 0) { foreach ($required as $name) { if ($this->attributeExists ($name) && isset (static::$attributes[$name]['name'])) { $name = static::$attributes[$name]['name']; } $word = in_array (strtoupper ($name[0]), array ('A', 'E', 'I', 'O'))? 'an' : 'a'; new Message ('error', 'You have not entered ' . $word . ' ' . ucwords ($name)); } } } // Set errors as framework messages catch (Resource\Parser\Exception $e) { new Message ('error', $e->getMessage ()); } }
Populate object attributes from an array @param array $attributes Attributes array @param boolean $removeClass Remove class prefix from the attribute name @param boolean $validate Validate attributes during set @param array $required Required attributes @param array $valid Valid attributes to set @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1738-L1840
andyburton/Sonic-Framework
src/Model.php
Model.getRelated
public function getRelated ($class, $fork = array (), $params = array ()) { // Get the tree paths to the required class $paths = self::_getRelationPaths ($class, $fork); // If there are no paths return FALSE if (!$paths) { return FALSE; } // Get the shortest path to the required class $path = self::_getShortestPath ($paths); // Return the related object return self::_getRelation ($this, $path, $params); }
php
public function getRelated ($class, $fork = array (), $params = array ()) { // Get the tree paths to the required class $paths = self::_getRelationPaths ($class, $fork); // If there are no paths return FALSE if (!$paths) { return FALSE; } // Get the shortest path to the required class $path = self::_getShortestPath ($paths); // Return the related object return self::_getRelation ($this, $path, $params); }
Return the specified object that is related to the current object e.g. the following would return a Sonic\Model\C object that is indirectly linked to the Sonic\Model\A class though Sonic\Model\B $c = $a->getRelated ('Sonic\Model\C'); @param string $class The object type to return @param array $fork Can be used to set which attribute to use when you have multiple attributes in the same object related to the same class. e.g. If Sonic\Model\B had attributes c1 and c2, both related to Sonic\Model\C, the example above would use the first by default. To specifically set c2 you would pass $fork = array ('Sonic\Model\B' => 'c2'); Multiple classes and attributes can be listed in fork to decide which attribute to use for each class. @param array $params Query parameter array @return object|boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1857-L1879
andyburton/Sonic-Framework
src/Model.php
Model.getChildren
public function getChildren ($class, $recursive = FALSE, $index = FALSE, $key = FALSE, $params = array ()) { // Get children $children = self::_getChildren ($class, $this->iget (self::$pk), $recursive, $key, $params); // If we want the indexes if ($index) { $children = static::_getChildrenIndex ($children); } return $children; }
php
public function getChildren ($class, $recursive = FALSE, $index = FALSE, $key = FALSE, $params = array ()) { // Get children $children = self::_getChildren ($class, $this->iget (self::$pk), $recursive, $key, $params); // If we want the indexes if ($index) { $children = static::_getChildrenIndex ($children); } return $children; }
Return child objects matching class type @param string $class Child class type @param boolean $recursive Whether to load childrens children. This will create an object attribute called 'children' on all objects @param boolean $index Return indexed child array rather than object array @param string $key Attribute to use as array key @param array $params Query parameter array @return array|boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1893-L1909
andyburton/Sonic-Framework
src/Model.php
Model.getValue
public function getValue ($params, $fetchMode = \PDO::FETCH_ASSOC, &$db = FALSE) { // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } // Set table $params['from'] = '`' . static::$dbTable . '`'; // Return value return $db->getValue ($params, $fetchMode); }
php
public function getValue ($params, $fetchMode = \PDO::FETCH_ASSOC, &$db = FALSE) { // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } // Set table $params['from'] = '`' . static::$dbTable . '`'; // Return value return $db->getValue ($params, $fetchMode); }
Return a single row @param array $params Parameter array @param int $fetchMode PDO fetch mode, default to assoc @param \PDO $db Database connection to use, default to slave resource @return mixed
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1920-L1938
andyburton/Sonic-Framework
src/Model.php
Model.getValues
public function getValues ($params, &$db = FALSE) { // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } // Set table $params['from'] = '`' . static::$dbTable . '`'; // Return value return $db->getValues ($params); }
php
public function getValues ($params, &$db = FALSE) { // Get database slave for read if ($db === FALSE) { $db =& self::_getDbSlave (); } // Set table $params['from'] = '`' . static::$dbTable . '`'; // Return value return $db->getValues ($params); }
Return all rows @param array $params Parameter array @param \PDO $db Database connection to use, default to slave resource @return mixed
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1948-L1966
andyburton/Sonic-Framework
src/Model.php
Model.&
public function &getDbMaster () { // Get the default master $obj =& $this->getResource ('db-master'); // Failing that try to get a random master if (!$obj) { $obj =& self::_getRandomDbResource ('db-master'); // Default to database resource if no valid master if (!$obj) { $obj =& $this->getResource ('db'); } // Set object master to use in the future $this->setResourceObj ('db-master', $obj); } // Return database connection return $obj; }
php
public function &getDbMaster () { // Get the default master $obj =& $this->getResource ('db-master'); // Failing that try to get a random master if (!$obj) { $obj =& self::_getRandomDbResource ('db-master'); // Default to database resource if no valid master if (!$obj) { $obj =& $this->getResource ('db'); } // Set object master to use in the future $this->setResourceObj ('db-master', $obj); } // Return database connection return $obj; }
Return database master @return \PDO
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L1974-L2005
andyburton/Sonic-Framework
src/Model.php
Model.&
public function &getDbSlave () { // Get the default slave $obj =& $this->getResource ('db-slave'); // Failing that try to get a random slave if (!$obj) { $obj =& self::_getRandomDbResource ('db-slave'); // Default to database resource if no valid slave if (!$obj) { $obj =& $this->getResource ('db'); } // Set object slave to use in the future $this->setResourceObj ('db-slave', $obj); } // Return database connection return $obj; }
php
public function &getDbSlave () { // Get the default slave $obj =& $this->getResource ('db-slave'); // Failing that try to get a random slave if (!$obj) { $obj =& self::_getRandomDbResource ('db-slave'); // Default to database resource if no valid slave if (!$obj) { $obj =& $this->getResource ('db'); } // Set object slave to use in the future $this->setResourceObj ('db-slave', $obj); } // Return database connection return $obj; }
Return database slave @return \PDO
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2013-L2044
andyburton/Sonic-Framework
src/Model.php
Model.&
public function &getResource ($name) { // If the resource is not set if (!isset ($this->resources[$name])) { // Return FALSE $bln = FALSE; return $bln; } // Return resource reference return $this->resources[$name]; }
php
public function &getResource ($name) { // If the resource is not set if (!isset ($this->resources[$name])) { // Return FALSE $bln = FALSE; return $bln; } // Return resource reference return $this->resources[$name]; }
Return a class resource reference @param string $name Resource name @return object|boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2053-L2072
andyburton/Sonic-Framework
src/Model.php
Model.setResource
public function setResource ($name, $resource) { // Get the resource $obj =& Sonic::getResource ($resource); if (!$obj) { return FALSE; } // Set resource object $this->setResourceObj ($name, $obj); // Return return TRUE; }
php
public function setResource ($name, $resource) { // Get the resource $obj =& Sonic::getResource ($resource); if (!$obj) { return FALSE; } // Set resource object $this->setResourceObj ($name, $obj); // Return return TRUE; }
Set an internal resource from a framework resource @param string $name Resource name @param string|array $resource Framework resource referece @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2082-L2102
andyburton/Sonic-Framework
src/Model.php
Model.setResourceObj
public function setResourceObj ($name, &$resource) { // Set the resource $this->resources[$name] =& $resource; // If the object variable exists if (isset ($this->$name)) { // Assign to object variable $this->$name =& $this->resources[$name]; } }
php
public function setResourceObj ($name, &$resource) { // Set the resource $this->resources[$name] =& $resource; // If the object variable exists if (isset ($this->$name)) { // Assign to object variable $this->$name =& $this->resources[$name]; } }
Set a class resource from the resource object @param string $name Resource name @param object $resource Resource object @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2112-L2130
andyburton/Sonic-Framework
src/Model.php
Model.removeResource
public function removeResource ($name) { if (isset ($this->resources[$name])) { unset ($this->resources[$name]); if (isset ($this->$name)) { unset ($this->$name); } } }
php
public function removeResource ($name) { if (isset ($this->resources[$name])) { unset ($this->resources[$name]); if (isset ($this->$name)) { unset ($this->$name); } } }
Remove a class resource @param string $name Resource name @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2139-L2154
andyburton/Sonic-Framework
src/Model.php
Model.removeResources
public function removeResources () { foreach (array_keys ($this->resources) as $name) { if (isset ($this->$name)) { unset ($this->$name); } } unset ($this->resources); }
php
public function removeResources () { foreach (array_keys ($this->resources) as $name) { if (isset ($this->$name)) { unset ($this->$name); } } unset ($this->resources); }
Remove all class resources @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2162-L2175
andyburton/Sonic-Framework
src/Model.php
Model._attributeProperties
public static function _attributeProperties ($name, $property = FALSE) { // If the attribute exists if (isset (static::$attributes[$name])) { // If a property is specified if ($property) { // If the property doesnt exist if (!isset (static::$attributes[$name][$property])) { return FALSE; } // Return property return static::$attributes[$name][$property]; } // Return attribute return static::$attributes[$name]; } // Return FALSE return FALSE; }
php
public static function _attributeProperties ($name, $property = FALSE) { // If the attribute exists if (isset (static::$attributes[$name])) { // If a property is specified if ($property) { // If the property doesnt exist if (!isset (static::$attributes[$name][$property])) { return FALSE; } // Return property return static::$attributes[$name][$property]; } // Return attribute return static::$attributes[$name]; } // Return FALSE return FALSE; }
Return an attribute parameters array or FALSE if it doesnt exist Also pass option property array to return a single attribute property @param string $name Attribute name @param string $property Attribute property @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2258-L2294
andyburton/Sonic-Framework
src/Model.php
Model._read
public static function _read ($params, &$db = FALSE) { // Create the object $obj = new static; // If the params are an array if (is_array ($params)) { // Select all $params['select'] = '*'; // Get data $row = static::_getValue ($params, \PDO::FETCH_ASSOC, $db); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($obj->attributeExists ($name)) { $obj->iset ($name, $val); } } } // Else the params are not an array, so assume pk else { // Read the object if (!$obj->read ($params, $db)) { return FALSE; } } // Return the object return $obj; }
php
public static function _read ($params, &$db = FALSE) { // Create the object $obj = new static; // If the params are an array if (is_array ($params)) { // Select all $params['select'] = '*'; // Get data $row = static::_getValue ($params, \PDO::FETCH_ASSOC, $db); // If no data was returned return FALSE if (!$row) { return FALSE; } // Set each attribute value foreach ($row as $name => $val) { if ($obj->attributeExists ($name)) { $obj->iset ($name, $val); } } } // Else the params are not an array, so assume pk else { // Read the object if (!$obj->read ($params, $db)) { return FALSE; } } // Return the object return $obj; }
Create a new object instance and read it from the database, populating the object attributes @param mixed $params Object to read. This can be an instance ID or a parameter array. @param \PDO $db Database connection to use @return \Sonic\Model
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model.php#L2373-L2432