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
|
---|---|---|---|---|---|---|---|
codeblanche/Depend | src/Depend/Manager.php | Manager.describe | public function describe(
$className,
$params = null,
$actions = null,
ReflectionClass $reflectionClass = null,
$implementation = null
) {
$key = $this->makeKey($className);
if (isset($this->descriptors[$key]) && empty($implementation)) {
$descriptor = $this->descriptors[$key];
$descriptor->setParams($params);
if (!is_null($actions)) {
$descriptor->setActions($actions);
}
return $descriptor;
}
if (!class_exists($className) && !interface_exists($className)) {
throw new InvalidArgumentException("Class '$className' could not be found");
}
if (!is_null($implementation)) {
if (!class_exists($implementation) && !interface_exists($implementation)) {
throw new InvalidArgumentException("Class '$implementation' could not be found");
}
$reflectionClass = new ReflectionClass($implementation);
if (!$reflectionClass->isSubclassOf($className)) {
throw new InvalidArgumentException("Given class '$implementation' does not inherit from '$className'");
}
}
if (!($reflectionClass instanceof ReflectionClass)) {
$reflectionClass = new ReflectionClass($className);
}
$descriptor = clone $this->descriptorPrototype;
$this->descriptors[$key] = $descriptor;
$descriptor->load($reflectionClass)->setParams($params)->setActions($actions);
return $descriptor;
} | php | public function describe(
$className,
$params = null,
$actions = null,
ReflectionClass $reflectionClass = null,
$implementation = null
) {
$key = $this->makeKey($className);
if (isset($this->descriptors[$key]) && empty($implementation)) {
$descriptor = $this->descriptors[$key];
$descriptor->setParams($params);
if (!is_null($actions)) {
$descriptor->setActions($actions);
}
return $descriptor;
}
if (!class_exists($className) && !interface_exists($className)) {
throw new InvalidArgumentException("Class '$className' could not be found");
}
if (!is_null($implementation)) {
if (!class_exists($implementation) && !interface_exists($implementation)) {
throw new InvalidArgumentException("Class '$implementation' could not be found");
}
$reflectionClass = new ReflectionClass($implementation);
if (!$reflectionClass->isSubclassOf($className)) {
throw new InvalidArgumentException("Given class '$implementation' does not inherit from '$className'");
}
}
if (!($reflectionClass instanceof ReflectionClass)) {
$reflectionClass = new ReflectionClass($className);
}
$descriptor = clone $this->descriptorPrototype;
$this->descriptors[$key] = $descriptor;
$descriptor->load($reflectionClass)->setParams($params)->setActions($actions);
return $descriptor;
} | @param string $className
@param array $params
@param array $actions
@param ReflectionClass $reflectionClass
@param string $implementation
@throws Exception\RuntimeException
@throws Exception\InvalidArgumentException
@return Descriptor|DescriptorInterface | https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L142-L188 |
codeblanche/Depend | src/Depend/Manager.php | Manager.get | public function get($name, $paramsOverride = array())
{
$key = $this->makeKey($name);
$descriptor = $this->describe($name);
$reflectionClass = $descriptor->getReflectionClass();
$class = $reflectionClass->getName();
if (in_array($class, $this->queue)) {
$parent = end($this->queue);
throw new CircularReferenceException("Circular dependency found for class '$class' in class '$parent'. Please use a setter method to resolve this.");
}
array_push($this->queue, $class);
$params = $descriptor->getParams();
if (!empty($paramsOverride)) {
$paramsKeys = array_map(array($descriptor, 'resolveParamName'), array_keys($paramsOverride));
$paramsOverride = array_combine($paramsKeys, $paramsOverride);
$params = array_replace($params, $paramsOverride);
}
$args = $this->resolveParams($params);
array_pop($this->queue);
if ($descriptor->isShared() && isset($this->instances[$key])) {
return $this->instances[$key];
}
if ($descriptor->isCloneable() && isset($this->instances[$key])) {
return clone $this->instances[$key];
}
if (!$reflectionClass->isInstantiable()) {
throw new RuntimeException("Class '$class' is is not instantiable");
}
$this->instances[$key] = null;
if (empty($args)) {
$instance = $reflectionClass->newInstance();
}
else {
$instance = $reflectionClass->newInstanceArgs($args);
}
$this->instances[$key] = $instance;
$this->executeActions($descriptor->getActions(), $this->instances[$key]);
return $instance;
} | php | public function get($name, $paramsOverride = array())
{
$key = $this->makeKey($name);
$descriptor = $this->describe($name);
$reflectionClass = $descriptor->getReflectionClass();
$class = $reflectionClass->getName();
if (in_array($class, $this->queue)) {
$parent = end($this->queue);
throw new CircularReferenceException("Circular dependency found for class '$class' in class '$parent'. Please use a setter method to resolve this.");
}
array_push($this->queue, $class);
$params = $descriptor->getParams();
if (!empty($paramsOverride)) {
$paramsKeys = array_map(array($descriptor, 'resolveParamName'), array_keys($paramsOverride));
$paramsOverride = array_combine($paramsKeys, $paramsOverride);
$params = array_replace($params, $paramsOverride);
}
$args = $this->resolveParams($params);
array_pop($this->queue);
if ($descriptor->isShared() && isset($this->instances[$key])) {
return $this->instances[$key];
}
if ($descriptor->isCloneable() && isset($this->instances[$key])) {
return clone $this->instances[$key];
}
if (!$reflectionClass->isInstantiable()) {
throw new RuntimeException("Class '$class' is is not instantiable");
}
$this->instances[$key] = null;
if (empty($args)) {
$instance = $reflectionClass->newInstance();
}
else {
$instance = $reflectionClass->newInstanceArgs($args);
}
$this->instances[$key] = $instance;
$this->executeActions($descriptor->getActions(), $this->instances[$key]);
return $instance;
} | @param string $name Class name or alias
@param array $paramsOverride
@return object
@throws \RuntimeException | https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L197-L250 |
codeblanche/Depend | src/Depend/Manager.php | Manager.implement | public function implement($interface, $name, $actions = null)
{
return $this->describe($interface, null, $actions, null, $name);
} | php | public function implement($interface, $name, $actions = null)
{
return $this->describe($interface, null, $actions, null, $name);
} | @param string $interface
@param string $name
@param array $actions
@return Descriptor|DescriptorInterface | https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L259-L262 |
codeblanche/Depend | src/Depend/Manager.php | Manager.resolveParams | public function resolveParams($params)
{
$resolved = array();
foreach ($params as $param) {
if ($param instanceof DescriptorInterface) {
$resolved[] = $this->get($param->getName());
continue;
}
$resolved[] = $param;
}
return $resolved;
} | php | public function resolveParams($params)
{
$resolved = array();
foreach ($params as $param) {
if ($param instanceof DescriptorInterface) {
$resolved[] = $this->get($param->getName());
continue;
}
$resolved[] = $param;
}
return $resolved;
} | Resolve an array of mixed parameters and possible Descriptors.
@param array $params
@return array | https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L271-L286 |
codeblanche/Depend | src/Depend/Manager.php | Manager.set | public function set($name, $instance)
{
$key = $this->makeKey($name);
$this->alias($name, $this->describe(get_class($instance)));
$this->instances[$key] = $instance;
return $this;
} | php | public function set($name, $instance)
{
$key = $this->makeKey($name);
$this->alias($name, $this->describe(get_class($instance)));
$this->instances[$key] = $instance;
return $this;
} | Store an instance for injection by class name or alias.
@param string $name Class name or alias
@param object $instance
@return Manager | https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L296-L305 |
nnx-framework/zf2-test-toolkit | src/Listener/CallbacksListenerAggregate.php | CallbacksListenerAggregate.attach | public function attach(EventManagerInterface $events)
{
foreach ($this->eventMap as $eventName => $items) {
if (!is_array($items)) {
$errMsg = 'Handlers config not array';
throw new Exception\RuntimeException($errMsg);
}
foreach ($items as $item) {
if (!is_array($item)) {
$errMsg = 'Handler not array';
throw new Exception\RuntimeException($errMsg);
}
if (!array_key_exists('handler', $item)) {
$errMsg = 'Handler not found';
throw new Exception\RuntimeException($errMsg);
}
$handler = $item['handler'];
$priority = 1;
if (array_key_exists('priority', $item)) {
$priority = (integer)$priority;
}
$this->listeners[] = $events->attach($eventName, $handler, $priority);
}
}
} | php | public function attach(EventManagerInterface $events)
{
foreach ($this->eventMap as $eventName => $items) {
if (!is_array($items)) {
$errMsg = 'Handlers config not array';
throw new Exception\RuntimeException($errMsg);
}
foreach ($items as $item) {
if (!is_array($item)) {
$errMsg = 'Handler not array';
throw new Exception\RuntimeException($errMsg);
}
if (!array_key_exists('handler', $item)) {
$errMsg = 'Handler not found';
throw new Exception\RuntimeException($errMsg);
}
$handler = $item['handler'];
$priority = 1;
if (array_key_exists('priority', $item)) {
$priority = (integer)$priority;
}
$this->listeners[] = $events->attach($eventName, $handler, $priority);
}
}
} | @param EventManagerInterface $events
@throws \Nnx\ZF2TestToolkit\Listener\Exception\RuntimeException | https://github.com/nnx-framework/zf2-test-toolkit/blob/517a3efb28b6e88770b37dd035e76480cedb255c/src/Listener/CallbacksListenerAggregate.php#L42-L70 |
KDF5000/EasyThink | src/ThinkPHP/Mode/Api/Controller.php | Controller.ajaxReturn | protected function ajaxReturn($data,$type='') {
if(empty($type)) $type = C('DEFAULT_AJAX_RETURN');
switch (strtoupper($type)){
case 'JSON' :
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/json; charset=utf-8');
exit(json_encode($data));
case 'XML' :
// 返回xml格式数据
header('Content-Type:text/xml; charset=utf-8');
exit(xml_encode($data));
case 'JSONP':
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/json; charset=utf-8');
$handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
exit($handler.'('.json_encode($data).');');
case 'EVAL' :
// 返回可执行的js脚本
header('Content-Type:text/html; charset=utf-8');
exit($data);
}
} | php | protected function ajaxReturn($data,$type='') {
if(empty($type)) $type = C('DEFAULT_AJAX_RETURN');
switch (strtoupper($type)){
case 'JSON' :
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/json; charset=utf-8');
exit(json_encode($data));
case 'XML' :
// 返回xml格式数据
header('Content-Type:text/xml; charset=utf-8');
exit(xml_encode($data));
case 'JSONP':
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/json; charset=utf-8');
$handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
exit($handler.'('.json_encode($data).');');
case 'EVAL' :
// 返回可执行的js脚本
header('Content-Type:text/html; charset=utf-8');
exit($data);
}
} | Ajax方式返回数据到客户端
@access protected
@param mixed $data 要返回的数据
@param String $type AJAX返回数据格式
@return void | https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Mode/Api/Controller.php#L55-L76 |
RetItaliaSpA/AuthenticationBundle | Controller/GoogleController.php | GoogleController.connectAction | public function connectAction()
{
// will redirect to Facebook!
$scope = $this->getParameter('scope_auth');
if(!isset($scope)){
$scope = [];
}
return $this->get('oauth2.registry')
->getClient('google_main') // key used in config.yml
->redirect($scope);
} | php | public function connectAction()
{
// will redirect to Facebook!
$scope = $this->getParameter('scope_auth');
if(!isset($scope)){
$scope = [];
}
return $this->get('oauth2.registry')
->getClient('google_main') // key used in config.yml
->redirect($scope);
} | Link to this controller to start the "connect" process
@Route("/login", name="login") | https://github.com/RetItaliaSpA/AuthenticationBundle/blob/4c2b28d0d290a68ade9215f872c417749deea2cd/Controller/GoogleController.php#L23-L34 |
nguyenanhung/requests | src/SoapRequest.php | SoapRequest.setEndpoint | public function setEndpoint($endpoint = '')
{
$this->endpoint = $endpoint;
$this->debug->info(__FUNCTION__, 'setEndpoint: ', $this->endpoint);
return $this;
} | php | public function setEndpoint($endpoint = '')
{
$this->endpoint = $endpoint;
$this->debug->info(__FUNCTION__, 'setEndpoint: ', $this->endpoint);
return $this;
} | Function setEndpoint
@author: 713uk13m <[email protected]>
@time : 10/7/18 02:26
@param string $endpoint Link to Url Endpoint
@return $this | https://github.com/nguyenanhung/requests/blob/fae98614a256be6a3ff9bea34a273d182a3ae730/src/SoapRequest.php#L108-L114 |
nguyenanhung/requests | src/SoapRequest.php | SoapRequest.setData | public function setData($data = [])
{
$this->data = $data;
$this->debug->info(__FUNCTION__, 'setData: ', $this->data);
return $this;
} | php | public function setData($data = [])
{
$this->data = $data;
$this->debug->info(__FUNCTION__, 'setData: ', $this->data);
return $this;
} | Function setData
@author: 713uk13m <[email protected]>
@time : 10/7/18 02:26
@param array $data Data to SOAP Request, call
@return $this | https://github.com/nguyenanhung/requests/blob/fae98614a256be6a3ff9bea34a273d182a3ae730/src/SoapRequest.php#L126-L132 |
nguyenanhung/requests | src/SoapRequest.php | SoapRequest.setCallFunction | public function setCallFunction($callFunction = '')
{
$this->callFunction = $callFunction;
$this->debug->info(__FUNCTION__, 'setCallFunction: ', $this->callFunction);
return $this;
} | php | public function setCallFunction($callFunction = '')
{
$this->callFunction = $callFunction;
$this->debug->info(__FUNCTION__, 'setCallFunction: ', $this->callFunction);
return $this;
} | Function setCallFunction
@author: 713uk13m <[email protected]>
@time : 10/7/18 02:36
@param string $callFunction Require Set Function to call SOAP endpoint
@return $this | https://github.com/nguyenanhung/requests/blob/fae98614a256be6a3ff9bea34a273d182a3ae730/src/SoapRequest.php#L144-L150 |
nguyenanhung/requests | src/SoapRequest.php | SoapRequest.setFieldResult | public function setFieldResult($fieldResult = '')
{
$this->fieldResult = $fieldResult;
$this->debug->info(__FUNCTION__, 'setFieldResult: ', $this->fieldResult);
return $this;
} | php | public function setFieldResult($fieldResult = '')
{
$this->fieldResult = $fieldResult;
$this->debug->info(__FUNCTION__, 'setFieldResult: ', $this->fieldResult);
return $this;
} | Function setFieldResult
Nếu input giá trì vào đây, result sẽ map trực tiếp đến mã này
nếu không có sẽ trả error luôn
@author: 713uk13m <[email protected]>
@time : 10/7/18 02:37
@param string $fieldResult If input fieldResult, result return $response[$fieldResult] f
from Response SOAP Service
Return Error Code if not find $fieldResult from Response
@return $this | https://github.com/nguyenanhung/requests/blob/fae98614a256be6a3ff9bea34a273d182a3ae730/src/SoapRequest.php#L166-L172 |
nguyenanhung/requests | src/SoapRequest.php | SoapRequest.setResponseIsJson | public function setResponseIsJson($responseIsJson = '')
{
$this->responseIsJson = $responseIsJson;
$this->debug->info(__FUNCTION__, 'setResponseIsJson: ', $this->responseIsJson);
return $this;
} | php | public function setResponseIsJson($responseIsJson = '')
{
$this->responseIsJson = $responseIsJson;
$this->debug->info(__FUNCTION__, 'setResponseIsJson: ', $this->responseIsJson);
return $this;
} | Function setResponseIsJson
Return Response is Json if value = true
@author: 713uk13m <[email protected]>
@time : 10/8/18 19:00
@param string $responseIsJson
@return $this|mixed if set value = TRUE, response is Json string
@see clientRequestWsdl() method | https://github.com/nguyenanhung/requests/blob/fae98614a256be6a3ff9bea34a273d182a3ae730/src/SoapRequest.php#L186-L192 |
nguyenanhung/requests | src/SoapRequest.php | SoapRequest.clientRequestWsdl | public function clientRequestWsdl()
{
$this->debug->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\');
if (!class_exists('nguyenanhung\MyNuSOAP\nusoap_client')) {
$this->debug->critical(__FUNCTION__, 'nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not exists');
return NULL;
}
try {
$client = new nusoap_client($this->endpoint, TRUE);
$client->soap_defencoding = self::SOAP_ENCODING;
$client->xml_encoding = self::XML_ENCODING;
$client->decode_utf8 = self::DECODE_UTF8;
$error = $client->getError();
if ($error) {
$message = "Client Request WSDL Error: " . json_encode($error);
$this->debug->error(__FUNCTION__, $message);
} else {
$result = $client->call($this->callFunction, $this->data);
$this->debug->info(__FUNCTION__, 'Result from Endpoint: ', $result);
if ($this->fieldResult) {
if (isset($result[$this->fieldResult])) {
$this->debug->info(__FUNCTION__, 'Output Result: ', $result[$this->fieldResult]);
$message = [
'status' => 0,
'code' => $result[$this->fieldResult],
'data' => $result
];
} else {
$this->debug->info(__FUNCTION__, 'Missing Result from ' . $this->fieldResult);
$message = [
'status' => 1,
'code' => 'Missing Result from ' . $this->fieldResult,
'data' => $result
];
}
} else {
$message = [
'status' => 0,
'code' => 'Return full Response',
'data' => $result
];
}
}
}
catch (\Exception $e) {
$message = [
'status' => 2,
'code' => 'Exception Error',
'data' => [
'File' => $e->getFile(),
'Line' => $e->getLine(),
'Code' => $e->getCode(),
'Message' => $e->getMessage(),
]
];
$error_message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
$this->debug->error(__FUNCTION__, $error_message);
}
if ($this->responseIsJson) {
$this->debug->debug(__FUNCTION__, 'Response is Json');
$message = json_encode($message);
}
$this->debug->info(__FUNCTION__, 'Final Result: ', $message);
return $message;
} | php | public function clientRequestWsdl()
{
$this->debug->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\');
if (!class_exists('nguyenanhung\MyNuSOAP\nusoap_client')) {
$this->debug->critical(__FUNCTION__, 'nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not exists');
return NULL;
}
try {
$client = new nusoap_client($this->endpoint, TRUE);
$client->soap_defencoding = self::SOAP_ENCODING;
$client->xml_encoding = self::XML_ENCODING;
$client->decode_utf8 = self::DECODE_UTF8;
$error = $client->getError();
if ($error) {
$message = "Client Request WSDL Error: " . json_encode($error);
$this->debug->error(__FUNCTION__, $message);
} else {
$result = $client->call($this->callFunction, $this->data);
$this->debug->info(__FUNCTION__, 'Result from Endpoint: ', $result);
if ($this->fieldResult) {
if (isset($result[$this->fieldResult])) {
$this->debug->info(__FUNCTION__, 'Output Result: ', $result[$this->fieldResult]);
$message = [
'status' => 0,
'code' => $result[$this->fieldResult],
'data' => $result
];
} else {
$this->debug->info(__FUNCTION__, 'Missing Result from ' . $this->fieldResult);
$message = [
'status' => 1,
'code' => 'Missing Result from ' . $this->fieldResult,
'data' => $result
];
}
} else {
$message = [
'status' => 0,
'code' => 'Return full Response',
'data' => $result
];
}
}
}
catch (\Exception $e) {
$message = [
'status' => 2,
'code' => 'Exception Error',
'data' => [
'File' => $e->getFile(),
'Line' => $e->getLine(),
'Code' => $e->getCode(),
'Message' => $e->getMessage(),
]
];
$error_message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
$this->debug->error(__FUNCTION__, $error_message);
}
if ($this->responseIsJson) {
$this->debug->debug(__FUNCTION__, 'Response is Json');
$message = json_encode($message);
}
$this->debug->info(__FUNCTION__, 'Final Result: ', $message);
return $message;
} | Function clientRequestWsdl
@author: 713uk13m <[email protected]>
@time : 10/7/18 02:41
@return array|null|string Call to SOAP request and received Response from Server
Return is Json String if set setResponseIsJson(true)
Return Null if class nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not
exists | https://github.com/nguyenanhung/requests/blob/fae98614a256be6a3ff9bea34a273d182a3ae730/src/SoapRequest.php#L205-L271 |
phossa/phossa-cache | src/Phossa/Cache/Driver/DriverAwareTrait.php | DriverAwareTrait.setDriver | public function setDriver(
DriverInterface $driver,
/*# bool */ $fallback = true
) {
// ping first
if ($driver->ping()) {
$this->driver = $driver;
return;
}
// fallback
if ($fallback) {
// set to fallback driver
$this->driver = $driver->getFallback();
// issue warning
trigger_error(
Message::get(
Message::CACHE_FALLBACK_DRIVER,
get_class($driver),
get_class($this->driver)
),
E_USER_WARNING
);
} else {
throw new InvalidArgumentException(
Message::get(Message::CACHE_FAIL_DRIVER, get_class($driver)),
Message::CACHE_FAIL_DRIVER
);
}
} | php | public function setDriver(
DriverInterface $driver,
/*# bool */ $fallback = true
) {
// ping first
if ($driver->ping()) {
$this->driver = $driver;
return;
}
// fallback
if ($fallback) {
// set to fallback driver
$this->driver = $driver->getFallback();
// issue warning
trigger_error(
Message::get(
Message::CACHE_FALLBACK_DRIVER,
get_class($driver),
get_class($this->driver)
),
E_USER_WARNING
);
} else {
throw new InvalidArgumentException(
Message::get(Message::CACHE_FAIL_DRIVER, get_class($driver)),
Message::CACHE_FAIL_DRIVER
);
}
} | {@inheritDoc} | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/DriverAwareTrait.php#L44-L74 |
judus/minimal-middlewares | src/Middleware.php | Middleware.dispatch | public function dispatch(\Closure $task, $middlewares = null)
{
is_array($middlewares) || $middlewares = $this->getMiddlewares();
$beforeReturnValue = $this->before($middlewares);
if ($beforeReturnValue === false || $beforeReturnValue !== true) {
return $beforeReturnValue;
}
$this->setPayload($task());
$afterReturnValue = $this->after(array_reverse($middlewares));
if ($afterReturnValue === false || $afterReturnValue !== true) {
return $afterReturnValue;
}
return $this->getPayload();
} | php | public function dispatch(\Closure $task, $middlewares = null)
{
is_array($middlewares) || $middlewares = $this->getMiddlewares();
$beforeReturnValue = $this->before($middlewares);
if ($beforeReturnValue === false || $beforeReturnValue !== true) {
return $beforeReturnValue;
}
$this->setPayload($task());
$afterReturnValue = $this->after(array_reverse($middlewares));
if ($afterReturnValue === false || $afterReturnValue !== true) {
return $afterReturnValue;
}
return $this->getPayload();
} | @param \Closure $task
@param null $middlewares
@return mixed | https://github.com/judus/minimal-middlewares/blob/19500782209c43420732d0e678c49e4fa3e166f8/src/Middleware.php#L58-L77 |
MichaelJ2324/PHP-REST-Client | src/Endpoint/Abstracts/AbstractModelEndpoint.php | AbstractModelEndpoint.setCurrentAction | public function setCurrentAction($action,array $actionArgs = array()){
$action = (string) $action;
if (array_key_exists($action,$this->actions)){
$this->action = $action;
$this->configureAction($this->action,$actionArgs);
}
return $this;
} | php | public function setCurrentAction($action,array $actionArgs = array()){
$action = (string) $action;
if (array_key_exists($action,$this->actions)){
$this->action = $action;
$this->configureAction($this->action,$actionArgs);
}
return $this;
} | Set the current action taking place on the Model
@param string $action
@param array $actionArgs
@return $this | https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Endpoint/Abstracts/AbstractModelEndpoint.php#L232-L239 |
MichaelJ2324/PHP-REST-Client | src/Endpoint/Abstracts/AbstractModelEndpoint.php | AbstractModelEndpoint.configureAction | protected function configureAction($action,array $arguments = array()){
$this->setProperty(self::PROPERTY_HTTP_METHOD,$this->actions[$action]);
} | php | protected function configureAction($action,array $arguments = array()){
$this->setProperty(self::PROPERTY_HTTP_METHOD,$this->actions[$action]);
} | Update any properties or data based on the current action
- Called when setting the Current Action
@param $action
@param array $arguments | https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Endpoint/Abstracts/AbstractModelEndpoint.php#L254-L256 |
MichaelJ2324/PHP-REST-Client | src/Endpoint/Abstracts/AbstractModelEndpoint.php | AbstractModelEndpoint.updateModel | protected function updateModel(){
$body = $this->Response->getBody();
switch ($this->action){
case self::MODEL_ACTION_CREATE:
case self::MODEL_ACTION_UPDATE:
case self::MODEL_ACTION_RETRIEVE:
if (is_array($body)){
$this->update($body);
}
break;
case self::MODEL_ACTION_DELETE:
$this->clear();
}
} | php | protected function updateModel(){
$body = $this->Response->getBody();
switch ($this->action){
case self::MODEL_ACTION_CREATE:
case self::MODEL_ACTION_UPDATE:
case self::MODEL_ACTION_RETRIEVE:
if (is_array($body)){
$this->update($body);
}
break;
case self::MODEL_ACTION_DELETE:
$this->clear();
}
} | Called after Execute if a Request Object exists, and Request returned 200 response | https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Endpoint/Abstracts/AbstractModelEndpoint.php#L294-L307 |
tamagokun/rackem | lib/Rackem/URLMap.php | URLMap.remap | protected function remap($map)
{
$mapped = array();
foreach($map as $route=>$app)
{
$host = null;
if(preg_match('/https?:\/\/(.*?)(\/.*)/', $route, $m))
list($host, $route) = array_slice($m, 1);
if(substr($route,0,1) !== '/') throw new Exception('paths need to start with /');
$route = rtrim($route, "/");
$regex_route = str_replace("/", "\/+", $route);
$match = "/^{$regex_route}(.*)/";
$mapped[$route] = array($host, $route, $match, $app);
}
uksort($mapped, function($a, $b) { return strlen($a) < strlen($b); });
return $mapped;
} | php | protected function remap($map)
{
$mapped = array();
foreach($map as $route=>$app)
{
$host = null;
if(preg_match('/https?:\/\/(.*?)(\/.*)/', $route, $m))
list($host, $route) = array_slice($m, 1);
if(substr($route,0,1) !== '/') throw new Exception('paths need to start with /');
$route = rtrim($route, "/");
$regex_route = str_replace("/", "\/+", $route);
$match = "/^{$regex_route}(.*)/";
$mapped[$route] = array($host, $route, $match, $app);
}
uksort($mapped, function($a, $b) { return strlen($a) < strlen($b); });
return $mapped;
} | /* private | https://github.com/tamagokun/rackem/blob/8f6df86f717f9e88a31a44c0bd152f22562daea9/lib/Rackem/URLMap.php#L45-L63 |
zicht/tinymce-bundle | src/Zicht/Bundle/TinymceBundle/Helper/LocaleHelper.php | LocaleHelper.getLanguage | public static function getLanguage($locale)
{
return isset(self::$locales[$locale])
? self::$locales[$locale]
: $locale;
} | php | public static function getLanguage($locale)
{
return isset(self::$locales[$locale])
? self::$locales[$locale]
: $locale;
} | @param string $locale
@return string | https://github.com/zicht/tinymce-bundle/blob/43d2eb4eb3f7f0e4752fb496f4aada6f2d805c96/src/Zicht/Bundle/TinymceBundle/Helper/LocaleHelper.php#L29-L34 |
Dhii/iterator-abstract | src/IteratorTrait.php | IteratorTrait._rewind | protected function _rewind()
{
try {
$this->_setIteration($this->_reset());
} catch (RootException $exception) {
$this->_throwIteratorException(
$this->__('An error occurred while rewinding'),
null,
$exception
);
}
} | php | protected function _rewind()
{
try {
$this->_setIteration($this->_reset());
} catch (RootException $exception) {
$this->_throwIteratorException(
$this->__('An error occurred while rewinding'),
null,
$exception
);
}
} | Resets the iterator.
@since [*next-version*]
@see Iterator::rewind() | https://github.com/Dhii/iterator-abstract/blob/576484183865575ffc2a0d586132741329626fb8/src/IteratorTrait.php#L22-L33 |
Dhii/iterator-abstract | src/IteratorTrait.php | IteratorTrait._next | protected function _next()
{
try {
$this->_setIteration($this->_loop());
} catch (RootException $exception) {
$this->_throwIteratorException(
$this->__('An error occurred while iterating'),
null,
$exception
);
}
} | php | protected function _next()
{
try {
$this->_setIteration($this->_loop());
} catch (RootException $exception) {
$this->_throwIteratorException(
$this->__('An error occurred while iterating'),
null,
$exception
);
}
} | Advances the iterator to the next element.
@since [*next-version*]
@see Iterator::next()
@throws IteratorExceptionInterface If an error occurred during iteration. | https://github.com/Dhii/iterator-abstract/blob/576484183865575ffc2a0d586132741329626fb8/src/IteratorTrait.php#L43-L54 |
stubbles/stubbles-date | src/main/php/assert/DateEquals.php | DateEquals.describeValue | public function describeValue(Exporter $exporter, $value): string
{
if ($value instanceof Date) {
return 'date ' . $value->format('c');
}
return parent::describeValue($exporter, $value);
} | php | public function describeValue(Exporter $exporter, $value): string
{
if ($value instanceof Date) {
return 'date ' . $value->format('c');
}
return parent::describeValue($exporter, $value);
} | returns a textual description of given value
@param \SebastianBergmann\Exporter\Exporter $exporter
@param mixed $value
@return string | https://github.com/stubbles/stubbles-date/blob/98553392bec03affc53a6e3eb7f88408c2720d1c/src/main/php/assert/DateEquals.php#L117-L124 |
nirou8/php-multiple-saml | lib/Saml2/Settings.php | OneLogin_Saml2_Settings.checkIdPSettings | public function checkIdPSettings($settings)
{
assert('is_array($settings)');
if (!is_array($settings) || empty($settings)) {
return array('invalid_syntax');
}
$errors = array();
if (!isset($settings['idp']) || empty($settings['idp'])) {
$errors[] = 'idp_not_found';
} else {
$idp = $settings['idp'];
if (!isset($idp['entityId']) || empty($idp['entityId'])) {
$errors[] = 'idp_entityId_not_found';
}
if (!isset($idp['singleSignOnService'])
|| !isset($idp['singleSignOnService']['url'])
|| empty($idp['singleSignOnService']['url'])
) {
$errors[] = 'idp_sso_not_found';
} else if (!filter_var($idp['singleSignOnService']['url'], FILTER_VALIDATE_URL)) {
$errors[] = 'idp_sso_url_invalid';
}
if (isset($idp['singleLogoutService'])
&& isset($idp['singleLogoutService']['url'])
&& !empty($idp['singleLogoutService']['url'])
&& !filter_var($idp['singleLogoutService']['url'], FILTER_VALIDATE_URL)
) {
$errors[] = 'idp_slo_url_invalid';
}
if (isset($settings['security'])) {
$security = $settings['security'];
$existsX509 = isset($idp['x509cert']) && !empty($idp['x509cert']);
$existsMultiX509Sign = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['signing']) && !empty($idp['x509certMulti']['signing']);
$existsMultiX509Enc = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['encryption']) && !empty($idp['x509certMulti']['encryption']);
$existsFingerprint = isset($idp['certFingerprint']) && !empty($idp['certFingerprint']);
if (!($existsX509 || $existsFingerprint || $existsMultiX509Sign)
) {
$errors[] = 'idp_cert_or_fingerprint_not_found_and_required';
}
if ((isset($security['nameIdEncrypted']) && $security['nameIdEncrypted'] == true)
&& !($existsX509 || $existsMultiX509Enc)
) {
$errors[] = 'idp_cert_not_found_and_required';
}
}
}
return $errors;
} | php | public function checkIdPSettings($settings)
{
assert('is_array($settings)');
if (!is_array($settings) || empty($settings)) {
return array('invalid_syntax');
}
$errors = array();
if (!isset($settings['idp']) || empty($settings['idp'])) {
$errors[] = 'idp_not_found';
} else {
$idp = $settings['idp'];
if (!isset($idp['entityId']) || empty($idp['entityId'])) {
$errors[] = 'idp_entityId_not_found';
}
if (!isset($idp['singleSignOnService'])
|| !isset($idp['singleSignOnService']['url'])
|| empty($idp['singleSignOnService']['url'])
) {
$errors[] = 'idp_sso_not_found';
} else if (!filter_var($idp['singleSignOnService']['url'], FILTER_VALIDATE_URL)) {
$errors[] = 'idp_sso_url_invalid';
}
if (isset($idp['singleLogoutService'])
&& isset($idp['singleLogoutService']['url'])
&& !empty($idp['singleLogoutService']['url'])
&& !filter_var($idp['singleLogoutService']['url'], FILTER_VALIDATE_URL)
) {
$errors[] = 'idp_slo_url_invalid';
}
if (isset($settings['security'])) {
$security = $settings['security'];
$existsX509 = isset($idp['x509cert']) && !empty($idp['x509cert']);
$existsMultiX509Sign = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['signing']) && !empty($idp['x509certMulti']['signing']);
$existsMultiX509Enc = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['encryption']) && !empty($idp['x509certMulti']['encryption']);
$existsFingerprint = isset($idp['certFingerprint']) && !empty($idp['certFingerprint']);
if (!($existsX509 || $existsFingerprint || $existsMultiX509Sign)
) {
$errors[] = 'idp_cert_or_fingerprint_not_found_and_required';
}
if ((isset($security['nameIdEncrypted']) && $security['nameIdEncrypted'] == true)
&& !($existsX509 || $existsMultiX509Enc)
) {
$errors[] = 'idp_cert_not_found_and_required';
}
}
}
return $errors;
} | Checks the IdP settings info.
@param array $settings Array with settings data
@return array $errors Errors found on the IdP settings data | https://github.com/nirou8/php-multiple-saml/blob/7eb5786e678db7d45459ce3441fa187946ae9a3b/lib/Saml2/Settings.php#L497-L553 |
nirou8/php-multiple-saml | lib/Saml2/Settings.php | OneLogin_Saml2_Settings.getSPMetadata | public function getSPMetadata()
{
$metadata = OneLogin_Saml2_Metadata::builder($this->_sp, $this->_security['authnRequestsSigned'], $this->_security['wantAssertionsSigned'], null, null, $this->getContacts(), $this->getOrganization());
$certNew = $this->getSPcertNew();
if (!empty($certNew)) {
$metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors(
$metadata,
$certNew,
$this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted']
);
}
$cert = $this->getSPcert();
if (!empty($cert)) {
$metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors(
$metadata,
$cert,
$this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted']
);
}
//Sign Metadata
if (isset($this->_security['signMetadata']) && $this->_security['signMetadata'] !== false) {
if ($this->_security['signMetadata'] === true) {
$keyMetadata = $this->getSPkey();
$certMetadata = $cert;
if (!$keyMetadata) {
throw new OneLogin_Saml2_Error(
'SP Private key not found.',
OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND
);
}
if (!$certMetadata) {
throw new OneLogin_Saml2_Error(
'SP Public cert not found.',
OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND
);
}
} else {
if (!isset($this->_security['signMetadata']['keyFileName'])
|| !isset($this->_security['signMetadata']['certFileName'])
) {
throw new OneLogin_Saml2_Error(
'Invalid Setting: signMetadata value of the sp is not valid',
OneLogin_Saml2_Error::SETTINGS_INVALID_SYNTAX
);
}
$keyFileName = $this->_security['signMetadata']['keyFileName'];
$certFileName = $this->_security['signMetadata']['certFileName'];
$keyMetadataFile = $this->_paths['cert'].$keyFileName;
$certMetadataFile = $this->_paths['cert'].$certFileName;
if (!file_exists($keyMetadataFile)) {
throw new OneLogin_Saml2_Error(
'SP Private key file not found: %s',
OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND,
array($keyMetadataFile)
);
}
if (!file_exists($certMetadataFile)) {
throw new OneLogin_Saml2_Error(
'SP Public cert file not found: %s',
OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND,
array($certMetadataFile)
);
}
$keyMetadata = file_get_contents($keyMetadataFile);
$certMetadata = file_get_contents($certMetadataFile);
}
$signatureAlgorithm = $this->_security['signatureAlgorithm'];
$digestAlgorithm = $this->_security['digestAlgorithm'];
$metadata = OneLogin_Saml2_Metadata::signMetadata($metadata, $keyMetadata, $certMetadata, $signatureAlgorithm, $digestAlgorithm);
}
return $metadata;
} | php | public function getSPMetadata()
{
$metadata = OneLogin_Saml2_Metadata::builder($this->_sp, $this->_security['authnRequestsSigned'], $this->_security['wantAssertionsSigned'], null, null, $this->getContacts(), $this->getOrganization());
$certNew = $this->getSPcertNew();
if (!empty($certNew)) {
$metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors(
$metadata,
$certNew,
$this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted']
);
}
$cert = $this->getSPcert();
if (!empty($cert)) {
$metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors(
$metadata,
$cert,
$this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted']
);
}
//Sign Metadata
if (isset($this->_security['signMetadata']) && $this->_security['signMetadata'] !== false) {
if ($this->_security['signMetadata'] === true) {
$keyMetadata = $this->getSPkey();
$certMetadata = $cert;
if (!$keyMetadata) {
throw new OneLogin_Saml2_Error(
'SP Private key not found.',
OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND
);
}
if (!$certMetadata) {
throw new OneLogin_Saml2_Error(
'SP Public cert not found.',
OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND
);
}
} else {
if (!isset($this->_security['signMetadata']['keyFileName'])
|| !isset($this->_security['signMetadata']['certFileName'])
) {
throw new OneLogin_Saml2_Error(
'Invalid Setting: signMetadata value of the sp is not valid',
OneLogin_Saml2_Error::SETTINGS_INVALID_SYNTAX
);
}
$keyFileName = $this->_security['signMetadata']['keyFileName'];
$certFileName = $this->_security['signMetadata']['certFileName'];
$keyMetadataFile = $this->_paths['cert'].$keyFileName;
$certMetadataFile = $this->_paths['cert'].$certFileName;
if (!file_exists($keyMetadataFile)) {
throw new OneLogin_Saml2_Error(
'SP Private key file not found: %s',
OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND,
array($keyMetadataFile)
);
}
if (!file_exists($certMetadataFile)) {
throw new OneLogin_Saml2_Error(
'SP Public cert file not found: %s',
OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND,
array($certMetadataFile)
);
}
$keyMetadata = file_get_contents($keyMetadataFile);
$certMetadata = file_get_contents($certMetadataFile);
}
$signatureAlgorithm = $this->_security['signatureAlgorithm'];
$digestAlgorithm = $this->_security['digestAlgorithm'];
$metadata = OneLogin_Saml2_Metadata::signMetadata($metadata, $keyMetadata, $certMetadata, $signatureAlgorithm, $digestAlgorithm);
}
return $metadata;
} | Gets the SP metadata. The XML representation.
@return string SP metadata (xml)
@throws Exception
@throws OneLogin_Saml2_Error | https://github.com/nirou8/php-multiple-saml/blob/7eb5786e678db7d45459ce3441fa187946ae9a3b/lib/Saml2/Settings.php#L807-L888 |
marando/Units | src/Marando/Units/Time.php | Time.hms | public static function hms($h, $m = 0, $s = 0, $f = 0)
{
$sec = static::hmsf2sec($h, $m, $s, $f);
return static::sec($sec);
} | php | public static function hms($h, $m = 0, $s = 0, $f = 0)
{
$sec = static::hmsf2sec($h, $m, $s, $f);
return static::sec($sec);
} | Creates a new Time instance from hour, minute and second components.
@param $h Hour component
@param int $m Minute component
@param int|double $s Second component
@param int|double $f Fractional second component
@return Time | https://github.com/marando/Units/blob/1721f16a2fdbd3fd8acb9061d393ce9ef1ce6e70/src/Marando/Units/Time.php#L195-L200 |
marando/Units | src/Marando/Units/Time.php | Time.format | public function format($format)
{
$pad = false;
$rChar = 'hmsfHMS';
$string = $this->format = $format;
$string = static::encode($string, $rChar);
// Perform rounding.
$this->round = static::maxRound($format);
// Decimal years, weeks, days, hours, minutes, and seconds
static::fmtRep('Y', $string, $this->years);
static::fmtRep('W', $string, $this->weeks);
static::fmtRep('D', $string, $this->days);
static::fmtRep('H', $string, $this->hours);
static::fmtRep('M', $string, $this->min);
static::fmtRep('S', $string, $this->sec);
// Leading zeros h m s
$string = str_replace('0h', sprintf('%02d', $this->h), $string);
$string = str_replace('0m', sprintf('%02d', $this->m), $string);
$string = str_replace('0s', sprintf('%02d', $this->s), $string);
// No leading zeros, h m s
$string = str_replace('h', $this->h, $string);
$string = str_replace('m', $this->m, $string);
$string = str_replace('s', $this->s, $string);
// Fractional seconds.
if (preg_match_all('/([0-9])f/', $string, $m)) {
for ($i = 0; $i < count($m[0]); $i++) {
$f = substr($this->f, 0, $m[1][$i]);
if ($pad) {
$f = str_pad($f, $m[1][$i], '0');
$string = str_replace($m[0][$i], $f, $string);
} else {
if ($f == 0) {
$string = str_replace('.' . $m[0][$i], '', $string);
$string = str_replace($m[0][$i], '', $string);
} else {
$string = str_replace($m[0][$i], $f, $string);
}
}
}
}
return static::decode($string, $rChar);
} | php | public function format($format)
{
$pad = false;
$rChar = 'hmsfHMS';
$string = $this->format = $format;
$string = static::encode($string, $rChar);
// Perform rounding.
$this->round = static::maxRound($format);
// Decimal years, weeks, days, hours, minutes, and seconds
static::fmtRep('Y', $string, $this->years);
static::fmtRep('W', $string, $this->weeks);
static::fmtRep('D', $string, $this->days);
static::fmtRep('H', $string, $this->hours);
static::fmtRep('M', $string, $this->min);
static::fmtRep('S', $string, $this->sec);
// Leading zeros h m s
$string = str_replace('0h', sprintf('%02d', $this->h), $string);
$string = str_replace('0m', sprintf('%02d', $this->m), $string);
$string = str_replace('0s', sprintf('%02d', $this->s), $string);
// No leading zeros, h m s
$string = str_replace('h', $this->h, $string);
$string = str_replace('m', $this->m, $string);
$string = str_replace('s', $this->s, $string);
// Fractional seconds.
if (preg_match_all('/([0-9])f/', $string, $m)) {
for ($i = 0; $i < count($m[0]); $i++) {
$f = substr($this->f, 0, $m[1][$i]);
if ($pad) {
$f = str_pad($f, $m[1][$i], '0');
$string = str_replace($m[0][$i], $f, $string);
} else {
if ($f == 0) {
$string = str_replace('.' . $m[0][$i], '', $string);
$string = str_replace($m[0][$i], '', $string);
} else {
$string = str_replace($m[0][$i], $f, $string);
}
}
}
}
return static::decode($string, $rChar);
} | Formats this instance in the specified string format.
@param string $format Formatter string, e.g. 0h:0m:0s.3f
@return string | https://github.com/marando/Units/blob/1721f16a2fdbd3fd8acb9061d393ce9ef1ce6e70/src/Marando/Units/Time.php#L363-L411 |
beMang/Config-System | src/Config.php | Config.getInstance | public static function getInstance() :Config
{
if (is_null(Config::$selfInstance) || !Config::$selfInstance instanceof Config) {
Config::$selfInstance = new Config();
}
return Config::$selfInstance;
} | php | public static function getInstance() :Config
{
if (is_null(Config::$selfInstance) || !Config::$selfInstance instanceof Config) {
Config::$selfInstance = new Config();
}
return Config::$selfInstance;
} | Récupère une l'instance courante (ne change pas)
@return Config | https://github.com/beMang/Config-System/blob/3dde820cb9c40f919c173e10eccb14f2b3289aa2/src/Config.php#L26-L32 |
beMang/Config-System | src/Config.php | Config.getEmptyInstance | public static function getEmptyInstance(array $baseConfig = null) :Config
{
if (!is_null($baseConfig)) {
$config = new Config($baseConfig);
} else {
$config = new Config();
}
return $config;
} | php | public static function getEmptyInstance(array $baseConfig = null) :Config
{
if (!is_null($baseConfig)) {
$config = new Config($baseConfig);
} else {
$config = new Config();
}
return $config;
} | Récupère une instance vide de Coonfig
@return Config | https://github.com/beMang/Config-System/blob/3dde820cb9c40f919c173e10eccb14f2b3289aa2/src/Config.php#L39-L47 |
Wedeto/FileFormats | src/YAML/Reader.php | Reader.readFile | public function readFile(string $file_name)
{
// yaml_read_file does not support stream wrappers
$file_handle = @fopen($file_name, "r");
if (!is_resource($file_handle))
throw new IOException("Failed to read file: " . $file_name);
return $this->readFileHandle($file_handle);
} | php | public function readFile(string $file_name)
{
// yaml_read_file does not support stream wrappers
$file_handle = @fopen($file_name, "r");
if (!is_resource($file_handle))
throw new IOException("Failed to read file: " . $file_name);
return $this->readFileHandle($file_handle);
} | Read YAML from a file
@param string filename The file to read from
@return array The parsed data | https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/YAML/Reader.php#L46-L53 |
Wedeto/FileFormats | src/YAML/Reader.php | Reader.readFileHandle | public function readFileHandle($file_handle)
{
if (!is_resource($file_handle))
throw new \InvalidArgumentException("No file handle was provided");
$contents = "";
while (!feof($file_handle))
$contents .= fread($file_handle, 8192);
return $this->readString($contents);
} | php | public function readFileHandle($file_handle)
{
if (!is_resource($file_handle))
throw new \InvalidArgumentException("No file handle was provided");
$contents = "";
while (!feof($file_handle))
$contents .= fread($file_handle, 8192);
return $this->readString($contents);
} | Read YAML from an open resource
@param resource $file_handle The resource to read from
@return array The parsed data | https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/YAML/Reader.php#L61-L71 |
Wedeto/FileFormats | src/YAML/Reader.php | Reader.readString | public function readString(string $data)
{
$interceptor = new ErrorInterceptor(function ($data) {
return yaml_parse($data);
});
$interceptor->registerError(E_WARNING, "yaml_parse");
$result = $interceptor->execute($data);
foreach ($interceptor->getInterceptedErrors() as $error)
throw new IOException("Failed to read YAML data", $error->getCode(), $error);
return $result;
} | php | public function readString(string $data)
{
$interceptor = new ErrorInterceptor(function ($data) {
return yaml_parse($data);
});
$interceptor->registerError(E_WARNING, "yaml_parse");
$result = $interceptor->execute($data);
foreach ($interceptor->getInterceptedErrors() as $error)
throw new IOException("Failed to read YAML data", $error->getCode(), $error);
return $result;
} | Read YAML from a string
@param string $data The YAML data
@return array The parsed data | https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/YAML/Reader.php#L79-L93 |
wb-crowdfusion/crowdfusion | system/core/classes/systemdb/version/UpgradeService.php | UpgradeService.upgrade | public function upgrade()
{
$cv = $this->VersionService->getCrowdFusionVersion();
if(empty($cv))
die('Your installation lacks a Crowd Fusion version number.');
$log = "Upgrading from version [$cv] to [{$this->cfVersion}]\n";
$this->VersionService->incrementDeploymentRevision("Upgrading from version [$cv] to [{$this->cfVersion}]\n\n");
//echo str_replace("\n","<br/>",$log."<a href=\"/\">Proceed »</a>");
//exit;
} | php | public function upgrade()
{
$cv = $this->VersionService->getCrowdFusionVersion();
if(empty($cv))
die('Your installation lacks a Crowd Fusion version number.');
$log = "Upgrading from version [$cv] to [{$this->cfVersion}]\n";
$this->VersionService->incrementDeploymentRevision("Upgrading from version [$cv] to [{$this->cfVersion}]\n\n");
//echo str_replace("\n","<br/>",$log."<a href=\"/\">Proceed »</a>");
//exit;
} | } | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/version/UpgradeService.php#L53-L65 |
CalderaWP/caldera-interop | src/ComplexEntity.php | ComplexEntity.addAttribute | public function addAttribute(Attribute $attribute): ComplexEntity
{
$this->attributesCollection = $this->getAttributes()->addAttribute($attribute);
return $this;
} | php | public function addAttribute(Attribute $attribute): ComplexEntity
{
$this->attributesCollection = $this->getAttributes()->addAttribute($attribute);
return $this;
} | Add attribute definition
@param Attribute $attribute
@return ComplexEntity | https://github.com/CalderaWP/caldera-interop/blob/d25c4bc930200b314fbd42d084080b5d85261c94/src/ComplexEntity.php#L26-L30 |
CalderaWP/caldera-interop | src/ComplexEntity.php | ComplexEntity.toRestResponse | public function toRestResponse(int$status = 200, array $headers = []): RestResponseContract
{
return (new Response())->setData($this->toArray())->setStatus($status)->setHeaders($headers);
} | php | public function toRestResponse(int$status = 200, array $headers = []): RestResponseContract
{
return (new Response())->setData($this->toArray())->setStatus($status)->setHeaders($headers);
} | Create REST response from entity
@param int $status
@param array $headers
@return RestResponseContract | https://github.com/CalderaWP/caldera-interop/blob/d25c4bc930200b314fbd42d084080b5d85261c94/src/ComplexEntity.php#L53-L56 |
CalderaWP/caldera-interop | src/ComplexEntity.php | ComplexEntity.fromArray | public static function fromArray(array $items = []) : ComplexEntity
{
$obj = new static();
foreach ($obj->getAllowedProperties() as $prop) {
if (isset($items[$prop ])) {
$obj->$prop = $items[$prop ];
}
}
return $obj;
} | php | public static function fromArray(array $items = []) : ComplexEntity
{
$obj = new static();
foreach ($obj->getAllowedProperties() as $prop) {
if (isset($items[$prop ])) {
$obj->$prop = $items[$prop ];
}
}
return $obj;
} | Create from array
@param array $items
@return ComplexEntity | https://github.com/CalderaWP/caldera-interop/blob/d25c4bc930200b314fbd42d084080b5d85261c94/src/ComplexEntity.php#L78-L87 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.endsWith | public function endsWith($searchString, $position = null)
{
$length = $this->length();
$position = is_null($position) === true || $position > $length ? $length : $position;
$position -= strlen($searchString);
$lastIndex = $this->lastIndexOf($searchString, $position);
return $lastIndex !== -1 && $lastIndex === $position;
} | php | public function endsWith($searchString, $position = null)
{
$length = $this->length();
$position = is_null($position) === true || $position > $length ? $length : $position;
$position -= strlen($searchString);
$lastIndex = $this->lastIndexOf($searchString, $position);
return $lastIndex !== -1 && $lastIndex === $position;
} | The endsWith() method determines whether a string ends with the characters of another string,
returning true or false as appropriate.
@param string $searchString
@param int $position
@return bool | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L85-L93 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.includes | public function includes($searchString, $position = 0)
{
if ($position + strlen($searchString) > $this->length()) {
return false;
}
return $this->indexOf($searchString, $position) !== -1;
} | php | public function includes($searchString, $position = 0)
{
if ($position + strlen($searchString) > $this->length()) {
return false;
}
return $this->indexOf($searchString, $position) !== -1;
} | The includes() method determines whether one string may be found within another string,
returning true or false as appropriate.
@param string $searchString
@param int $position
@return bool | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L103-L110 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.indexOf | public function indexOf($searchValue, $fromIndex = 0)
{
if (empty($searchValue) === true) {
return $fromIndex;
}
$result = strpos($this->subject, $searchValue, $fromIndex);
return $result === false ? -1 : $result;
} | php | public function indexOf($searchValue, $fromIndex = 0)
{
if (empty($searchValue) === true) {
return $fromIndex;
}
$result = strpos($this->subject, $searchValue, $fromIndex);
return $result === false ? -1 : $result;
} | The indexOf() method returns the index within the calling String object of the first occurrence of the specified value,
starting the search at fromIndex. Returns -1 if the value is not found.
@param string $searchValue
@param int $fromIndex
@return int | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L120-L129 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.lastIndexOf | public function lastIndexOf($searchValue, $fromIndex = null)
{
if (empty($searchValue) === true) {
return $fromIndex ?: $this->length();
}
if ($fromIndex === 0 || $fromIndex < 0) {
return strrpos($this->subject, $searchValue, $fromIndex) !== 0 ? -1 : 0;
}
$fromIndex = $fromIndex ?: 0;
$result = strrpos($this->subject, $searchValue, $fromIndex);
return $result === false ? -1 : $result;
} | php | public function lastIndexOf($searchValue, $fromIndex = null)
{
if (empty($searchValue) === true) {
return $fromIndex ?: $this->length();
}
if ($fromIndex === 0 || $fromIndex < 0) {
return strrpos($this->subject, $searchValue, $fromIndex) !== 0 ? -1 : 0;
}
$fromIndex = $fromIndex ?: 0;
$result = strrpos($this->subject, $searchValue, $fromIndex);
return $result === false ? -1 : $result;
} | The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value,
searching backwards from fromIndex. Returns -1 if the value is not found.
@param string $searchValue
@param int $fromIndex
@return int | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L139-L153 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.match | public function match($regexp, $flag = PREG_PATTERN_ORDER, $offset = 0)
{
if ((bool) preg_match_all($regexp, $this->subject, $matches, $flag, $offset) === false) {
return;
}
return $matches;
} | php | public function match($regexp, $flag = PREG_PATTERN_ORDER, $offset = 0)
{
if ((bool) preg_match_all($regexp, $this->subject, $matches, $flag, $offset) === false) {
return;
}
return $matches;
} | The match() method retrieves the matches when matching a string against a regular expression.
@param string $regexp
@param int $flag
@param int $offset
@return array | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L173-L180 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.replace | public function replace($regexp, $replacement = null)
{
if (is_array($regexp) === true && is_null($replacement) === true) {
return new static(strtr($this->subject, $regexp));
}
if (is_callable($replacement) === true) {
return new static(preg_replace_callback($regexp, $replacement, $this->subject));
}
return new static(preg_replace($regexp, $replacement, $this->subject));
} | php | public function replace($regexp, $replacement = null)
{
if (is_array($regexp) === true && is_null($replacement) === true) {
return new static(strtr($this->subject, $regexp));
}
if (is_callable($replacement) === true) {
return new static(preg_replace_callback($regexp, $replacement, $this->subject));
}
return new static(preg_replace($regexp, $replacement, $this->subject));
} | The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
@param mixed $regexp
@param mixed $replacement
@return static | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L226-L237 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.search | public function search($regexp)
{
if ((bool) preg_match($regexp, $this->subject, $match, PREG_OFFSET_CAPTURE) === false) {
return -1;
}
return $match[0][1];
} | php | public function search($regexp)
{
if ((bool) preg_match($regexp, $this->subject, $match, PREG_OFFSET_CAPTURE) === false) {
return -1;
}
return $match[0][1];
} | The search() method executes a search for a match between a regular expression and this String object.
@param string $regexp
@return int | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L245-L252 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.slice | public function slice($startSlice, $endSlice = null)
{
$length = $this->length();
$startSlice = $startSlice < 0 ? $length + $startSlice : $startSlice;
if (is_null($endSlice) === true) {
return $this->substr($startSlice, $length - $startSlice);
}
$endSlice = $endSlice < 0 ? $length + $endSlice : $endSlice;
$endSlice -= $startSlice;
return $this->substr($startSlice, $endSlice);
} | php | public function slice($startSlice, $endSlice = null)
{
$length = $this->length();
$startSlice = $startSlice < 0 ? $length + $startSlice : $startSlice;
if (is_null($endSlice) === true) {
return $this->substr($startSlice, $length - $startSlice);
}
$endSlice = $endSlice < 0 ? $length + $endSlice : $endSlice;
$endSlice -= $startSlice;
return $this->substr($startSlice, $endSlice);
} | The slice() method extracts a section of a string and returns a new string.
@param int $startSlice
@param int $endSlice
@return static | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L261-L274 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.split | public function split($separator = null)
{
if (is_null($separator) === true) {
return [$this->subject];
}
return new JArray(explode($separator, $this->subject));
} | php | public function split($separator = null)
{
if (is_null($separator) === true) {
return [$this->subject];
}
return new JArray(explode($separator, $this->subject));
} | The split() method splits a String object into an array of strings by separating the string into substrings.
@param string|null $separator
@return Recca0120\Lodash\Arr | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L282-L289 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.startsWith | public function startsWith($searchString, $position = 0)
{
return $this->substr($position, strlen($searchString))->value() === $searchString;
} | php | public function startsWith($searchString, $position = 0)
{
return $this->substr($position, strlen($searchString))->value() === $searchString;
} | The startsWith() method determines whether a string begins with the characters of another string, returning true or false as appropriate.
@param string $searchString
@param int $position
@return bool | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L298-L301 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.substr | public function substr()
{
$result = call_user_func_array('substr', array_merge([$this->subject], func_get_args()));
$result = $result === false ? '' : $result;
return new static($result);
} | php | public function substr()
{
$result = call_user_func_array('substr', array_merge([$this->subject], func_get_args()));
$result = $result === false ? '' : $result;
return new static($result);
} | The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
@return static | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L308-L314 |
recca0120/lodash-php | src/JString/Javascript.php | Javascript.substring | public function substring($indexStart, $indexEnd = null)
{
if (is_null($indexEnd) === true) {
$indexEnd = $this->length();
}
$temp = [$indexStart, $indexEnd];
sort($temp);
return $this->slice($temp[0], $temp[1]);
} | php | public function substring($indexStart, $indexEnd = null)
{
if (is_null($indexEnd) === true) {
$indexEnd = $this->length();
}
$temp = [$indexStart, $indexEnd];
sort($temp);
return $this->slice($temp[0], $temp[1]);
} | The substring() method returns a subset of a string between one index and another, or through the end of the string.
@param int $indexStart
@param int $indexEnd
@return static | https://github.com/recca0120/lodash-php/blob/65f8c80accfc2b087abf6d0590a5bd9fd15b467d/src/JString/Javascript.php#L323-L333 |
horntell/php-sdk | lib/guzzle/GuzzleHttp/QueryParser.php | QueryParser.parseInto | public function parseInto(Query $query, $str, $urlEncoding = true)
{
if ($str === '') {
return;
}
$result = [];
$this->duplicates = false;
$this->numericIndices = true;
$decoder = self::getDecoder($urlEncoding);
foreach (explode('&', $str) as $kvp) {
$parts = explode('=', $kvp, 2);
$key = $decoder($parts[0]);
$value = isset($parts[1]) ? $decoder($parts[1]) : null;
// Special handling needs to be taken for PHP nested array syntax
if (strpos($key, '[') !== false) {
$this->parsePhpValue($key, $value, $result);
continue;
}
if (!isset($result[$key])) {
$result[$key] = $value;
} else {
$this->duplicates = true;
if (!is_array($result[$key])) {
$result[$key] = [$result[$key]];
}
$result[$key][] = $value;
}
}
$query->replace($result);
if (!$this->numericIndices) {
$query->setAggregator(Query::phpAggregator(false));
} elseif ($this->duplicates) {
$query->setAggregator(Query::duplicateAggregator());
}
} | php | public function parseInto(Query $query, $str, $urlEncoding = true)
{
if ($str === '') {
return;
}
$result = [];
$this->duplicates = false;
$this->numericIndices = true;
$decoder = self::getDecoder($urlEncoding);
foreach (explode('&', $str) as $kvp) {
$parts = explode('=', $kvp, 2);
$key = $decoder($parts[0]);
$value = isset($parts[1]) ? $decoder($parts[1]) : null;
// Special handling needs to be taken for PHP nested array syntax
if (strpos($key, '[') !== false) {
$this->parsePhpValue($key, $value, $result);
continue;
}
if (!isset($result[$key])) {
$result[$key] = $value;
} else {
$this->duplicates = true;
if (!is_array($result[$key])) {
$result[$key] = [$result[$key]];
}
$result[$key][] = $value;
}
}
$query->replace($result);
if (!$this->numericIndices) {
$query->setAggregator(Query::phpAggregator(false));
} elseif ($this->duplicates) {
$query->setAggregator(Query::duplicateAggregator());
}
} | Parse a query string into a Query object.
@param Query $query Query object to populate
@param string $str Query string to parse
@param bool|string $urlEncoding How the query string is encoded | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/QueryParser.php#L26-L67 |
horntell/php-sdk | lib/guzzle/GuzzleHttp/QueryParser.php | QueryParser.getDecoder | private static function getDecoder($type)
{
if ($type === true) {
return function ($value) {
return rawurldecode(str_replace('+', ' ', $value));
};
} elseif ($type == Query::RFC3986) {
return 'rawurldecode';
} elseif ($type == Query::RFC1738) {
return 'urldecode';
} else {
return function ($str) { return $str; };
}
} | php | private static function getDecoder($type)
{
if ($type === true) {
return function ($value) {
return rawurldecode(str_replace('+', ' ', $value));
};
} elseif ($type == Query::RFC3986) {
return 'rawurldecode';
} elseif ($type == Query::RFC1738) {
return 'urldecode';
} else {
return function ($str) { return $str; };
}
} | Returns a callable that is used to URL decode query keys and values.
@param string|bool $type One of true, false, RFC3986, and RFC1738
@return callable|string | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/QueryParser.php#L76-L89 |
horntell/php-sdk | lib/guzzle/GuzzleHttp/QueryParser.php | QueryParser.parsePhpValue | private function parsePhpValue($key, $value, array &$result)
{
$node =& $result;
$keyBuffer = '';
for ($i = 0, $t = strlen($key); $i < $t; $i++) {
switch ($key[$i]) {
case '[':
if ($keyBuffer) {
$this->prepareNode($node, $keyBuffer);
$node =& $node[$keyBuffer];
$keyBuffer = '';
}
break;
case ']':
$k = $this->cleanKey($node, $keyBuffer);
$this->prepareNode($node, $k);
$node =& $node[$k];
$keyBuffer = '';
break;
default:
$keyBuffer .= $key[$i];
break;
}
}
if (isset($node)) {
$this->duplicates = true;
$node[] = $value;
} else {
$node = $value;
}
} | php | private function parsePhpValue($key, $value, array &$result)
{
$node =& $result;
$keyBuffer = '';
for ($i = 0, $t = strlen($key); $i < $t; $i++) {
switch ($key[$i]) {
case '[':
if ($keyBuffer) {
$this->prepareNode($node, $keyBuffer);
$node =& $node[$keyBuffer];
$keyBuffer = '';
}
break;
case ']':
$k = $this->cleanKey($node, $keyBuffer);
$this->prepareNode($node, $k);
$node =& $node[$k];
$keyBuffer = '';
break;
default:
$keyBuffer .= $key[$i];
break;
}
}
if (isset($node)) {
$this->duplicates = true;
$node[] = $value;
} else {
$node = $value;
}
} | Parses a PHP style key value pair.
@param string $key Key to parse (e.g., "foo[a][b]")
@param string|null $value Value to set
@param array $result Result to modify by reference | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/QueryParser.php#L98-L130 |
horntell/php-sdk | lib/guzzle/GuzzleHttp/QueryParser.php | QueryParser.prepareNode | private function prepareNode(&$node, $key)
{
if (!isset($node[$key])) {
$node[$key] = null;
} elseif (!is_array($node[$key])) {
$node[$key] = [$node[$key]];
}
} | php | private function prepareNode(&$node, $key)
{
if (!isset($node[$key])) {
$node[$key] = null;
} elseif (!is_array($node[$key])) {
$node[$key] = [$node[$key]];
}
} | Prepares a value in the array at the given key.
If the key already exists, the key value is converted into an array.
@param array $node Result node to modify
@param string $key Key to add or modify in the node | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/QueryParser.php#L140-L147 |
horntell/php-sdk | lib/guzzle/GuzzleHttp/QueryParser.php | QueryParser.cleanKey | private function cleanKey($node, $key)
{
if ($key === '') {
$key = $node ? (string) count($node) : 0;
// Found a [] key, so track this to ensure that we disable numeric
// indexing of keys in the resolved query aggregator.
$this->numericIndices = false;
}
return $key;
} | php | private function cleanKey($node, $key)
{
if ($key === '') {
$key = $node ? (string) count($node) : 0;
// Found a [] key, so track this to ensure that we disable numeric
// indexing of keys in the resolved query aggregator.
$this->numericIndices = false;
}
return $key;
} | Returns the appropriate key based on the node and key. | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/QueryParser.php#L152-L162 |
froq/froq-acl | src/Acl.php | Acl.setUser | public function setUser(User $user): void
{
$this->user = $user;
$this->user->setAcl($this);
$userRole = $this->user->getRole();
if ($userRole != null && !empty($this->rules)) {
foreach ($this->rules as $role => $rules) {
if ($userRole == $role) {
foreach ($rules as $uri => $rules) {
$this->user->setPermissionsOf($uri, (array) explode(',', $rules) /* 'read,write' etc. */);
}
break;
}
}
}
} | php | public function setUser(User $user): void
{
$this->user = $user;
$this->user->setAcl($this);
$userRole = $this->user->getRole();
if ($userRole != null && !empty($this->rules)) {
foreach ($this->rules as $role => $rules) {
if ($userRole == $role) {
foreach ($rules as $uri => $rules) {
$this->user->setPermissionsOf($uri, (array) explode(',', $rules) /* 'read,write' etc. */);
}
break;
}
}
}
} | Set user.
@param froq\acl\User $user
@return void | https://github.com/froq/froq-acl/blob/ab1897dea20b16dfd8f0a6349224e94d160a0540/src/Acl.php#L89-L105 |
zhaoxianfang/tools | src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php | NodeBuilder.append | public function append(NodeDefinition $node)
{
if ($node instanceof ParentNodeDefinitionInterface) {
$builder = clone $this;
$builder->setParent(null);
$node->setBuilder($builder);
}
if (null !== $this->parent) {
$this->parent->append($node);
// Make this builder the node parent to allow for a fluid interface
$node->setParent($this);
}
return $this;
} | php | public function append(NodeDefinition $node)
{
if ($node instanceof ParentNodeDefinitionInterface) {
$builder = clone $this;
$builder->setParent(null);
$node->setBuilder($builder);
}
if (null !== $this->parent) {
$this->parent->append($node);
// Make this builder the node parent to allow for a fluid interface
$node->setParent($this);
}
return $this;
} | Appends a node definition.
Usage:
$node = new ArrayNodeDefinition('name')
->children()
->scalarNode('foo')->end()
->scalarNode('baz')->end()
->append($this->getBarNodeDefinition())
->end()
;
@return $this | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/Config/Definition/Builder/NodeBuilder.php#L180-L195 |
anime-db/catalog-bundle | src/Form/Type/Entity/Item.php | Item.getRefillAttr | protected function getRefillAttr($field, ItemEntity $item = null)
{
// item exists and can be refilled
if ($item instanceof ItemEntity && $item->getName() &&
($plugins = $this->chain->getPluginsThatCanFillItem($item, $field))
) {
/* @var $plugin RefillerInterface */
foreach ($plugins as $key => $plugin) {
$plugins[$key] = [
'name' => $plugin->getName(),
'title' => $plugin->getTitle(),
'can_refill' => $plugin->isCanRefill($item, $field), // can refill or can search
];
}
return [
'data-type' => 'refill',
'data-plugins' => $this->templating->render(
'AnimeDbCatalogBundle:Form:refillers.html.twig',
[
'item' => $item,
'field' => $field,
'plugins' => $plugins,
]
),
];
}
return [];
} | php | protected function getRefillAttr($field, ItemEntity $item = null)
{
// item exists and can be refilled
if ($item instanceof ItemEntity && $item->getName() &&
($plugins = $this->chain->getPluginsThatCanFillItem($item, $field))
) {
/* @var $plugin RefillerInterface */
foreach ($plugins as $key => $plugin) {
$plugins[$key] = [
'name' => $plugin->getName(),
'title' => $plugin->getTitle(),
'can_refill' => $plugin->isCanRefill($item, $field), // can refill or can search
];
}
return [
'data-type' => 'refill',
'data-plugins' => $this->templating->render(
'AnimeDbCatalogBundle:Form:refillers.html.twig',
[
'item' => $item,
'field' => $field,
'plugins' => $plugins,
]
),
];
}
return [];
} | Get the field refill attributes.
@param string $field
@param ItemEntity|null $item
@return array | https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Form/Type/Entity/Item.php#L259-L288 |
azhai/code-refactor | src/CodeRefactor/Mixin/BaseMixin.php | BaseMixin.dupAllDocComments | public function dupAllDocComments()
{
if ($doc_comments = $this->getDocComment(true)) {
foreach ($doc_comments as $doc_comment) {
$this->addComment($doc_comment);
}
}
} | php | public function dupAllDocComments()
{
if ($doc_comments = $this->getDocComment(true)) {
foreach ($doc_comments as $doc_comment) {
$this->addComment($doc_comment);
}
}
} | 复制所有文档式注释 | https://github.com/azhai/code-refactor/blob/cddb437d72f8239957daeba8211dda5e9366d6ca/src/CodeRefactor/Mixin/BaseMixin.php#L44-L51 |
azhai/code-refactor | src/CodeRefactor/Mixin/BaseMixin.php | BaseMixin.find | public function find($type, $pattern = false, $callback = null)
{
if (!isset($this->{$type})) {
return [];
}
$components = to_array($this->{$type}, false);
$result = [];
foreach ($components as $name => $node) {
if (empty($pattern) || preg_match($pattern, $name)) {
if (is_callable($callback)) {
$node = exec_function_array($callback, [$node, $this]);
}
$result[$name] = $node;
}
}
return $result;
} | php | public function find($type, $pattern = false, $callback = null)
{
if (!isset($this->{$type})) {
return [];
}
$components = to_array($this->{$type}, false);
$result = [];
foreach ($components as $name => $node) {
if (empty($pattern) || preg_match($pattern, $name)) {
if (is_callable($callback)) {
$node = exec_function_array($callback, [$node, $this]);
}
$result[$name] = $node;
}
}
return $result;
} | 查找和修改下级代码对象
@param string $type 代码类型
@param bool/string $pattern 名称正则式
@param null/function $callback 修改回调函数
@return array | https://github.com/azhai/code-refactor/blob/cddb437d72f8239957daeba8211dda5e9366d6ca/src/CodeRefactor/Mixin/BaseMixin.php#L61-L77 |
azhai/code-refactor | src/CodeRefactor/Mixin/BaseMixin.php | BaseMixin.fixedBy | public function fixedBy(Refactor $refactor)
{
if ($traverser = $refactor->getTraverser()) {
$this->stmts = $traverser->traverse($this->stmts);
}
return $this;
} | php | public function fixedBy(Refactor $refactor)
{
if ($traverser = $refactor->getTraverser()) {
$this->stmts = $traverser->traverse($this->stmts);
}
return $this;
} | 遍历和修改代码. | https://github.com/azhai/code-refactor/blob/cddb437d72f8239957daeba8211dda5e9366d6ca/src/CodeRefactor/Mixin/BaseMixin.php#L82-L88 |
romm/configuration_object | Classes/Validation/Validator/IconExistsValidator.php | IconExistsValidator.isValid | public function isValid($value)
{
if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '7.6.0', '<')) {
throw new UnsupportedVersionException(
'The validator "' . self::class . '" cannot be used in TYPO3 versions anterior to `7.6.0`.',
1506281412
);
}
$value = (string)$value;
if (false === $this->getIconRegistry()->isRegistered($value)) {
$errorMessage = $this->translateErrorMessage('validator.icon_exists.not_valid', 'configuration_object', [$value]);
$this->addError($errorMessage, 1506272737);
}
} | php | public function isValid($value)
{
if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '7.6.0', '<')) {
throw new UnsupportedVersionException(
'The validator "' . self::class . '" cannot be used in TYPO3 versions anterior to `7.6.0`.',
1506281412
);
}
$value = (string)$value;
if (false === $this->getIconRegistry()->isRegistered($value)) {
$errorMessage = $this->translateErrorMessage('validator.icon_exists.not_valid', 'configuration_object', [$value]);
$this->addError($errorMessage, 1506272737);
}
} | Checks that the given icon identifier exists in the TYPO3 icon registry.
@param mixed $value
@throws UnsupportedVersionException | https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Validation/Validator/IconExistsValidator.php#L30-L45 |
spryker/shopping-list-data-import | src/Spryker/Zed/ShoppingListDataImport/Business/ShoppingListDataImportStep/ShoppingListKeyToIdShoppingList.php | ShoppingListKeyToIdShoppingList.execute | public function execute(DataSetInterface $dataSet): void
{
$shoppingListKey = $dataSet[ShoppingListItemDataSetInterface::COLUMN_SHOPPING_LIST_KEY];
if (!isset($this->idShoppingListCache[$shoppingListKey])) {
$shoppingListQuery = new SpyShoppingListQuery();
$idShoppingList = $shoppingListQuery
->select([SpyShoppingListTableMap::COL_ID_SHOPPING_LIST])
->findOneByKey($shoppingListKey);
if (!$idShoppingList) {
throw new EntityNotFoundException(sprintf('Could not find shopping list by key "%s"', $shoppingListKey));
}
$this->idShoppingListCache[$shoppingListKey] = $idShoppingList;
}
$dataSet[ShoppingListItemDataSetInterface::ID_SHOPPING_LIST] = $this->idShoppingListCache[$shoppingListKey];
} | php | public function execute(DataSetInterface $dataSet): void
{
$shoppingListKey = $dataSet[ShoppingListItemDataSetInterface::COLUMN_SHOPPING_LIST_KEY];
if (!isset($this->idShoppingListCache[$shoppingListKey])) {
$shoppingListQuery = new SpyShoppingListQuery();
$idShoppingList = $shoppingListQuery
->select([SpyShoppingListTableMap::COL_ID_SHOPPING_LIST])
->findOneByKey($shoppingListKey);
if (!$idShoppingList) {
throw new EntityNotFoundException(sprintf('Could not find shopping list by key "%s"', $shoppingListKey));
}
$this->idShoppingListCache[$shoppingListKey] = $idShoppingList;
}
$dataSet[ShoppingListItemDataSetInterface::ID_SHOPPING_LIST] = $this->idShoppingListCache[$shoppingListKey];
} | @param \Spryker\Zed\DataImport\Business\Model\DataSet\DataSetInterface $dataSet
@throws \Spryker\Zed\DataImport\Business\Exception\EntityNotFoundException
@return void | https://github.com/spryker/shopping-list-data-import/blob/6313fc39e8ee79a08f7b97d81da7f4056c066674/src/Spryker/Zed/ShoppingListDataImport/Business/ShoppingListDataImportStep/ShoppingListKeyToIdShoppingList.php#L31-L49 |
ekyna/MediaBundle | Controller/MediaController.php | MediaController.downloadAction | public function downloadAction(Request $request)
{
/**
* @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media
* @var \League\Flysystem\File $file
*/
list($media, $file) = $this->findMedia($request->attributes->get('key'));
$lastModified = $media->getUpdatedAt();
$response = new Response();
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag(md5($file->getPath().$lastModified->getTimestamp()));
if ($response->isNotModified($request)) {
return $response;
}
$response = new StreamedResponse();
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag(md5($file->getPath().$lastModified->getTimestamp()));
// Set the headers
$response->headers->set('Content-Type', $file->getMimetype());
$response->headers->set('Content-Length', $file->getSize());
$response->setCallback(function () use ($file) {
fpassthru($file->readStream());
});
return $response;
} | php | public function downloadAction(Request $request)
{
/**
* @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media
* @var \League\Flysystem\File $file
*/
list($media, $file) = $this->findMedia($request->attributes->get('key'));
$lastModified = $media->getUpdatedAt();
$response = new Response();
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag(md5($file->getPath().$lastModified->getTimestamp()));
if ($response->isNotModified($request)) {
return $response;
}
$response = new StreamedResponse();
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag(md5($file->getPath().$lastModified->getTimestamp()));
// Set the headers
$response->headers->set('Content-Type', $file->getMimetype());
$response->headers->set('Content-Length', $file->getSize());
$response->setCallback(function () use ($file) {
fpassthru($file->readStream());
});
return $response;
} | Download local file.
@param Request $request
@return Response
@throws NotFoundHttpException | https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/MediaController.php#L26-L58 |
ekyna/MediaBundle | Controller/MediaController.php | MediaController.playerAction | public function playerAction(Request $request)
{
/**
* @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media
* @var \League\Flysystem\File $file
*/
list ($media, $file) = $this->findMedia($request->attributes->get('key'));
if (in_array($media->getType(), [MediaTypes::FILE, MediaTypes::ARCHIVE])) {
return $this->redirect($this->generateUrl('ekyna_media_download', ['key' => $media->getPath()]));
}
$lastModified = $media->getUpdatedAt();
if ($request->isXmlHttpRequest()) {
$eTag = md5($file->getPath().'-xhr-'.$lastModified->getTimestamp());
} else {
$eTag = md5($file->getPath().$lastModified->getTimestamp());
}
$response = new Response();
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag($eTag);
if ($response->isNotModified($request)) {
return $response;
}
if ($request->isXmlHttpRequest()) {
$twig = $this->get('twig');
$twig->initRuntime();
/** @var \Ekyna\Bundle\MediaBundle\Twig\PlayerExtension $extension */
$extension = $twig->getExtension('ekyna_media_player');
$content = $extension->renderMedia($media);
} else {
$template = "EkynaMediaBundle:Media:{$media->getType()}.html.twig";
$content = $this->renderView($template, [
'media' => $media,
'file' => $file,
]);
}
$response->setContent($content);
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag($eTag);
return $response;
} | php | public function playerAction(Request $request)
{
/**
* @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media
* @var \League\Flysystem\File $file
*/
list ($media, $file) = $this->findMedia($request->attributes->get('key'));
if (in_array($media->getType(), [MediaTypes::FILE, MediaTypes::ARCHIVE])) {
return $this->redirect($this->generateUrl('ekyna_media_download', ['key' => $media->getPath()]));
}
$lastModified = $media->getUpdatedAt();
if ($request->isXmlHttpRequest()) {
$eTag = md5($file->getPath().'-xhr-'.$lastModified->getTimestamp());
} else {
$eTag = md5($file->getPath().$lastModified->getTimestamp());
}
$response = new Response();
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag($eTag);
if ($response->isNotModified($request)) {
return $response;
}
if ($request->isXmlHttpRequest()) {
$twig = $this->get('twig');
$twig->initRuntime();
/** @var \Ekyna\Bundle\MediaBundle\Twig\PlayerExtension $extension */
$extension = $twig->getExtension('ekyna_media_player');
$content = $extension->renderMedia($media);
} else {
$template = "EkynaMediaBundle:Media:{$media->getType()}.html.twig";
$content = $this->renderView($template, [
'media' => $media,
'file' => $file,
]);
}
$response->setContent($content);
$response->setPublic();
$response->setLastModified($lastModified);
$response->setEtag($eTag);
return $response;
} | Download local file.
@param Request $request
@return Response
@throws NotFoundHttpException | https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/MediaController.php#L67-L114 |
ekyna/MediaBundle | Controller/MediaController.php | MediaController.findMedia | private function findMedia($path)
{
/** @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media */
$media = $this
->get('ekyna_media.media.repository')
->findOneBy(['path' => $path])
;
if (null === $media) {
throw new NotFoundHttpException('Media not found');
}
$fs = $this->get('local_media_filesystem');
if (!$fs->has($media->getPath())) {
throw new NotFoundHttpException('Media not found');
}
$file = $fs->get($media->getPath());
return [$media, $file];
} | php | private function findMedia($path)
{
/** @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $media */
$media = $this
->get('ekyna_media.media.repository')
->findOneBy(['path' => $path])
;
if (null === $media) {
throw new NotFoundHttpException('Media not found');
}
$fs = $this->get('local_media_filesystem');
if (!$fs->has($media->getPath())) {
throw new NotFoundHttpException('Media not found');
}
$file = $fs->get($media->getPath());
return [$media, $file];
} | Finds the media by his path.
@param string $path
@return array
@throws NotFoundHttpException | https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Controller/MediaController.php#L123-L141 |
lightwerk/SurfCaptain | Classes/Lightwerk/SurfCaptain/Package.php | Package.boot | public function boot(\TYPO3\Flow\Core\Bootstrap $bootstrap)
{
$dispatcher = $bootstrap->getSignalSlotDispatcher();
$dispatcher->connect(
'Lightwerk\SurfCaptain\GitApi\ApiRequest',
'apiCall',
'Lightwerk\SurfCaptain\GitApi\RequestListener',
'saveApiCall'
);
$dispatcher->connect(
'Lightwerk\SurfCaptain\GitApi\ApiRequest',
'apiCall',
'Lightwerk\SurfCaptain\GitApi\RequestListener',
'logApiCall'
);
$dispatcher->connect(
'Lightwerk\SurfCaptain\GitApi\ApiRequest',
'beforeApiCall',
'Lightwerk\SurfCaptain\GitApi\RequestListener',
'logBeforeApiCall'
);
} | php | public function boot(\TYPO3\Flow\Core\Bootstrap $bootstrap)
{
$dispatcher = $bootstrap->getSignalSlotDispatcher();
$dispatcher->connect(
'Lightwerk\SurfCaptain\GitApi\ApiRequest',
'apiCall',
'Lightwerk\SurfCaptain\GitApi\RequestListener',
'saveApiCall'
);
$dispatcher->connect(
'Lightwerk\SurfCaptain\GitApi\ApiRequest',
'apiCall',
'Lightwerk\SurfCaptain\GitApi\RequestListener',
'logApiCall'
);
$dispatcher->connect(
'Lightwerk\SurfCaptain\GitApi\ApiRequest',
'beforeApiCall',
'Lightwerk\SurfCaptain\GitApi\RequestListener',
'logBeforeApiCall'
);
} | Boot the package. We wire some signals to slots here.
@param \TYPO3\Flow\Core\Bootstrap $bootstrap The current bootstrap
@return void | https://github.com/lightwerk/SurfCaptain/blob/2865e963fd634504d8923902cf422873749a0940/Classes/Lightwerk/SurfCaptain/Package.php#L24-L45 |
TeknooSoftware/east-foundation | src/symfony/Listener/KernelListener.php | KernelListener.getPsrRequest | private function getPsrRequest(Request $symfonyRequest): ServerRequestInterface
{
$psrRequest = $this->diactorosFactory->createRequest($symfonyRequest);
$psrRequest = $psrRequest->withAttribute('request', $symfonyRequest);
return $psrRequest;
} | php | private function getPsrRequest(Request $symfonyRequest): ServerRequestInterface
{
$psrRequest = $this->diactorosFactory->createRequest($symfonyRequest);
$psrRequest = $psrRequest->withAttribute('request', $symfonyRequest);
return $psrRequest;
} | To transform a symfony request as a psr request and inject the symfony request as attribute if the endpoint need
the symfony request.
@param Request $symfonyRequest
@return ServerRequestInterface | https://github.com/TeknooSoftware/east-foundation/blob/45ca97c83ba08b973877a472c731f27ca1e82cdf/src/symfony/Listener/KernelListener.php#L88-L94 |
TeknooSoftware/east-foundation | src/symfony/Listener/KernelListener.php | KernelListener.onKernelRequest | public function onKernelRequest(GetResponseEvent $event): KernelListener
{
//To ignore sub request generated by symfony to handle non catch exception
$request = $event->getRequest();
if (!empty($request->attributes->has('exception'))) {
return $this;
}
$client = clone $this->clientWithResponseEvent;
$client->setGetResponseEvent($event);
$psrRequest = $this->getPsrRequest($event->getRequest());
$this->manager->receiveRequest($client, $psrRequest);
$client->sendResponse(null, true);
return $this;
} | php | public function onKernelRequest(GetResponseEvent $event): KernelListener
{
//To ignore sub request generated by symfony to handle non catch exception
$request = $event->getRequest();
if (!empty($request->attributes->has('exception'))) {
return $this;
}
$client = clone $this->clientWithResponseEvent;
$client->setGetResponseEvent($event);
$psrRequest = $this->getPsrRequest($event->getRequest());
$this->manager->receiveRequest($client, $psrRequest);
$client->sendResponse(null, true);
return $this;
} | To intercept a GetResponseEvent in the kernel loop to extract the request (if it's not an exception request) and
process it into East foundation.
@param GetResponseEvent $event
@return KernelListener | https://github.com/TeknooSoftware/east-foundation/blob/45ca97c83ba08b973877a472c731f27ca1e82cdf/src/symfony/Listener/KernelListener.php#L105-L121 |
yuncms/yii2-tag | widgets/TagsinputWidget.php | TagsinputWidget.registerClientScript | public function registerClientScript()
{
$view = $this->getView();
TagsinputAsset::register($view);
$clientOptions = Json::encode($this->clientOptions);
$view->registerJs("jQuery(\"#{$this->options['id']}\").tagsinput({$clientOptions});");
} | php | public function registerClientScript()
{
$view = $this->getView();
TagsinputAsset::register($view);
$clientOptions = Json::encode($this->clientOptions);
$view->registerJs("jQuery(\"#{$this->options['id']}\").tagsinput({$clientOptions});");
} | Registers the needed client script and options. | https://github.com/yuncms/yii2-tag/blob/35f5629e7c075abee62d0da6b48c3958e1d7b335/widgets/TagsinputWidget.php#L51-L57 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/deployment/AbstractFileDeploymentService.php | AbstractFileDeploymentService.deploy | public function deploy()
{
if (empty($this->context) || empty($this->siteDomain) || empty($this->deviceView) || empty($this->design))
return;
$files = null;
$md5 = null;
$contents = null;
$aggregatePath = $this->getAggregatePath();
$this->Logger->debug("Aggregate Path: {$aggregatePath}");
if ($this->isDevelopmentMode || $this->isOneOffRedeploy || !$this->deploymentCacheExists($aggregatePath)) {
$this->Logger->debug("Retrieving file list...");
list($files,$md5) = $this->getFiles();
}
if ($this->deploymentCacheExists($aggregatePath)) {
//if this is NOT development mode, the only way to force a refresh is to delete the .json file
if($this->isDevelopmentMode === false && $this->isOneOffRedeploy === false)
return;
$this->Logger->debug("Checking cache JSON...");
$this->getDeployedFiles();
//if this IS development mode, a refresh is performed everytime the md5's dont' match
if (($this->isDevelopmentMode === true || $this->isOneOffRedeploy === true) && $md5 === $this->deployedFiles['md5']) {
//files haven't changed
return;
}
}
$this->Logger->debug("Rebuilding...");
//rebuild file
$this->aggregateFiles($md5, $files, $aggregatePath);
} | php | public function deploy()
{
if (empty($this->context) || empty($this->siteDomain) || empty($this->deviceView) || empty($this->design))
return;
$files = null;
$md5 = null;
$contents = null;
$aggregatePath = $this->getAggregatePath();
$this->Logger->debug("Aggregate Path: {$aggregatePath}");
if ($this->isDevelopmentMode || $this->isOneOffRedeploy || !$this->deploymentCacheExists($aggregatePath)) {
$this->Logger->debug("Retrieving file list...");
list($files,$md5) = $this->getFiles();
}
if ($this->deploymentCacheExists($aggregatePath)) {
//if this is NOT development mode, the only way to force a refresh is to delete the .json file
if($this->isDevelopmentMode === false && $this->isOneOffRedeploy === false)
return;
$this->Logger->debug("Checking cache JSON...");
$this->getDeployedFiles();
//if this IS development mode, a refresh is performed everytime the md5's dont' match
if (($this->isDevelopmentMode === true || $this->isOneOffRedeploy === true) && $md5 === $this->deployedFiles['md5']) {
//files haven't changed
return;
}
}
$this->Logger->debug("Rebuilding...");
//rebuild file
$this->aggregateFiles($md5, $files, $aggregatePath);
} | Aggregates the files if necessary.
@return void | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/deployment/AbstractFileDeploymentService.php#L47-L85 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/deployment/AbstractFileDeploymentService.php | AbstractFileDeploymentService.aggregateFiles | protected function aggregateFiles($md5, array $files, $aggregatePath)
{
$file = array("md5"=>$md5,$this->subject=>array());
try {
$this->getDeployedFiles();
}catch(Exception $e){}
$deployedFiles = array();
if(!empty($this->deployedFiles[$this->subject]))
$deployedFiles = $this->deployedFiles[$this->subject];
foreach ($files as $relpath => $filename) {
$ts = filemtime($filename);
$prevFile = null;
if(isset($deployedFiles[$relpath]))
$prevFile = $deployedFiles[$relpath];
if($prevFile == null || $prevFile['ts'] != $ts){
$this->putFile($relpath, $filename, $ts);
}
$file[$this->subject][$relpath] = array('ts' => $ts, 'origin' => str_replace($this->rootPath.DIRECTORY_SEPARATOR, '', $filename));
}
foreach((array)$deployedFiles as $relpath => $deployedfile)
{
if(!array_key_exists($relpath, $file[$this->subject]))
{
$this->deleteFile($relpath);
}
}
$this->deployedFiles = $file;
$this->storeDeploymentCache($aggregatePath, $file);
} | php | protected function aggregateFiles($md5, array $files, $aggregatePath)
{
$file = array("md5"=>$md5,$this->subject=>array());
try {
$this->getDeployedFiles();
}catch(Exception $e){}
$deployedFiles = array();
if(!empty($this->deployedFiles[$this->subject]))
$deployedFiles = $this->deployedFiles[$this->subject];
foreach ($files as $relpath => $filename) {
$ts = filemtime($filename);
$prevFile = null;
if(isset($deployedFiles[$relpath]))
$prevFile = $deployedFiles[$relpath];
if($prevFile == null || $prevFile['ts'] != $ts){
$this->putFile($relpath, $filename, $ts);
}
$file[$this->subject][$relpath] = array('ts' => $ts, 'origin' => str_replace($this->rootPath.DIRECTORY_SEPARATOR, '', $filename));
}
foreach((array)$deployedFiles as $relpath => $deployedfile)
{
if(!array_key_exists($relpath, $file[$this->subject]))
{
$this->deleteFile($relpath);
}
}
$this->deployedFiles = $file;
$this->storeDeploymentCache($aggregatePath, $file);
} | Combines all the listed files into a single file at {@link $aggregatePath}
@param string $md5 The md5 (stored in the aggregate)
@param array $files A list of files to store
@param string $aggregatePath The name of the file to write our aggregate to
@return void | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/deployment/AbstractFileDeploymentService.php#L108-L145 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/deployment/AbstractFileDeploymentService.php | AbstractFileDeploymentService.resolveFile | public function resolveFile($name)
{
$resolvedFilename = $this->getBaseDeployDirectory().$this->subject.'/'.ltrim($name, '/');
return new StorageFacilityFile('/'.ltrim($name, '/'), $resolvedFilename);
} | php | public function resolveFile($name)
{
$resolvedFilename = $this->getBaseDeployDirectory().$this->subject.'/'.ltrim($name, '/');
return new StorageFacilityFile('/'.ltrim($name, '/'), $resolvedFilename);
} | Returns the full filename of an existing deployed file with the name specified.
If the file does not exist, it returns null.
@param string $name The filename to expand (full path)
@return StorageFacilityFile | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/deployment/AbstractFileDeploymentService.php#L208-L212 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/deployment/AbstractFileDeploymentService.php | AbstractFileDeploymentService.putFile | public function putFile($relpath, $filename, $ts)
{
$basedir = $this->getBaseDeployDirectory().$this->subject.'/';
//move files from themes to public app directory
$newfile = $basedir.$relpath;
// @FileSystemUtils::safeCopy($filename, $newfile);
// $ts = filemtime($filename);
if(!file_exists($newfile) || $ts != filemtime($newfile)) {
@FileSystemUtils::safeCopy($filename, $newfile);
//@touch($newfile,$ts); //preserve original modified time
}
return new StorageFacilityFile('/'.ltrim($relpath, '/'), $newfile);
} | php | public function putFile($relpath, $filename, $ts)
{
$basedir = $this->getBaseDeployDirectory().$this->subject.'/';
//move files from themes to public app directory
$newfile = $basedir.$relpath;
// @FileSystemUtils::safeCopy($filename, $newfile);
// $ts = filemtime($filename);
if(!file_exists($newfile) || $ts != filemtime($newfile)) {
@FileSystemUtils::safeCopy($filename, $newfile);
//@touch($newfile,$ts); //preserve original modified time
}
return new StorageFacilityFile('/'.ltrim($relpath, '/'), $newfile);
} | Moves the file from the themes to the public app directory
NOTE: the following code will overwrite files
@param string $relpath The relative path where the file lives
@param string $filename The file to move
@return string the full path and filename of the moved file | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/deployment/AbstractFileDeploymentService.php#L229-L245 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/deployment/AbstractFileDeploymentService.php | AbstractFileDeploymentService.getFiles | protected function getFiles()
{
if ($this->isSiteDeployment) {
if ($this->deviceView != 'main' && !is_dir("{$this->viewDirectory}/{$this->context}/{$this->siteDomain}/{$this->deviceView}")) {
$this->deviceView = 'main';
}
if ($this->design != 'default' && !is_dir("{$this->viewDirectory}/{$this->context}/{$this->siteDomain}/{$this->deviceView}/{$this->design}")) {
$this->design = 'default';
}
}
$list = array();
if (!empty($this->viewDirectory))
$list[] = $this->viewDirectory;
// Build the list from all the plugin directorys, and the theme directory
$list = array_merge($this->ApplicationContext->getEnabledPluginDirectories(),$list);
if (count($list) > 0) {
$files = array();
foreach ($list as $tp) {
if (is_dir($tp)) {
$paths = $this->getPathsToCheck($tp, $this->subject);
foreach ($paths as $basepath) {
if(!is_dir($basepath))
continue;
$cutoffDepth = null;
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basepath),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($objects as $name => $object) {
if($cutoffDepth !== null && $objects->getDepth() > $cutoffDepth)
continue;
else
$cutoffDepth = null;
if ($cutoffDepth === null && $object->isDir() && substr($object->getBasename(), 0, 1) == '.') {
$cutoffDepth = $objects->getDepth();
continue;
}
if (!$object->isFile() || substr($object->getBasename(), 0, 1) == '.')
continue;
$files[substr($name, strlen($basepath))] = $name;
}
}
} else {
$this->Logger->warn('Directory does not exist: '.$tp);
}
}
if(empty($files))
return array(array(),null);
$timestamps = array();
foreach ($files as $relpath => $filename) {
$timestamps[] = filemtime($filename);
}
$md5 = md5(serialize(array($files,$timestamps/*, $this->VersionService->getSystemVersion(), $this->VersionService->getDeploymentRevision()*/)));
return array($files, $md5);
}
throw new Exception('No active themes or plugins.');
} | php | protected function getFiles()
{
if ($this->isSiteDeployment) {
if ($this->deviceView != 'main' && !is_dir("{$this->viewDirectory}/{$this->context}/{$this->siteDomain}/{$this->deviceView}")) {
$this->deviceView = 'main';
}
if ($this->design != 'default' && !is_dir("{$this->viewDirectory}/{$this->context}/{$this->siteDomain}/{$this->deviceView}/{$this->design}")) {
$this->design = 'default';
}
}
$list = array();
if (!empty($this->viewDirectory))
$list[] = $this->viewDirectory;
// Build the list from all the plugin directorys, and the theme directory
$list = array_merge($this->ApplicationContext->getEnabledPluginDirectories(),$list);
if (count($list) > 0) {
$files = array();
foreach ($list as $tp) {
if (is_dir($tp)) {
$paths = $this->getPathsToCheck($tp, $this->subject);
foreach ($paths as $basepath) {
if(!is_dir($basepath))
continue;
$cutoffDepth = null;
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($basepath),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($objects as $name => $object) {
if($cutoffDepth !== null && $objects->getDepth() > $cutoffDepth)
continue;
else
$cutoffDepth = null;
if ($cutoffDepth === null && $object->isDir() && substr($object->getBasename(), 0, 1) == '.') {
$cutoffDepth = $objects->getDepth();
continue;
}
if (!$object->isFile() || substr($object->getBasename(), 0, 1) == '.')
continue;
$files[substr($name, strlen($basepath))] = $name;
}
}
} else {
$this->Logger->warn('Directory does not exist: '.$tp);
}
}
if(empty($files))
return array(array(),null);
$timestamps = array();
foreach ($files as $relpath => $filename) {
$timestamps[] = filemtime($filename);
}
$md5 = md5(serialize(array($files,$timestamps/*, $this->VersionService->getSystemVersion(), $this->VersionService->getDeploymentRevision()*/)));
return array($files, $md5);
}
throw new Exception('No active themes or plugins.');
} | Returns a list of all the files in the theme directory combined with all the asset files of all installed plugins
@return array Contains 2 items, the first being an array of all the files, the second is a unique md5 identifier of the fileset | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/deployment/AbstractFileDeploymentService.php#L257-L326 |
holyshared/file-fixture | src/loader/ArtLoader.php | ArtLoader.load | public function load($path, array $arguments = [])
{
$content = $this->loader->load($path, $arguments);
$this->cli->out($content);
$bufferWriter = $this->output->get('buffer');
return $bufferWriter->get();
} | php | public function load($path, array $arguments = [])
{
$content = $this->loader->load($path, $arguments);
$this->cli->out($content);
$bufferWriter = $this->output->get('buffer');
return $bufferWriter->get();
} | {@inheritdoc} | https://github.com/holyshared/file-fixture/blob/65bfc8def327362392eef1bdf2f6d822b70e7c33/src/loader/ArtLoader.php#L66-L73 |
KDF5000/EasyThink | src/ThinkPHP/Library/Think/Model/ViewModel.php | ViewModel.checkOrder | protected function checkOrder($order='') {
if(is_string($order) && !empty($order)) {
$orders = explode(',',$order);
$_order = array();
foreach ($orders as $order){
$array = explode(' ',trim($order));
$field = $array[0];
$sort = isset($array[1])?$array[1]:'ASC';
// 解析成视图字段
foreach ($this->viewFields as $name=>$val){
$k = isset($val['_as'])?$val['_as']:$name;
$val = $this->_checkFields($name,$val);
if(false !== $_field = array_search($field,$val,true)) {
// 存在视图字段
$field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field;
break;
}
}
$_order[] = $field.' '.$sort;
}
$order = implode(',',$_order);
}
return $order;
} | php | protected function checkOrder($order='') {
if(is_string($order) && !empty($order)) {
$orders = explode(',',$order);
$_order = array();
foreach ($orders as $order){
$array = explode(' ',trim($order));
$field = $array[0];
$sort = isset($array[1])?$array[1]:'ASC';
// 解析成视图字段
foreach ($this->viewFields as $name=>$val){
$k = isset($val['_as'])?$val['_as']:$name;
$val = $this->_checkFields($name,$val);
if(false !== $_field = array_search($field,$val,true)) {
// 存在视图字段
$field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field;
break;
}
}
$_order[] = $field.' '.$sort;
}
$order = implode(',',$_order);
}
return $order;
} | 检查Order表达式中的视图字段
@access protected
@param string $order 字段
@return string | https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Model/ViewModel.php#L128-L151 |
realboard/DBInstance | src/Realboard/Component/Database/DBInstance/Client/SoapClient.php | SoapClient.setInstance | public function setInstance(DBInstance $instance, ConfigInterface $config)
{
$this->http = false;
parent::setInstance($instance, $config);
$this->setDispatcherClass(ArrayDispatcher::class);
if (!class_exists('SoapClient')) {
$this->getError()->setError('Class SoapClient not found. Please enable extension.');
}
return $this;
} | php | public function setInstance(DBInstance $instance, ConfigInterface $config)
{
$this->http = false;
parent::setInstance($instance, $config);
$this->setDispatcherClass(ArrayDispatcher::class);
if (!class_exists('SoapClient')) {
$this->getError()->setError('Class SoapClient not found. Please enable extension.');
}
return $this;
} | [setInstance description].
@param DBInstance $instance [description]
@param ConfigInterface $config [description] | https://github.com/realboard/DBInstance/blob/f2cde7fdf480d5eb5a491a5cf81ff7f4b3be0a35/src/Realboard/Component/Database/DBInstance/Client/SoapClient.php#L31-L43 |
realboard/DBInstance | src/Realboard/Component/Database/DBInstance/Client/SoapClient.php | SoapClient.sendRequest | public function sendRequest()
{
if ($this->getError()->hasError()) {
return;
}
if (class_exists($this->dispatcher)) {
$dispatcherClass = $this->dispatcher;
$dispatcher = new $dispatcherClass($this->instance->getQuery());
if ($dispatcher instanceof AbstractDispatcher) {
try {
$client = new \SoapCLient($this->getUrl(), array('trace' => 1));
$config = $this->config->getRawConfig();
$sql = $this->instance->getQuery()->toString();
$limit = $this->instance->getQuery()->getLimit();
$offset = $this->instance->getQuery()->getOffset();
$single = $this->instance->getQuery()->isSingle();
if ($this->method == 'getAvailableDrivers') {
$this->availableDrivers = $client->getAvailableDrivers();
} elseif ($this->method == 'getServerVersion') {
$res = $client->getServerVersion();
$this->serverVersion = isset($res['version']) ? $res['version'] : null;
} else {
$response = $client->getResult($config, $sql, $limit, $offset, $single, $this->getKey(), 'array');
$dispatcher->dispatch($response);
}
} catch (\SoapFault $e) {
$this->getError()->setMessage($e->getMessage());
} catch (\Exception $e) {
$this->getError()->setMessage('Error server response');
}
} else {
$this->getError()->setMessage(sprintf(
'Dispatcher class must be instance of %s, %s given',
AbstractDispatcher::class,
(string) $this->dispatcher
));
}
} else {
$this->getError()->setMessage(sprintf('Class %s not found', (string) $this->dispatcher));
}
} | php | public function sendRequest()
{
if ($this->getError()->hasError()) {
return;
}
if (class_exists($this->dispatcher)) {
$dispatcherClass = $this->dispatcher;
$dispatcher = new $dispatcherClass($this->instance->getQuery());
if ($dispatcher instanceof AbstractDispatcher) {
try {
$client = new \SoapCLient($this->getUrl(), array('trace' => 1));
$config = $this->config->getRawConfig();
$sql = $this->instance->getQuery()->toString();
$limit = $this->instance->getQuery()->getLimit();
$offset = $this->instance->getQuery()->getOffset();
$single = $this->instance->getQuery()->isSingle();
if ($this->method == 'getAvailableDrivers') {
$this->availableDrivers = $client->getAvailableDrivers();
} elseif ($this->method == 'getServerVersion') {
$res = $client->getServerVersion();
$this->serverVersion = isset($res['version']) ? $res['version'] : null;
} else {
$response = $client->getResult($config, $sql, $limit, $offset, $single, $this->getKey(), 'array');
$dispatcher->dispatch($response);
}
} catch (\SoapFault $e) {
$this->getError()->setMessage($e->getMessage());
} catch (\Exception $e) {
$this->getError()->setMessage('Error server response');
}
} else {
$this->getError()->setMessage(sprintf(
'Dispatcher class must be instance of %s, %s given',
AbstractDispatcher::class,
(string) $this->dispatcher
));
}
} else {
$this->getError()->setMessage(sprintf('Class %s not found', (string) $this->dispatcher));
}
} | [sendRequest description].
@return [type] [description] | https://github.com/realboard/DBInstance/blob/f2cde7fdf480d5eb5a491a5cf81ff7f4b3be0a35/src/Realboard/Component/Database/DBInstance/Client/SoapClient.php#L79-L122 |
bseddon/XPath20 | DOM/DOMSchemaAttribute.php | DOMSchemaAttribute.fromQName | public static function fromQName( $name )
{
if ( $name instanceof QName )
{
$name = "{$name->prefix}:{$name->localName}";
}
if ( ! is_string( $name ) )
{
throw new \InvalidArgumentException( "$name must be string or a QName instanxe" );
}
$types = SchemaTypes::getInstance();
$attribute = $types->getElement( $name );
if ( ! $attribute )
{
return null;
}
$result = new DOMSchemaAttribute();
error_log( __CLASS__ . " need to populate the DOMSchemaAttribute instance" );
return $result;
} | php | public static function fromQName( $name )
{
if ( $name instanceof QName )
{
$name = "{$name->prefix}:{$name->localName}";
}
if ( ! is_string( $name ) )
{
throw new \InvalidArgumentException( "$name must be string or a QName instanxe" );
}
$types = SchemaTypes::getInstance();
$attribute = $types->getElement( $name );
if ( ! $attribute )
{
return null;
}
$result = new DOMSchemaAttribute();
error_log( __CLASS__ . " need to populate the DOMSchemaAttribute instance" );
return $result;
} | The qualified name of the attribute
@param QName|string $name | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/DOM/DOMSchemaAttribute.php#L51-L73 |
anime-db/catalog-bundle | src/Repository/Storage.php | Storage.getList | public function getList(array $types = [])
{
if (!$types || $types == StorageEntity::getTypes()) {
return $this->getEntityManager()->createQuery('
SELECT
s
FROM
AnimeDbCatalogBundle:Storage s
ORDER BY
s.id DESC
')->getResult();
}
return $this->getEntityManager()->createQuery('
SELECT
s
FROM
AnimeDbCatalogBundle:Storage s
WHERE
s.type IN (:types)
ORDER BY
s.id DESC
')
->setParameter(':types', $types)
->getResult();
} | php | public function getList(array $types = [])
{
if (!$types || $types == StorageEntity::getTypes()) {
return $this->getEntityManager()->createQuery('
SELECT
s
FROM
AnimeDbCatalogBundle:Storage s
ORDER BY
s.id DESC
')->getResult();
}
return $this->getEntityManager()->createQuery('
SELECT
s
FROM
AnimeDbCatalogBundle:Storage s
WHERE
s.type IN (:types)
ORDER BY
s.id DESC
')
->setParameter(':types', $types)
->getResult();
} | @param array $types
@return StorageEntity[] | https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Repository/Storage.php#L38-L63 |
AdamB7586/menu-builder | src/Helpers/URI.php | URI.setURI | protected static function setURI($uri){
if(!is_string($uri)){
throw new InvalidArgumentException(
'$uri must be a string or null'
);
}
self::$uri = filter_var($uri, FILTER_SANITIZE_URL);
} | php | protected static function setURI($uri){
if(!is_string($uri)){
throw new InvalidArgumentException(
'$uri must be a string or null'
);
}
self::$uri = filter_var($uri, FILTER_SANITIZE_URL);
} | Sets the link URI
@param string $uri This should be the link string
@throws InvalidArgumentException | https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Helpers/URI.php#L16-L23 |
AdamB7586/menu-builder | src/Helpers/URI.php | URI.setAnchorPoint | protected static function setAnchorPoint($anchor){
if(is_string($anchor) && !empty(trim($anchor))){
self::$anchor = '#'.trim($anchor, '#');
}
else{
self::$anchor = false;
}
} | php | protected static function setAnchorPoint($anchor){
if(is_string($anchor) && !empty(trim($anchor))){
self::$anchor = '#'.trim($anchor, '#');
}
else{
self::$anchor = false;
}
} | Sets the anchor point for the link
@param mixed $anchor If the anchor point exists set to the string here | https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Helpers/URI.php#L37-L44 |
AdamB7586/menu-builder | src/Helpers/URI.php | URI.getHref | public static function getHref($link) {
self::setURI($link['uri']);
self::setAnchorPoint($link['fragment']);
return self::getURI().self::getAnchorPoint();
} | php | public static function getHref($link) {
self::setURI($link['uri']);
self::setAnchorPoint($link['fragment']);
return self::getURI().self::getAnchorPoint();
} | Returns the correctly formatted link string
@param array $link This should be the link information
@return mixed Will return the link string if it exists else will return false | https://github.com/AdamB7586/menu-builder/blob/dbc192bca7d59475068c19d1a07a039e5f997ee4/src/Helpers/URI.php#L59-L63 |
codeblanche/Entity | src/Entity/Definition/PropertyDefinition.php | PropertyDefinition.extractGeneric | protected function extractGeneric($type)
{
if (empty($type)) {
return null;
}
$generic = null;
if (substr($type, -2) === '[]') {
$generic = substr($type, 0, -2);
}
elseif (strtolower(substr($type, 0, 6)) === 'array<' && substr($type, -1) === '>') {
$generic = substr($type, 6, -1);
}
return $generic;
} | php | protected function extractGeneric($type)
{
if (empty($type)) {
return null;
}
$generic = null;
if (substr($type, -2) === '[]') {
$generic = substr($type, 0, -2);
}
elseif (strtolower(substr($type, 0, 6)) === 'array<' && substr($type, -1) === '>') {
$generic = substr($type, 6, -1);
}
return $generic;
} | Extract the generic subtype from the specified type if there is one.
@param string $type
@return string|null | https://github.com/codeblanche/Entity/blob/1d3839c09d7639ae8bbfc9d2721223202f3a5cdd/src/Entity/Definition/PropertyDefinition.php#L107-L123 |
devlabmtl/haven-core | Lib/NestedSet/Config.php | Config.setClass | public function setClass($clazz)
{
if($clazz instanceof ClassMetadata)
{
$classMetadata = $clazz;
$classname = $clazz->getReflectionClass()->getName();
}
else if (class_exists($clazz))
{
$classname = $clazz;
$classMetadata = $this->getEntityManager()->getClassMetadata($clazz);
} else
{
$parts = explode(':', $clazz);
$alias = array_shift($parts);
$rest = implode('\\', $parts);
try
{
$namespace = $this->getEntityManager()->getConfiguration()->getEntityNamespace($alias);
}
catch (\Doctrine\ORM\ORMException $e) {
throw new \InvalidArgumentException("Can't find class: $clazz'");
}
$classname = $namespace.'\\'.$rest;
$classMetadata = $this->getEntityManager()->getClassMetadata($classname);
}
$reflectionClass = $classMetadata->getReflectionClass();
if(!$reflectionClass->implementsInterface('Haven\CoreBundle\Lib\NestedSet\Node'))
{
throw new \InvalidArgumentException('Class must implement Node interface: ' . $classname);
}
$this->hasManyRoots = $reflectionClass->implementsInterface('Haven\CoreBundle\Lib\NestedSet\MultipleRootNode');
$this->classMetadata = $classMetadata;
$this->classname = $classname;
return $this;
} | php | public function setClass($clazz)
{
if($clazz instanceof ClassMetadata)
{
$classMetadata = $clazz;
$classname = $clazz->getReflectionClass()->getName();
}
else if (class_exists($clazz))
{
$classname = $clazz;
$classMetadata = $this->getEntityManager()->getClassMetadata($clazz);
} else
{
$parts = explode(':', $clazz);
$alias = array_shift($parts);
$rest = implode('\\', $parts);
try
{
$namespace = $this->getEntityManager()->getConfiguration()->getEntityNamespace($alias);
}
catch (\Doctrine\ORM\ORMException $e) {
throw new \InvalidArgumentException("Can't find class: $clazz'");
}
$classname = $namespace.'\\'.$rest;
$classMetadata = $this->getEntityManager()->getClassMetadata($classname);
}
$reflectionClass = $classMetadata->getReflectionClass();
if(!$reflectionClass->implementsInterface('Haven\CoreBundle\Lib\NestedSet\Node'))
{
throw new \InvalidArgumentException('Class must implement Node interface: ' . $classname);
}
$this->hasManyRoots = $reflectionClass->implementsInterface('Haven\CoreBundle\Lib\NestedSet\MultipleRootNode');
$this->classMetadata = $classMetadata;
$this->classname = $classname;
return $this;
} | Sets the class associated with this configuration
@param mixed $clazz a class name or ClassMetadata object representing
the entity class associated with this configuration
@return Config $this for fluent API | https://github.com/devlabmtl/haven-core/blob/f13410f996fd4002efafe482b927adadb211dec8/Lib/NestedSet/Config.php#L81-L121 |
devlabmtl/haven-core | Lib/NestedSet/Config.php | Config.setBaseQueryBuilder | public function setBaseQueryBuilder(QueryBuilder $baseQueryBuilder=null)
{
if($baseQueryBuilder === null)
{
$this->baseQueryBuilder = $this->getDefaultQueryBuilder();
}
else
{
$this->baseQueryBuilder = $baseQueryBuilder;
}
} | php | public function setBaseQueryBuilder(QueryBuilder $baseQueryBuilder=null)
{
if($baseQueryBuilder === null)
{
$this->baseQueryBuilder = $this->getDefaultQueryBuilder();
}
else
{
$this->baseQueryBuilder = $baseQueryBuilder;
}
} | sets the base query builder
@param Query $baseQueryBuilder or null to reset the base query builder | https://github.com/devlabmtl/haven-core/blob/f13410f996fd4002efafe482b927adadb211dec8/Lib/NestedSet/Config.php#L260-L270 |
devlabmtl/haven-core | Lib/NestedSet/Config.php | Config.getDefaultQueryBuilder | public function getDefaultQueryBuilder()
{
$em = $this->getEntityManager();
return $em->createQueryBuilder()
->select('n')
->from($this->getClassname(), 'n');
} | php | public function getDefaultQueryBuilder()
{
$em = $this->getEntityManager();
return $em->createQueryBuilder()
->select('n')
->from($this->getClassname(), 'n');
} | gets the default query builder
@return QueryBuilder | https://github.com/devlabmtl/haven-core/blob/f13410f996fd4002efafe482b927adadb211dec8/Lib/NestedSet/Config.php#L287-L293 |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php | CompositeIdentifier.addNotExistsToQueryCondition | public function addNotExistsToQueryCondition(Expr $expr)
{
parent::addNotExistsToQueryCondition($expr);
$expr->attr($this->getRangeKey()->getPropertyMetadata()->name)->exists(false);
} | php | public function addNotExistsToQueryCondition(Expr $expr)
{
parent::addNotExistsToQueryCondition($expr);
$expr->attr($this->getRangeKey()->getPropertyMetadata()->name)->exists(false);
} | {@inheritdoc} | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php#L38-L43 |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php | CompositeIdentifier.addToQueryCondition | public function addToQueryCondition(Expr $expr)
{
parent::addToQueryCondition($expr);
$expr->attr($this->getRangeKey()->getPropertyMetadata()->name)->equals($this->getRangeValue());
} | php | public function addToQueryCondition(Expr $expr)
{
parent::addToQueryCondition($expr);
$expr->attr($this->getRangeKey()->getPropertyMetadata()->name)->equals($this->getRangeValue());
} | {@inheritdoc} | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php#L48-L53 |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php | CompositeIdentifier.addToDocument | protected function addToDocument($document)
{
parent::addToDocument($document);
$this->getRangeKey()->getPropertyMetadata()->setValue(
$document,
$this->getRangeValue()
);
} | php | protected function addToDocument($document)
{
parent::addToDocument($document);
$this->getRangeKey()->getPropertyMetadata()->setValue(
$document,
$this->getRangeValue()
);
} | Set this identifier's values on the provided document instance.
@param object $document
@return void | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php#L62-L70 |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php | CompositeIdentifier.getArray | protected function getArray()
{
$key = $this->getRangeKey()->getPropertyMetadata()->name;
$array = parent::getArray();
$array[$key] = $this->getRangeValue();
return $array;
} | php | protected function getArray()
{
$key = $this->getRangeKey()->getPropertyMetadata()->name;
$array = parent::getArray();
$array[$key] = $this->getRangeValue();
return $array;
} | Return this identifier's key names and values.
Useful for compatibility with Doctrine\Common interfaces.
@return array | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php#L79-L86 |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php | CompositeIdentifier.getDatabaseValue | public function getDatabaseValue()
{
$attribute = $this->getRangeKey()->getPropertyMetadata()->attributeName;
$dynamoType = $this->getRangeKey()->getType();
$value = $dynamoType->convertToDatabaseValue($this->getRangeValue());
$marshaled = parent::getDatabaseValue();
$marshaled[$attribute] = $value;
return $marshaled;
} | php | public function getDatabaseValue()
{
$attribute = $this->getRangeKey()->getPropertyMetadata()->attributeName;
$dynamoType = $this->getRangeKey()->getType();
$value = $dynamoType->convertToDatabaseValue($this->getRangeValue());
$marshaled = parent::getDatabaseValue();
$marshaled[$attribute] = $value;
return $marshaled;
} | {@inheritdoc} | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Schema/Identifier/CompositeIdentifier.php#L91-L101 |
DreadLabs/VantomasWebsite | src/Twitter/SimpleEntityParser.php | SimpleEntityParser.parseUrls | public function parseUrls($tweet)
{
foreach ($this->entities->urls as $url) {
$tweet = $this->replaceEntityInTweet(
$tweet,
$url->url,
'<a href="' . $url->url . '">' . $url->url . '</a>'
);
}
return $tweet;
} | php | public function parseUrls($tweet)
{
foreach ($this->entities->urls as $url) {
$tweet = $this->replaceEntityInTweet(
$tweet,
$url->url,
'<a href="' . $url->url . '">' . $url->url . '</a>'
);
}
return $tweet;
} | @param string $tweet
@return string | https://github.com/DreadLabs/VantomasWebsite/blob/7f85f2b45bdf5ed9fa9d320c805c416bf99cd668/src/Twitter/SimpleEntityParser.php#L42-L53 |
DreadLabs/VantomasWebsite | src/Twitter/SimpleEntityParser.php | SimpleEntityParser.parseHashTags | public function parseHashTags($tweet)
{
foreach ($this->entities->hashtags as $hashTag) {
$tweet = $this->replaceEntityInTweet(
$tweet,
'#' . $hashTag->text,
'<a href="https://twitter.com/search?q=%23' . $hashTag->text . '&src=hash">#' . $hashTag->text . '</a>'
);
}
return $tweet;
} | php | public function parseHashTags($tweet)
{
foreach ($this->entities->hashtags as $hashTag) {
$tweet = $this->replaceEntityInTweet(
$tweet,
'#' . $hashTag->text,
'<a href="https://twitter.com/search?q=%23' . $hashTag->text . '&src=hash">#' . $hashTag->text . '</a>'
);
}
return $tweet;
} | @param string $tweet
@return string | https://github.com/DreadLabs/VantomasWebsite/blob/7f85f2b45bdf5ed9fa9d320c805c416bf99cd668/src/Twitter/SimpleEntityParser.php#L74-L85 |
ItalyStrap/config | src/Config/Config.php | Config.push | public function push( string $key, $value ) : self {
$this->offsetSet( $key, $value );
return $this;
} | php | public function push( string $key, $value ) : self {
$this->offsetSet( $key, $value );
return $this;
} | Push a configuration in via the key
@since 1.0.0
@param string $key Key to be assigned, which also becomes the property
@param mixed $value Value to be assigned to the parameter key
@return self | https://github.com/ItalyStrap/config/blob/cb4c163e124a98e0b4af67b10bbbdae6469f7113/src/Config/Config.php#L73-L76 |
ItalyStrap/config | src/Config/Config.php | Config.remove | public function remove( ...$with_keys ) : self {
foreach ( $with_keys as $keys ) {
foreach ( (array) $keys as $k ) {
$this->offsetUnset( $k );
}
}
return $this;
} | php | public function remove( ...$with_keys ) : self {
foreach ( $with_keys as $keys ) {
foreach ( (array) $keys as $k ) {
$this->offsetUnset( $k );
}
}
return $this;
} | Removes an item or multiple items.
@since 2.0.0
@param mixed ...$with_keys
@return self | https://github.com/ItalyStrap/config/blob/cb4c163e124a98e0b4af67b10bbbdae6469f7113/src/Config/Config.php#L86-L95 |
ItalyStrap/config | src/Config/Config.php | Config.merge | public function merge( array ...$array_to_merge ) : self {
foreach ( $array_to_merge as $arr ) {
$items = array_replace_recursive( $this->getArrayCopy(), $arr );
foreach ( $items as $key => $value ) {
$this->offsetSet( $key, $value );
}
}
return $this;
} | php | public function merge( array ...$array_to_merge ) : self {
foreach ( $array_to_merge as $arr ) {
$items = array_replace_recursive( $this->getArrayCopy(), $arr );
foreach ( $items as $key => $value ) {
$this->offsetSet( $key, $value );
}
}
return $this;
} | Merge a new array into this config
@since 1.1.0
@param array ...$array_to_merge
@return self | https://github.com/ItalyStrap/config/blob/cb4c163e124a98e0b4af67b10bbbdae6469f7113/src/Config/Config.php#L105-L116 |
Stinger-Soft/TwigExtensions | src/StingerSoft/TwigExtensions/ArrayExtensions.php | ArrayExtensions.unsetFilter | public function unsetFilter($array, $keys) {
if(is_array($array)) {
if(!is_array($keys)) {
$keys = array(
$keys
);
}
foreach($keys as $key) {
if(array_key_exists($key, $array)) {
unset($array[$key]);
}
}
}
return $array;
} | php | public function unsetFilter($array, $keys) {
if(is_array($array)) {
if(!is_array($keys)) {
$keys = array(
$keys
);
}
foreach($keys as $key) {
if(array_key_exists($key, $array)) {
unset($array[$key]);
}
}
}
return $array;
} | Removes an element from the given array
@param array $array
@param array|string $keys
@return array | https://github.com/Stinger-Soft/TwigExtensions/blob/7bfce337b0dd33106e22f80b221338451a02d7c5/src/StingerSoft/TwigExtensions/ArrayExtensions.php#L41-L55 |
RocketPropelledTortoise/Core | src/Taxonomy/migrations/2014_03_03_190649_create taxonomies.php | CreateTaxonomies.up | public function up()
{
Schema::create(
'taxonomy_vocabularies',
function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('machine_name', 255)->unique();
$table->text('description')->nullable();
$table->integer('hierarchy')->default(0); // 0 = disabled, 1 = single, 2 = multiple
$table->integer('translatable')->default(1);
}
);
Schema::create(
'taxonomy_terms',
function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('vocabulary_id');
$table->integer('type')->default(0); // 0 = simple, 1 = category
$table->foreign('vocabulary_id')->references('id')->on('taxonomy_vocabularies');
}
);
Schema::create(
'taxonomy_terms_data',
function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('term_id');
$table->unsignedInteger('language_id');
$table->string('title', 255);
$table->text('description')->nullable();
$table->foreign('term_id')->references('id')->on('taxonomy_terms');
$table->foreign('language_id')->references('id')->on('languages');
}
);
Schema::create(
'taxonomy_term_hierarchy',
function (Blueprint $table) {
$table->unsignedInteger('term_id');
$table->unsignedInteger('parent_id');
$table->foreign('term_id')->references('id')->on('taxonomy_terms');
$table->foreign('parent_id')->references('id')->on('taxonomy_terms');
$table->primary(['term_id', 'parent_id']);
}
);
Schema::create(
'taxonomy_content',
function (Blueprint $table) {
$table->unsignedInteger('term_id');
$table->unsignedInteger('relationable_id');
$table->string('relationable_type');
$table->foreign('term_id')->references('id')->on('taxonomy_terms');
$table->primary(
['term_id', 'relationable_id', 'relationable_type'],
'taxonomy_contents_composed_primary'
);
}
);
} | php | public function up()
{
Schema::create(
'taxonomy_vocabularies',
function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('machine_name', 255)->unique();
$table->text('description')->nullable();
$table->integer('hierarchy')->default(0); // 0 = disabled, 1 = single, 2 = multiple
$table->integer('translatable')->default(1);
}
);
Schema::create(
'taxonomy_terms',
function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('vocabulary_id');
$table->integer('type')->default(0); // 0 = simple, 1 = category
$table->foreign('vocabulary_id')->references('id')->on('taxonomy_vocabularies');
}
);
Schema::create(
'taxonomy_terms_data',
function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('term_id');
$table->unsignedInteger('language_id');
$table->string('title', 255);
$table->text('description')->nullable();
$table->foreign('term_id')->references('id')->on('taxonomy_terms');
$table->foreign('language_id')->references('id')->on('languages');
}
);
Schema::create(
'taxonomy_term_hierarchy',
function (Blueprint $table) {
$table->unsignedInteger('term_id');
$table->unsignedInteger('parent_id');
$table->foreign('term_id')->references('id')->on('taxonomy_terms');
$table->foreign('parent_id')->references('id')->on('taxonomy_terms');
$table->primary(['term_id', 'parent_id']);
}
);
Schema::create(
'taxonomy_content',
function (Blueprint $table) {
$table->unsignedInteger('term_id');
$table->unsignedInteger('relationable_id');
$table->string('relationable_type');
$table->foreign('term_id')->references('id')->on('taxonomy_terms');
$table->primary(
['term_id', 'relationable_id', 'relationable_type'],
'taxonomy_contents_composed_primary'
);
}
);
} | Run the migrations.
@return void | https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Taxonomy/migrations/2014_03_03_190649_create taxonomies.php#L13-L80 |
fridge-project/dbal | src/Fridge/DBAL/Driver/Statement/StatementRewriter.php | StatementRewriter.getRewritedParameters | public function getRewritedParameters($parameter)
{
if (is_int($parameter)) {
return array($parameter);
}
if (!isset($this->parameters[$parameter])) {
throw StatementRewriterException::parameterDoesNotExist($parameter);
}
return $this->parameters[$parameter];
} | php | public function getRewritedParameters($parameter)
{
if (is_int($parameter)) {
return array($parameter);
}
if (!isset($this->parameters[$parameter])) {
throw StatementRewriterException::parameterDoesNotExist($parameter);
}
return $this->parameters[$parameter];
} | Gets the rewrited positional statement parameters according to the named parameter.
The metod returns an array because a named parameter can be used multiple times in the statement.
@param string $parameter The named parameter.
@throws \Fridge\DBAL\Exception\StatementRewriterException If the parameter does not exist.
@return array The rewrited positional parameters. | https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Driver/Statement/StatementRewriter.php#L67-L78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.