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
as3io/modlr
src/Rest/RestRequest.php
RestRequest.parse
private function parse($uri) { $this->parsedUri = parse_url($uri); if (false === strstr($this->parsedUri['path'], $this->config->getRootEndpoint())) { throw RestException::invalidEndpoint($this->parsedUri['path']); } $this->adjustRootEndpoint($this->parsedUri['path']); $this->parsedUri['path'] = str_replace($this->config->getRootEndpoint(), '', $this->parsedUri['path']); $this->parsePath($this->parsedUri['path']); $this->parsedUri['query'] = isset($this->parsedUri['query']) ? $this->parsedUri['query'] : ''; $this->parseQueryString($this->parsedUri['query']); return $this; }
php
private function parse($uri) { $this->parsedUri = parse_url($uri); if (false === strstr($this->parsedUri['path'], $this->config->getRootEndpoint())) { throw RestException::invalidEndpoint($this->parsedUri['path']); } $this->adjustRootEndpoint($this->parsedUri['path']); $this->parsedUri['path'] = str_replace($this->config->getRootEndpoint(), '', $this->parsedUri['path']); $this->parsePath($this->parsedUri['path']); $this->parsedUri['query'] = isset($this->parsedUri['query']) ? $this->parsedUri['query'] : ''; $this->parseQueryString($this->parsedUri['query']); return $this; }
Parses the incoming request URI/URL and sets the appropriate properties on this RestRequest object. @param string $uri @return self @throws RestException
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L554-L571
as3io/modlr
src/Rest/RestRequest.php
RestRequest.parsePath
private function parsePath($path) { $parts = explode('/', trim($path, '/')); for ($i = 0; $i < 1; $i++) { // All paths must contain /{workspace_entityType} if (false === $this->issetNotEmpty($i, $parts)) { throw RestException::invalidEndpoint($path); } } $this->extractEntityType($parts); $this->extractIdentifier($parts); $this->extractRelationship($parts); return $this; }
php
private function parsePath($path) { $parts = explode('/', trim($path, '/')); for ($i = 0; $i < 1; $i++) { // All paths must contain /{workspace_entityType} if (false === $this->issetNotEmpty($i, $parts)) { throw RestException::invalidEndpoint($path); } } $this->extractEntityType($parts); $this->extractIdentifier($parts); $this->extractRelationship($parts); return $this; }
Parses the incoming request path and sets appropriate properties on this RestRequest object. @param string $path @return self @throws RestException
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L580-L593
as3io/modlr
src/Rest/RestRequest.php
RestRequest.extractRelationship
private function extractRelationship(array $parts) { if (isset($parts[2])) { if ('relationships' === $parts[2]) { if (!isset($parts[3])) { throw RestException::invalidRelationshipEndpoint($this->parsedUri['path']); } $this->relationship = [ 'type' => 'self', 'field' => $parts[3], ]; } else { $this->relationship = [ 'type' => 'related', 'field' => $parts[2], ]; } } return $this; }
php
private function extractRelationship(array $parts) { if (isset($parts[2])) { if ('relationships' === $parts[2]) { if (!isset($parts[3])) { throw RestException::invalidRelationshipEndpoint($this->parsedUri['path']); } $this->relationship = [ 'type' => 'self', 'field' => $parts[3], ]; } else { $this->relationship = [ 'type' => 'related', 'field' => $parts[2], ]; } } return $this; }
Extracts the entity relationship properties from an array of path parts. @param array $parts @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L627-L646
as3io/modlr
src/Rest/RestRequest.php
RestRequest.parseQueryString
private function parseQueryString($queryString) { parse_str($queryString, $parsed); $supported = $this->getSupportedParams(); foreach ($parsed as $param => $value) { if (!isset($supported[$param])) { throw RestException::unsupportedQueryParam($param, array_keys($supported)); } } $this->extractInclusions($parsed); $this->extractSorting($parsed); $this->extractFields($parsed); $this->extractPagination($parsed); $this->extractFilters($parsed); return $this; }
php
private function parseQueryString($queryString) { parse_str($queryString, $parsed); $supported = $this->getSupportedParams(); foreach ($parsed as $param => $value) { if (!isset($supported[$param])) { throw RestException::unsupportedQueryParam($param, array_keys($supported)); } } $this->extractInclusions($parsed); $this->extractSorting($parsed); $this->extractFields($parsed); $this->extractPagination($parsed); $this->extractFilters($parsed); return $this; }
Parses the incoming request query string and sets appropriate properties on this RestRequest object. @param string $queryString @return self @throws RestException
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L655-L672
as3io/modlr
src/Rest/RestRequest.php
RestRequest.extractInclusions
private function extractInclusions(array $params) { if (false === $this->issetNotEmpty(self::PARAM_INCLUSIONS, $params)) { if (true === $this->config->includeAllByDefault()) { $this->inclusions = ['*' => true]; } return $this; } $inclusions = explode(',', $params[self::PARAM_INCLUSIONS]); foreach ($inclusions as $inclusion) { if (false !== stristr($inclusion, '.')) { throw RestException::invalidParamValue(self::PARAM_INCLUSIONS, sprintf('Inclusion via a relationship path, e.g. "%s" is currently not supported.', $inclusion)); } $this->inclusions[$inclusion] = true; } return $this; }
php
private function extractInclusions(array $params) { if (false === $this->issetNotEmpty(self::PARAM_INCLUSIONS, $params)) { if (true === $this->config->includeAllByDefault()) { $this->inclusions = ['*' => true]; } return $this; } $inclusions = explode(',', $params[self::PARAM_INCLUSIONS]); foreach ($inclusions as $inclusion) { if (false !== stristr($inclusion, '.')) { throw RestException::invalidParamValue(self::PARAM_INCLUSIONS, sprintf('Inclusion via a relationship path, e.g. "%s" is currently not supported.', $inclusion)); } $this->inclusions[$inclusion] = true; } return $this; }
Extracts relationship inclusions from an array of query params. @param array $params @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L680-L696
as3io/modlr
src/Rest/RestRequest.php
RestRequest.extractSorting
private function extractSorting(array $params) { if (false === $this->issetNotEmpty(self::PARAM_SORTING, $params)) { return $this; } $sort = explode(',', $params[self::PARAM_SORTING]); $this->sorting = []; foreach ($sort as $field) { $direction = 1; if (0 === strpos($field, '-')) { $direction = -1; $field = str_replace('-', '', $field); } $this->sorting[$field] = $direction; } return $this; }
php
private function extractSorting(array $params) { if (false === $this->issetNotEmpty(self::PARAM_SORTING, $params)) { return $this; } $sort = explode(',', $params[self::PARAM_SORTING]); $this->sorting = []; foreach ($sort as $field) { $direction = 1; if (0 === strpos($field, '-')) { $direction = -1; $field = str_replace('-', '', $field); } $this->sorting[$field] = $direction; } return $this; }
Extracts sorting criteria from an array of query params. @param array $params @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L704-L720
as3io/modlr
src/Rest/RestRequest.php
RestRequest.extractFields
private function extractFields(array $params) { if (false === $this->issetNotEmpty(self::PARAM_FIELDSETS, $params)) { return $this; } $fields = $params[self::PARAM_FIELDSETS]; if (!is_array($fields)) { throw RestException::invalidQueryParam(self::PARAM_FIELDSETS, 'The field parameter must be an array of entity type keys to fields.'); } foreach ($fields as $entityType => $string) { $this->fields[$entityType] = explode(',', $string); } return $this; }
php
private function extractFields(array $params) { if (false === $this->issetNotEmpty(self::PARAM_FIELDSETS, $params)) { return $this; } $fields = $params[self::PARAM_FIELDSETS]; if (!is_array($fields)) { throw RestException::invalidQueryParam(self::PARAM_FIELDSETS, 'The field parameter must be an array of entity type keys to fields.'); } foreach ($fields as $entityType => $string) { $this->fields[$entityType] = explode(',', $string); } return $this; }
Extracts fields to return from an array of query params. @param array $params @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L728-L741
as3io/modlr
src/Rest/RestRequest.php
RestRequest.extractPagination
private function extractPagination(array $params) { if (false === $this->issetNotEmpty(self::PARAM_PAGINATION, $params)) { return $this; } $page = $params[self::PARAM_PAGINATION]; if (!is_array($page) || !isset($page['limit'])) { throw RestException::invalidQueryParam(self::PARAM_PAGINATION, 'The page parameter must be an array containing at least a limit.'); } $this->pagination = [ 'offset' => isset($page['offset']) ? (Integer) $page['offset'] : 0, 'limit' => (Integer) $page['limit'], ]; return $this; }
php
private function extractPagination(array $params) { if (false === $this->issetNotEmpty(self::PARAM_PAGINATION, $params)) { return $this; } $page = $params[self::PARAM_PAGINATION]; if (!is_array($page) || !isset($page['limit'])) { throw RestException::invalidQueryParam(self::PARAM_PAGINATION, 'The page parameter must be an array containing at least a limit.'); } $this->pagination = [ 'offset' => isset($page['offset']) ? (Integer) $page['offset'] : 0, 'limit' => (Integer) $page['limit'], ]; return $this; }
Extracts pagination criteria from an array of query params. @param array $params @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L749-L763
as3io/modlr
src/Rest/RestRequest.php
RestRequest.extractFilters
private function extractFilters(array $params) { if (false === $this->issetNotEmpty(self::PARAM_FILTERING, $params)) { return $this; } $filters = $params[self::PARAM_FILTERING]; if (!is_array($filters)) { throw RestException::invalidQueryParam(self::PARAM_FILTERING, 'The filter parameter must be an array keyed by filter name and value.'); } foreach ($filters as $key => $value) { $this->filters[$key] = $value; } return $this; }
php
private function extractFilters(array $params) { if (false === $this->issetNotEmpty(self::PARAM_FILTERING, $params)) { return $this; } $filters = $params[self::PARAM_FILTERING]; if (!is_array($filters)) { throw RestException::invalidQueryParam(self::PARAM_FILTERING, 'The filter parameter must be an array keyed by filter name and value.'); } foreach ($filters as $key => $value) { $this->filters[$key] = $value; } return $this; }
Extracts filtering criteria from an array of query params. @param array $params @return self
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L771-L784
as3io/modlr
src/Rest/RestRequest.php
RestRequest.getSupportedParams
public function getSupportedParams() { return [ self::PARAM_INCLUSIONS => true, self::PARAM_FIELDSETS => true, self::PARAM_SORTING => true, self::PARAM_PAGINATION => true, self::PARAM_FILTERING => true, ]; }
php
public function getSupportedParams() { return [ self::PARAM_INCLUSIONS => true, self::PARAM_FIELDSETS => true, self::PARAM_SORTING => true, self::PARAM_PAGINATION => true, self::PARAM_FILTERING => true, ]; }
Gets query string parameters that this request supports. @return array
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Rest/RestRequest.php#L791-L800
orchestral/publisher
src/CommandServiceProvider.php
CommandServiceProvider.registerConfigPublisher
protected function registerConfigPublisher() { $this->app->singleton('config.publisher', function (Application $app) { $path = $app->configPath(); // Once we have created the configuration publisher, we will set the default // package path on the object so that it knows where to find the packages // that are installed for the application and can move them to the app. $publisher = new ConfigPublisher($app->make('files'), $path); $publisher->setPackagePath($app->basePath().'/vendor'); return $publisher; }); }
php
protected function registerConfigPublisher() { $this->app->singleton('config.publisher', function (Application $app) { $path = $app->configPath(); // Once we have created the configuration publisher, we will set the default // package path on the object so that it knows where to find the packages // that are installed for the application and can move them to the app. $publisher = new ConfigPublisher($app->make('files'), $path); $publisher->setPackagePath($app->basePath().'/vendor'); return $publisher; }); }
Register the configuration publisher class and command. @return void
https://github.com/orchestral/publisher/blob/d36377d7f407f794cedca976a336f2e32086ae29/src/CommandServiceProvider.php#L80-L94
orchestral/publisher
src/CommandServiceProvider.php
CommandServiceProvider.registerViewPublisher
protected function registerViewPublisher() { $this->app->singleton('view.publisher', function (Application $app) { $viewPath = $app->basePath().'/resources/views'; // Once we have created the view publisher, we will set the default packages // path on this object so that it knows where to find all of the packages // that are installed for the application and can move them to the app. $publisher = new ViewPublisher($app->make('files'), $viewPath); $publisher->setPackagePath($app->basePath().'/vendor'); return $publisher; }); }
php
protected function registerViewPublisher() { $this->app->singleton('view.publisher', function (Application $app) { $viewPath = $app->basePath().'/resources/views'; // Once we have created the view publisher, we will set the default packages // path on this object so that it knows where to find all of the packages // that are installed for the application and can move them to the app. $publisher = new ViewPublisher($app->make('files'), $viewPath); $publisher->setPackagePath($app->basePath().'/vendor'); return $publisher; }); }
Register the view publisher class and command. @return void
https://github.com/orchestral/publisher/blob/d36377d7f407f794cedca976a336f2e32086ae29/src/CommandServiceProvider.php#L101-L115
soliantconsulting/SoliantEntityAudit
src/SoliantEntityAudit/Controller/IndexController.php
IndexController.userAction
public function userAction() { $page = (int)$this->getEvent()->getRouteMatch()->getParam('page'); $userId = (int)$this->getEvent()->getRouteMatch()->getParam('userId'); $user = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository(\SoliantEntityAudit\Module::getModuleOptions()->getUserEntityClassName())->find($userId); return array( 'page' => $page, 'user' => $user, ); }
php
public function userAction() { $page = (int)$this->getEvent()->getRouteMatch()->getParam('page'); $userId = (int)$this->getEvent()->getRouteMatch()->getParam('userId'); $user = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository(\SoliantEntityAudit\Module::getModuleOptions()->getUserEntityClassName())->find($userId); return array( 'page' => $page, 'user' => $user, ); }
Renders a paginated list of revisions for the given user @param int $page
https://github.com/soliantconsulting/SoliantEntityAudit/blob/9e77a39ca8399d43c2113c532f3cf2df5349d4a5/src/SoliantEntityAudit/Controller/IndexController.php#L31-L43
soliantconsulting/SoliantEntityAudit
src/SoliantEntityAudit/Controller/IndexController.php
IndexController.revisionAction
public function revisionAction() { $revisionId = (int)$this->getEvent()->getRouteMatch()->getParam('revisionId'); $revision = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\Revision') ->find($revisionId); if (!$revision) return $this->plugin('redirect')->toRoute('audit'); return array( 'revision' => $revision, ); }
php
public function revisionAction() { $revisionId = (int)$this->getEvent()->getRouteMatch()->getParam('revisionId'); $revision = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\Revision') ->find($revisionId); if (!$revision) return $this->plugin('redirect')->toRoute('audit'); return array( 'revision' => $revision, ); }
Shows entities changed in the specified revision. @param integer $rev
https://github.com/soliantconsulting/SoliantEntityAudit/blob/9e77a39ca8399d43c2113c532f3cf2df5349d4a5/src/SoliantEntityAudit/Controller/IndexController.php#L51-L65
soliantconsulting/SoliantEntityAudit
src/SoliantEntityAudit/Controller/IndexController.php
IndexController.revisionEntityAction
public function revisionEntityAction() { $this->mapAllAuditedClasses(); $page = (int)$this->getEvent()->getRouteMatch()->getParam('page'); $revisionEntityId = (int) $this->getEvent()->getRouteMatch()->getParam('revisionEntityId'); $revisionEntity = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity')->find($revisionEntityId); if (!$revisionEntity) return $this->plugin('redirect')->toRoute('audit'); $repository = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity'); return array( 'page' => $page, 'revisionEntity' => $revisionEntity, 'auditService' => $this->getServiceLocator()->get('auditService'), ); }
php
public function revisionEntityAction() { $this->mapAllAuditedClasses(); $page = (int)$this->getEvent()->getRouteMatch()->getParam('page'); $revisionEntityId = (int) $this->getEvent()->getRouteMatch()->getParam('revisionEntityId'); $revisionEntity = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity')->find($revisionEntityId); if (!$revisionEntity) return $this->plugin('redirect')->toRoute('audit'); $repository = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity'); return array( 'page' => $page, 'revisionEntity' => $revisionEntity, 'auditService' => $this->getServiceLocator()->get('auditService'), ); }
Show the detail for a specific revision entity
https://github.com/soliantconsulting/SoliantEntityAudit/blob/9e77a39ca8399d43c2113c532f3cf2df5349d4a5/src/SoliantEntityAudit/Controller/IndexController.php#L70-L91
soliantconsulting/SoliantEntityAudit
src/SoliantEntityAudit/Controller/IndexController.php
IndexController.entityAction
public function entityAction() { $page = (int)$this->getEvent()->getRouteMatch()->getParam('page'); $entityClass = $this->getEvent()->getRouteMatch()->getParam('entityClass'); return array( 'entityClass' => $entityClass, 'page' => $page, ); }
php
public function entityAction() { $page = (int)$this->getEvent()->getRouteMatch()->getParam('page'); $entityClass = $this->getEvent()->getRouteMatch()->getParam('entityClass'); return array( 'entityClass' => $entityClass, 'page' => $page, ); }
Lists revisions for the supplied entity. Takes an audited entity class or audit class @param string $className @param string $id
https://github.com/soliantconsulting/SoliantEntityAudit/blob/9e77a39ca8399d43c2113c532f3cf2df5349d4a5/src/SoliantEntityAudit/Controller/IndexController.php#L99-L108
soliantconsulting/SoliantEntityAudit
src/SoliantEntityAudit/Controller/IndexController.php
IndexController.compareAction
public function compareAction() { $revisionEntityId_old = $this->getRequest()->getPost()->get('revisionEntityId_old'); $revisionEntityId_new = $this->getRequest()->getPost()->get('revisionEntityId_new'); $revisionEntity_old = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity')->find($revisionEntityId_old); $revisionEntity_new = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity')->find($revisionEntityId_new); if (!$revisionEntity_old and !$revisionEntity_new) return $this->plugin('redirect')->toRoute('audit'); return array( 'revisionEntity_old' => $revisionEntity_old, 'revisionEntity_new' => $revisionEntity_new, ); }
php
public function compareAction() { $revisionEntityId_old = $this->getRequest()->getPost()->get('revisionEntityId_old'); $revisionEntityId_new = $this->getRequest()->getPost()->get('revisionEntityId_new'); $revisionEntity_old = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity')->find($revisionEntityId_old); $revisionEntity_new = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager() ->getRepository('SoliantEntityAudit\\Entity\\RevisionEntity')->find($revisionEntityId_new); if (!$revisionEntity_old and !$revisionEntity_new) return $this->plugin('redirect')->toRoute('audit'); return array( 'revisionEntity_old' => $revisionEntity_old, 'revisionEntity_new' => $revisionEntity_new, ); }
Compares an entity at 2 different revisions. @param string $className @param string $id Comma separated list of identifiers @param null|int $oldRev if null, pulled from the posted data @param null|int $newRev if null, pulled from the posted data @return Response
https://github.com/soliantconsulting/SoliantEntityAudit/blob/9e77a39ca8399d43c2113c532f3cf2df5349d4a5/src/SoliantEntityAudit/Controller/IndexController.php#L120-L137
yjv/ReportRendering
Filter/AbstractSessionFilterCollection.php
AbstractSessionFilterCollection.set
public function set($name, $value) { $this->filters[$name] = $value; $this->syncFilters(); return $this; }
php
public function set($name, $value) { $this->filters[$name] = $value; $this->syncFilters(); return $this; }
(non-PHPdoc) @see \Yjv\ReportRendering\Filter\FilterCollectionInterface::set()
https://github.com/yjv/ReportRendering/blob/56b27749483df3d6d00f85832e973e662b9809b0/Filter/AbstractSessionFilterCollection.php#L39-L44
yjv/ReportRendering
Filter/AbstractSessionFilterCollection.php
AbstractSessionFilterCollection.setAll
public function setAll(array $values) { $this->filters = array_replace($this->filters, $values); $this->syncFilters(); return $this; }
php
public function setAll(array $values) { $this->filters = array_replace($this->filters, $values); $this->syncFilters(); return $this; }
(non-PHPdoc) @see \Yjv\ReportRendering\Filter\FilterCollectionInterface::setAll()
https://github.com/yjv/ReportRendering/blob/56b27749483df3d6d00f85832e973e662b9809b0/Filter/AbstractSessionFilterCollection.php#L50-L55
yjv/ReportRendering
Filter/AbstractSessionFilterCollection.php
AbstractSessionFilterCollection.setDefaults
public function setDefaults(array $defaults) { $this->filters = array_replace($defaults, $this->filters); $this->syncFilters(); return $this; }
php
public function setDefaults(array $defaults) { $this->filters = array_replace($defaults, $this->filters); $this->syncFilters(); return $this; }
{@inheritdoc}
https://github.com/yjv/ReportRendering/blob/56b27749483df3d6d00f85832e973e662b9809b0/Filter/AbstractSessionFilterCollection.php#L80-L85
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.write
public function write(int $id, int $offset, $data, int $flags = 0): int { $this->logger->beginProfile("write_{$id}"); $storeValue = null; $stateFlags = 0; if (is_object($data)) { $storeValue = Serializer::serialize($data); $stateFlags |= self::F_SERIALIZED; $this->logger->debug(sprintf("Set F_SERIALIZED 0x%02x to process result value for id %d", self::F_SERIALIZED, $id)); } else if (is_int($data)) { $storeValue = pack(self::P_INT, $data); $stateFlags |= self::F_IS_INT | self::F_PACKED; $this->logger->debug(sprintf("Set F_IS_INT | F_PACKED 0x%02x to process result value for id %d", self::F_IS_INT | self::F_PACKED, $id)); } else if (is_float($data)) { $storeValue = pack(self::P_FLOAT, $data); $stateFlags |= self::F_IS_FLOAT | self::F_PACKED; $this->logger->debug(sprintf("Set F_IS_FLOAT | F_PACKED 0x%02x to process result value for id %d", self::F_IS_FLOAT | self::F_PACKED, $id)); } else if (is_array($data)) { $storeValue = Serializer::serialize($data); $stateFlags |= self::F_IS_ARRAY | self::F_SERIALIZED; $this->logger->debug(sprintf("Set F_IS_ARRAY | F_SERIALIZED 0x%02x to process result value for id %d", self::F_IS_ARRAY | self::F_SERIALIZED, $id)); } else if (is_bool($data)) { $stateFlags |= self::F_IS_BOOL; $this->logger->debug(sprintf("Set F_IS_BOOL 0x%02x to process result value for id %d", self::F_IS_BOOL, $id)); $storeValue = $data; } else if (is_null($data)) { $stateFlags |= self::F_IS_NULL; $this->logger->debug(sprintf("Set F_IS_NULL 0x%02x to process result value for id %d", self::F_IS_NULL, $id)); $storeValue = 0; } else if (is_string($data)) { $stateFlags |= self::F_IS_STRING; $this->logger->debug(sprintf("Set F_IS_STRING 0x%02x to process result value for id %d", self::F_IS_STRING, $id)); $storeValue = $data; } else { throw new \InvalidArgumentException('Unsupported result type: ' . gettype($data)); } $stateFlags |= $flags; $size = $this->sizeof($storeValue); $this->logger->debug(sprintf("Size of result value for id %d: 0x%08x", $id, $size)); $header = $this->packHeader($id, $offset, $size, $stateFlags); if ($this->exists($id)) { $this->logger->debug("New shared block already exists for id {$id}. Deleting..."); $this->delete($id); } try { $sh = shmop_open($this->getSharedItemKey($id), 'c', 0644, self::HEADER_SIZE + $size); if (!$sh) { $this->logger->error(sprintf("Cannot open shared memory block with size 0x%08x for id %d", $size, $id)); return 0; } } catch (\Throwable $e) { $this->getLogger()->error($e); return 0; } $written = shmop_write($sh, $header, 0); $written += shmop_write($sh, $storeValue, self::HEADER_SIZE); $this->logger->debug(sprintf("Written memory bytes for id %d: 0x%08x", $id, $written)); shmop_close($sh); $this->logger->endProfile("write_{$id}", "Writing {$id} data"); return $written; }
php
public function write(int $id, int $offset, $data, int $flags = 0): int { $this->logger->beginProfile("write_{$id}"); $storeValue = null; $stateFlags = 0; if (is_object($data)) { $storeValue = Serializer::serialize($data); $stateFlags |= self::F_SERIALIZED; $this->logger->debug(sprintf("Set F_SERIALIZED 0x%02x to process result value for id %d", self::F_SERIALIZED, $id)); } else if (is_int($data)) { $storeValue = pack(self::P_INT, $data); $stateFlags |= self::F_IS_INT | self::F_PACKED; $this->logger->debug(sprintf("Set F_IS_INT | F_PACKED 0x%02x to process result value for id %d", self::F_IS_INT | self::F_PACKED, $id)); } else if (is_float($data)) { $storeValue = pack(self::P_FLOAT, $data); $stateFlags |= self::F_IS_FLOAT | self::F_PACKED; $this->logger->debug(sprintf("Set F_IS_FLOAT | F_PACKED 0x%02x to process result value for id %d", self::F_IS_FLOAT | self::F_PACKED, $id)); } else if (is_array($data)) { $storeValue = Serializer::serialize($data); $stateFlags |= self::F_IS_ARRAY | self::F_SERIALIZED; $this->logger->debug(sprintf("Set F_IS_ARRAY | F_SERIALIZED 0x%02x to process result value for id %d", self::F_IS_ARRAY | self::F_SERIALIZED, $id)); } else if (is_bool($data)) { $stateFlags |= self::F_IS_BOOL; $this->logger->debug(sprintf("Set F_IS_BOOL 0x%02x to process result value for id %d", self::F_IS_BOOL, $id)); $storeValue = $data; } else if (is_null($data)) { $stateFlags |= self::F_IS_NULL; $this->logger->debug(sprintf("Set F_IS_NULL 0x%02x to process result value for id %d", self::F_IS_NULL, $id)); $storeValue = 0; } else if (is_string($data)) { $stateFlags |= self::F_IS_STRING; $this->logger->debug(sprintf("Set F_IS_STRING 0x%02x to process result value for id %d", self::F_IS_STRING, $id)); $storeValue = $data; } else { throw new \InvalidArgumentException('Unsupported result type: ' . gettype($data)); } $stateFlags |= $flags; $size = $this->sizeof($storeValue); $this->logger->debug(sprintf("Size of result value for id %d: 0x%08x", $id, $size)); $header = $this->packHeader($id, $offset, $size, $stateFlags); if ($this->exists($id)) { $this->logger->debug("New shared block already exists for id {$id}. Deleting..."); $this->delete($id); } try { $sh = shmop_open($this->getSharedItemKey($id), 'c', 0644, self::HEADER_SIZE + $size); if (!$sh) { $this->logger->error(sprintf("Cannot open shared memory block with size 0x%08x for id %d", $size, $id)); return 0; } } catch (\Throwable $e) { $this->getLogger()->error($e); return 0; } $written = shmop_write($sh, $header, 0); $written += shmop_write($sh, $storeValue, self::HEADER_SIZE); $this->logger->debug(sprintf("Written memory bytes for id %d: 0x%08x", $id, $written)); shmop_close($sh); $this->logger->endProfile("write_{$id}", "Writing {$id} data"); return $written; }
@param int $id @param int $offset @param mixed $data @param int $flags @return int
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L65-L145
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.delete
public function delete(int $id) { try { $sh = @shmop_open($this->getSharedItemKey($id), 'w', 0, 0); } catch (\Throwable $e) { return false; } if (!$sh) { return false; } $deleted = shmop_delete($sh); shmop_close($sh); return $deleted; }
php
public function delete(int $id) { try { $sh = @shmop_open($this->getSharedItemKey($id), 'w', 0, 0); } catch (\Throwable $e) { return false; } if (!$sh) { return false; } $deleted = shmop_delete($sh); shmop_close($sh); return $deleted; }
@param int $id @return bool
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L177-L193
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.read
public function read(int $id, int &$offset = 0, bool $cleanup = true) { $this->logger->beginProfile('read_' . $id); $key = $this->getSharedItemKey($id); $sh = shmop_open($key, 'a', 0, 0); $header = shmop_read($sh, 0, self::HEADER_SIZE); list($id, $off, $size, $flags) = $this->unpackHeader($header); $this->logger->debug(sprintf('Reading state: (key = 0x%08x, shmid = %d)', $key, $sh)); $this->logger->debug(sprintf("State header: (id = %d, offset = %d, size = 0x%08x, flags = 0x%03x)", $id, $offset, $size, $flags)); $result = shmop_read($sh, self::HEADER_SIZE, $size); $this->logger->debug(sprintf('State data: (size = 0x%08x)', mb_strlen($result, 'utf-8'))); if ($cleanup) { shmop_delete($sh); } shmop_close($sh); $result = $this->getResult($result, $flags); $offset = $off; $this->logger->endProfile('read_' . $id, "Reading {$id} data"); return $result; }
php
public function read(int $id, int &$offset = 0, bool $cleanup = true) { $this->logger->beginProfile('read_' . $id); $key = $this->getSharedItemKey($id); $sh = shmop_open($key, 'a', 0, 0); $header = shmop_read($sh, 0, self::HEADER_SIZE); list($id, $off, $size, $flags) = $this->unpackHeader($header); $this->logger->debug(sprintf('Reading state: (key = 0x%08x, shmid = %d)', $key, $sh)); $this->logger->debug(sprintf("State header: (id = %d, offset = %d, size = 0x%08x, flags = 0x%03x)", $id, $offset, $size, $flags)); $result = shmop_read($sh, self::HEADER_SIZE, $size); $this->logger->debug(sprintf('State data: (size = 0x%08x)', mb_strlen($result, 'utf-8'))); if ($cleanup) { shmop_delete($sh); } shmop_close($sh); $result = $this->getResult($result, $flags); $offset = $off; $this->logger->endProfile('read_' . $id, "Reading {$id} data"); return $result; }
@param int $id @param int $offset @param bool $cleanup Be carefully! If not clean up memory automatic, you must delete this by yourself @return bool|int|mixed|string
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L202-L228
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.removeTerminationNull
private function removeTerminationNull(string $value) { $i = strpos((string)$value, "\0"); if ($i === false) { return $value; } $result = substr((string)$value, 0, $i); return $result; }
php
private function removeTerminationNull(string $value) { $i = strpos((string)$value, "\0"); if ($i === false) { return $value; } $result = substr((string)$value, 0, $i); return $result; }
@param string $value @return string
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L243-L253
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.getResult
private function getResult(string $value, int $flags) { if (($flags & self::F_PACKED) !== self::F_PACKED) { $value = $this->removeTerminationNull($value); } $out = null; if (($flags & self::F_SERIALIZED) === self::F_SERIALIZED) { $out = Serializer::unserialize($value); } if (($flags & self::F_IS_BOOL) === self::F_IS_BOOL) { $out = (bool)$value; } else if (($flags & self::F_IS_INT) === self::F_IS_INT) { if (($flags & self::F_PACKED) === self::F_PACKED) { $res = unpack(self::P_INT . 'num', $value); $out = $res['num']; unset($res); } else { $out = (int)$value; } } else if (($flags & self::F_IS_FLOAT) === self::F_IS_FLOAT) { if (($flags & self::F_PACKED) === self::F_PACKED) { $res = unpack(self::P_FLOAT . 'num', $value); $out = $res['num']; unset($res); } else { $out = (double)$value; } } else if (($flags & self::F_IS_STRING) === self::F_IS_STRING) { $out = (string)$value; } else if (($flags & self::F_IS_NULL) === self::F_IS_NULL) { $out = null; } else if (($flags & self::F_IS_ARRAY) === self::F_IS_ARRAY) { if (($flags & self::F_SERIALIZED) === self::F_SERIALIZED) { $value = Serializer::unserialize($value); } if (($flags & self::F_IS_ARRAY_OBJECT) === self::F_IS_ARRAY_OBJECT) { $out = (object)$value; } else { $out = (array)$value; } } return $out; }
php
private function getResult(string $value, int $flags) { if (($flags & self::F_PACKED) !== self::F_PACKED) { $value = $this->removeTerminationNull($value); } $out = null; if (($flags & self::F_SERIALIZED) === self::F_SERIALIZED) { $out = Serializer::unserialize($value); } if (($flags & self::F_IS_BOOL) === self::F_IS_BOOL) { $out = (bool)$value; } else if (($flags & self::F_IS_INT) === self::F_IS_INT) { if (($flags & self::F_PACKED) === self::F_PACKED) { $res = unpack(self::P_INT . 'num', $value); $out = $res['num']; unset($res); } else { $out = (int)$value; } } else if (($flags & self::F_IS_FLOAT) === self::F_IS_FLOAT) { if (($flags & self::F_PACKED) === self::F_PACKED) { $res = unpack(self::P_FLOAT . 'num', $value); $out = $res['num']; unset($res); } else { $out = (double)$value; } } else if (($flags & self::F_IS_STRING) === self::F_IS_STRING) { $out = (string)$value; } else if (($flags & self::F_IS_NULL) === self::F_IS_NULL) { $out = null; } else if (($flags & self::F_IS_ARRAY) === self::F_IS_ARRAY) { if (($flags & self::F_SERIALIZED) === self::F_SERIALIZED) { $value = Serializer::unserialize($value); } if (($flags & self::F_IS_ARRAY_OBJECT) === self::F_IS_ARRAY_OBJECT) { $out = (object)$value; } else { $out = (array)$value; } } return $out; }
@param string $value @param int $flags @return bool|int|mixed|string|null
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L261-L309
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.packHeader
private function packHeader(int $id, int $offset, int $size, int $flags = 0): string { return pack('SSQI', $id, $offset, $size, $flags); }
php
private function packHeader(int $id, int $offset, int $size, int $flags = 0): string { return pack('SSQI', $id, $offset, $size, $flags); }
Blocking method, writes process result state to state file @param int $id @param int $offset @param int $size @param int $flags @return string binary data sizes: 2 (ushort) + 2 (ushort) + 8(ulong long) + 4(uint) bytes, order - machine-dependent @see SharedMemoryManager::F_SERIALIZED and other flags
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L323-L326
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.unpackHeader
private function unpackHeader(string $bin): array { $data = unpack('Sid/Soffset/Qsize/Iflags', $bin); return [ $data['id'], $data['offset'], $data['size'], $data['flags'], ]; }
php
private function unpackHeader(string $bin): array { $data = unpack('Sid/Soffset/Qsize/Iflags', $bin); return [ $data['id'], $data['offset'], $data['size'], $data['flags'], ]; }
@param string $bin @return array [$id, $offset, $size, $flags]
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L333-L343
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.getSharedItemKey
private function getSharedItemKey(int $id): int { if ($id <= 0) { throw new \InvalidArgumentException('ID cannot be less or equals zero'); } $st = @stat(__FILE__); if (!$st) { return -1; } //@TODO collisions? need more unique key $key = (int)sprintf("%u", ( ($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($id & 0xff) << 24) ) ); return $key; }
php
private function getSharedItemKey(int $id): int { if ($id <= 0) { throw new \InvalidArgumentException('ID cannot be less or equals zero'); } $st = @stat(__FILE__); if (!$st) { return -1; } //@TODO collisions? need more unique key $key = (int)sprintf("%u", ( ($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($id & 0xff) << 24) ) ); return $key; }
maximum size of processes with result see in /proc/sys/kernel/pid_max @param int $id @return int unsigned @throws \RuntimeException
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L353-L374
edwardstock/forker
src/system/SharedMemoryManager.php
SharedMemoryManager.sizeof
private function sizeof($any): int { if (is_object($any)) { $start = memory_get_usage(); $new = Serializer::unserialize(Serializer::serialize($any)); $end = memory_get_usage() - $start; } else if (is_bool($any)) { return 2; } else if (is_int($any)) { $end = PHP_INT_SIZE; } else if (is_float($any) || is_double($any)) { $end = PHP_INT_SIZE * 3; } else { $end = mb_strlen($any, '8bit'); } return (int)$end; }
php
private function sizeof($any): int { if (is_object($any)) { $start = memory_get_usage(); $new = Serializer::unserialize(Serializer::serialize($any)); $end = memory_get_usage() - $start; } else if (is_bool($any)) { return 2; } else if (is_int($any)) { $end = PHP_INT_SIZE; } else if (is_float($any) || is_double($any)) { $end = PHP_INT_SIZE * 3; } else { $end = mb_strlen($any, '8bit'); } return (int)$end; }
@param $any @todo sizes is very rounded @return int
https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/system/SharedMemoryManager.php#L382-L399
BenGorFile/FileBundle
src/BenGorFile/FileBundle/DependencyInjection/Compiler/DomainServicesPass.php
DomainServicesPass.process
public function process(ContainerBuilder $container) { $config = $container->getParameter('bengor_file.config'); foreach ($config['file_class'] as $key => $file) { $container->setDefinition( 'bengor.file.infrastructure.domain.model.' . $key . '_factory', (new Definition( FileFactory::class, [ $file['class'], ] ))->setPublic(false) ); $container->setAlias( 'bengor_file.' . $key . '.factory', 'bengor.file.infrastructure.domain.model.' . $key . '_factory' ); } }
php
public function process(ContainerBuilder $container) { $config = $container->getParameter('bengor_file.config'); foreach ($config['file_class'] as $key => $file) { $container->setDefinition( 'bengor.file.infrastructure.domain.model.' . $key . '_factory', (new Definition( FileFactory::class, [ $file['class'], ] ))->setPublic(false) ); $container->setAlias( 'bengor_file.' . $key . '.factory', 'bengor.file.infrastructure.domain.model.' . $key . '_factory' ); } }
{@inheritdoc}
https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/DependencyInjection/Compiler/DomainServicesPass.php#L33-L50
ben-gibson/foursquare-venue-client
src/Options/Explore.php
Explore.parametrise
public function parametrise() { return array_filter([ 'limit' => $this->limit, 'll' => $this->coordinates, 'near' => $this->place, 'radius' => $this->radius, 'query' => $this->query, 'time' => $this->targetToCurrentTime ? null : 'any', 'day' => $this->targetToCurrentDay ? null : 'any', 'openNow' => (int)$this->includeOpenOnly, 'sortByDistance' => (int)$this->sortByDistance, ]); }
php
public function parametrise() { return array_filter([ 'limit' => $this->limit, 'll' => $this->coordinates, 'near' => $this->place, 'radius' => $this->radius, 'query' => $this->query, 'time' => $this->targetToCurrentTime ? null : 'any', 'day' => $this->targetToCurrentDay ? null : 'any', 'openNow' => (int)$this->includeOpenOnly, 'sortByDistance' => (int)$this->sortByDistance, ]); }
{@inheritdoc}
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Options/Explore.php#L162-L175
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.&
public function &setDatabaseName($database_name, $select_database = true) { if (empty($select_database) || $this->link->select_db($database_name)) { $this->database_name = $database_name; } else { throw new ConnectionException("Failed to select database '$database_name'"); } return $this; }
php
public function &setDatabaseName($database_name, $select_database = true) { if (empty($select_database) || $this->link->select_db($database_name)) { $this->database_name = $database_name; } else { throw new ConnectionException("Failed to select database '$database_name'"); } return $this; }
Set database name and optionally select that database. @param string $database_name @param bool|true $select_database @return $this @throws ConnectionException
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L71-L80
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.advancedExecute
public function advancedExecute($sql, $arguments = null, $load_mode = ConnectionInterface::LOAD_ALL_ROWS, $return_mode = ConnectionInterface::RETURN_ARRAY, $return_class_or_field = null, array $constructor_arguments = null, ContainerInterface &$container = null) { if ($return_mode == ConnectionInterface::RETURN_OBJECT_BY_CLASS && empty($return_class_or_field)) { throw new InvalidArgumentException('Class is required'); } elseif ($return_mode == ConnectionInterface::RETURN_OBJECT_BY_FIELD && empty($return_class_or_field)) { throw new InvalidArgumentException('Field name is required'); } $query_result = $this->prepareAndExecuteQuery($sql, $arguments); if ($query_result === false) { $query_result = $this->tryToRecoverFromFailedQuery($sql, $arguments, $load_mode, $return_mode); } if ($query_result instanceof mysqli_result) { if ($query_result->num_rows > 0) { switch ($load_mode) { case ConnectionInterface::LOAD_FIRST_ROW: $result = $query_result->fetch_assoc(); $this->getDefaultCaster()->castRowValues($result); break; case ConnectionInterface::LOAD_FIRST_COLUMN: $result = []; while ($row = $query_result->fetch_assoc()) { foreach ($row as $k => $v) { $result[] = $this->getDefaultCaster()->castValue($k, $v); break; // Done after first cell in a row } } break; case ConnectionInterface::LOAD_FIRST_CELL: $result = null; foreach ($query_result->fetch_assoc() as $k => $v) { $result = $this->getDefaultCaster()->castValue($k, $v); break; // Done after first cell } break; default: return new Result($query_result, $return_mode, $return_class_or_field, $constructor_arguments, $container); // Don't close result, we need it } } else { $result = null; } $query_result->close(); return $result; } elseif ($query_result === true) { return true; } else { throw new QueryException($this->link->error, $this->link->errno); } }
php
public function advancedExecute($sql, $arguments = null, $load_mode = ConnectionInterface::LOAD_ALL_ROWS, $return_mode = ConnectionInterface::RETURN_ARRAY, $return_class_or_field = null, array $constructor_arguments = null, ContainerInterface &$container = null) { if ($return_mode == ConnectionInterface::RETURN_OBJECT_BY_CLASS && empty($return_class_or_field)) { throw new InvalidArgumentException('Class is required'); } elseif ($return_mode == ConnectionInterface::RETURN_OBJECT_BY_FIELD && empty($return_class_or_field)) { throw new InvalidArgumentException('Field name is required'); } $query_result = $this->prepareAndExecuteQuery($sql, $arguments); if ($query_result === false) { $query_result = $this->tryToRecoverFromFailedQuery($sql, $arguments, $load_mode, $return_mode); } if ($query_result instanceof mysqli_result) { if ($query_result->num_rows > 0) { switch ($load_mode) { case ConnectionInterface::LOAD_FIRST_ROW: $result = $query_result->fetch_assoc(); $this->getDefaultCaster()->castRowValues($result); break; case ConnectionInterface::LOAD_FIRST_COLUMN: $result = []; while ($row = $query_result->fetch_assoc()) { foreach ($row as $k => $v) { $result[] = $this->getDefaultCaster()->castValue($k, $v); break; // Done after first cell in a row } } break; case ConnectionInterface::LOAD_FIRST_CELL: $result = null; foreach ($query_result->fetch_assoc() as $k => $v) { $result = $this->getDefaultCaster()->castValue($k, $v); break; // Done after first cell } break; default: return new Result($query_result, $return_mode, $return_class_or_field, $constructor_arguments, $container); // Don't close result, we need it } } else { $result = null; } $query_result->close(); return $result; } elseif ($query_result === true) { return true; } else { throw new QueryException($this->link->error, $this->link->errno); } }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L125-L184
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.select
public function select($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->execute($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
php
public function select($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->execute($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L189-L192
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.selectFirstRow
public function selectFirstRow($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->executeFirstRow($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
php
public function selectFirstRow($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->executeFirstRow($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L197-L200
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.selectFirstColumn
public function selectFirstColumn($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->executeFirstColumn($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
php
public function selectFirstColumn($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->executeFirstColumn($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L205-L208
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.selectFirstCell
public function selectFirstCell($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->executeFirstCell($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
php
public function selectFirstCell($table_name, $fields = null, $conditions = null, $order_by_fields = null) { return $this->executeFirstCell($this->prepareSelectQueryFromArguments($table_name, $fields, $conditions, $order_by_fields)); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L213-L216
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.prepareSelectQueryFromArguments
private function prepareSelectQueryFromArguments($table_name, $fields, $conditions = null, $order_by_fields = null) { if (empty($table_name)) { throw new InvalidArgumentException('Table name is required'); } $escaped_field_names = empty($fields) ? '*' : implode(',', array_map(function ($field_name) { return $this->escapeFieldName($field_name); }, (array) $fields)); if ($conditions) { $where = 'WHERE ' . $this->prepareConditions($conditions); } else { $where = ''; } $escaped_order_by_field_names = ''; if (!empty($order_by_fields)) { $escaped_order_by_field_names = implode(',', array_map(function ($field_name) { return $this->escapeFieldName($field_name); }, (array) $order_by_fields)); } $order_by = $escaped_order_by_field_names ? "ORDER BY $escaped_order_by_field_names" : ''; return trim("SELECT $escaped_field_names FROM {$this->escapeTableName($table_name)} $where $order_by"); }
php
private function prepareSelectQueryFromArguments($table_name, $fields, $conditions = null, $order_by_fields = null) { if (empty($table_name)) { throw new InvalidArgumentException('Table name is required'); } $escaped_field_names = empty($fields) ? '*' : implode(',', array_map(function ($field_name) { return $this->escapeFieldName($field_name); }, (array) $fields)); if ($conditions) { $where = 'WHERE ' . $this->prepareConditions($conditions); } else { $where = ''; } $escaped_order_by_field_names = ''; if (!empty($order_by_fields)) { $escaped_order_by_field_names = implode(',', array_map(function ($field_name) { return $this->escapeFieldName($field_name); }, (array) $order_by_fields)); } $order_by = $escaped_order_by_field_names ? "ORDER BY $escaped_order_by_field_names" : ''; return trim("SELECT $escaped_field_names FROM {$this->escapeTableName($table_name)} $where $order_by"); }
Prepare SELECT query from arguments used by select*() methods. @param string $table_name @param array|string|null $fields @param array|string|null $conditions @param array|string|null $order_by_fields @return string
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L227-L254
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.count
public function count($table_name, $conditions = null, $field = 'id') { if (empty($table_name)) { throw new InvalidArgumentException('Table name is required'); } if (empty($field)) { throw new InvalidArgumentException('Field name is required'); } if ($conditions) { $where = ' WHERE ' . $this->prepareConditions($conditions); } else { $where = ''; } $count = $field == '*' ? 'COUNT(*)' : 'COUNT(' . $this->escapeFieldName($field) . ')'; return $this->executeFirstCell("SELECT $count AS 'row_count' FROM " . $this->escapeTableName($table_name) . $where); }
php
public function count($table_name, $conditions = null, $field = 'id') { if (empty($table_name)) { throw new InvalidArgumentException('Table name is required'); } if (empty($field)) { throw new InvalidArgumentException('Field name is required'); } if ($conditions) { $where = ' WHERE ' . $this->prepareConditions($conditions); } else { $where = ''; } $count = $field == '*' ? 'COUNT(*)' : 'COUNT(' . $this->escapeFieldName($field) . ')'; return $this->executeFirstCell("SELECT $count AS 'row_count' FROM " . $this->escapeTableName($table_name) . $where); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L259-L278
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.insert
public function insert($table, array $field_value_map, $mode = ConnectionInterface::INSERT) { if (empty($field_value_map)) { throw new InvalidArgumentException("Values array can't be empty"); } $mode = strtoupper($mode); if ($mode != ConnectionInterface::INSERT && $mode != ConnectionInterface::REPLACE) { throw new InvalidArgumentException("Mode '$mode' is not a valid insert mode"); } $this->execute("$mode INTO " . $this->escapeTableName($table) . ' (' . implode(',', array_map(function ($field_name) { return $this->escapeFieldName($field_name); }, array_keys($field_value_map))) . ') VALUES (' . implode(',', array_map(function ($value) { return $this->escapeValue($value); }, $field_value_map)) . ')'); return $this->lastInsertId(); }
php
public function insert($table, array $field_value_map, $mode = ConnectionInterface::INSERT) { if (empty($field_value_map)) { throw new InvalidArgumentException("Values array can't be empty"); } $mode = strtoupper($mode); if ($mode != ConnectionInterface::INSERT && $mode != ConnectionInterface::REPLACE) { throw new InvalidArgumentException("Mode '$mode' is not a valid insert mode"); } $this->execute("$mode INTO " . $this->escapeTableName($table) . ' (' . implode(',', array_map(function ($field_name) { return $this->escapeFieldName($field_name); }, array_keys($field_value_map))) . ') VALUES (' . implode(',', array_map(function ($value) { return $this->escapeValue($value); }, $field_value_map)) . ')'); return $this->lastInsertId(); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L283-L302
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.batchInsert
public function batchInsert($table_name, array $fields, $rows_per_batch = 50, $mode = self::INSERT) { return new BatchInsert($this, $table_name, $fields, $rows_per_batch, $mode); }
php
public function batchInsert($table_name, array $fields, $rows_per_batch = 50, $mode = self::INSERT) { return new BatchInsert($this, $table_name, $fields, $rows_per_batch, $mode); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L307-L310
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.update
public function update($table_name, array $field_value_map, $conditions = null) { if (empty($field_value_map)) { throw new InvalidArgumentException("Values array can't be empty"); } if ($conditions = $this->prepareConditions($conditions)) { $conditions = " WHERE $conditions"; } $this->execute('UPDATE ' . $this->escapeTableName($table_name) . ' SET ' . implode(',', array_map(function ($field_name, $value) { return $this->escapeFieldName($field_name) . ' = ' . $this->escapeValue($value); }, array_keys($field_value_map), $field_value_map)) . $conditions); return $this->affectedRows(); }
php
public function update($table_name, array $field_value_map, $conditions = null) { if (empty($field_value_map)) { throw new InvalidArgumentException("Values array can't be empty"); } if ($conditions = $this->prepareConditions($conditions)) { $conditions = " WHERE $conditions"; } $this->execute('UPDATE ' . $this->escapeTableName($table_name) . ' SET ' . implode(',', array_map(function ($field_name, $value) { return $this->escapeFieldName($field_name) . ' = ' . $this->escapeValue($value); }, array_keys($field_value_map), $field_value_map)) . $conditions); return $this->affectedRows(); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L323-L338
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.delete
public function delete($table_name, $conditions = null) { if ($conditions = $this->prepareConditions($conditions)) { $conditions = " WHERE $conditions"; } $this->execute('DELETE FROM ' . $this->escapeTableName($table_name) . $conditions); return $this->affectedRows(); }
php
public function delete($table_name, $conditions = null) { if ($conditions = $this->prepareConditions($conditions)) { $conditions = " WHERE $conditions"; } $this->execute('DELETE FROM ' . $this->escapeTableName($table_name) . $conditions); return $this->affectedRows(); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L343-L352
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.transact
public function transact(Closure $body, $on_success = null, $on_error = null) { if ($body instanceof Closure) { try { $this->beginWork(); call_user_func($body); $this->commit(); if ($on_success instanceof Closure) { call_user_func($on_success); } } catch (Exception $e) { $this->rollback(); if ($on_error instanceof Closure) { call_user_func($on_error, $e); } else { throw $e; } } } else { throw new InvalidArgumentException('Closure expected'); } }
php
public function transact(Closure $body, $on_success = null, $on_error = null) { if ($body instanceof Closure) { try { $this->beginWork(); call_user_func($body); $this->commit(); if ($on_success instanceof Closure) { call_user_func($on_success); } } catch (Exception $e) { $this->rollback(); if ($on_error instanceof Closure) { call_user_func($on_error, $e); } else { throw $e; } } } else { throw new InvalidArgumentException('Closure expected'); } }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L365-L388
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.dropUser
public function dropUser($user_name, $hostname = '%') { if ($this->userExists($user_name)) { $this->execute('DROP USER ?@?', $user_name, $hostname); } }
php
public function dropUser($user_name, $hostname = '%') { if ($this->userExists($user_name)) { $this->execute('DROP USER ?@?', $user_name, $hostname); } }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L489-L494
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.getTableNames
public function getTableNames($database_name = '') { if ($database_name) { $tables = $this->executeFirstColumn('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME', $database_name); } elseif ($this->database_name) { $tables = $this->executeFirstColumn('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME', $this->database_name); } else { $tables = $this->executeFirstColumn('SHOW TABLES'); } if (empty($tables)) { $tables = []; } return $tables; }
php
public function getTableNames($database_name = '') { if ($database_name) { $tables = $this->executeFirstColumn('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME', $database_name); } elseif ($this->database_name) { $tables = $this->executeFirstColumn('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME', $this->database_name); } else { $tables = $this->executeFirstColumn('SHOW TABLES'); } if (empty($tables)) { $tables = []; } return $tables; }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L499-L514
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.getFieldNames
public function getFieldNames($table_name) { $result = []; if ($rows = $this->execute("DESCRIBE {$this->escapeTableName($table_name)}")) { foreach ($rows as $row) { $result[] = $row['Field']; } } return $result; }
php
public function getFieldNames($table_name) { $result = []; if ($rows = $this->execute("DESCRIBE {$this->escapeTableName($table_name)}")) { foreach ($rows as $row) { $result[] = $row['Field']; } } return $result; }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L535-L546
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.dropField
public function dropField($table_name, $field_name, $check_if_exists = true) { if ($check_if_exists && !$this->fieldExists($table_name, $field_name)) { return; } $this->execute("ALTER TABLE {$this->escapeTableName($table_name)} DROP {$this->escapeFieldName($field_name)}"); }
php
public function dropField($table_name, $field_name, $check_if_exists = true) { if ($check_if_exists && !$this->fieldExists($table_name, $field_name)) { return; } $this->execute("ALTER TABLE {$this->escapeTableName($table_name)} DROP {$this->escapeFieldName($field_name)}"); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L559-L566
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.getIndexNames
public function getIndexNames($table_name) { $result = []; if ($rows = $this->execute("SHOW INDEXES FROM {$this->escapeTableName($table_name)}")) { foreach ($rows as $row) { $key_name = $row['Key_name']; if (!in_array($key_name, $result)) { $result[] = $key_name; } } } return $result; }
php
public function getIndexNames($table_name) { $result = []; if ($rows = $this->execute("SHOW INDEXES FROM {$this->escapeTableName($table_name)}")) { foreach ($rows as $row) { $key_name = $row['Key_name']; if (!in_array($key_name, $result)) { $result[] = $key_name; } } } return $result; }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L571-L586
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.dropIndex
public function dropIndex($table_name, $index_name, $check_if_exists = true) { if ($check_if_exists && !$this->indexExists($table_name, $index_name)) { return; } $this->execute("ALTER TABLE {$this->escapeTableName($table_name)} DROP INDEX {$this->escapeFieldName($index_name)}"); }
php
public function dropIndex($table_name, $index_name, $check_if_exists = true) { if ($check_if_exists && !$this->indexExists($table_name, $index_name)) { return; } $this->execute("ALTER TABLE {$this->escapeTableName($table_name)} DROP INDEX {$this->escapeFieldName($index_name)}"); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L599-L606
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.getForeignKeyNames
public function getForeignKeyNames($table_name) { $result = []; if ($rows = $this->execute('SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = ? AND CONSTRAINT_NAME != ?', $table_name, 'PRIMARY')) { foreach ($rows as $row) { $result[] = $row['CONSTRAINT_NAME']; } } return $result; }
php
public function getForeignKeyNames($table_name) { $result = []; if ($rows = $this->execute('SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = ? AND CONSTRAINT_NAME != ?', $table_name, 'PRIMARY')) { foreach ($rows as $row) { $result[] = $row['CONSTRAINT_NAME']; } } return $result; }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L639-L650
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.dropForeignKey
public function dropForeignKey($table_name, $fk_name, $check_if_exists = true) { if ($check_if_exists && !$this->foreignKeyExists($table_name, $fk_name)) { return; } $this->execute("ALTER TABLE {$this->escapeTableName($table_name)} DROP FOREIGN KEY {$this->escapeFieldName($fk_name)}"); }
php
public function dropForeignKey($table_name, $fk_name, $check_if_exists = true) { if ($check_if_exists && !$this->foreignKeyExists($table_name, $fk_name)) { return; } $this->execute("ALTER TABLE {$this->escapeTableName($table_name)} DROP FOREIGN KEY {$this->escapeFieldName($fk_name)}"); }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L663-L670
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.prepareAndExecuteQuery
private function prepareAndExecuteQuery($sql, $arguments) { if ($this->log || $this->on_log_query) { $microtime = microtime(true); $prepared_sql = empty($arguments) ? $sql : call_user_func_array([&$this, 'prepare'], array_merge([$sql], $arguments)); $result = $this->link->query($prepared_sql); $execution_time = rtrim(number_format(microtime(true) - $microtime, 6, '.', ''), '0'); if ($this->log) { if ($result === false) { $this->log->error('Query error {error_message}', [ 'error_message' => $this->link->error, 'error_code' => $this->link->errno, 'sql' => $prepared_sql, 'exec_time' => $execution_time, ]); } else { $this->log->debug('Query {sql} executed in {exec_time}s', [ 'sql' => $prepared_sql, 'exec_time' => $execution_time, ]); } } if ($this->on_log_query) { call_user_func($this->on_log_query, $prepared_sql, $execution_time); } return $result; } else { return empty($arguments) ? $this->link->query($sql) : $this->link->query(call_user_func_array([&$this, 'prepare'], array_merge([$sql], $arguments))); } }
php
private function prepareAndExecuteQuery($sql, $arguments) { if ($this->log || $this->on_log_query) { $microtime = microtime(true); $prepared_sql = empty($arguments) ? $sql : call_user_func_array([&$this, 'prepare'], array_merge([$sql], $arguments)); $result = $this->link->query($prepared_sql); $execution_time = rtrim(number_format(microtime(true) - $microtime, 6, '.', ''), '0'); if ($this->log) { if ($result === false) { $this->log->error('Query error {error_message}', [ 'error_message' => $this->link->error, 'error_code' => $this->link->errno, 'sql' => $prepared_sql, 'exec_time' => $execution_time, ]); } else { $this->log->debug('Query {sql} executed in {exec_time}s', [ 'sql' => $prepared_sql, 'exec_time' => $execution_time, ]); } } if ($this->on_log_query) { call_user_func($this->on_log_query, $prepared_sql, $execution_time); } return $result; } else { return empty($arguments) ? $this->link->query($sql) : $this->link->query(call_user_func_array([&$this, 'prepare'], array_merge([$sql], $arguments))); } }
Prepare (if needed) and execute SQL query. @param string $sql @param array|null $arguments @return mysqli_result|bool
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L679-L718
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.prepare
public function prepare($sql, ...$arguments) { if (empty($arguments)) { return $sql; } else { $offset = 0; foreach ($arguments as $argument) { $question_mark_pos = mb_strpos($sql, '?', $offset); if ($question_mark_pos !== false) { $escaped = $this->escapeValue($argument); $escaped_len = mb_strlen($escaped); $sql = mb_substr($sql, 0, $question_mark_pos) . $escaped . mb_substr($sql, $question_mark_pos + 1, mb_strlen($sql)); $offset = $question_mark_pos + $escaped_len; } } return $sql; } }
php
public function prepare($sql, ...$arguments) { if (empty($arguments)) { return $sql; } else { $offset = 0; foreach ($arguments as $argument) { $question_mark_pos = mb_strpos($sql, '?', $offset); if ($question_mark_pos !== false) { $escaped = $this->escapeValue($argument); $escaped_len = mb_strlen($escaped); $sql = mb_substr($sql, 0, $question_mark_pos) . $escaped . mb_substr($sql, $question_mark_pos + 1, mb_strlen($sql)); $offset = $question_mark_pos + $escaped_len; } } return $sql; } }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L723-L745
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.prepareConditions
public function prepareConditions($conditions) { if ($conditions === null || is_string($conditions)) { return $conditions; } elseif (is_array($conditions)) { switch (count($conditions)) { case 0: throw new InvalidArgumentException("Conditions can't be an empty array"); case 1: return array_shift($conditions); default: return call_user_func_array([&$this, 'prepare'], $conditions); } } else { throw new InvalidArgumentException('Invalid conditions argument value'); } }
php
public function prepareConditions($conditions) { if ($conditions === null || is_string($conditions)) { return $conditions; } elseif (is_array($conditions)) { switch (count($conditions)) { case 0: throw new InvalidArgumentException("Conditions can't be an empty array"); case 1: return array_shift($conditions); default: return call_user_func_array([&$this, 'prepare'], $conditions); } } else { throw new InvalidArgumentException('Invalid conditions argument value'); } }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L750-L766
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.tryToRecoverFromFailedQuery
private function tryToRecoverFromFailedQuery($sql, $arguments, $load_mode, $return_mode) { switch ($this->link->errno) { // Non-transactional tables not rolled back! case 1196: return null; // Server gone away case 2006: case 2013: return $this->handleMySqlGoneAway($sql, $arguments, $load_mode, $return_mode); // Deadlock detection and retry case 1213: return $this->handleDeadlock(); // Other error default: throw new QueryException($this->link->error, $this->link->errno); } }
php
private function tryToRecoverFromFailedQuery($sql, $arguments, $load_mode, $return_mode) { switch ($this->link->errno) { // Non-transactional tables not rolled back! case 1196: return null; // Server gone away case 2006: case 2013: return $this->handleMySqlGoneAway($sql, $arguments, $load_mode, $return_mode); // Deadlock detection and retry case 1213: return $this->handleDeadlock(); // Other error default: throw new QueryException($this->link->error, $this->link->errno); } }
Try to recover from failed query. @param string $sql @param array|null $arguments @param $load_mode @param $return_mode @return array|bool|DateTime|float|int|mixed|null|string|void @throws QueryException
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L778-L799
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.escapeValue
public function escapeValue($unescaped) { // Date value if ($unescaped instanceof DateValue) { return "'" . $this->link->real_escape_string($unescaped->format('Y-m-d')) . "'"; // Date time value (including DateTimeValue) } elseif ($unescaped instanceof DateTime) { return "'" . $this->link->real_escape_string($unescaped->format('Y-m-d H:i:s')) . "'"; // Float } else { if (is_float($unescaped)) { return "'" . str_replace(',', '.', (float) $unescaped) . "'"; // replace , with . for locales where comma is used by the system (German for example) // Boolean (maps to TINYINT(1)) } else { if (is_bool($unescaped)) { return $unescaped ? "'1'" : "'0'"; // NULL } else { if ($unescaped === null) { return 'NULL'; // Escape first cell of each row } else { if ($unescaped instanceof ResultInterface) { if ($unescaped->count() < 1) { throw new InvalidArgumentException("Empty results can't be escaped"); } $escaped = []; foreach ($unescaped as $v) { $escaped[] = $this->escapeValue(array_shift($v)); } return '(' . implode(',', $escaped) . ')'; // Escape each array element } else { if (is_array($unescaped)) { if (empty($unescaped)) { throw new InvalidArgumentException("Empty arrays can't be escaped"); } $escaped = []; foreach ($unescaped as $v) { $escaped[] = $this->escapeValue($v); } return '(' . implode(',', $escaped) . ')'; // Regular string and integer escape } else { if (is_scalar($unescaped)) { return "'" . $this->link->real_escape_string($unescaped) . "'"; } else { throw new InvalidArgumentException('Value is expected to be scalar, array, or instance of: DateTime or Result'); } } } } } } } }
php
public function escapeValue($unescaped) { // Date value if ($unescaped instanceof DateValue) { return "'" . $this->link->real_escape_string($unescaped->format('Y-m-d')) . "'"; // Date time value (including DateTimeValue) } elseif ($unescaped instanceof DateTime) { return "'" . $this->link->real_escape_string($unescaped->format('Y-m-d H:i:s')) . "'"; // Float } else { if (is_float($unescaped)) { return "'" . str_replace(',', '.', (float) $unescaped) . "'"; // replace , with . for locales where comma is used by the system (German for example) // Boolean (maps to TINYINT(1)) } else { if (is_bool($unescaped)) { return $unescaped ? "'1'" : "'0'"; // NULL } else { if ($unescaped === null) { return 'NULL'; // Escape first cell of each row } else { if ($unescaped instanceof ResultInterface) { if ($unescaped->count() < 1) { throw new InvalidArgumentException("Empty results can't be escaped"); } $escaped = []; foreach ($unescaped as $v) { $escaped[] = $this->escapeValue(array_shift($v)); } return '(' . implode(',', $escaped) . ')'; // Escape each array element } else { if (is_array($unescaped)) { if (empty($unescaped)) { throw new InvalidArgumentException("Empty arrays can't be escaped"); } $escaped = []; foreach ($unescaped as $v) { $escaped[] = $this->escapeValue($v); } return '(' . implode(',', $escaped) . ')'; // Regular string and integer escape } else { if (is_scalar($unescaped)) { return "'" . $this->link->real_escape_string($unescaped) . "'"; } else { throw new InvalidArgumentException('Value is expected to be scalar, array, or instance of: DateTime or Result'); } } } } } } } }
{@inheritdoc}
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L828-L896
activecollab/databaseconnection
src/Connection/MysqliConnection.php
MysqliConnection.onLogQuery
public function onLogQuery(callable $callback = null) { if ($callback === null || is_callable($callback)) { $this->on_log_query = $callback; } else { throw new InvalidArgumentException('Callback needs to be NULL or callable'); } }
php
public function onLogQuery(callable $callback = null) { if ($callback === null || is_callable($callback)) { $this->on_log_query = $callback; } else { throw new InvalidArgumentException('Callback needs to be NULL or callable'); } }
Set a callback that will receive every query after we run it. Callback should accept two parameters: first for SQL that was ran, and second for time that it took to run @param callable|null $callback
https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Connection/MysqliConnection.php#L955-L962
nice-php/security
src/Extension/SecurityExtension.php
SecurityExtension.load
public function load(array $configs, ContainerBuilder $container) { $configs[] = $this->options; $configuration = $this->getConfiguration($configs, $container); $config = $this->processConfiguration($configuration, $configs); $container->register('security.firewall_matcher', 'Symfony\Component\HttpFoundation\RequestMatcher') ->setPublic(false) ->addArgument($config['firewall']); $container->register('security.auth_matcher', 'Symfony\Component\HttpFoundation\RequestMatcher') ->setPublic(false) ->addArgument($config['login_path']) ->addArgument(null) ->addArgument('POST'); $container->register('security.logout_matcher', 'Symfony\Component\HttpFoundation\RequestMatcher') ->setPublic(false) ->addArgument($config['logout_path']); $authenticatorService = $this->configureAuthenticator($config['authenticator'], $container); $container->register('security.security_subscriber', 'Nice\Security\FirewallSubscriber') ->addArgument(new Reference('event_dispatcher')) ->addArgument(new Reference('security.firewall_matcher')) ->addArgument(new Reference('security.auth_matcher')) ->addArgument(new Reference('security.logout_matcher')) ->addArgument(new Reference($authenticatorService)) ->addArgument($config['login_path']) ->addArgument($config['success_path']) ->addArgument($config['token_session_key']) ->addTag('kernel.event_subscriber'); $container->register('security.auth_failure_subscriber', 'Nice\Security\AuthenticationFailureSubscriber') ->addTag('kernel.event_subscriber'); }
php
public function load(array $configs, ContainerBuilder $container) { $configs[] = $this->options; $configuration = $this->getConfiguration($configs, $container); $config = $this->processConfiguration($configuration, $configs); $container->register('security.firewall_matcher', 'Symfony\Component\HttpFoundation\RequestMatcher') ->setPublic(false) ->addArgument($config['firewall']); $container->register('security.auth_matcher', 'Symfony\Component\HttpFoundation\RequestMatcher') ->setPublic(false) ->addArgument($config['login_path']) ->addArgument(null) ->addArgument('POST'); $container->register('security.logout_matcher', 'Symfony\Component\HttpFoundation\RequestMatcher') ->setPublic(false) ->addArgument($config['logout_path']); $authenticatorService = $this->configureAuthenticator($config['authenticator'], $container); $container->register('security.security_subscriber', 'Nice\Security\FirewallSubscriber') ->addArgument(new Reference('event_dispatcher')) ->addArgument(new Reference('security.firewall_matcher')) ->addArgument(new Reference('security.auth_matcher')) ->addArgument(new Reference('security.logout_matcher')) ->addArgument(new Reference($authenticatorService)) ->addArgument($config['login_path']) ->addArgument($config['success_path']) ->addArgument($config['token_session_key']) ->addTag('kernel.event_subscriber'); $container->register('security.auth_failure_subscriber', 'Nice\Security\AuthenticationFailureSubscriber') ->addTag('kernel.event_subscriber'); }
Loads a specific configuration. @param array $configs An array of configuration values @param ContainerBuilder $container A ContainerBuilder instance
https://github.com/nice-php/security/blob/b8ec84988c2384e317b9202004e82811a49ac481/src/Extension/SecurityExtension.php#L55-L88
QoboLtd/cakephp-translations
src/Model/Table/TranslationsTable.php
TranslationsTable.getTranslations
public function getTranslations(string $modelName, string $recordId, array $options = []) { $conditions = [ 'object_model' => $modelName, 'object_foreign_key' => $recordId ]; if (!empty($options['language'])) { $conditions['language_id'] = $options['language']; } if (!empty($options['field'])) { $conditions['object_field'] = $options['field']; } $query = $this->find('all', [ 'conditions' => $conditions, 'contain' => ['Languages'], 'fields' => [ 'Translations.id', 'Translations.translation', 'Translations.object_model', 'Translations.object_field', 'Translations.object_foreign_key', 'Languages.code', ], ]); if (!empty($options['toEntity'])) { /** * @var \Translations\Model\Entity\Translation $entity */ $entity = $query->first(); return $entity; } else { $query->enableHydration(false); return $query->toList(); } }
php
public function getTranslations(string $modelName, string $recordId, array $options = []) { $conditions = [ 'object_model' => $modelName, 'object_foreign_key' => $recordId ]; if (!empty($options['language'])) { $conditions['language_id'] = $options['language']; } if (!empty($options['field'])) { $conditions['object_field'] = $options['field']; } $query = $this->find('all', [ 'conditions' => $conditions, 'contain' => ['Languages'], 'fields' => [ 'Translations.id', 'Translations.translation', 'Translations.object_model', 'Translations.object_field', 'Translations.object_foreign_key', 'Languages.code', ], ]); if (!empty($options['toEntity'])) { /** * @var \Translations\Model\Entity\Translation $entity */ $entity = $query->first(); return $entity; } else { $query->enableHydration(false); return $query->toList(); } }
getTranslations returns a list of translations existing for specified record and field. In case of passing language the result will be filtered by it additionally @param string $modelName model name @param string $recordId uuid of record the translated field belogns to @param mixed[] $options ID of the language used for translation @return \Translations\Model\Entity\Translation|array|null single record or list of saved translations
https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/TranslationsTable.php#L109-L146
QoboLtd/cakephp-translations
src/Model/Table/TranslationsTable.php
TranslationsTable.addTranslation
public function addTranslation(string $modelName, string $recordId, string $fieldName, string $language, string $translatedText): bool { /** * @var \Translations\Model\Entity\Translation $translationEntity */ $translationEntity = $this->newEntity(); $translationEntity->object_model = $modelName; $translationEntity->object_field = $fieldName; $translationEntity->object_foreign_key = $recordId; $translationEntity->language_id = $this->getLanguageId($language); $translationEntity->translation = $translatedText; $result = $this->save($translationEntity); return !empty($result->id) ? true : false; }
php
public function addTranslation(string $modelName, string $recordId, string $fieldName, string $language, string $translatedText): bool { /** * @var \Translations\Model\Entity\Translation $translationEntity */ $translationEntity = $this->newEntity(); $translationEntity->object_model = $modelName; $translationEntity->object_field = $fieldName; $translationEntity->object_foreign_key = $recordId; $translationEntity->language_id = $this->getLanguageId($language); $translationEntity->translation = $translatedText; $result = $this->save($translationEntity); return !empty($result->id) ? true : false; }
addTranslation adding a new translation for specified language and field @param string $modelName UUID record the translated field belongs to @param string $recordId translated field name @param string $fieldName language used for translation @param string $language Language @param string $translatedText Translated text @return bool true in case of successfully saved translation and false otherwise
https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/TranslationsTable.php#L160-L176
QoboLtd/cakephp-translations
src/Model/Table/TranslationsTable.php
TranslationsTable.getLanguageId
public function getLanguageId(string $shortCode): string { $query = $this->Languages->find('all', [ 'conditions' => ['Languages.code' => $shortCode] ]); $language = $query->first(); if (empty($language->id)) { throw new InvalidArgumentException("Unsupported language code [$shortCode]"); } return $language->id; }
php
public function getLanguageId(string $shortCode): string { $query = $this->Languages->find('all', [ 'conditions' => ['Languages.code' => $shortCode] ]); $language = $query->first(); if (empty($language->id)) { throw new InvalidArgumentException("Unsupported language code [$shortCode]"); } return $language->id; }
Retrive language ID by code @throws \InvalidArgumentException for unknown short code @param string $shortCode language code i.e. ru, cn etc @return string language's uuid
https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/TranslationsTable.php#L185-L197
schpill/thin
src/Minify/Css.php
Css.process
protected function process($css) { $css = str_replace("\r\n", "\n", $css); // preserve empty comment after '>' // http://www.webdevout.net/css-hacks#in_css-selectors $css = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $css); // preserve empty comment between property and value // http://css-discuss.incutio.com/?page=BoxModelHack $css = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $css); $css = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $css); // apply callback to all valid comments (and strip out surrounding ws $css = preg_replace_callback( '@\\s*/\\*([\\s\\S]*?)\\*/\\s*@', array( $this, '_commentCB' ), $css ); // remove ws around { } and last semicolon in declaration block $css = preg_replace('/\\s*{\\s*/', '{', $css); $css = preg_replace('/;?\\s*}\\s*/', '}', $css); // remove ws surrounding semicolons $css = preg_replace('/\\s*;\\s*/', ';', $css); // remove ws around urls $css = preg_replace('/ url\\( # url( \\s* ([^\\)]+?) # 1 = the URL (really just a bunch of non right parenthesis) \\s* \\) # ) /x', 'url($1)', $css ); // remove ws between rules and colons $css = preg_replace('/ \\s* ([{;]) # 1 = beginning of block or rule separator \\s* ([\\*_]?[\\w\\-]+) # 2 = property (and maybe IE filter) \\s* : \\s* (\\b|[#\'"]) # 3 = first character of a value /x', '$1$2:$3', $css ); // remove ws in selectors $css = preg_replace_callback('/ (?: # non-capture \\s* [^~>+,\\s]+ # selector part \\s* [,>+~] # combinators )+ \\s* [^~>+,\\s]+ # selector part { # open declaration block /x', array( $this, '_selectorsCB' ), $css ); // minimize hex colors $css = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i', '$1#$2$3$4$5', $css); // remove spaces between font families $css = preg_replace_callback('/font-family:([^;}]+)([;}])/', array($this, '_fontFamilyCB'), $css); $css = preg_replace('/@import\\s+url/', '@import url', $css); // replace any ws involving newlines with a single newline $css = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $css); // separate common descendent selectors w/ newlines (to limit line lengths) $css = preg_replace('/([\\w#\\.\\*]+)\\s+([\\w#\\.\\*]+){/', "$1\n$2{", $css); // Use newline after 1st numeric value (to limit line lengths). $css = preg_replace('/ ((?:padding|margin|border|outline):\\d+(?:px|em)?) # 1 = prop : 1st numeric value \\s+ /x', "$1\n", $css ); // prevent triggering IE6 bug: http://www.crankygeek.com/ie6pebug/ $css = preg_replace('/:first-l(etter|ine)\\{/', ':first-l$1 {', $css); return trim($css); }
php
protected function process($css) { $css = str_replace("\r\n", "\n", $css); // preserve empty comment after '>' // http://www.webdevout.net/css-hacks#in_css-selectors $css = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $css); // preserve empty comment between property and value // http://css-discuss.incutio.com/?page=BoxModelHack $css = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $css); $css = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $css); // apply callback to all valid comments (and strip out surrounding ws $css = preg_replace_callback( '@\\s*/\\*([\\s\\S]*?)\\*/\\s*@', array( $this, '_commentCB' ), $css ); // remove ws around { } and last semicolon in declaration block $css = preg_replace('/\\s*{\\s*/', '{', $css); $css = preg_replace('/;?\\s*}\\s*/', '}', $css); // remove ws surrounding semicolons $css = preg_replace('/\\s*;\\s*/', ';', $css); // remove ws around urls $css = preg_replace('/ url\\( # url( \\s* ([^\\)]+?) # 1 = the URL (really just a bunch of non right parenthesis) \\s* \\) # ) /x', 'url($1)', $css ); // remove ws between rules and colons $css = preg_replace('/ \\s* ([{;]) # 1 = beginning of block or rule separator \\s* ([\\*_]?[\\w\\-]+) # 2 = property (and maybe IE filter) \\s* : \\s* (\\b|[#\'"]) # 3 = first character of a value /x', '$1$2:$3', $css ); // remove ws in selectors $css = preg_replace_callback('/ (?: # non-capture \\s* [^~>+,\\s]+ # selector part \\s* [,>+~] # combinators )+ \\s* [^~>+,\\s]+ # selector part { # open declaration block /x', array( $this, '_selectorsCB' ), $css ); // minimize hex colors $css = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i', '$1#$2$3$4$5', $css); // remove spaces between font families $css = preg_replace_callback('/font-family:([^;}]+)([;}])/', array($this, '_fontFamilyCB'), $css); $css = preg_replace('/@import\\s+url/', '@import url', $css); // replace any ws involving newlines with a single newline $css = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $css); // separate common descendent selectors w/ newlines (to limit line lengths) $css = preg_replace('/([\\w#\\.\\*]+)\\s+([\\w#\\.\\*]+){/', "$1\n$2{", $css); // Use newline after 1st numeric value (to limit line lengths). $css = preg_replace('/ ((?:padding|margin|border|outline):\\d+(?:px|em)?) # 1 = prop : 1st numeric value \\s+ /x', "$1\n", $css ); // prevent triggering IE6 bug: http://www.crankygeek.com/ie6pebug/ $css = preg_replace('/:first-l(etter|ine)\\{/', ':first-l$1 {', $css); return trim($css); }
Minify a CSS string @param string $css @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Minify/Css.php#L55-L158
jtallant/skimpy-engine
spec/CMS/ContentItemSpec.php
ContentItemSpec.it_returns_a_taxonomy_if_you_access_a_property_matching_the_taxonomy_key
function it_returns_a_taxonomy_if_you_access_a_property_matching_the_taxonomy_key() { $term = $this->getTestTerm(); $this->addTerm($term); $this->categories()->shouldHaveType(Taxonomy::class); }
php
function it_returns_a_taxonomy_if_you_access_a_property_matching_the_taxonomy_key() { $term = $this->getTestTerm(); $this->addTerm($term); $this->categories()->shouldHaveType(Taxonomy::class); }
Calling contentItem->taxonomyKey() (post->categories()) should return the taxonomy with a key of 'categories' given the ContentItem has a term belonging to that taxonomy.
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/spec/CMS/ContentItemSpec.php#L125-L132
andyburton/Sonic-Framework
src/Resource/Crypt.php
Crypt._randomPassword
public static function _randomPassword ($length = 10) { // Set random characters variables $charset = self::CHARSET_RANDOM; // Set variables $charsetLength = strlen ($charset); $password = NULL; // Generate Password for ($i = 0; $i < $length; $i++) { $password .= $charset[rand (0, $charsetLength-1)]; } // Return password return $password; }
php
public static function _randomPassword ($length = 10) { // Set random characters variables $charset = self::CHARSET_RANDOM; // Set variables $charsetLength = strlen ($charset); $password = NULL; // Generate Password for ($i = 0; $i < $length; $i++) { $password .= $charset[rand (0, $charsetLength-1)]; } // Return password return $password; }
Generate a random password @param integer $length Password length @return string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Crypt.php#L38-L61
andyburton/Sonic-Framework
src/Resource/Crypt.php
Crypt._genRijndael256IV
public static function _genRijndael256IV ($cypher = FALSE) { // If a module has not been passed if (!$cypher) { // Open the cypher $cypher = mcrypt_module_open ('rijndael-256', '', 'ofb', ''); } // Create the IV $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($cypher), MCRYPT_RAND); // Close Module mcrypt_module_close ($cypher); // Return IV return $iv; }
php
public static function _genRijndael256IV ($cypher = FALSE) { // If a module has not been passed if (!$cypher) { // Open the cypher $cypher = mcrypt_module_open ('rijndael-256', '', 'ofb', ''); } // Create the IV $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($cypher), MCRYPT_RAND); // Close Module mcrypt_module_close ($cypher); // Return IV return $iv; }
Generate a rijndael 256 initialisation vector @param resource $cypher Encryption Resource @return string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Crypt.php#L70-L96
andyburton/Sonic-Framework
src/Resource/Crypt.php
Crypt._encryptRijndael256
public static function _encryptRijndael256 ($str, $key, $iv = FALSE) { // If the string is empty if (empty ($str)) { return ''; } // Open the cypher $cypher = mcrypt_module_open ('rijndael-256', '', 'ofb', ''); // Create the IV if there is none if ($iv === FALSE) { $iv = self::_genRijndael256IV ($cypher); } // Set Key $key = substr ($key, 0, mcrypt_enc_get_key_size ($cypher)); // Initialise encryption mcrypt_generic_init ($cypher, $key, $iv); // Encrypt String $encrypted = mcrypt_generic ($cypher, $strString); // Terminate encryption hander mcrypt_generic_deinit ($cypher); // Close Module mcrypt_module_close ($cypher); // Return encrypted string return $encrypted; }
php
public static function _encryptRijndael256 ($str, $key, $iv = FALSE) { // If the string is empty if (empty ($str)) { return ''; } // Open the cypher $cypher = mcrypt_module_open ('rijndael-256', '', 'ofb', ''); // Create the IV if there is none if ($iv === FALSE) { $iv = self::_genRijndael256IV ($cypher); } // Set Key $key = substr ($key, 0, mcrypt_enc_get_key_size ($cypher)); // Initialise encryption mcrypt_generic_init ($cypher, $key, $iv); // Encrypt String $encrypted = mcrypt_generic ($cypher, $strString); // Terminate encryption hander mcrypt_generic_deinit ($cypher); // Close Module mcrypt_module_close ($cypher); // Return encrypted string return $encrypted; }
Encrypt and return a string using the Rijndael 256 cypher @param string $str String to encrypt @param string $key Key to encrypt the string @param string $iv Initialisation vector @return string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Crypt.php#L107-L152
andyburton/Sonic-Framework
src/Resource/Crypt.php
Crypt._decryptRijndael256
public static function _decryptRijndael256 ($str, $key, $iv) { // If the string is empty if (empty ($str)) { return ''; } // Open the cypher $cypher = mcrypt_module_open ('rijndael-256', '', 'ofb', ''); // Set Key $key = substr ($key, 0, mcrypt_enc_get_key_size ($cypher)); // Initialise decryption mcrypt_generic_init ($cypher, $key, $iv); // Decrypt String $decrypted = mdecrypt_generic ($cypher, $str); // Terminate encryption hander mcrypt_generic_deinit ($cypher); // Close Module mcrypt_module_close ($cypher); // Return decrypted string return $decrypted; }
php
public static function _decryptRijndael256 ($str, $key, $iv) { // If the string is empty if (empty ($str)) { return ''; } // Open the cypher $cypher = mcrypt_module_open ('rijndael-256', '', 'ofb', ''); // Set Key $key = substr ($key, 0, mcrypt_enc_get_key_size ($cypher)); // Initialise decryption mcrypt_generic_init ($cypher, $key, $iv); // Decrypt String $decrypted = mdecrypt_generic ($cypher, $str); // Terminate encryption hander mcrypt_generic_deinit ($cypher); // Close Module mcrypt_module_close ($cypher); // Return decrypted string return $decrypted; }
Decrypt and return a string using the Rijndael 256 cypher @param string $str String to decrypt @param string $key Key to decrypt the string @param string $ic Initialisation vector @return string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Crypt.php#L163-L201
andyburton/Sonic-Framework
src/Resource/Crypt.php
Crypt._encryptGnuPG
public static function _encryptGnuPG ($recipient, $message, $sender = FALSE, $senderKey = '', $binary = FALSE) { // Create new GnuPG object $gpg = new \gnupg (); // Set error mode $gpg->seterrormode (\gnupg::ERROR_EXCEPTION); // If binary if ($binary) { // Turn off armored mode $gpg->setarmor (0); } // Add the recipient encryption key $gpg->addencryptkey ($recipient); // If there is a sender if ($sender !== FALSE) { // Add signature $gpg->addsignkey ($sender, $senderKey); // Return encrypted and signed data return $gpg->encryptsign ($message); } // Return encrypted data return $gpg->encrypt ($message); }
php
public static function _encryptGnuPG ($recipient, $message, $sender = FALSE, $senderKey = '', $binary = FALSE) { // Create new GnuPG object $gpg = new \gnupg (); // Set error mode $gpg->seterrormode (\gnupg::ERROR_EXCEPTION); // If binary if ($binary) { // Turn off armored mode $gpg->setarmor (0); } // Add the recipient encryption key $gpg->addencryptkey ($recipient); // If there is a sender if ($sender !== FALSE) { // Add signature $gpg->addsignkey ($sender, $senderKey); // Return encrypted and signed data return $gpg->encryptsign ($message); } // Return encrypted data return $gpg->encrypt ($message); }
GnuPG encrypt a message using the recipient public key and optionally sign http://devzone.zend.com/article/3753-Using-GnuPG-with-PHP NOTE: GnuPG must be installed and configured with PHP. The recipient must be in your public key ring @param string $recipient Recipient Indentity (e.g. email address) @param string $message Message to encrypt @param string $sender Sender Identity @param string $senderKey Key Sender Secret Key (Only required if signing) @param boolean $binary Output in binary (non-ASCII armored) @return string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Crypt.php#L232-L277
andyburton/Sonic-Framework
src/Resource/Crypt.php
Crypt._decryptGnuPG
public static function _decryptGnuPG ($recipient, $recipientKey, $message) { // Create new GnuPG object $gpg = new \gnupg (); // Set error mode $gpg->seterrormode (\gnupg::ERROR_EXCEPTION); // Add the recipient decryption key $gpg->adddecryptkey ($recipient, $recipientKey); // Return decrypted data return $gpg->decrypt ($message); }
php
public static function _decryptGnuPG ($recipient, $recipientKey, $message) { // Create new GnuPG object $gpg = new \gnupg (); // Set error mode $gpg->seterrormode (\gnupg::ERROR_EXCEPTION); // Add the recipient decryption key $gpg->adddecryptkey ($recipient, $recipientKey); // Return decrypted data return $gpg->decrypt ($message); }
GnuPG decrypt a message using the recipient private key http://devzone.zend.com/article/3753-Using-GnuPG-with-PHP NOTE: GnuPG must be installed and configured with PHP. The recipient must be in your private key ring @param string $recipient Recipient Indentity (e.g. email address) @param string $recipientKey Recipient Secret Key @param string $message Message to decrypt @return string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Crypt.php#L291-L310
andyburton/Sonic-Framework
src/Resource/Crypt.php
Crypt._verifyGnuPG
public static function _verifyGnuPG ($recipient, $recipientKey, $message) { // Create new GnuPG object $gpg = new \gnupg (); // Set error mode $gpg->seterrormode (\gnupg::ERROR_EXCEPTION); // Add the recipient decryption key $gpg->adddecryptkey ($recipient, $recipientKey); // Set decrpyted string $decrypted = ''; // Set decrypted and verification data $return[1] = $gpg->decryptverify ($message, $decrypted); // For each signature foreach ($return[1] as $key => &$signature) { // Get further user data $signature['user'] = $gpg->keyinfo ($signature['fingerprint']); } // Add decrypted data to return array $return[0] = $decrypted; // Return decryption data return $return; }
php
public static function _verifyGnuPG ($recipient, $recipientKey, $message) { // Create new GnuPG object $gpg = new \gnupg (); // Set error mode $gpg->seterrormode (\gnupg::ERROR_EXCEPTION); // Add the recipient decryption key $gpg->adddecryptkey ($recipient, $recipientKey); // Set decrpyted string $decrypted = ''; // Set decrypted and verification data $return[1] = $gpg->decryptverify ($message, $decrypted); // For each signature foreach ($return[1] as $key => &$signature) { // Get further user data $signature['user'] = $gpg->keyinfo ($signature['fingerprint']); } // Add decrypted data to return array $return[0] = $decrypted; // Return decryption data return $return; }
GnuPG decrypt and verify a message using the recipient private key Returns an array in the format: array (0 => $message, 1 => $signatures) http://devzone.zend.com/article/3753-Using-GnuPG-with-PHP NOTE: GnuPG must be installed and configured with PHP. The recipient must be in your private key ring @param string $recipient Recipient Indentity (e.g. email address) @param string $recipientKey Recipient Secret Key @param string $message Message to decrypt @return array
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Crypt.php#L325-L367
davin-bao/php-git
src/PhpGitServiceProvider.php
PhpGitServiceProvider.boot
public function boot() { // $app = $this->app; $configPath = __DIR__ . '/../config/phpgit.php'; $this->publishes([$configPath => config_path('phpgit.php')], 'config'); // If enabled is null, set from the app.debug value $enabled = $this->app['config']->get('phpgit.enabled'); if (is_null($enabled)) { $enabled = $this->checkAppDebug(); } if (! $enabled) { return; } $routeConfig = [ 'namespace' => 'DavinBao\PhpGit\Controllers', 'prefix' => $app['config']->get('phpgit.route_prefix'), 'module'=>'', ]; $this->getRouter()->group($routeConfig, function($router) { $router->get('git', [ 'uses' => 'GitController@index', 'as' => 'git.index', ]); $router->get('git/repo-list', [ 'uses' => 'GitController@getRepoList', 'as' => 'git.repo-list', ]); $router->get('git/branches', [ 'uses' => 'GitController@getBranches', 'as' => 'git.branches', ]); $router->get('git/remote-branches', [ 'uses' => 'GitController@getRemoteBranches', 'as' => 'git.remote-branches', ]); $router->post('git/checkout', [ 'uses' => 'GitController@postCheckout', 'as' => 'git.checkout', ]); $router->post('git/remote-checkout', [ 'uses' => 'GitController@postRemoteCheckout', 'as' => 'git.remote-checkout', ]); $router->post('git/delete', [ 'uses' => 'GitController@postDelete', 'as' => 'git.delete', ]); $router->get('assets/css/{name}', [ 'uses' => 'AssetController@css', 'as' => 'git.assets.css', ]); $router->get('assets/javascript/{name}', [ 'uses' => 'AssetController@js', 'as' => 'git.assets.js', ]); }); $this->loadViewsFrom(__DIR__.'/Views', 'php_git'); $this->registerMiddleware('php_git_catch_exception', 'DavinBao\PhpGit\Middleware\CatchException'); }
php
public function boot() { // $app = $this->app; $configPath = __DIR__ . '/../config/phpgit.php'; $this->publishes([$configPath => config_path('phpgit.php')], 'config'); // If enabled is null, set from the app.debug value $enabled = $this->app['config']->get('phpgit.enabled'); if (is_null($enabled)) { $enabled = $this->checkAppDebug(); } if (! $enabled) { return; } $routeConfig = [ 'namespace' => 'DavinBao\PhpGit\Controllers', 'prefix' => $app['config']->get('phpgit.route_prefix'), 'module'=>'', ]; $this->getRouter()->group($routeConfig, function($router) { $router->get('git', [ 'uses' => 'GitController@index', 'as' => 'git.index', ]); $router->get('git/repo-list', [ 'uses' => 'GitController@getRepoList', 'as' => 'git.repo-list', ]); $router->get('git/branches', [ 'uses' => 'GitController@getBranches', 'as' => 'git.branches', ]); $router->get('git/remote-branches', [ 'uses' => 'GitController@getRemoteBranches', 'as' => 'git.remote-branches', ]); $router->post('git/checkout', [ 'uses' => 'GitController@postCheckout', 'as' => 'git.checkout', ]); $router->post('git/remote-checkout', [ 'uses' => 'GitController@postRemoteCheckout', 'as' => 'git.remote-checkout', ]); $router->post('git/delete', [ 'uses' => 'GitController@postDelete', 'as' => 'git.delete', ]); $router->get('assets/css/{name}', [ 'uses' => 'AssetController@css', 'as' => 'git.assets.css', ]); $router->get('assets/javascript/{name}', [ 'uses' => 'AssetController@js', 'as' => 'git.assets.js', ]); }); $this->loadViewsFrom(__DIR__.'/Views', 'php_git'); $this->registerMiddleware('php_git_catch_exception', 'DavinBao\PhpGit\Middleware\CatchException'); }
Bootstrap the application services. @return void
https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/PhpGitServiceProvider.php#L18-L87
davin-bao/php-git
src/PhpGitServiceProvider.php
PhpGitServiceProvider.register
public function register() { $configPath = __DIR__ . '/../config/phpgit.php'; $this->mergeConfigFrom($configPath, 'phpgit'); $this->app->bindShared('command.patch.script', function () { return new \DavinBao\PhpGit\Console\Commands\PatchScript; }); $this->app->bindShared('command.patch.db', function () { return new \DavinBao\PhpGit\Console\Commands\PatchDb; }); $this->commands(array('command.patch.script', 'command.patch.db')); }
php
public function register() { $configPath = __DIR__ . '/../config/phpgit.php'; $this->mergeConfigFrom($configPath, 'phpgit'); $this->app->bindShared('command.patch.script', function () { return new \DavinBao\PhpGit\Console\Commands\PatchScript; }); $this->app->bindShared('command.patch.db', function () { return new \DavinBao\PhpGit\Console\Commands\PatchDb; }); $this->commands(array('command.patch.script', 'command.patch.db')); }
Register the application services. @return void
https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/PhpGitServiceProvider.php#L94-L108
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Input.php
Input.initFormElement
protected function initFormElement(ElementInterface $element) { $this->name($element->getName())->type('text'); $this->getElement()->addAttributes($element->getAttributes()); $type = $element->getAttribute('type'); if (null !== $type) { $this->type(strtolower($type)); } $this->value($element->getValue()); return $this; }
php
protected function initFormElement(ElementInterface $element) { $this->name($element->getName())->type('text'); $this->getElement()->addAttributes($element->getAttributes()); $type = $element->getAttribute('type'); if (null !== $type) { $this->type(strtolower($type)); } $this->value($element->getValue()); return $this; }
@param ElementInterface $element @return \SxBootstrap\View\Helper\Bootstrap\Form\Input
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Input.php#L35-L50
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Input.php
Input.render
public function render() { /* @var $doctypeHelper \Zend\View\Helper\Doctype */ $doctypeHelper = $this->getView()->plugin('doctype'); $this->getElement()->setIsXhtml($doctypeHelper->isXhtml()); return parent::render(); }
php
public function render() { /* @var $doctypeHelper \Zend\View\Helper\Doctype */ $doctypeHelper = $this->getView()->plugin('doctype'); $this->getElement()->setIsXhtml($doctypeHelper->isXhtml()); return parent::render(); }
Return the HTML string of this HTML element @return string
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Input.php#L165-L173
canax/anax-ramverk1-me
src/StyleChooser/StyleChooserController.php
StyleChooserController.initialize
public function initialize() : void { foreach (glob("{$this->cssDir}/*.css") as $file) { $filename = basename($file); $url = "{$this->cssUrl}/$filename"; $content = file_get_contents($file); $comment = strstr($content, "*/", true); $comment = preg_replace(["#\/\*!#", "#\*#"], "", $comment); $comment = preg_replace("#@#", "<br>@", $comment); $first = strpos($comment, "."); $short = substr($comment, 0, $first + 1); $long = substr($comment, $first + 1); $this->styles[$url] = [ "shortDescription" => $short, "longDescription" => $long, ]; } foreach ($this->styles as $key => $value) { $isMinified = strstr($key, ".min.css", true); if ($isMinified) { unset($this->styles["$isMinified.css"]); } } }
php
public function initialize() : void { foreach (glob("{$this->cssDir}/*.css") as $file) { $filename = basename($file); $url = "{$this->cssUrl}/$filename"; $content = file_get_contents($file); $comment = strstr($content, "*/", true); $comment = preg_replace(["#\/\*!#", "#\*#"], "", $comment); $comment = preg_replace("#@#", "<br>@", $comment); $first = strpos($comment, "."); $short = substr($comment, 0, $first + 1); $long = substr($comment, $first + 1); $this->styles[$url] = [ "shortDescription" => $short, "longDescription" => $long, ]; } foreach ($this->styles as $key => $value) { $isMinified = strstr($key, ".min.css", true); if ($isMinified) { unset($this->styles["$isMinified.css"]); } } }
The initialize method is optional and will always be called before the target method/action. This is a convienient method where you could setup internal properties that are commonly used by several methods. @return void
https://github.com/canax/anax-ramverk1-me/blob/592d5e7891f20b68047009ae2c9efdff45763543/src/StyleChooser/StyleChooserController.php#L50-L74
canax/anax-ramverk1-me
src/StyleChooser/StyleChooserController.php
StyleChooserController.indexAction
public function indexAction() : object { $title = "Stylechooser"; $page = $this->di->get("page"); $session = $this->di->get("session"); $active = $session->get(self::$key, null); $page->add("anax/stylechooser/index", [ "styles" => $this->styles, "activeStyle" => $active, "activeShortDescription" => $this->styles[$active]["shortDescription"] ?? null, "activeLongDescription" => $this->styles[$active]["longDescription"] ?? null, ]); return $page->render([ "title" => $title, ]); }
php
public function indexAction() : object { $title = "Stylechooser"; $page = $this->di->get("page"); $session = $this->di->get("session"); $active = $session->get(self::$key, null); $page->add("anax/stylechooser/index", [ "styles" => $this->styles, "activeStyle" => $active, "activeShortDescription" => $this->styles[$active]["shortDescription"] ?? null, "activeLongDescription" => $this->styles[$active]["longDescription"] ?? null, ]); return $page->render([ "title" => $title, ]); }
Display the stylechooser with details on current selected style. @return object
https://github.com/canax/anax-ramverk1-me/blob/592d5e7891f20b68047009ae2c9efdff45763543/src/StyleChooser/StyleChooserController.php#L83-L102
canax/anax-ramverk1-me
src/StyleChooser/StyleChooserController.php
StyleChooserController.updateActionPost
public function updateActionPost() : object { $response = $this->di->get("response"); $request = $this->di->get("request"); $session = $this->di->get("session"); $key = $request->getPost("stylechooser"); if ($key === "none") { $session->set("flashmessage", "Unsetting the style and using deafult style."); $session->set(self::$key, null); } elseif (array_key_exists($key, $this->styles)) { $session->set("flashmessage", "Using the style '$key'."); $session->set(self::$key, $key); } return $response->redirect("style"); }
php
public function updateActionPost() : object { $response = $this->di->get("response"); $request = $this->di->get("request"); $session = $this->di->get("session"); $key = $request->getPost("stylechooser"); if ($key === "none") { $session->set("flashmessage", "Unsetting the style and using deafult style."); $session->set(self::$key, null); } elseif (array_key_exists($key, $this->styles)) { $session->set("flashmessage", "Using the style '$key'."); $session->set(self::$key, $key); } return $response->redirect("style"); }
Update current selected style. @return object
https://github.com/canax/anax-ramverk1-me/blob/592d5e7891f20b68047009ae2c9efdff45763543/src/StyleChooser/StyleChooserController.php#L111-L127
canax/anax-ramverk1-me
src/StyleChooser/StyleChooserController.php
StyleChooserController.updateActionGet
public function updateActionGet($style) : object { $response = $this->di->get("response"); $session = $this->di->get("session"); $key = $this->cssUrl . "/" . $style . ".css"; $keyMin = $this->cssUrl . "/" . $style . ".min.css"; if ($style === "none") { $session->set("flashmessage", "Unsetting the style and using the default style."); $session->set(self::$key, null); } elseif (array_key_exists($keyMin, $this->styles)) { $session->set("flashmessage", "Now using the style '$keyMin'."); $session->set(self::$key, $keyMin); } elseif (array_key_exists($key, $this->styles)) { $session->set("flashmessage", "Now using the style '$key'."); $session->set(self::$key, $key); } $url = $session->getOnce("redirect", "style"); return $response->redirect($url); }
php
public function updateActionGet($style) : object { $response = $this->di->get("response"); $session = $this->di->get("session"); $key = $this->cssUrl . "/" . $style . ".css"; $keyMin = $this->cssUrl . "/" . $style . ".min.css"; if ($style === "none") { $session->set("flashmessage", "Unsetting the style and using the default style."); $session->set(self::$key, null); } elseif (array_key_exists($keyMin, $this->styles)) { $session->set("flashmessage", "Now using the style '$keyMin'."); $session->set(self::$key, $keyMin); } elseif (array_key_exists($key, $this->styles)) { $session->set("flashmessage", "Now using the style '$key'."); $session->set(self::$key, $key); } $url = $session->getOnce("redirect", "style"); return $response->redirect($url); }
Update current selected style using a GET url and redirect to last page visited. @param string $style the key to the style to use. @return object
https://github.com/canax/anax-ramverk1-me/blob/592d5e7891f20b68047009ae2c9efdff45763543/src/StyleChooser/StyleChooserController.php#L139-L160
schpill/thin
src/Reflection.php
Reflection.add
public function add($class = null) { $class = $this->getClass($class); if (!Arrays::exists($class, $this->reflections)) { $this->reflections[$class] = new ReflectionClass($class); } return $this; }
php
public function add($class = null) { $class = $this->getClass($class); if (!Arrays::exists($class, $this->reflections)) { $this->reflections[$class] = new ReflectionClass($class); } return $this; }
Instantiates a new ReflectionClass for the given class. @param string $class Name of a class @return Reflections $this so you can chain calls like Reflections::instance()->add('class')->get()
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Reflection.php#L25-L34
schpill/thin
src/Reflection.php
Reflection.get
public function get($class = null) { $class = $this->getClass($class); if (Arrays::exists($class, $this->reflections)) { return $this->reflections[$class]; } throw new Exception("Class not found: $class"); }
php
public function get($class = null) { $class = $this->getClass($class); if (Arrays::exists($class, $this->reflections)) { return $this->reflections[$class]; } throw new Exception("Class not found: $class"); }
Get an Instantiated ReflectionClass. @param string $class Optional name of a class @return mixed null or a ReflectionClass instance @throws Exception if class was not found
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Reflection.php#L58-L67
schpill/thin
src/Reflection.php
Reflection.getClass
private function getClass($mixed = null) { if (is_object($mixed)) { return get_class($mixed); } if (!is_null($mixed)) { return $mixed; } return $this->getCalledClass(); }
php
private function getClass($mixed = null) { if (is_object($mixed)) { return get_class($mixed); } if (!is_null($mixed)) { return $mixed; } return $this->getCalledClass(); }
Retrieve a class name to be reflected. @param mixed $mixed An object or name of a class @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Reflection.php#L75-L86
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.appendIgnorePattern
protected function appendIgnorePattern($config, $latestWrapper, $previousWrapper) { $latestWrapper->setFilter($config->filter()); $previousWrapper->setFilter($config->filter()); }
php
protected function appendIgnorePattern($config, $latestWrapper, $previousWrapper) { $latestWrapper->setFilter($config->filter()); $previousWrapper->setFilter($config->filter()); }
Add pattern to exclude files. @param Config $config @param AbstractWrapper $latestWrapper @param AbstractWrapper $previousWrapper
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L54-L58
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.debug
public function debug($message) { if ( ! $this->getOutput()->isDebug()) { return null; } if (func_num_args() > 1) { $message = vsprintf($message, array_slice(func_get_args(), 1)); } $this->getOutput()->writeln($message); }
php
public function debug($message) { if ( ! $this->getOutput()->isDebug()) { return null; } if (func_num_args() > 1) { $message = vsprintf($message, array_slice(func_get_args(), 1)); } $this->getOutput()->writeln($message); }
Print debug message. Prints debug message, if debug mode is enabled (via -vvv). @param $message @return null
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L97-L108
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.getEnvironment
public function getEnvironment($config = null) { if ( ! $this->environment) { if (null == $config) { $config = $this->getConfig(); } $this->environment = new Environment($config); } return $this->environment; }
php
public function getEnvironment($config = null) { if ( ! $this->environment) { if (null == $config) { $config = $this->getConfig(); } $this->environment = new Environment($config); } return $this->environment; }
Get environment object. @param Config $config Deprecated 4.0.0, command config will be used instead. @return Environment
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L154-L165
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.getPreviousWrapper
protected function getPreviousWrapper() { if ($this->previousWrapper) { return $this->previousWrapper; } $input = $this->getInput(); $this->previousWrapper = $this->getWrapperInstance( $input->getArgument('previous'), $input->getOption('type') ); return $this->previousWrapper; }
php
protected function getPreviousWrapper() { if ($this->previousWrapper) { return $this->previousWrapper; } $input = $this->getInput(); $this->previousWrapper = $this->getWrapperInstance( $input->getArgument('previous'), $input->getOption('type') ); return $this->previousWrapper; }
Get the wrapper for the VCS. @return AbstractWrapper
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L213-L227
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.getWrapperInstance
protected function getWrapperInstance($base, $type = 'Directory') { $wrapper = $this->getWrapperClass($type); if ( ! $wrapper) { throw new \InvalidArgumentException( sprintf( '<error>Unknown wrapper-type "%s"</error>', $type ) ); } if (is_dir($base)) { $wrapper = $this->getWrapperClass('Directory'); } $this->debug('Using wrapper "' . $wrapper . '" for "' . $base . '"'); return new $wrapper($base); }
php
protected function getWrapperInstance($base, $type = 'Directory') { $wrapper = $this->getWrapperClass($type); if ( ! $wrapper) { throw new \InvalidArgumentException( sprintf( '<error>Unknown wrapper-type "%s"</error>', $type ) ); } if (is_dir($base)) { $wrapper = $this->getWrapperClass('Directory'); } $this->debug('Using wrapper "' . $wrapper . '" for "' . $base . '"'); return new $wrapper($base); }
Create a wrapper for the given target. When the target is a directory, then the type overridden with "Directory". @param string $base @param string $type @return AbstractWrapper
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L251-L271
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.parseFiles
protected function parseFiles($wrapper, $prefix) { $this->verbose($prefix . 'Fetching files ...'); $time = microtime(true); $fileAmount = count($wrapper->getAllFileNames()); $this->verbose( sprintf( "\r" . $prefix . "Collected %d files in %0.2f seconds.", $fileAmount, microtime(true) - $time ) ); $this->verbose($prefix . 'Parsing ' . $fileAmount . ' files '); $this->debug(' in ' . $wrapper->getBasePath()); $time = microtime(true); $progress = new ProgressBar($this->getOutput(), $fileAmount); $progress->setFormat('%current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s% RAM'); $dataTree = []; foreach ($wrapper->getDataTree() as $tree) { $dataTree = $wrapper->mergeTrees($dataTree, $tree); $progress->advance(); } $progress->clear(); $this->verbose( sprintf( $prefix . "Parsed %d files in %0.2f seconds.", $fileAmount, microtime(true) - $time ) ); return $dataTree; }
php
protected function parseFiles($wrapper, $prefix) { $this->verbose($prefix . 'Fetching files ...'); $time = microtime(true); $fileAmount = count($wrapper->getAllFileNames()); $this->verbose( sprintf( "\r" . $prefix . "Collected %d files in %0.2f seconds.", $fileAmount, microtime(true) - $time ) ); $this->verbose($prefix . 'Parsing ' . $fileAmount . ' files '); $this->debug(' in ' . $wrapper->getBasePath()); $time = microtime(true); $progress = new ProgressBar($this->getOutput(), $fileAmount); $progress->setFormat('%current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s% RAM'); $dataTree = []; foreach ($wrapper->getDataTree() as $tree) { $dataTree = $wrapper->mergeTrees($dataTree, $tree); $progress->advance(); } $progress->clear(); $this->verbose( sprintf( $prefix . "Parsed %d files in %0.2f seconds.", $fileAmount, microtime(true) - $time ) ); return $dataTree; }
Parse files within a wrapper. @param AbstractWrapper $wrapper @param string $prefix @return mixed
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L348-L386
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.printConfig
protected function printConfig() { $config = $this->getConfig(); $output = $this->getOutput(); foreach ($config->ruleSet()->getChildren() as $ruleSet) { $output->writeln('Using rule set ' . $ruleSet->getName()); if ( ! $output->isDebug()) { continue; } if ( ! $ruleSet->trigger()) { $output->writeln(' No triggers found.'); continue; } foreach ($ruleSet->trigger()->getAll() as $singleTrigger) { $output->writeln(' Contains trigger ' . $singleTrigger); } } }
php
protected function printConfig() { $config = $this->getConfig(); $output = $this->getOutput(); foreach ($config->ruleSet()->getChildren() as $ruleSet) { $output->writeln('Using rule set ' . $ruleSet->getName()); if ( ! $output->isDebug()) { continue; } if ( ! $ruleSet->trigger()) { $output->writeln(' No triggers found.'); continue; } foreach ($ruleSet->trigger()->getAll() as $singleTrigger) { $output->writeln(' Contains trigger ' . $singleTrigger); } } }
Print debug information of the used config. @param Config $config @param OutputInterface $output
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L394-L415
ScreamingDev/phpsemver
lib/PHPSemVer/Console/AbstractCommand.php
AbstractCommand.resolveConfigFile
protected function resolveConfigFile() { $ruleSet = $this->getInput()->getOption('ruleSet'); if (null === $ruleSet && file_exists('phpsemver.xml')) { return 'phpsemver.xml'; } if (null === $ruleSet) { $ruleSet = 'SemVer2'; } if (file_exists($ruleSet)) { return $ruleSet; } $defaultPath = PHPSEMVER_LIB_PATH . '/PHPSemVer/Rules/'; if (file_exists($defaultPath . $ruleSet . '.xml')) { return $defaultPath . $ruleSet . '.xml'; } throw new \InvalidArgumentException( 'Could not find rule set: ' . $ruleSet ); }
php
protected function resolveConfigFile() { $ruleSet = $this->getInput()->getOption('ruleSet'); if (null === $ruleSet && file_exists('phpsemver.xml')) { return 'phpsemver.xml'; } if (null === $ruleSet) { $ruleSet = 'SemVer2'; } if (file_exists($ruleSet)) { return $ruleSet; } $defaultPath = PHPSEMVER_LIB_PATH . '/PHPSemVer/Rules/'; if (file_exists($defaultPath . $ruleSet . '.xml')) { return $defaultPath . $ruleSet . '.xml'; } throw new \InvalidArgumentException( 'Could not find rule set: ' . $ruleSet ); }
Resolve path to rule set XML. @param string $ruleSet Path to XML config file. @return string
https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Console/AbstractCommand.php#L424-L448
infusephp/auth
src/Models/UserLink.php
UserLink.url
public function url() { if ($this->type === self::FORGOT_PASSWORD) { return $this->getApp()['base_url'].'users/forgot/'.$this->link; } else if ($this->type === self::TEMPORARY) { return $this->getApp()['base_url'].'users/signup/'.$this->link; } return false; }
php
public function url() { if ($this->type === self::FORGOT_PASSWORD) { return $this->getApp()['base_url'].'users/forgot/'.$this->link; } else if ($this->type === self::TEMPORARY) { return $this->getApp()['base_url'].'users/signup/'.$this->link; } return false; }
Gets the URL for this link. @return string|false
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Models/UserLink.php#L84-L93
graze/csv-token
src/Tokeniser/StreamTokeniser.php
StreamTokeniser.getTokens
public function getTokens() { fseek($this->stream, 0); $this->buffer = new StreamBuffer($this->stream, static::BUFFER_SIZE, $this->minLength); $this->buffer->read(); /** @var Token $last */ $last = null; while (!$this->buffer->isEof()) { foreach ($this->state->match($this->buffer) as $token) { if ($token[0] == Token::T_BOM) { $this->changeEncoding($token[1]); } $this->state = $this->state->getNextState($token[0]); // merge tokens together to condense T_CONTENT tokens if ($token[0] == Token::T_CONTENT) { if (!is_null($last)) { $last[1] .= $token[1]; $last[3] = strlen($last[1]); } else { $last = $token; } } else { if (!is_null($last)) { yield $last; $last = null; } yield $token; } $this->buffer->move($token[3]); $this->buffer->read(); } } if (!is_null($last)) { yield $last; } fclose($this->stream); }
php
public function getTokens() { fseek($this->stream, 0); $this->buffer = new StreamBuffer($this->stream, static::BUFFER_SIZE, $this->minLength); $this->buffer->read(); /** @var Token $last */ $last = null; while (!$this->buffer->isEof()) { foreach ($this->state->match($this->buffer) as $token) { if ($token[0] == Token::T_BOM) { $this->changeEncoding($token[1]); } $this->state = $this->state->getNextState($token[0]); // merge tokens together to condense T_CONTENT tokens if ($token[0] == Token::T_CONTENT) { if (!is_null($last)) { $last[1] .= $token[1]; $last[3] = strlen($last[1]); } else { $last = $token; } } else { if (!is_null($last)) { yield $last; $last = null; } yield $token; } $this->buffer->move($token[3]); $this->buffer->read(); } } if (!is_null($last)) { yield $last; } fclose($this->stream); }
Loop through the stream, pulling maximum type length each time, find the largest type that matches and create a token, then move on length characters @return Iterator
https://github.com/graze/csv-token/blob/ad11cfc83e7f0cae56da6844f9216bbaf5c8dcb8/src/Tokeniser/StreamTokeniser.php#L61-L104
pmdevelopment/tool-bundle
Components/Traits/HasDoctrineTrait.php
HasDoctrineTrait.persistAndFlush
public function persistAndFlush() { if (0 === func_num_args()) { throw new \LogicException('Missing arguments'); } $persists = []; $entities = func_get_args(); foreach ($entities as $entity) { if (true === is_array($entity)) { $persists = array_merge($persists, $entity); } else { $persists[] = $entity; } } foreach ($persists as $persist) { $this->getDoctrine()->getManager()->persist($persist); } $this->getDoctrine()->getManager()->flush(); return $this; }
php
public function persistAndFlush() { if (0 === func_num_args()) { throw new \LogicException('Missing arguments'); } $persists = []; $entities = func_get_args(); foreach ($entities as $entity) { if (true === is_array($entity)) { $persists = array_merge($persists, $entity); } else { $persists[] = $entity; } } foreach ($persists as $persist) { $this->getDoctrine()->getManager()->persist($persist); } $this->getDoctrine()->getManager()->flush(); return $this; }
Persist and Flush @return $this
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Components/Traits/HasDoctrineTrait.php#L35-L59
pmdevelopment/tool-bundle
Components/Traits/HasDoctrineTrait.php
HasDoctrineTrait.removeAndFlush
public function removeAndFlush() { if (0 === func_num_args()) { throw new \LogicException('Missing arguments'); } foreach (func_get_args() as $remove) { $this->getDoctrine()->getManager()->remove($remove); } $this->getDoctrine()->getManager()->flush(); return $this; }
php
public function removeAndFlush() { if (0 === func_num_args()) { throw new \LogicException('Missing arguments'); } foreach (func_get_args() as $remove) { $this->getDoctrine()->getManager()->remove($remove); } $this->getDoctrine()->getManager()->flush(); return $this; }
Remove and Flush @return $this
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Components/Traits/HasDoctrineTrait.php#L66-L79
saxulum/saxulum-crud
src/Twig/FormLabelExtension.php
FormLabelExtension.prepareFormLabel
public function prepareFormLabel(FormView $formView) { $labelParts = $this->getLabelParts($formView); if ($labelParts[0] === '') { $labelParts[0] = 'form'; } // hack for main form: entity_edit, will be entity.edit $mainFormParts = explode('_', $labelParts[0]); unset($labelParts[0]); $labelParts = array_merge($mainFormParts, array('label'), $labelParts); foreach ($labelParts as $i => $labelPart) { $labelParts[$i] = Helper::camelCaseToUnderscore($labelPart); } return implode('.', $labelParts); }
php
public function prepareFormLabel(FormView $formView) { $labelParts = $this->getLabelParts($formView); if ($labelParts[0] === '') { $labelParts[0] = 'form'; } // hack for main form: entity_edit, will be entity.edit $mainFormParts = explode('_', $labelParts[0]); unset($labelParts[0]); $labelParts = array_merge($mainFormParts, array('label'), $labelParts); foreach ($labelParts as $i => $labelPart) { $labelParts[$i] = Helper::camelCaseToUnderscore($labelPart); } return implode('.', $labelParts); }
@param FormView $formView @return string
https://github.com/saxulum/saxulum-crud/blob/9936a1722a308ac846b0b3cfd2e099e2f50d9eb8/src/Twig/FormLabelExtension.php#L25-L44
saxulum/saxulum-crud
src/Twig/FormLabelExtension.php
FormLabelExtension.getLabelParts
protected function getLabelParts(FormView $formView) { $labelParts = array(); $collection = false; do { $name = $formView->vars['name']; if (is_numeric($name) || $name === '__name__') { $collection = true; } else { if ($collection) { $name .= '_collection'; } $labelParts[] = $name; $collection = false; } } while ($formView = $formView->parent); return array_reverse($labelParts); }
php
protected function getLabelParts(FormView $formView) { $labelParts = array(); $collection = false; do { $name = $formView->vars['name']; if (is_numeric($name) || $name === '__name__') { $collection = true; } else { if ($collection) { $name .= '_collection'; } $labelParts[] = $name; $collection = false; } } while ($formView = $formView->parent); return array_reverse($labelParts); }
@param FormView $formView @return array
https://github.com/saxulum/saxulum-crud/blob/9936a1722a308ac846b0b3cfd2e099e2f50d9eb8/src/Twig/FormLabelExtension.php#L51-L69
schpill/thin
src/Imdb/Helper.php
Helper.cleanString
public static function cleanString($sInput) { $aSearch = array( 'Full summary &raquo;', 'Full synopsis &raquo;', 'Add summary &raquo;', 'Add synopsis &raquo;', 'See more &raquo;', 'See why on IMDbPro.' ); $aReplace = array( '', '', '', '', '', '' ); $sInput = strip_tags($sInput); $sInput = str_replace('&nbsp;', ' ', $sInput); $sInput = str_replace($aSearch, $aReplace, $sInput); $sInput = html_entity_decode($sInput, ENT_QUOTES | ENT_HTML5); if (mb_substr($sInput, -3) === ' | ') { $sInput = mb_substr($sInput, 0, -3); } return trim($sInput); }
php
public static function cleanString($sInput) { $aSearch = array( 'Full summary &raquo;', 'Full synopsis &raquo;', 'Add summary &raquo;', 'Add synopsis &raquo;', 'See more &raquo;', 'See why on IMDbPro.' ); $aReplace = array( '', '', '', '', '', '' ); $sInput = strip_tags($sInput); $sInput = str_replace('&nbsp;', ' ', $sInput); $sInput = str_replace($aSearch, $aReplace, $sInput); $sInput = html_entity_decode($sInput, ENT_QUOTES | ENT_HTML5); if (mb_substr($sInput, -3) === ' | ') { $sInput = mb_substr($sInput, 0, -3); } return trim($sInput); }
@param string $sInput Input (eg. HTML). @return string Cleaned string.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Imdb/Helper.php#L81-L111
schpill/thin
src/Imdb/Helper.php
Helper.runCurl
public static function runCurl($sUrl, $bDownload = false) { $oCurl = curl_init($sUrl); curl_setopt_array($oCurl, array( CURLOPT_BINARYTRANSFER => ($bDownload ? true : false), CURLOPT_CONNECTTIMEOUT => self::IMDB_TIMEOUT, CURLOPT_ENCODING => '', CURLOPT_FOLLOWLOCATION => false, CURLOPT_FRESH_CONNECT => true, CURLOPT_HEADER => ($bDownload ? false : true), CURLOPT_HTTPHEADER => array( 'Accept-Language:' . self::IMDB_LANG, 'Accept-Charset:' . 'utf-8, iso-8859-1;q=0.8', ), CURLOPT_REFERER => 'http://www.google.com', CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => self::IMDB_TIMEOUT, CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', CURLOPT_VERBOSE => false )); $sOutput = curl_exec($oCurl); $aCurlInfo = curl_getinfo($oCurl); curl_close($oCurl); $aCurlInfo['contents'] = $sOutput; if (200 !== $aCurlInfo['http_code'] && 302 !== $aCurlInfo['http_code']) { if (true === self::IMDB_DEBUG) { echo '<pre><b>cURL returned wrong HTTP code “' . $aCurlInfo['http_code'] . '”, aborting.</b></pre>'; } return false; } return $aCurlInfo; }
php
public static function runCurl($sUrl, $bDownload = false) { $oCurl = curl_init($sUrl); curl_setopt_array($oCurl, array( CURLOPT_BINARYTRANSFER => ($bDownload ? true : false), CURLOPT_CONNECTTIMEOUT => self::IMDB_TIMEOUT, CURLOPT_ENCODING => '', CURLOPT_FOLLOWLOCATION => false, CURLOPT_FRESH_CONNECT => true, CURLOPT_HEADER => ($bDownload ? false : true), CURLOPT_HTTPHEADER => array( 'Accept-Language:' . self::IMDB_LANG, 'Accept-Charset:' . 'utf-8, iso-8859-1;q=0.8', ), CURLOPT_REFERER => 'http://www.google.com', CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => self::IMDB_TIMEOUT, CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', CURLOPT_VERBOSE => false )); $sOutput = curl_exec($oCurl); $aCurlInfo = curl_getinfo($oCurl); curl_close($oCurl); $aCurlInfo['contents'] = $sOutput; if (200 !== $aCurlInfo['http_code'] && 302 !== $aCurlInfo['http_code']) { if (true === self::IMDB_DEBUG) { echo '<pre><b>cURL returned wrong HTTP code “' . $aCurlInfo['http_code'] . '”, aborting.</b></pre>'; } return false; } return $aCurlInfo; }
@param string $sUrl The URL to fetch. @param bool $bDownload Download? @return bool|mixed Array on success, false on failure.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Imdb/Helper.php#L146-L184
amarcinkowski/hospitalplugin
src/WP/Menu.php
Menu.init
public function init($menus, $url, $unregister = null) { $this->menus = $menus; $this->url = $url; $this->unregister = $unregister; add_action('admin_menu', array( $this, 'registerPages' )); }
php
public function init($menus, $url, $unregister = null) { $this->menus = $menus; $this->url = $url; $this->unregister = $unregister; add_action('admin_menu', array( $this, 'registerPages' )); }
init
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/Menu.php#L51-L60
amarcinkowski/hospitalplugin
src/WP/Menu.php
Menu.registerPages
public function registerPages() { foreach ($this->menus as $menu) { $this->registerPage($menu['title'], $menu['cap'], $menu['link'], $menu['class'], $menu['callback'], $menu['type']); } $this->hideMenu(); }
php
public function registerPages() { foreach ($this->menus as $menu) { $this->registerPage($menu['title'], $menu['cap'], $menu['link'], $menu['class'], $menu['callback'], $menu['type']); } $this->hideMenu(); }
register menu pages
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/Menu.php#L65-L71