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
|
---|---|---|---|---|---|---|---|
AntonyThorpe/consumer | src/Consumer.php | Consumer.setMaxExternalLastEdited | public function setMaxExternalLastEdited(array $apidata)
{
$external_last_edited_key = $this->ExternalLastEditedKey;
// Validation
if (!$external_last_edited_key) {
user_error(
_t('Consumer.ExternalLastEditedKeyNeeded', 'Property ExternalLastEditedKey needs to be set before calling setMaxExternalLastEdited method'),
E_USER_WARNING
);
}
$dates = array_map(function ($item) use ($external_last_edited_key) {
return $item[$external_last_edited_key];
}, $apidata);
$max_date = max($dates);
if (self::isTimestamp($max_date)) {
$max_date = self::convertUnix2UTC($max_date);
}
$this->ExternalLastEdited = $max_date;
return $this;
} | php | public function setMaxExternalLastEdited(array $apidata)
{
$external_last_edited_key = $this->ExternalLastEditedKey;
// Validation
if (!$external_last_edited_key) {
user_error(
_t('Consumer.ExternalLastEditedKeyNeeded', 'Property ExternalLastEditedKey needs to be set before calling setMaxExternalLastEdited method'),
E_USER_WARNING
);
}
$dates = array_map(function ($item) use ($external_last_edited_key) {
return $item[$external_last_edited_key];
}, $apidata);
$max_date = max($dates);
if (self::isTimestamp($max_date)) {
$max_date = self::convertUnix2UTC($max_date);
}
$this->ExternalLastEdited = $max_date;
return $this;
} | Set the ExternalLastEdited to the maximum last edited date
@param array $apidata
@return $this | https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/Consumer.php#L68-L91 |
smalldb/libSmalldb | class/GraphMLReader.php | GraphMLReader.loadString | public function loadString(string $machine_type, string $data_string, array $options = [], string $filename = null)
{
// Options
$graphml_group_name = isset($options['group']) ? $options['group'] : null;
// Graph
$keys = array();
$nodes = array();
$edges = array();
// Load GraphML into DOM
$dom = new \DOMDocument;
$dom->loadXml($data_string);
// Prepare XPath query engine
$xpath = new \DOMXpath($dom);
$xpath->registerNameSpace('g', 'http://graphml.graphdrawing.org/xmlns');
// Find group node
if ($graphml_group_name) {
$root_graph = null;
foreach($xpath->query('//g:graph') as $el) {
foreach($xpath->query('../g:data/*/*/y:GroupNode/y:NodeLabel', $el) as $label_el) {
$label = trim($label_el->textContent);
if ($label == $graphml_group_name) {
$root_graph = $el;
break 2;
}
}
}
} else {
$root_graph = $xpath->query('/g:graphml/g:graph')->item(0);
}
if ($root_graph == null) {
throw new GraphMLException('Graph node not found.');
}
// Load keys
foreach($xpath->query('./g:key[@attr.name][@id]') as $el) {
$id = $el->attributes->getNamedItem('id')->value;
$name = $el->attributes->getNamedItem('attr.name')->value;
//debug_msg("tag> %s => %s", $id, $name);
$keys[$id] = $name;
}
// Load graph properties
$graph_props = array();
foreach($xpath->query('./g:data[@key]', $root_graph) as $data_el) {
$k = $data_el->attributes->getNamedItem('key')->value;
if (isset($keys[$k])) {
if ($keys[$k] == 'Properties') {
// Special handling of machine properties
$properties = array();
foreach ($xpath->query('./property[@name]', $data_el) as $property_el) {
$property_name = $property_el->attributes->getNamedItem('name')->value;
foreach ($property_el->attributes as $property_attr_name => $property_attr) {
$properties[$property_name][$property_attr_name] = $property_attr->value;
}
}
$graph_props['properties'] = $properties;
} else {
$graph_props[$this->str2key($keys[$k])] = trim($data_el->textContent);
}
}
}
//debug_dump($graph_props, '$graph_props');
// Load nodes
foreach($xpath->query('.//g:node[@id]', $root_graph) as $el) {
$id = $el->attributes->getNamedItem('id')->value;
$node_props = array();
foreach($xpath->query('.//g:data[@key]', $el) as $data_el) {
$k = $data_el->attributes->getNamedItem('key')->value;
if (isset($keys[$k])) {
$node_props[$this->str2key($keys[$k])] = $data_el->textContent;
}
}
$label = $xpath->query('.//y:NodeLabel', $el)->item(0)->textContent;
if ($label !== null) {
$node_props['label'] = trim($label);
}
$color = $xpath->query('.//y:Fill', $el)->item(0)->attributes->getNamedItem('color')->value;
if ($color !== null) {
$node_props['color'] = trim($color);
}
//debug_msg("node> %s: \"%s\"", $id, @ $node_props['state']);
//debug_dump($node_props, '$node_props');
$nodes[$id] = $node_props;
}
// Load edges
foreach($xpath->query('//g:graph/g:edge[@id][@source][@target]') as $el) {
$id = $el->attributes->getNamedItem('id')->value;
$source = $el->attributes->getNamedItem('source')->value;
$target = $el->attributes->getNamedItem('target')->value;
if (!isset($nodes[$source]) || !isset($nodes[$target])) {
continue;
}
$edge_props = array();
foreach($xpath->query('.//g:data[@key]', $el) as $data_el) {
$k = $data_el->attributes->getNamedItem('key')->value;
if (isset($keys[$k])) {
$edge_props[$this->str2key($keys[$k])] = $data_el->textContent;
}
}
$label_query_result = $xpath->query('.//y:EdgeLabel', $el)->item(0);
if (!$label_query_result) {
throw new GraphMLException(sprintf('Missing edge label. Edge: %s -> %s',
isset($nodes[$source]['label']) ? $nodes[$source]['label'] : $source,
isset($nodes[$target]['label']) ? $nodes[$target]['label'] : $target));
}
$label = $label_query_result->textContent;
if ($label !== null) {
$edge_props['label'] = trim($label);
}
$color_query_result = $xpath->query('.//y:LineStyle', $el)->item(0);
if ($color_query_result) {
$color = $color_query_result->attributes->getNamedItem('color')->value;
if ($color !== null) {
$edge_props['color'] = trim($color);
}
}
//debug_msg("edge> %s: %s -> %s", $id, $source, $target);
//debug_dump($edge_props, '$edge_props');
$edges[$id] = array($source, $target, $edge_props);
}
// Build machine definition
$machine = array('_' => "<?php printf('_%c%c}%c',34,10,10);__halt_compiler();?>");
// Graph properties
foreach($graph_props as $k => $v) {
$machine[$k] = $v;
}
// Store states
foreach ($nodes as & $n) {
if (empty($n['state'])) {
if (empty($n['label'])) {
// Skip 'nonexistent' state, it is present by default
$n['state'] = '';
continue;
} else {
// Use label as state name
$n['state'] = (string) $n['label'];
}
}
if (empty($n['label'])) {
$n['label'] = $n['state'];
}
$machine['states'][(string) $n['state']] = $n;
}
// Store actions and transitions
foreach ($edges as $e) {
list($source_id, $target_id, $props) = $e;
$source = $source_id != '' ? (isset($nodes[$source_id]) ? (string) $nodes[$source_id]['state'] : null) : '';
$target = $target_id != '' ? (isset($nodes[$target_id]) ? (string) $nodes[$target_id]['state'] : null) : '';
if ($source === null || $target === null) {
// Ignore nonexistent nodes
continue;
}
if (@ $props['action'] != '') {
$action = $props['action'];
} else if (@ $props['label'] != '') {
$action = $props['label'];
} else {
throw new GraphMLException(sprintf('Missing label at edge "%s" -> "%s".',
$nodes[$source]['label'], $nodes[$target]['label']));
}
$tr = & $machine['actions'][$action]['transitions'][$source];
foreach ($props as $k => $v) {
$tr[$k] = $v;
}
$tr['targets'][] = $target;
unset($tr);
}
// Sort stuff to keep them in order when file is modified
asort($machine['states']);
asort($machine['actions']);
//debug_dump($machine['states'], 'States');
//debug_dump($machine['actions'], 'Actions');
//debug_dump($machine, '$machine');
return $machine;
} | php | public function loadString(string $machine_type, string $data_string, array $options = [], string $filename = null)
{
// Options
$graphml_group_name = isset($options['group']) ? $options['group'] : null;
// Graph
$keys = array();
$nodes = array();
$edges = array();
// Load GraphML into DOM
$dom = new \DOMDocument;
$dom->loadXml($data_string);
// Prepare XPath query engine
$xpath = new \DOMXpath($dom);
$xpath->registerNameSpace('g', 'http://graphml.graphdrawing.org/xmlns');
// Find group node
if ($graphml_group_name) {
$root_graph = null;
foreach($xpath->query('//g:graph') as $el) {
foreach($xpath->query('../g:data/*/*/y:GroupNode/y:NodeLabel', $el) as $label_el) {
$label = trim($label_el->textContent);
if ($label == $graphml_group_name) {
$root_graph = $el;
break 2;
}
}
}
} else {
$root_graph = $xpath->query('/g:graphml/g:graph')->item(0);
}
if ($root_graph == null) {
throw new GraphMLException('Graph node not found.');
}
// Load keys
foreach($xpath->query('./g:key[@attr.name][@id]') as $el) {
$id = $el->attributes->getNamedItem('id')->value;
$name = $el->attributes->getNamedItem('attr.name')->value;
//debug_msg("tag> %s => %s", $id, $name);
$keys[$id] = $name;
}
// Load graph properties
$graph_props = array();
foreach($xpath->query('./g:data[@key]', $root_graph) as $data_el) {
$k = $data_el->attributes->getNamedItem('key')->value;
if (isset($keys[$k])) {
if ($keys[$k] == 'Properties') {
// Special handling of machine properties
$properties = array();
foreach ($xpath->query('./property[@name]', $data_el) as $property_el) {
$property_name = $property_el->attributes->getNamedItem('name')->value;
foreach ($property_el->attributes as $property_attr_name => $property_attr) {
$properties[$property_name][$property_attr_name] = $property_attr->value;
}
}
$graph_props['properties'] = $properties;
} else {
$graph_props[$this->str2key($keys[$k])] = trim($data_el->textContent);
}
}
}
//debug_dump($graph_props, '$graph_props');
// Load nodes
foreach($xpath->query('.//g:node[@id]', $root_graph) as $el) {
$id = $el->attributes->getNamedItem('id')->value;
$node_props = array();
foreach($xpath->query('.//g:data[@key]', $el) as $data_el) {
$k = $data_el->attributes->getNamedItem('key')->value;
if (isset($keys[$k])) {
$node_props[$this->str2key($keys[$k])] = $data_el->textContent;
}
}
$label = $xpath->query('.//y:NodeLabel', $el)->item(0)->textContent;
if ($label !== null) {
$node_props['label'] = trim($label);
}
$color = $xpath->query('.//y:Fill', $el)->item(0)->attributes->getNamedItem('color')->value;
if ($color !== null) {
$node_props['color'] = trim($color);
}
//debug_msg("node> %s: \"%s\"", $id, @ $node_props['state']);
//debug_dump($node_props, '$node_props');
$nodes[$id] = $node_props;
}
// Load edges
foreach($xpath->query('//g:graph/g:edge[@id][@source][@target]') as $el) {
$id = $el->attributes->getNamedItem('id')->value;
$source = $el->attributes->getNamedItem('source')->value;
$target = $el->attributes->getNamedItem('target')->value;
if (!isset($nodes[$source]) || !isset($nodes[$target])) {
continue;
}
$edge_props = array();
foreach($xpath->query('.//g:data[@key]', $el) as $data_el) {
$k = $data_el->attributes->getNamedItem('key')->value;
if (isset($keys[$k])) {
$edge_props[$this->str2key($keys[$k])] = $data_el->textContent;
}
}
$label_query_result = $xpath->query('.//y:EdgeLabel', $el)->item(0);
if (!$label_query_result) {
throw new GraphMLException(sprintf('Missing edge label. Edge: %s -> %s',
isset($nodes[$source]['label']) ? $nodes[$source]['label'] : $source,
isset($nodes[$target]['label']) ? $nodes[$target]['label'] : $target));
}
$label = $label_query_result->textContent;
if ($label !== null) {
$edge_props['label'] = trim($label);
}
$color_query_result = $xpath->query('.//y:LineStyle', $el)->item(0);
if ($color_query_result) {
$color = $color_query_result->attributes->getNamedItem('color')->value;
if ($color !== null) {
$edge_props['color'] = trim($color);
}
}
//debug_msg("edge> %s: %s -> %s", $id, $source, $target);
//debug_dump($edge_props, '$edge_props');
$edges[$id] = array($source, $target, $edge_props);
}
// Build machine definition
$machine = array('_' => "<?php printf('_%c%c}%c',34,10,10);__halt_compiler();?>");
// Graph properties
foreach($graph_props as $k => $v) {
$machine[$k] = $v;
}
// Store states
foreach ($nodes as & $n) {
if (empty($n['state'])) {
if (empty($n['label'])) {
// Skip 'nonexistent' state, it is present by default
$n['state'] = '';
continue;
} else {
// Use label as state name
$n['state'] = (string) $n['label'];
}
}
if (empty($n['label'])) {
$n['label'] = $n['state'];
}
$machine['states'][(string) $n['state']] = $n;
}
// Store actions and transitions
foreach ($edges as $e) {
list($source_id, $target_id, $props) = $e;
$source = $source_id != '' ? (isset($nodes[$source_id]) ? (string) $nodes[$source_id]['state'] : null) : '';
$target = $target_id != '' ? (isset($nodes[$target_id]) ? (string) $nodes[$target_id]['state'] : null) : '';
if ($source === null || $target === null) {
// Ignore nonexistent nodes
continue;
}
if (@ $props['action'] != '') {
$action = $props['action'];
} else if (@ $props['label'] != '') {
$action = $props['label'];
} else {
throw new GraphMLException(sprintf('Missing label at edge "%s" -> "%s".',
$nodes[$source]['label'], $nodes[$target]['label']));
}
$tr = & $machine['actions'][$action]['transitions'][$source];
foreach ($props as $k => $v) {
$tr[$k] = $v;
}
$tr['targets'][] = $target;
unset($tr);
}
// Sort stuff to keep them in order when file is modified
asort($machine['states']);
asort($machine['actions']);
//debug_dump($machine['states'], 'States');
//debug_dump($machine['actions'], 'Actions');
//debug_dump($machine, '$machine');
return $machine;
} | / @copydoc IMachineDefinitionReader::loadString | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/GraphMLReader.php#L44-L232 |
acacha/forge-publish | src/Console/Commands/PublishAssignmentUsers.php | PublishAssignmentUsers.handle | public function handle()
{
$this->abortCommandExecution();
$this->users = $this->option('user') ? $this->argument('user') : $this->askForUsers();
if (count($this->users) == 0) {
$this->info('Skipping users...');
return;
}
$this->assignUsersToAssignment();
} | php | public function handle()
{
$this->abortCommandExecution();
$this->users = $this->option('user') ? $this->argument('user') : $this->askForUsers();
if (count($this->users) == 0) {
$this->info('Skipping users...');
return;
}
$this->assignUsersToAssignment();
} | Execute the console command. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignmentUsers.php#L64-L76 |
acacha/forge-publish | src/Console/Commands/PublishAssignmentUsers.php | PublishAssignmentUsers.assignUsersToAssignment | protected function assignUsersToAssignment()
{
$assignment = fp_env('ACACHA_FORGE_ASSIGNMENT');
foreach ( $this->users as $user) {
$uri = str_replace('{assignment}', $assignment, config('forge-publish.assign_user_to_assignment_uri'));
$uri = str_replace('{user}', $user, $uri);
$url = config('forge-publish.url') . $uri;
try {
$response = $this->http->post($url, [
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]);
} catch (\Exception $e) {
if ($e->getResponse()->getStatusCode() == 422) {
$this->error('The user is already assigned');
return;
}
$this->error('And error occurs connecting to the api url: ' . $url);
$this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
return;
}
}
} | php | protected function assignUsersToAssignment()
{
$assignment = fp_env('ACACHA_FORGE_ASSIGNMENT');
foreach ( $this->users as $user) {
$uri = str_replace('{assignment}', $assignment, config('forge-publish.assign_user_to_assignment_uri'));
$uri = str_replace('{user}', $user, $uri);
$url = config('forge-publish.url') . $uri;
try {
$response = $this->http->post($url, [
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]);
} catch (\Exception $e) {
if ($e->getResponse()->getStatusCode() == 422) {
$this->error('The user is already assigned');
return;
}
$this->error('And error occurs connecting to the api url: ' . $url);
$this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
return;
}
}
} | Assign users to assignment
@return array|mixed | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignmentUsers.php#L83-L107 |
acacha/forge-publish | src/Console/Commands/PublishAssignmentUsers.php | PublishAssignmentUsers.askForUsers | protected function askForUsers()
{
$default = 0;
$users = $this->users();
$user_names = array_merge(
['Skip'],
collect($users)->pluck('name')->toArray()
);
$selected_user_names = $this->choice('Users?', $user_names ,$default, null, true);
if ($selected_user_names == 0) return null;
$users = collect($users)->filter(function ($user) use ($selected_user_names) {
return in_array($user->name,$selected_user_names);
});
return $users->pluck('id');
} | php | protected function askForUsers()
{
$default = 0;
$users = $this->users();
$user_names = array_merge(
['Skip'],
collect($users)->pluck('name')->toArray()
);
$selected_user_names = $this->choice('Users?', $user_names ,$default, null, true);
if ($selected_user_names == 0) return null;
$users = collect($users)->filter(function ($user) use ($selected_user_names) {
return in_array($user->name,$selected_user_names);
});
return $users->pluck('id');
} | Ask for users.
@return string | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignmentUsers.php#L135-L152 |
emaphp/omocha | lib/ValueParser.php | ValueParser.parse | public function parse($value) {
$json = $this->decode($value);
if (JSON_ERROR_NONE == json_last_error()) {
return $json;
}
$float = filter_var($value, FILTER_VALIDATE_FLOAT);
return $float !== false ? $float : $value;
} | php | public function parse($value) {
$json = $this->decode($value);
if (JSON_ERROR_NONE == json_last_error()) {
return $json;
}
$float = filter_var($value, FILTER_VALIDATE_FLOAT);
return $float !== false ? $float : $value;
} | Parses an annotation value
@param string $value
@return mixed | https://github.com/emaphp/omocha/blob/6635b2a7d5feeb7c8627a1a50a871220b1861024/lib/ValueParser.php#L10-L17 |
schpill/thin | src/Paypal.php | Paypal.ipn | public static function ipn()
{
// only accept post data
if (!count($_POST)) {
return false;
}
// if production mode...
if (Config::get('paypal.production_mode')) {
// use production endpoint
$endpoint = 'https://www.paypal.com/cgi-bin/webscr';
} else {
// use sandbox endpoint
$endpoint = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
}
// build response
$fields = http_build_query(array('cmd' => '_notify-validate') + Input::all());
// curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// if errors...
if (curl_errno($ch)) {
#$errors = curl_error($ch);
curl_close($ch);
// return false
return false;
} else {
// close connection
curl_close($ch);
// if success...
if ($code === 200 and $response === 'VERIFIED') {
return true;
} else {
return false;
}
}
} | php | public static function ipn()
{
// only accept post data
if (!count($_POST)) {
return false;
}
// if production mode...
if (Config::get('paypal.production_mode')) {
// use production endpoint
$endpoint = 'https://www.paypal.com/cgi-bin/webscr';
} else {
// use sandbox endpoint
$endpoint = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
}
// build response
$fields = http_build_query(array('cmd' => '_notify-validate') + Input::all());
// curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// if errors...
if (curl_errno($ch)) {
#$errors = curl_error($ch);
curl_close($ch);
// return false
return false;
} else {
// close connection
curl_close($ch);
// if success...
if ($code === 200 and $response === 'VERIFIED') {
return true;
} else {
return false;
}
}
} | Automatically verify Paypal IPN communications.
@return boolean | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Paypal.php#L79-L128 |
ajaxtown/eaglehorn_framework | src/Eaglehorn/worker/Profiler/Profiler.php | Profiler.profile | public function profile($classname, $methodname, $methodargs, $invocations = 1)
{
if (class_exists($classname) != TRUE) {
throw new Exception("{$classname} doesn't exist");
}
$method = new ReflectionMethod($classname, $methodname);
$instance = NULL;
if (!$method->isStatic()) {
$class = new ReflectionClass($classname);
$instance = $class->newInstance();
}
$durations = array();
for ($i = 0; $i < $invocations; $i++) {
$start = microtime(true);
$method->invokeArgs($instance, $methodargs);
$durations[] = microtime(true) - $start;
}
$durations['worst'] = round(max($durations), 5);
$durations['total'] = round(array_sum($durations), 5);
$durations['average'] = round($durations['total'] / count($durations), 5);
$this->details = array('class' => $classname,
'method' => $methodname,
'arguments' => $methodargs,
'duration' => $durations,
'invocations' => $invocations);
return $durations['average'];
} | php | public function profile($classname, $methodname, $methodargs, $invocations = 1)
{
if (class_exists($classname) != TRUE) {
throw new Exception("{$classname} doesn't exist");
}
$method = new ReflectionMethod($classname, $methodname);
$instance = NULL;
if (!$method->isStatic()) {
$class = new ReflectionClass($classname);
$instance = $class->newInstance();
}
$durations = array();
for ($i = 0; $i < $invocations; $i++) {
$start = microtime(true);
$method->invokeArgs($instance, $methodargs);
$durations[] = microtime(true) - $start;
}
$durations['worst'] = round(max($durations), 5);
$durations['total'] = round(array_sum($durations), 5);
$durations['average'] = round($durations['total'] / count($durations), 5);
$this->details = array('class' => $classname,
'method' => $methodname,
'arguments' => $methodargs,
'duration' => $durations,
'invocations' => $invocations);
return $durations['average'];
} | Runs a method with the provided arguments, and
returns details about how long it took. Works
with instance methods and static methods.
@param string $classname
@param string $methodname
@param array $methodargs
@param int $invocations
@throws Exception
@internal param string $classname
@internal param string $methodname
@internal param array $methodargs
@internal param int $invocations The number of times to call the method
@return float average invocation duration in seconds | https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/worker/Profiler/Profiler.php#L53-L85 |
matryoshka-model/matryoshka | library/Service/ModelManagerFactory.php | ModelManagerFactory.createService | public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$modelConfig = [];
if (isset($config['matryoshka']) && isset($config['matryoshka']['model_manager'])) {
$modelConfig = $config['matryoshka']['model_manager'];
}
return new ModelManager(new Config($modelConfig));
} | php | public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$modelConfig = [];
if (isset($config['matryoshka']) && isset($config['matryoshka']['model_manager'])) {
$modelConfig = $config['matryoshka']['model_manager'];
}
return new ModelManager(new Config($modelConfig));
} | Create service
@param ServiceLocatorInterface $serviceLocator
@return mixed | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Service/ModelManagerFactory.php#L27-L35 |
PhoxPHP/Glider | src/Model/Uses/Finder.php | Finder.initializeFindBy | protected function initializeFindBy(Model $context, Model $childModel, String $childClassName, String $clause, Array $clauseArguments=[])
{
$this->table = $childModel->table;
$builder = $this->toSql(
$this->getAccessibleProperties(
[Attributes::ALL_SELECTOR],
false
)
)->whereIn(
$clause, $clauseArguments
)->get();
if ($builder->first()) {
// If the result is not empty, the accessible properties will be extracted and returned.
$accessibleProperties = $childModel->accessibleProperties();
$resultArray = $builder->toArray()->all();
if (count($resultArray) > 1) {
$results = [];
foreach($resultArray as $i => $result) {
$res = $resultArray[$i];
// If '$childModel' property is used here, same records will be returned so we are
// to create new instances of the model class.
$accessible = new $childClassName;
foreach(array_keys($res) as $i => $key) {
if ($childModel->isAccessible($key)) {
$accessible->softProperties[$key] = $res[$key];
}
}
$results[] = $accessible;
$accessible = null;
}
return new Collection($results, $childModel);
}else{
foreach($resultArray[0] as $key => $result) {
if ($childModel->isAccessible($key)) {
$childModel->softProperties[$key] = $resultArray[0][$key];
}
}
}
}else{
return false;
}
return $childModel;
} | php | protected function initializeFindBy(Model $context, Model $childModel, String $childClassName, String $clause, Array $clauseArguments=[])
{
$this->table = $childModel->table;
$builder = $this->toSql(
$this->getAccessibleProperties(
[Attributes::ALL_SELECTOR],
false
)
)->whereIn(
$clause, $clauseArguments
)->get();
if ($builder->first()) {
// If the result is not empty, the accessible properties will be extracted and returned.
$accessibleProperties = $childModel->accessibleProperties();
$resultArray = $builder->toArray()->all();
if (count($resultArray) > 1) {
$results = [];
foreach($resultArray as $i => $result) {
$res = $resultArray[$i];
// If '$childModel' property is used here, same records will be returned so we are
// to create new instances of the model class.
$accessible = new $childClassName;
foreach(array_keys($res) as $i => $key) {
if ($childModel->isAccessible($key)) {
$accessible->softProperties[$key] = $res[$key];
}
}
$results[] = $accessible;
$accessible = null;
}
return new Collection($results, $childModel);
}else{
foreach($resultArray[0] as $key => $result) {
if ($childModel->isAccessible($key)) {
$childModel->softProperties[$key] = $resultArray[0][$key];
}
}
}
}else{
return false;
}
return $childModel;
} | Handles findBy methods called via __callStatic magic method. If the result returned is more than
one, an array of the model object is returned.
@param $context <Kit\Glider\Model\Model>
@param $childModel <Kit\Glider\Model\Model>
@param $childClassName <String>
@param $clause <String>
@param $clauseArguments <Array>
@access protected
@return <Mixed> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Uses/Finder.php#L45-L96 |
kvantstudio/site_geo | src/Form/ImportForm.php | ImportForm.getPluginList | protected function getPluginList() {
$definitions = \Drupal::service('plugin.manager.site_geo')->getDefinitions();
$plugin_list = [];
foreach ($definitions as $plugin_id => $plugin) {
$plugin_list[$plugin_id] = $plugin['label']->render();
}
return $plugin_list;
} | php | protected function getPluginList() {
$definitions = \Drupal::service('plugin.manager.site_geo')->getDefinitions();
$plugin_list = [];
foreach ($definitions as $plugin_id => $plugin) {
$plugin_list[$plugin_id] = $plugin['label']->render();
}
return $plugin_list;
} | {@inheritdoc} | https://github.com/kvantstudio/site_geo/blob/674c9fc2bbeb5bb71faf0020bdba2fb8f740b5be/src/Form/ImportForm.php#L26-L33 |
kvantstudio/site_geo | src/Form/ImportForm.php | ImportForm.validateImportPlugin | public function validateImportPlugin(array &$form, FormStateInterface $form_state) {
if ($form_state->getTriggeringElement()['#name'] == 'start_import') {
$plugin_id = $form_state->getValue('import_plugin');
if ($plugin_id == "") {
$form_state->setErrorByName('import_plugin', $this->t('You must select type to import.'));
}
}
} | php | public function validateImportPlugin(array &$form, FormStateInterface $form_state) {
if ($form_state->getTriggeringElement()['#name'] == 'start_import') {
$plugin_id = $form_state->getValue('import_plugin');
if ($plugin_id == "") {
$form_state->setErrorByName('import_plugin', $this->t('You must select type to import.'));
}
}
} | {@inheritdoc} | https://github.com/kvantstudio/site_geo/blob/674c9fc2bbeb5bb71faf0020bdba2fb8f740b5be/src/Form/ImportForm.php#L134-L141 |
kvantstudio/site_geo | src/Form/ImportForm.php | ImportForm.validateForm | public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
if ($form_state->getTriggeringElement()['#name'] == 'start_import') {
$plugin_id = $form_state->getValue('import_plugin');
if ($plugin_id == "") {
$form_state->setErrorByName('import_plugin', $this->t('You must select type to import.'));
}
if ($form_state->getValue('chunk_size') < 1) {
$form_state->setErrorByName('chunk_size', $this->t('Chunk size must be greater or equal 1.'));
}
}
} | php | public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
if ($form_state->getTriggeringElement()['#name'] == 'start_import') {
$plugin_id = $form_state->getValue('import_plugin');
if ($plugin_id == "") {
$form_state->setErrorByName('import_plugin', $this->t('You must select type to import.'));
}
if ($form_state->getValue('chunk_size') < 1) {
$form_state->setErrorByName('chunk_size', $this->t('Chunk size must be greater or equal 1.'));
}
}
} | {@inheritdoc} | https://github.com/kvantstudio/site_geo/blob/674c9fc2bbeb5bb71faf0020bdba2fb8f740b5be/src/Form/ImportForm.php#L146-L158 |
kvantstudio/site_geo | src/Form/ImportForm.php | ImportForm.startImport | public function startImport(array &$form, FormStateInterface $form_state) {
// Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках.
ConfigFormBase::validateForm($form, $form_state);
if (!$form_state->getValue('validate_error')) {
$config = $this->config('site_geo.import');
$fid = $config->get('fid');
$skip_first_line = $config->get('skip_first_line');
$delimiter = $config->get('delimiter');
$enclosure = $config->get('enclosure');
$chunk_size = $config->get('chunk_size');
$plugin_id = $form_state->getValue('import_plugin');
if ($plugin_id != "") {
$import = new SiteGeoCSVBatchImport($plugin_id, $fid, $skip_first_line, $delimiter, $enclosure, $chunk_size);
$import->setBatch();
}
}
} | php | public function startImport(array &$form, FormStateInterface $form_state) {
// Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках.
ConfigFormBase::validateForm($form, $form_state);
if (!$form_state->getValue('validate_error')) {
$config = $this->config('site_geo.import');
$fid = $config->get('fid');
$skip_first_line = $config->get('skip_first_line');
$delimiter = $config->get('delimiter');
$enclosure = $config->get('enclosure');
$chunk_size = $config->get('chunk_size');
$plugin_id = $form_state->getValue('import_plugin');
if ($plugin_id != "") {
$import = new SiteGeoCSVBatchImport($plugin_id, $fid, $skip_first_line, $delimiter, $enclosure, $chunk_size);
$import->setBatch();
}
}
} | {@inheritdoc}
Импорт из файла. | https://github.com/kvantstudio/site_geo/blob/674c9fc2bbeb5bb71faf0020bdba2fb8f740b5be/src/Form/ImportForm.php#L203-L222 |
phavour/phavour | Phavour/Cache/AdapterMemcache.php | AdapterMemcache.get | public function get($key)
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
try {
return $this->memcache->get($key);
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | php | public function get($key)
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
try {
return $this->memcache->get($key);
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | Get a value from cache
@param string $key
@return mixed|boolean false | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Cache/AdapterMemcache.php#L96-L112 |
phavour/phavour | Phavour/Cache/AdapterMemcache.php | AdapterMemcache.set | public function set($key, $value, $ttl = self::DEFAULT_TTL)
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
$flag = null;
if (!is_bool($value) && !is_int($value) && !is_float($value)) {
$flag = MEMCACHE_COMPRESSED;
}
try {
return $this->memcache->set($key, $value, $flag, $ttl);
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | php | public function set($key, $value, $ttl = self::DEFAULT_TTL)
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
$flag = null;
if (!is_bool($value) && !is_int($value) && !is_float($value)) {
$flag = MEMCACHE_COMPRESSED;
}
try {
return $this->memcache->set($key, $value, $flag, $ttl);
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | Set a cache value
@param string $key
@param mixed $value
@param integer $ttl (optional) default 86400
@return boolean | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Cache/AdapterMemcache.php#L121-L143 |
phavour/phavour | Phavour/Cache/AdapterMemcache.php | AdapterMemcache.remove | public function remove($key)
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
try {
return $this->memcache->delete($key);
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | php | public function remove($key)
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
try {
return $this->memcache->delete($key);
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | Remove a cached value by key.
@param string $key
@return boolean | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Cache/AdapterMemcache.php#L195-L211 |
phavour/phavour | Phavour/Cache/AdapterMemcache.php | AdapterMemcache.flush | public function flush()
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
try {
return $this->memcache->flush();
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | php | public function flush()
{
if (!$this->hasConnection()) {
// @codeCoverageIgnoreStart
return false;
// @codeCoverageIgnoreEnd
}
try {
return $this->memcache->flush();
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
}
return false;
// @codeCoverageIgnoreEnd
} | Flush all existing Cache
@return boolean | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Cache/AdapterMemcache.php#L217-L233 |
stonedz/pff2 | src/Abs/AController.php | AController.getParam | public function getParam($index, $errorMessage = "Page not found", $errorCode = 404) {
if(isset($this->_params[$index])){
return $this->_params[$index];
}
else{
throw new PffException($errorMessage, $errorCode);
}
} | php | public function getParam($index, $errorMessage = "Page not found", $errorCode = 404) {
if(isset($this->_params[$index])){
return $this->_params[$index];
}
else{
throw new PffException($errorMessage, $errorCode);
}
} | Gets a parameter (GET)
@param int|string $index
@param string $errorMessage
@param int $errorCode
@throws PffException
@return string | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AController.php#L282-L289 |
stonedz/pff2 | src/Abs/AController.php | AController.beforeFilter | public function beforeFilter() {
if(!isset($this->_beforeFilters[$this->_action])) {
return false;
}
foreach($this->_beforeFilters[$this->_action] as $method) {
call_user_func($method);
}
} | php | public function beforeFilter() {
if(!isset($this->_beforeFilters[$this->_action])) {
return false;
}
foreach($this->_beforeFilters[$this->_action] as $method) {
call_user_func($method);
}
} | Executes all the registered beforeFilters for the current action | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AController.php#L314-L322 |
stonedz/pff2 | src/Abs/AController.php | AController.afterFilter | public function afterFilter() {
if(!isset($this->_afterFilters[$this->_action])) {
return false;
}
foreach($this->_afterFilters[$this->_action] as $method) {
call_user_func($method);
}
} | php | public function afterFilter() {
if(!isset($this->_afterFilters[$this->_action])) {
return false;
}
foreach($this->_afterFilters[$this->_action] as $method) {
call_user_func($method);
}
} | Execute all the registered afterFilters for the current action | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AController.php#L327-L335 |
stonedz/pff2 | src/Abs/AController.php | AController.setLayout | public function setLayout($layout){
$this->_layout = $layout;
if(isset($this->_view[0])) {
$this->resetViews();
}
$this->addView($layout);
} | php | public function setLayout($layout){
$this->_layout = $layout;
if(isset($this->_view[0])) {
$this->resetViews();
}
$this->addView($layout);
} | This method RESET the layout (i.e. the first rendereable View in the rendering queue).
If a Layout has already been set it will
@param $layout AView | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AController.php#L356-L362 |
rujiali/acquia-site-factory-cli | src/AppBundle/Commands/ClearCacheCommand.php | ClearCacheCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$task = $this->connectorSites->clearCache();
if (is_object($task)) {
$headers = ['id', 'time', 'drupal_cache_clear_task_id', 'varnish_cache_clear_task_id'];
$taskList = [];
$taskList[] = [
'id' => $task->id,
'time' => $task->time,
// @codingStandardsIgnoreStart
'drupal_cache_clear-task_id' => $task->task_ids->drupal_cache_clear,
'varnish_cache_clear-task_id' => $task->task_ids->varnish_cache_clear,
// @codingStandardsIgnoreEnd
];
$table = new Table($output);
$table
->setHeaders($headers)
->setRows($taskList);
$table->render();
} else {
$output->write($task);
}
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$task = $this->connectorSites->clearCache();
if (is_object($task)) {
$headers = ['id', 'time', 'drupal_cache_clear_task_id', 'varnish_cache_clear_task_id'];
$taskList = [];
$taskList[] = [
'id' => $task->id,
'time' => $task->time,
// @codingStandardsIgnoreStart
'drupal_cache_clear-task_id' => $task->task_ids->drupal_cache_clear,
'varnish_cache_clear-task_id' => $task->task_ids->varnish_cache_clear,
// @codingStandardsIgnoreEnd
];
$table = new Table($output);
$table
->setHeaders($headers)
->setRows($taskList);
$table->render();
} else {
$output->write($task);
}
} | {@inheritdoc} | https://github.com/rujiali/acquia-site-factory-cli/blob/c9dbb9dfd71408adff0ea26db94678a61c584df6/src/AppBundle/Commands/ClearCacheCommand.php#L46-L68 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.initializeMachine | public final function initializeMachine(Smalldb $smalldb, string $type, array $config)
{
if ($this->smalldb !== null) {
throw new RuntimeException('Machine is already configured.');
}
$this->smalldb = $smalldb;
$this->machine_type = $type;
$this->configureMachine($config);
// Create default machine (see FlupdoCrudMachine)?
if (empty($config['no_default_machine'])) {
$this->setupDefaultMachine($config);
}
} | php | public final function initializeMachine(Smalldb $smalldb, string $type, array $config)
{
if ($this->smalldb !== null) {
throw new RuntimeException('Machine is already configured.');
}
$this->smalldb = $smalldb;
$this->machine_type = $type;
$this->configureMachine($config);
// Create default machine (see FlupdoCrudMachine)?
if (empty($config['no_default_machine'])) {
$this->setupDefaultMachine($config);
}
} | Configure machine. Machine gets reference to Smalldb entry point,
name of its type (under which is this machine registered) and
optional array of additional configuration (passed directly to
initializeMachine method).
This method is called only once, right after backend creates/gets
instance of this class. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L302-L315 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.loadMachineConfig | protected function loadMachineConfig(array $config, array $keys)
{
foreach ($keys as $k) {
if (isset($config[$k])) {
if ($this->$k === null) {
$this->$k = $config[$k];
} else if (is_array($this->$k) && is_array($config[$k])) {
$this->$k = array_replace_recursive($this->$k, $config[$k]);
}
}
}
} | php | protected function loadMachineConfig(array $config, array $keys)
{
foreach ($keys as $k) {
if (isset($config[$k])) {
if ($this->$k === null) {
$this->$k = $config[$k];
} else if (is_array($this->$k) && is_array($config[$k])) {
$this->$k = array_replace_recursive($this->$k, $config[$k]);
}
}
}
} | Merge $config into state machine member variables (helper method).
Already set member variables are not overwriten. If the member
variable is an array, the $config array is merged with the config,
overwriting only matching keys (using `array_replace_recursive`).
@param array $config Configuration passed to state machine
@param array $keys List of feys from $config to load into member variables
of the same name. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L391-L402 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.getView | public final function getView($id, $view, & $properties_cache = null, & $view_cache = null, & $persistent_view_cache = null)
{
// Check cache
if (isset($view_cache[$view])) {
return $view_cache[$view];
}
switch ($view) {
case 'url':
// Get URL of this state machine
return $this->urlFormat($id, $this->url_fmt, $properties_cache);
case 'parent_url':
// Get URL of parent state machine or collection or whatever it is
if ($this->parent_url_fmt !== null) {
return $this->urlFormat($id, $this->parent_url_fmt, $properties_cache);
} else {
return null;
}
case 'post_action_url':
// Get URL of redirect-after-post
return $this->urlFormat($id, $this->post_action_url_fmt !== null ? $this->post_action_url_fmt : $this->url_fmt, $properties_cache);
default:
// Check references
if (isset($this->references[$view])) {
// Populate properties cache if empty
if ($properties_cache === null) {
$properties_cache = $this->getProperties($id);
}
// Create reference & cache it
return ($view_cache[$view] = $this->resolveMachineReference($view, $properties_cache));
} else {
return ($view_cache[$view] = $this->calculateViewValue($id, $view, $properties_cache, $view_cache, $persistent_view_cache));
}
}
} | php | public final function getView($id, $view, & $properties_cache = null, & $view_cache = null, & $persistent_view_cache = null)
{
// Check cache
if (isset($view_cache[$view])) {
return $view_cache[$view];
}
switch ($view) {
case 'url':
// Get URL of this state machine
return $this->urlFormat($id, $this->url_fmt, $properties_cache);
case 'parent_url':
// Get URL of parent state machine or collection or whatever it is
if ($this->parent_url_fmt !== null) {
return $this->urlFormat($id, $this->parent_url_fmt, $properties_cache);
} else {
return null;
}
case 'post_action_url':
// Get URL of redirect-after-post
return $this->urlFormat($id, $this->post_action_url_fmt !== null ? $this->post_action_url_fmt : $this->url_fmt, $properties_cache);
default:
// Check references
if (isset($this->references[$view])) {
// Populate properties cache if empty
if ($properties_cache === null) {
$properties_cache = $this->getProperties($id);
}
// Create reference & cache it
return ($view_cache[$view] = $this->resolveMachineReference($view, $properties_cache));
} else {
return ($view_cache[$view] = $this->calculateViewValue($id, $view, $properties_cache, $view_cache, $persistent_view_cache));
}
}
} | Get properties in given view.
Just like SQL view, the property view is transformed set of
properties. These views are useful when some properties require
heavy calculations.
Keep in mind, that view name must not interfere with Reference
properties, otherwise the view is inaccessible directly.
Array $properties_cache is supplied by Reference class to make some
calculations faster and without duplicate database queries.
Make sure these cached properties are up to date or null.
Array $view_cache is writable cache inside the Reference class,
flushed together with $properties_cache. If cache is empty, but
available, an empty array is supplied.
Array $persistent_view_cache is kept untouched for entire Reference
lifetime. If cache is empty, but available, an empty array is
supplied.
@see AbstractMachine::calculateViewValue() | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L469-L504 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.calculateViewValue | protected function calculateViewValue($id, $view, & $properties_cache = null, & $view_cache = null, & $persistent_view_cache = null)
{
throw new InvalidArgumentException('Unknown view "'.$view.'" requested on machine "'.$this->machine_type.'".');
} | php | protected function calculateViewValue($id, $view, & $properties_cache = null, & $view_cache = null, & $persistent_view_cache = null)
{
throw new InvalidArgumentException('Unknown view "'.$view.'" requested on machine "'.$this->machine_type.'".');
} | Calculate value of a view.
Returned value is cached in $view_cache until a transition occurs or
the cache is invalidated.
@return mixed | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L514-L517 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.urlFormat | protected function urlFormat($id, $url_fmt, $properties_cache): string
{
if (isset($url_fmt)) {
if ($properties_cache === null) {
// URL contains ID only, so there is no need to load properties.
return Utils::filename_format($url_fmt, array_combine($this->describeId(), (array) $id));
} else {
// However, if properties are in cache, it is better to use them.
return Utils::filename_format($url_fmt, $properties_cache);
}
} else {
// Default fallback to something reasonable. It might not work, but meh.
return '/'.$this->machine_type.'/'.(is_array($id) ? join('/', $id) : $id);
}
} | php | protected function urlFormat($id, $url_fmt, $properties_cache): string
{
if (isset($url_fmt)) {
if ($properties_cache === null) {
// URL contains ID only, so there is no need to load properties.
return Utils::filename_format($url_fmt, array_combine($this->describeId(), (array) $id));
} else {
// However, if properties are in cache, it is better to use them.
return Utils::filename_format($url_fmt, $properties_cache);
}
} else {
// Default fallback to something reasonable. It might not work, but meh.
return '/'.$this->machine_type.'/'.(is_array($id) ? join('/', $id) : $id);
}
} | Create URL using properties and given format. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L523-L537 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.resolveMachineReference | protected function resolveMachineReference(string $reference_name, array $properties_cache): Reference
{
if (!isset($this->references[$reference_name])) {
throw new \InvalidArgumentException('Unknown reference: '.$reference_name);
}
// Get reference configuration
$r = $this->references[$reference_name];
// Get referenced machine id
$ref_machine_id = array();
foreach ($r['machine_id'] as $mid_prop) {
$ref_machine_id[] = $properties_cache[$mid_prop];
}
// Get referenced machine type
$ref_machine_type = $r['machine_type'];
return $this->smalldb->getMachine($ref_machine_type)->ref($ref_machine_id);
} | php | protected function resolveMachineReference(string $reference_name, array $properties_cache): Reference
{
if (!isset($this->references[$reference_name])) {
throw new \InvalidArgumentException('Unknown reference: '.$reference_name);
}
// Get reference configuration
$r = $this->references[$reference_name];
// Get referenced machine id
$ref_machine_id = array();
foreach ($r['machine_id'] as $mid_prop) {
$ref_machine_id[] = $properties_cache[$mid_prop];
}
// Get referenced machine type
$ref_machine_type = $r['machine_type'];
return $this->smalldb->getMachine($ref_machine_type)->ref($ref_machine_id);
} | Helper function to resolve reference to another machine.
@param string $reference_name Name of the reference in AbstractMachine::references.
@param array $properties_cache Properties of referencing machine.
@return Reference to referred machine. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L547-L566 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.isTransitionAllowed | public function isTransitionAllowed(Reference $ref, $transition_name, $state = null, & $access_policy = null)
{
if ($state === null) {
$state = $ref->state;
}
if ($transition_name == '') {
// Read access
$access_policy = $this->read_access_policy;
return $this->checkAccessPolicy($this->read_access_policy, $ref);
} else if (isset($this->actions[$transition_name]['transitions'][$state])) {
$tr = $this->actions[$transition_name]['transitions'][$state];
if (isset($tr['access_policy'])) {
// Transition-specific policy
$access_policy = $tr['access_policy'];
} else if (isset($this->actions[$transition_name]['access_policy'])) {
// Action-specific policy (for all transitions of this name)
$access_policy = $this->actions[$transition_name]['access_policy'];
} else {
// No policy, use default
$access_policy = $this->default_access_policy;
}
return $this->checkAccessPolicy($access_policy, $ref);
} else {
// Not a valid transition
return false;
}
} | php | public function isTransitionAllowed(Reference $ref, $transition_name, $state = null, & $access_policy = null)
{
if ($state === null) {
$state = $ref->state;
}
if ($transition_name == '') {
// Read access
$access_policy = $this->read_access_policy;
return $this->checkAccessPolicy($this->read_access_policy, $ref);
} else if (isset($this->actions[$transition_name]['transitions'][$state])) {
$tr = $this->actions[$transition_name]['transitions'][$state];
if (isset($tr['access_policy'])) {
// Transition-specific policy
$access_policy = $tr['access_policy'];
} else if (isset($this->actions[$transition_name]['access_policy'])) {
// Action-specific policy (for all transitions of this name)
$access_policy = $this->actions[$transition_name]['access_policy'];
} else {
// No policy, use default
$access_policy = $this->default_access_policy;
}
return $this->checkAccessPolicy($access_policy, $ref);
} else {
// Not a valid transition
return false;
}
} | Returns true if transition can be invoked right now.
TODO: Transition should not have full definition of the policy, only
its name. Definitions should be in common place. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L575-L602 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.getAvailableTransitions | public function getAvailableTransitions(Reference $ref, $state = null)
{
if ($state === null) {
$state = $ref->state;
}
$available_transitions = array();
foreach ($this->actions as $a => $action) {
if (!empty($action['transitions'][$state]) && $this->isTransitionAllowed($ref, $a, $state)) {
$available_transitions[] = $a;
}
}
return $available_transitions;
} | php | public function getAvailableTransitions(Reference $ref, $state = null)
{
if ($state === null) {
$state = $ref->state;
}
$available_transitions = array();
foreach ($this->actions as $a => $action) {
if (!empty($action['transitions'][$state]) && $this->isTransitionAllowed($ref, $a, $state)) {
$available_transitions[] = $a;
}
}
return $available_transitions;
} | Get list of all available actions for state machine instance identified by $id. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L608-L623 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.invokeTransition | public function invokeTransition(Reference $ref, $transition_name, $args, & $returns, callable $new_id_callback = null)
{
if (!empty($this->errors)) {
throw new StateMachineHasErrorsException('Cannot use state machine with errors in definition: "'.$this->machine_type.'".');
}
$state = $ref->state;
if ($this->debug_logger) {
$this->debug_logger->beforeTransition($this, $ref, $state, $transition_name, $args);
}
// get action
if (isset($this->actions[$transition_name])) {
$action = $this->actions[$transition_name];
} else {
throw new TransitionException('Unknown transition "'.$transition_name.'" requested on machine "'.$this->machine_type.'".');
}
// get transition (instance of action)
if (isset($action['transitions'][$state])) {
$transition = $action['transitions'][$state];
} else {
throw new TransitionException('Transition "'.$transition_name.'" not found in state "'.$state.'" of machine "'.$this->machine_type.'".');
}
$transition = array_merge($action, $transition);
// check access_policy
if (!$this->isTransitionAllowed($ref, $transition_name, $state, $access_policy)) {
throw new TransitionAccessException('Access denied to transition "'.$transition_name.'" '
.'of machine "'.$this->machine_type.'" (used access policy: "'.$access_policy.'").');
}
// invoke pre-transition checks
if (isset($transition['pre_check_methods'])) {
foreach ($transition['pre_check_methods'] as $m) {
if (call_user_func(array($this, $m), $ref, $transition_name, $args) === false) {
throw new TransitionPreCheckException('Transition "'.$transition_name.'" aborted by method "'.$m.'" of machine "'.$this->machine_type.'".');
}
}
}
// get method
$method = isset($transition['method']) ? $transition['method'] : $transition_name;
$prefix_args = isset($transition['args']) ? $transition['args'] : array();
// prepare arguments -- the first argument is $ref, rest are $args as passed to $ref->action($args...).
if (!empty($prefix_args)) {
array_splice($args, 0, 0, $prefix_args);
}
array_unshift($args, $ref);
// invoke method
$ret = call_user_func_array(array($this, $method), $args);
// interpret return value
$returns = @ $action['returns'];
switch ($returns) {
case self::RETURNS_VALUE:
// nop, just pass it back
break;
case self::RETURNS_NEW_ID:
if ($new_id_callback !== null) {
$new_id_callback($ret);
}
break;
default:
throw new RuntimeException('Unknown semantics of the return value: '.$returns);
}
// invalidate cached state and properties data in $ref
unset($ref->properties);
// check result using assertion function
$new_state = $ref->state;
$target_states = $transition['targets'];
if (!is_array($target_states)) {
throw new TransitionException('Target state is not defined for transition "'.$transition_name.'" from state "'.$state.'" of machine "'.$this->machine_type.'".');
}
if (!in_array($new_state, $target_states)) {
throw new RuntimeException('State machine ended in unexpected state "'.$new_state
.'" after transition "'.$transition_name.'" from state "'.$state.'" of machine "'.$this->machine_type.'". '
.'Expected states: '.join(', ', $target_states).'.');
}
// invoke post-transition callbacks
if (isset($transition['post_transition_methods'])) {
foreach ($transition['post_transition_methods'] as $m) {
call_user_func(array($this, $m), $ref, $transition_name, $args, $ret);
}
}
// state changed notification
if ($state != $new_state) {
$this->onStateChanged($ref, $state, $transition_name, $new_state);
}
if ($this->debug_logger) {
$this->debug_logger->afterTransition($this, $ref, $state, $transition_name, $new_state, $ret, $returns);
}
return $ret;
} | php | public function invokeTransition(Reference $ref, $transition_name, $args, & $returns, callable $new_id_callback = null)
{
if (!empty($this->errors)) {
throw new StateMachineHasErrorsException('Cannot use state machine with errors in definition: "'.$this->machine_type.'".');
}
$state = $ref->state;
if ($this->debug_logger) {
$this->debug_logger->beforeTransition($this, $ref, $state, $transition_name, $args);
}
// get action
if (isset($this->actions[$transition_name])) {
$action = $this->actions[$transition_name];
} else {
throw new TransitionException('Unknown transition "'.$transition_name.'" requested on machine "'.$this->machine_type.'".');
}
// get transition (instance of action)
if (isset($action['transitions'][$state])) {
$transition = $action['transitions'][$state];
} else {
throw new TransitionException('Transition "'.$transition_name.'" not found in state "'.$state.'" of machine "'.$this->machine_type.'".');
}
$transition = array_merge($action, $transition);
// check access_policy
if (!$this->isTransitionAllowed($ref, $transition_name, $state, $access_policy)) {
throw new TransitionAccessException('Access denied to transition "'.$transition_name.'" '
.'of machine "'.$this->machine_type.'" (used access policy: "'.$access_policy.'").');
}
// invoke pre-transition checks
if (isset($transition['pre_check_methods'])) {
foreach ($transition['pre_check_methods'] as $m) {
if (call_user_func(array($this, $m), $ref, $transition_name, $args) === false) {
throw new TransitionPreCheckException('Transition "'.$transition_name.'" aborted by method "'.$m.'" of machine "'.$this->machine_type.'".');
}
}
}
// get method
$method = isset($transition['method']) ? $transition['method'] : $transition_name;
$prefix_args = isset($transition['args']) ? $transition['args'] : array();
// prepare arguments -- the first argument is $ref, rest are $args as passed to $ref->action($args...).
if (!empty($prefix_args)) {
array_splice($args, 0, 0, $prefix_args);
}
array_unshift($args, $ref);
// invoke method
$ret = call_user_func_array(array($this, $method), $args);
// interpret return value
$returns = @ $action['returns'];
switch ($returns) {
case self::RETURNS_VALUE:
// nop, just pass it back
break;
case self::RETURNS_NEW_ID:
if ($new_id_callback !== null) {
$new_id_callback($ret);
}
break;
default:
throw new RuntimeException('Unknown semantics of the return value: '.$returns);
}
// invalidate cached state and properties data in $ref
unset($ref->properties);
// check result using assertion function
$new_state = $ref->state;
$target_states = $transition['targets'];
if (!is_array($target_states)) {
throw new TransitionException('Target state is not defined for transition "'.$transition_name.'" from state "'.$state.'" of machine "'.$this->machine_type.'".');
}
if (!in_array($new_state, $target_states)) {
throw new RuntimeException('State machine ended in unexpected state "'.$new_state
.'" after transition "'.$transition_name.'" from state "'.$state.'" of machine "'.$this->machine_type.'". '
.'Expected states: '.join(', ', $target_states).'.');
}
// invoke post-transition callbacks
if (isset($transition['post_transition_methods'])) {
foreach ($transition['post_transition_methods'] as $m) {
call_user_func(array($this, $m), $ref, $transition_name, $args, $ret);
}
}
// state changed notification
if ($state != $new_state) {
$this->onStateChanged($ref, $state, $transition_name, $new_state);
}
if ($this->debug_logger) {
$this->debug_logger->afterTransition($this, $ref, $state, $transition_name, $new_state, $ret, $returns);
}
return $ret;
} | Invoke state machine transition. State machine is not instance of
this class, but it is represented by record in database. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L630-L732 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.ref | public function ref($id): Reference
{
$ref = new $this->reference_class($this->smalldb, $this, $id);
if ($this->debug_logger) {
$this->debug_logger->afterReferenceCreated(null, $ref);
}
return $ref;
} | php | public function ref($id): Reference
{
$ref = new $this->reference_class($this->smalldb, $this, $id);
if ($this->debug_logger) {
$this->debug_logger->afterReferenceCreated(null, $ref);
}
return $ref;
} | Helper to create Reference to this machine.
@see AbstractBackend::ref | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L758-L765 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.hotRef | public function hotRef($properties): Reference
{
$ref = $this->reference_class::createPreheatedReference($this->smalldb, $this, $properties);
if ($this->debug_logger) {
$this->debug_logger->afterReferenceCreated(null, $ref, $properties);
}
return $ref;
} | php | public function hotRef($properties): Reference
{
$ref = $this->reference_class::createPreheatedReference($this->smalldb, $this, $properties);
if ($this->debug_logger) {
$this->debug_logger->afterReferenceCreated(null, $ref, $properties);
}
return $ref;
} | Create pre-heated reference using properties loaded from elsewhere.
@warning This may break things a lot. Be careful. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L788-L795 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.performSelfCheck | public function performSelfCheck()
{
$results = [];
$results['id'] = $this->describeId();
$results['class'] = get_class($this);
$results['missing_methods'] = [];
$results['errors'] = $this->errors;
foreach ($this->describeAllMachineActions() as $a => $action) {
foreach ($action['transitions'] as $t => $transition) {
$transition = array_merge($action, $transition);
$method = isset($transition['method']) ? $transition['method'] : $a;
if (!is_callable([$this, $method])) {
$results['missing_methods'][] = $method;
}
}
sort($results['missing_methods']);
$results['missing_methods'] = array_unique($results['missing_methods']);
}
$results['unreachable_states'] = $this->findUnreachableStates();
return $results;
} | php | public function performSelfCheck()
{
$results = [];
$results['id'] = $this->describeId();
$results['class'] = get_class($this);
$results['missing_methods'] = [];
$results['errors'] = $this->errors;
foreach ($this->describeAllMachineActions() as $a => $action) {
foreach ($action['transitions'] as $t => $transition) {
$transition = array_merge($action, $transition);
$method = isset($transition['method']) ? $transition['method'] : $a;
if (!is_callable([$this, $method])) {
$results['missing_methods'][] = $method;
}
}
sort($results['missing_methods']);
$results['missing_methods'] = array_unique($results['missing_methods']);
}
$results['unreachable_states'] = $this->findUnreachableStates();
return $results;
} | Perform self-check.
TODO: Extend this method with more checks.
@see AbstractBackend::performSelfCheck() | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L805-L829 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.findUnreachableStates | public function findUnreachableStates(): array
{
$g = new Graph();
$g->indexNodeAttr('unreachable');
$g->createNode('', ['unreachable' => false]);
foreach ($this->states as $s => $state) {
if ($s !== '') {
$g->createNode($s, ['unreachable' => true]);
}
}
foreach ($this->actions as $a => $action) {
foreach ($action['transitions'] ?? [] as $source => $transition) {
foreach ($transition['targets'] ?? [] as $target) {
$g->createEdge(null, $g->getNode($source), $g->getNode($target), []);
}
}
}
GraphSearch::DFS($g)
->onNode(function (Node $node) use ($g) {
$node->setAttr('unreachable', false);
return true;
})
->start([$g->getNode('')]);
return array_map(function(Node $n) { return $n->getId(); }, $g->getNodesByAttr('unreachable', true));
} | php | public function findUnreachableStates(): array
{
$g = new Graph();
$g->indexNodeAttr('unreachable');
$g->createNode('', ['unreachable' => false]);
foreach ($this->states as $s => $state) {
if ($s !== '') {
$g->createNode($s, ['unreachable' => true]);
}
}
foreach ($this->actions as $a => $action) {
foreach ($action['transitions'] ?? [] as $source => $transition) {
foreach ($transition['targets'] ?? [] as $target) {
$g->createEdge(null, $g->getNode($source), $g->getNode($target), []);
}
}
}
GraphSearch::DFS($g)
->onNode(function (Node $node) use ($g) {
$node->setAttr('unreachable', false);
return true;
})
->start([$g->getNode('')]);
return array_map(function(Node $n) { return $n->getId(); }, $g->getNodesByAttr('unreachable', true));
} | Run DFS from not-exists state and return list of unreachable states. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L835-L863 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.getAllMachineStates | public function getAllMachineStates($having_section = null)
{
if ($having_section === null) {
return array_keys($this->states);
} else {
return array_keys(array_filter($this->states,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | php | public function getAllMachineStates($having_section = null)
{
if ($having_section === null) {
return array_keys($this->states);
} else {
return array_keys(array_filter($this->states,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | Reflection: Get all states
List of can be filtered by section, just like getAllMachineActions
method does. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L944-L952 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeMachineState | public function describeMachineState($state, $field = null)
{
if ($field === null) {
return @ $this->states[$state];
} else {
return @ $this->states[$state][$field];
}
} | php | public function describeMachineState($state, $field = null)
{
if ($field === null) {
return @ $this->states[$state];
} else {
return @ $this->states[$state][$field];
}
} | Reflection: Describe given machine state
Returns state description in array or null. If field is specified,
only given field is returned. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L961-L968 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeAllMachineStates | public function describeAllMachineStates($having_section = null)
{
if ($having_section === null) {
return $this->states;
} else {
return array_filter($this->states,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | php | public function describeAllMachineStates($having_section = null)
{
if ($having_section === null) {
return $this->states;
} else {
return array_filter($this->states,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | Reflection: Describe all states | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L974-L982 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.getAllMachineActions | public function getAllMachineActions($having_section = null)
{
if ($having_section === null) {
return array_keys($this->actions);
} else {
return array_keys(array_filter($this->actions,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | php | public function getAllMachineActions($having_section = null)
{
if ($having_section === null) {
return array_keys($this->actions);
} else {
return array_keys(array_filter($this->actions,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | Reflection: Get all actions (transitions)
List of actions can be filtered by section defined in action
configuration. For example $this->getAllMachineStates('block') will
return only actions which have 'block' configuration defined.
Requested section must contain non-empty() value. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L993-L1001 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeMachineAction | public function describeMachineAction($action, $field = null)
{
if ($field === null) {
return @ $this->actions[$action];
} else {
return @ $this->actions[$action][$field];
}
} | php | public function describeMachineAction($action, $field = null)
{
if ($field === null) {
return @ $this->actions[$action];
} else {
return @ $this->actions[$action][$field];
}
} | Reflection: Describe given machine action (transition)
Returns action description in array or null. If field is specified,
only given field is returned. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1010-L1017 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeAllMachineActions | public function describeAllMachineActions($having_section = null)
{
if ($having_section === null) {
return $this->actions;
} else {
return array_filter($this->actions,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | php | public function describeAllMachineActions($having_section = null)
{
if ($having_section === null) {
return $this->actions;
} else {
return array_filter($this->actions,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | Reflection: Describe all actions (transitions) | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1023-L1031 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.getAllMachineProperties | public function getAllMachineProperties($having_section = null)
{
if ($having_section === null) {
return array_keys($this->properties);
} else {
return array_keys(array_filter($this->properties,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | php | public function getAllMachineProperties($having_section = null)
{
if ($having_section === null) {
return array_keys($this->properties);
} else {
return array_keys(array_filter($this->properties,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | Reflection: Get all properties
List of can be filtered by section, just like getAllMachineActions
method does. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1040-L1048 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeMachineProperty | public function describeMachineProperty($property, $field = null)
{
if ($field === null) {
return @ $this->properties[$property];
} else {
return @ $this->properties[$property][$field];
}
} | php | public function describeMachineProperty($property, $field = null)
{
if ($field === null) {
return @ $this->properties[$property];
} else {
return @ $this->properties[$property][$field];
}
} | Reflection: Describe given property
Returns property description in array or null. If field is
specified, only given field is returned. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1057-L1064 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeAllMachineProperties | public function describeAllMachineProperties($having_section = null)
{
if ($having_section === null) {
return $this->properties;
} else {
return array_filter($this->properties,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | php | public function describeAllMachineProperties($having_section = null)
{
if ($having_section === null) {
return $this->properties;
} else {
return array_filter($this->properties,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | Reflection: Describe all properties
Returns array of all properties and their descriptions.
See describeMachineProperty and getAllMachineProperties. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1073-L1081 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.getAllMachineViews | public function getAllMachineViews($having_section = null)
{
if ($having_section === null) {
return array_keys((array) @ $this->views);
} else {
return array_keys(array_filter((array) @ $this->views,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | php | public function getAllMachineViews($having_section = null)
{
if ($having_section === null) {
return array_keys((array) @ $this->views);
} else {
return array_keys(array_filter((array) @ $this->views,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | Reflection: Get all views
List of can be filtered by section, just like getAllMachineActions
method does. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1090-L1098 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeMachineView | public function describeMachineView($view, $field = null)
{
if ($field === null) {
return @ $this->views[$view];
} else {
return @ $this->views[$view][$field];
}
} | php | public function describeMachineView($view, $field = null)
{
if ($field === null) {
return @ $this->views[$view];
} else {
return @ $this->views[$view][$field];
}
} | Reflection: Describe given view
Returns view description in array or null. If field is
specified, only given field is returned. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1107-L1114 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeAllMachineViews | public function describeAllMachineViews($having_section = null)
{
if ($having_section === null) {
return (array) @ $this->views;
} else {
return array_filter((array) @ $this->views,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | php | public function describeAllMachineViews($having_section = null)
{
if ($having_section === null) {
return (array) @ $this->views;
} else {
return array_filter((array) @ $this->views,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | Reflection: Describe all views | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1120-L1128 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.getAllMachineReferences | public function getAllMachineReferences($having_section = null)
{
if ($having_section === null) {
return array_keys((array) @ $this->references);
} else {
return array_keys(array_filter((array) @ $this->references,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | php | public function getAllMachineReferences($having_section = null)
{
if ($having_section === null) {
return array_keys((array) @ $this->references);
} else {
return array_keys(array_filter((array) @ $this->references,
function($a) use ($having_section) { return !empty($a[$having_section]); }));
}
} | Reflection: Get all references
List of can be filtered by section, just like getAllMachineActions
method does. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1137-L1145 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeMachineReference | public function describeMachineReference($reference, $field = null)
{
if ($field === null) {
return @ $this->references[$reference];
} else {
return @ $this->references[$reference][$field];
}
} | php | public function describeMachineReference($reference, $field = null)
{
if ($field === null) {
return @ $this->references[$reference];
} else {
return @ $this->references[$reference][$field];
}
} | Reflection: Describe given reference
Returns reference description in array or null. If field is
specified, only given field is returned. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1154-L1161 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.describeAllMachineReferences | public function describeAllMachineReferences($having_section = null)
{
if ($having_section === null) {
return (array) @ $this->references;
} else {
return array_filter((array) @ $this->references,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | php | public function describeAllMachineReferences($having_section = null)
{
if ($having_section === null) {
return (array) @ $this->references;
} else {
return array_filter((array) @ $this->references,
function($a) use ($having_section) { return !empty($a[$having_section]); });
}
} | Reflection: Describe all references | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1167-L1175 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.exportJson | public function exportJson($debug_opts = false): array
{
$nodes = [
[
"id" => "BEGIN",
"shape" => "uml.initial_state",
]
];
$edges = [];
// States
if (!empty($this->states)) {
$is_unreachable_state = array_fill_keys($this->findUnreachableStates(), true);
foreach ($this->states as $s => $state) {
if ($s != '') {
$n = [
"id" => 's_'.$s,
"label" => $s,
"fill" => $state['color'] ?? "#eee",
"shape" => "uml.state",
];
// Highlight state if it is unreachable
if (!empty($is_unreachable_state[$s])) {
$n['label'] .= "\n(unreachable)";
$n['color'] = "#ff0000";
$n['fill'] = "#ffeedd";
}
$nodes[] = $n;
}
}
}
$have_final_state = false;
$missing_states = array();
// Transitions
if (!empty($this->actions)) {
foreach ($this->actions as $a => $action) {
if (empty($action['transitions'])) {
continue;
}
foreach ($action['transitions'] as $src => $transition) {
$transition = array_merge($action, $transition);
if ($src === null || $src === '') {
$s_src = 'BEGIN';
} else {
$s_src = 's_'.$src;
if (!array_key_exists($src, $this->states)) {
$missing_states[$src] = true;
}
}
foreach ($transition['targets'] as $dst) {
if ($dst === null || $dst === '') {
$s_dst = $src == '' ? 'BEGIN':'END';
$have_final_state = true;
} else {
$s_dst = 's_'.$dst;
if (!array_key_exists($dst, $this->states)) {
$missing_states[$dst] = true;
}
}
$edges[] = [
'start' => $s_src,
'end' => $s_dst,
'label' => $a,
'color' => $transition['color'] ?? "#000",
'weight' => $transition['weight'] ?? null,
'arrowTail' => isset($transition['access_policy']) && isset($this->access_policies[$transition['access_policy']]['arrow_tail'])
? $this->access_policies[$transition['access_policy']]['arrow_tail']
: null,
];
}
}
}
}
// Missing states
foreach ($missing_states as $s => $state) {
$nodes[] = [
'id' => 's_'.$s,
'label' => $s."\n(undefined)",
'color' => "#ff0000",
'fill' => "#ffeedd",
];
}
// Final state
if ($have_final_state) {
$nodes[] = [
'id' => 'END',
'shape' => 'uml.final_state',
];
}
// Smalldb state diagram
$machine_graph = [
'layout' => 'dagre',
'nodes' => $nodes,
'edges' => $edges,
];
// Optionaly render machine-specific debug data
if ($debug_opts) {
// Return the extended graph
return $this->exportJsonAddExtras($debug_opts, $machine_graph);
} else {
// Return the Smalldb state diagram only
return $machine_graph;
}
} | php | public function exportJson($debug_opts = false): array
{
$nodes = [
[
"id" => "BEGIN",
"shape" => "uml.initial_state",
]
];
$edges = [];
// States
if (!empty($this->states)) {
$is_unreachable_state = array_fill_keys($this->findUnreachableStates(), true);
foreach ($this->states as $s => $state) {
if ($s != '') {
$n = [
"id" => 's_'.$s,
"label" => $s,
"fill" => $state['color'] ?? "#eee",
"shape" => "uml.state",
];
// Highlight state if it is unreachable
if (!empty($is_unreachable_state[$s])) {
$n['label'] .= "\n(unreachable)";
$n['color'] = "#ff0000";
$n['fill'] = "#ffeedd";
}
$nodes[] = $n;
}
}
}
$have_final_state = false;
$missing_states = array();
// Transitions
if (!empty($this->actions)) {
foreach ($this->actions as $a => $action) {
if (empty($action['transitions'])) {
continue;
}
foreach ($action['transitions'] as $src => $transition) {
$transition = array_merge($action, $transition);
if ($src === null || $src === '') {
$s_src = 'BEGIN';
} else {
$s_src = 's_'.$src;
if (!array_key_exists($src, $this->states)) {
$missing_states[$src] = true;
}
}
foreach ($transition['targets'] as $dst) {
if ($dst === null || $dst === '') {
$s_dst = $src == '' ? 'BEGIN':'END';
$have_final_state = true;
} else {
$s_dst = 's_'.$dst;
if (!array_key_exists($dst, $this->states)) {
$missing_states[$dst] = true;
}
}
$edges[] = [
'start' => $s_src,
'end' => $s_dst,
'label' => $a,
'color' => $transition['color'] ?? "#000",
'weight' => $transition['weight'] ?? null,
'arrowTail' => isset($transition['access_policy']) && isset($this->access_policies[$transition['access_policy']]['arrow_tail'])
? $this->access_policies[$transition['access_policy']]['arrow_tail']
: null,
];
}
}
}
}
// Missing states
foreach ($missing_states as $s => $state) {
$nodes[] = [
'id' => 's_'.$s,
'label' => $s."\n(undefined)",
'color' => "#ff0000",
'fill' => "#ffeedd",
];
}
// Final state
if ($have_final_state) {
$nodes[] = [
'id' => 'END',
'shape' => 'uml.final_state',
];
}
// Smalldb state diagram
$machine_graph = [
'layout' => 'dagre',
'nodes' => $nodes,
'edges' => $edges,
];
// Optionaly render machine-specific debug data
if ($debug_opts) {
// Return the extended graph
return $this->exportJsonAddExtras($debug_opts, $machine_graph);
} else {
// Return the Smalldb state diagram only
return $machine_graph;
}
} | Export state machine as JSON siutable for Grafovatko.
Usage: json_encode($machine->exportJson());
@see https://grafovatko.smalldb.org/
@param $debug_opts Machine-specific debugging options - passed to
exportDotRenderDebugData(). If empty/false, no debug data are
added to the diagram.
@return array Array suitable for json_encode(). | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1190-L1302 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.exportDot | public function exportDot($debug_opts = false)
{
ob_start();
// DOT Header
echo "#\n",
"# State machine visualization\n",
"#\n",
"# Use \"dot -Tpng this-file.dot -o this-file.png\" to compile.\n",
"#\n",
"digraph structs {\n",
" rankdir = TB;\n",
" bgcolor = transparent;\n",
" pad = 0;\n",
" margin = 0;\n",
//" splines = line;\n",
" edge [ arrowtail=none, arrowhead=normal, dir=both, arrowsize=0.6, fontsize=8, fontname=\"sans\" ];\n",
" node [ shape=box, style=\"rounded,filled\", fontsize=9, fontname=\"sans\", fillcolor=\"#eeeeee\" ];\n",
" graph [ fontsize=9, fontname=\"sans bold\" ];\n",
"\n";
// Wrap state diagram into subgraph if there are extras to avoid mixing of them together
if (!empty($this->state_diagram_extras)) {
echo "\tsubgraph cluster_main {\n",
"\t\t", "graph [ margin = 10 ];\n",
"\t\t", "color = transparent;\n\n";
}
// Start state
echo "\t\t", "BEGIN [",
"id = \"BEGIN\",",
"label = \"\",",
"shape = circle,",
"color = black,",
"fillcolor = black,",
"penwidth = 0,",
"width = 0.25,",
"style = filled",
"];\n";
// States
echo "\t\t", "node [ shape=ellipse, fontsize=9, style=\"filled\", fontname=\"sans\", fillcolor=\"#eeeeee\", penwidth=2 ];\n";
$group_content = array();
if (!empty($this->states)) {
foreach ($this->states as $s => $state) {
if ($s != '') {
$id = $this->exportDotIdentifier($s);
echo "\t\t", $id;
//echo " [ label=\"", addcslashes(empty($state['label']) ? $s : $state['label'], '"'), "\"";
echo " [ id = \"", addcslashes($id, '"'), "\", label=\"", addcslashes($s, '"'), "\"";
if (!empty($state['color'])) {
echo ", fillcolor=\"", addcslashes($state['color'], '"'), "\"";
}
echo " ];\n";
}
if (isset($state['group'])) {
$group_content[$state['group']][] = $s;
}
}
}
echo "\n";
// State groups
if (!empty($this->state_groups)) {
$this->exportDotRenderGroups($this->state_groups, $group_content);
}
$have_final_state = false;
$missing_states = array();
// Transitions
if (!empty($this->actions)) {
foreach ($this->actions as $a => $action) {
if (empty($action['transitions'])) {
continue;
}
foreach ($action['transitions'] as $src => $transition) {
$transition = array_merge($action, $transition);
if ($src === null || $src === '') {
$s_src = 'BEGIN';
} else {
$s_src = $this->exportDotIdentifier($src);
if (!array_key_exists($src, $this->states)) {
$missing_states[$src] = true;
}
}
foreach ($transition['targets'] as $dst) {
if ($dst === null || $dst === '') {
$s_dst = $src == '' ? 'BEGIN':'END';
$have_final_state = true;
} else {
$s_dst = $this->exportDotIdentifier($dst);
if (!array_key_exists($dst, $this->states)) {
$missing_states[$dst] = true;
}
}
echo "\t\t", $s_src, " -> ", $s_dst, " [ ";
echo "label=\" ", addcslashes($a, '"'), " \"";
if (!empty($transition['color'])) {
echo ", color=\"", addcslashes($transition['color'], '"'), "\"";
echo ", fontcolor=\"", addcslashes($transition['color'], '"'), "\"";
}
if (isset($transition['weight'])) {
echo ", weight=", (int) $transition['weight'];
}
if (isset($transition['access_policy']) && isset($this->access_policies[$transition['access_policy']]['arrow_tail'])) {
$arrow_tail = $this->access_policies[$transition['access_policy']]['arrow_tail'];
echo ", arrowtail=\"", addcslashes($arrow_tail, '"'), "\"";
}
echo " ];\n";
}
}
}
}
// Missing states
foreach ($missing_states as $s => $state) {
echo "\t\t", $this->exportDotIdentifier($s), " [ label=\"", addcslashes($s, '"'), "\\n(undefined)\", fillcolor=\"#ffccaa\" ];\n";
}
// Final state
if ($have_final_state) {
echo "\n\t\t", "END [",
" id = \"END\",",
" label = \"\",",
" shape = doublecircle,",
" color = black,",
" fillcolor = black,",
" penwidth = 1.8,",
" width = 0.20,",
" style = filled",
" ];\n";
}
// Close state diagram subgraph
if (!empty($this->state_diagram_extras)) {
echo "\t}\n";
}
// Optionaly render machine-specific debug data
if ($debug_opts) {
$this->exportDotRenderExtras($debug_opts);
}
// DOT Footer
echo "}\n";
return ob_get_clean();
} | php | public function exportDot($debug_opts = false)
{
ob_start();
// DOT Header
echo "#\n",
"# State machine visualization\n",
"#\n",
"# Use \"dot -Tpng this-file.dot -o this-file.png\" to compile.\n",
"#\n",
"digraph structs {\n",
" rankdir = TB;\n",
" bgcolor = transparent;\n",
" pad = 0;\n",
" margin = 0;\n",
//" splines = line;\n",
" edge [ arrowtail=none, arrowhead=normal, dir=both, arrowsize=0.6, fontsize=8, fontname=\"sans\" ];\n",
" node [ shape=box, style=\"rounded,filled\", fontsize=9, fontname=\"sans\", fillcolor=\"#eeeeee\" ];\n",
" graph [ fontsize=9, fontname=\"sans bold\" ];\n",
"\n";
// Wrap state diagram into subgraph if there are extras to avoid mixing of them together
if (!empty($this->state_diagram_extras)) {
echo "\tsubgraph cluster_main {\n",
"\t\t", "graph [ margin = 10 ];\n",
"\t\t", "color = transparent;\n\n";
}
// Start state
echo "\t\t", "BEGIN [",
"id = \"BEGIN\",",
"label = \"\",",
"shape = circle,",
"color = black,",
"fillcolor = black,",
"penwidth = 0,",
"width = 0.25,",
"style = filled",
"];\n";
// States
echo "\t\t", "node [ shape=ellipse, fontsize=9, style=\"filled\", fontname=\"sans\", fillcolor=\"#eeeeee\", penwidth=2 ];\n";
$group_content = array();
if (!empty($this->states)) {
foreach ($this->states as $s => $state) {
if ($s != '') {
$id = $this->exportDotIdentifier($s);
echo "\t\t", $id;
//echo " [ label=\"", addcslashes(empty($state['label']) ? $s : $state['label'], '"'), "\"";
echo " [ id = \"", addcslashes($id, '"'), "\", label=\"", addcslashes($s, '"'), "\"";
if (!empty($state['color'])) {
echo ", fillcolor=\"", addcslashes($state['color'], '"'), "\"";
}
echo " ];\n";
}
if (isset($state['group'])) {
$group_content[$state['group']][] = $s;
}
}
}
echo "\n";
// State groups
if (!empty($this->state_groups)) {
$this->exportDotRenderGroups($this->state_groups, $group_content);
}
$have_final_state = false;
$missing_states = array();
// Transitions
if (!empty($this->actions)) {
foreach ($this->actions as $a => $action) {
if (empty($action['transitions'])) {
continue;
}
foreach ($action['transitions'] as $src => $transition) {
$transition = array_merge($action, $transition);
if ($src === null || $src === '') {
$s_src = 'BEGIN';
} else {
$s_src = $this->exportDotIdentifier($src);
if (!array_key_exists($src, $this->states)) {
$missing_states[$src] = true;
}
}
foreach ($transition['targets'] as $dst) {
if ($dst === null || $dst === '') {
$s_dst = $src == '' ? 'BEGIN':'END';
$have_final_state = true;
} else {
$s_dst = $this->exportDotIdentifier($dst);
if (!array_key_exists($dst, $this->states)) {
$missing_states[$dst] = true;
}
}
echo "\t\t", $s_src, " -> ", $s_dst, " [ ";
echo "label=\" ", addcslashes($a, '"'), " \"";
if (!empty($transition['color'])) {
echo ", color=\"", addcslashes($transition['color'], '"'), "\"";
echo ", fontcolor=\"", addcslashes($transition['color'], '"'), "\"";
}
if (isset($transition['weight'])) {
echo ", weight=", (int) $transition['weight'];
}
if (isset($transition['access_policy']) && isset($this->access_policies[$transition['access_policy']]['arrow_tail'])) {
$arrow_tail = $this->access_policies[$transition['access_policy']]['arrow_tail'];
echo ", arrowtail=\"", addcslashes($arrow_tail, '"'), "\"";
}
echo " ];\n";
}
}
}
}
// Missing states
foreach ($missing_states as $s => $state) {
echo "\t\t", $this->exportDotIdentifier($s), " [ label=\"", addcslashes($s, '"'), "\\n(undefined)\", fillcolor=\"#ffccaa\" ];\n";
}
// Final state
if ($have_final_state) {
echo "\n\t\t", "END [",
" id = \"END\",",
" label = \"\",",
" shape = doublecircle,",
" color = black,",
" fillcolor = black,",
" penwidth = 1.8,",
" width = 0.20,",
" style = filled",
" ];\n";
}
// Close state diagram subgraph
if (!empty($this->state_diagram_extras)) {
echo "\t}\n";
}
// Optionaly render machine-specific debug data
if ($debug_opts) {
$this->exportDotRenderExtras($debug_opts);
}
// DOT Footer
echo "}\n";
return ob_get_clean();
} | Export state machine to Graphviz source code.
@param $debug_opts Machine-specific debugging options - passed to
exportDotRenderDebugData(). If empty/false, no debug data are
added to the diagram. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1312-L1460 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.exportDotIdentifier | public static function exportDotIdentifier(string $str, string $prefix = 's_')
{
return $prefix.preg_replace('/[^a-zA-Z0-9_]+/', '_', $str).'_'.dechex(0xffff & crc32($str));
} | php | public static function exportDotIdentifier(string $str, string $prefix = 's_')
{
return $prefix.preg_replace('/[^a-zA-Z0-9_]+/', '_', $str).'_'.dechex(0xffff & crc32($str));
} | Convert state machine state name or group name to a safe dot identifier
FIXME: Extract Graphviz library to keep graphs and parts of the graphs contained.
@param string $str Unsafe generic identifier
@param string $prefix Prefix for the Dot identifier
@return string Dot identifier | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1471-L1474 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.exportDotRenderGroups | private function exportDotRenderGroups($groups, $group_content, $indent = "\t") {
foreach ($groups as $g => $group) {
echo $indent, "subgraph ", $this->exportDotIdentifier($g, 'cluster_'), " {\n";
if (isset($group['label'])) {
echo $indent, "\t", "label = \"", addcslashes($group['label'], '"'), "\";\n";
}
if (!empty($group['color'])) {
echo $indent, "\t", "color=\"", addcslashes($group['color'], '"'), "\";\n";
echo $indent, "\t", "fontcolor=\"", addcslashes($group['color'], '"'), "\";\n";
} else {
// This cannot be defined globally, since nested groups inherit the settings.
echo $indent, "\t", "color=\"#666666\";\n";
echo $indent, "\t", "fontcolor=\"#666666\";\n";
}
foreach ($group_content[$g] as $s) {
echo $indent, "\t", $this->exportDotIdentifier($s), ";\n";
}
if (isset($group['groups'])) {
$this->exportDotRenderGroups($group['groups'], $group_content, "\t".$indent);
}
echo $indent, "}\n";
}
} | php | private function exportDotRenderGroups($groups, $group_content, $indent = "\t") {
foreach ($groups as $g => $group) {
echo $indent, "subgraph ", $this->exportDotIdentifier($g, 'cluster_'), " {\n";
if (isset($group['label'])) {
echo $indent, "\t", "label = \"", addcslashes($group['label'], '"'), "\";\n";
}
if (!empty($group['color'])) {
echo $indent, "\t", "color=\"", addcslashes($group['color'], '"'), "\";\n";
echo $indent, "\t", "fontcolor=\"", addcslashes($group['color'], '"'), "\";\n";
} else {
// This cannot be defined globally, since nested groups inherit the settings.
echo $indent, "\t", "color=\"#666666\";\n";
echo $indent, "\t", "fontcolor=\"#666666\";\n";
}
foreach ($group_content[$g] as $s) {
echo $indent, "\t", $this->exportDotIdentifier($s), ";\n";
}
if (isset($group['groups'])) {
$this->exportDotRenderGroups($group['groups'], $group_content, "\t".$indent);
}
echo $indent, "}\n";
}
} | Recursively render groups in state machine diagram. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1480-L1502 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.exportDotRenderExtras | protected function exportDotRenderExtras($debug_opts)
{
if (!empty($this->state_diagram_extras)) {
echo "\tsubgraph cluster_extras {\n",
"\t\tgraph [ margin = 10; ];\n",
"\t\tcolor=transparent;\n\n";
foreach($this->state_diagram_extras as $i => $e) {
echo "\n\t# Extras ", str_replace("\n", " ", $i), "\n";
echo $e, "\n";
}
echo "\t}\n";
}
} | php | protected function exportDotRenderExtras($debug_opts)
{
if (!empty($this->state_diagram_extras)) {
echo "\tsubgraph cluster_extras {\n",
"\t\tgraph [ margin = 10; ];\n",
"\t\tcolor=transparent;\n\n";
foreach($this->state_diagram_extras as $i => $e) {
echo "\n\t# Extras ", str_replace("\n", " ", $i), "\n";
echo $e, "\n";
}
echo "\t}\n";
}
} | Render extra diagram features.
Writes Graphviz dot syntax to stdout (echo), output is placed just
before digraph's closing bracket.
@param mixed $debug_opts Machine-specific Options to configure visible
debug data. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1514-L1526 |
smalldb/libSmalldb | class/AbstractMachine.php | AbstractMachine.exportJsonAddExtras | protected function exportJsonAddExtras($debug_opts, array $machine_graph): array
{
if (!empty($this->state_diagram_extras_json)) {
$graph = $this->state_diagram_extras_json;
if (!isset($graph['layout'])) {
$graph['layout'] = 'row';
$graph['layoutOptions'] = [
'align' => 'top',
];
}
if (!isset($graph['nodes'])) {
$graph['nodes'] = [];
}
if (!isset($graph['edges'])) {
$graph['edges'] = [];
}
array_unshift($graph['nodes'], [
'id' => 'smalldb',
'label' => $this->machine_type,
'graph' => $machine_graph,
'color' => '#aaa',
'x' => 0,
'y' => 0,
]);
return $graph;
} else {
return $machine_graph;
}
} | php | protected function exportJsonAddExtras($debug_opts, array $machine_graph): array
{
if (!empty($this->state_diagram_extras_json)) {
$graph = $this->state_diagram_extras_json;
if (!isset($graph['layout'])) {
$graph['layout'] = 'row';
$graph['layoutOptions'] = [
'align' => 'top',
];
}
if (!isset($graph['nodes'])) {
$graph['nodes'] = [];
}
if (!isset($graph['edges'])) {
$graph['edges'] = [];
}
array_unshift($graph['nodes'], [
'id' => 'smalldb',
'label' => $this->machine_type,
'graph' => $machine_graph,
'color' => '#aaa',
'x' => 0,
'y' => 0,
]);
return $graph;
} else {
return $machine_graph;
}
} | Add extra diagram features into the diagram.
Extend this method to add debugging visualizations.
@see AbstractMachine::exportJson().
@see https://grafovatko.smalldb.org/
@param mixed $debug_opts Machine-specific Options to configure visible
debug data.
@param array $machine_graph Smalldb state chart wrapped in a 'smalldb' node. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/AbstractMachine.php#L1541-L1569 |
wigedev/farm | src/DataAccess/MsSQL.php | MsSQL.connect | public function connect() : bool
{
try {
$connection_string = 'sqlsrv:SERVER=' . $this->configuration['server'] . ';DATABASE=' . $this->configuration['dbname'];
if (isset($this->configuration['encrypt']) && true === $this->configuration['encrypt']) {
$connection_string .= ';ENCRYPT=1';
}
$this->logger->debug('Connecting to database engine.');
$this->dbconn = new PDO($connection_string, $this->configuration['username'],
$this->configuration['password']);
$this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->logger->debug('Connected to database engine.');
$this->is_connected = true;
} catch (\Exception $e) {
throw new DatabaseConnectionException('MSSQL Connection to <strong>' . $this->configuration['server'] . '</strong> failed!<br>' . $e->getMessage());
}
return true;
} | php | public function connect() : bool
{
try {
$connection_string = 'sqlsrv:SERVER=' . $this->configuration['server'] . ';DATABASE=' . $this->configuration['dbname'];
if (isset($this->configuration['encrypt']) && true === $this->configuration['encrypt']) {
$connection_string .= ';ENCRYPT=1';
}
$this->logger->debug('Connecting to database engine.');
$this->dbconn = new PDO($connection_string, $this->configuration['username'],
$this->configuration['password']);
$this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->logger->debug('Connected to database engine.');
$this->is_connected = true;
} catch (\Exception $e) {
throw new DatabaseConnectionException('MSSQL Connection to <strong>' . $this->configuration['server'] . '</strong> failed!<br>' . $e->getMessage());
}
return true;
} | Establish a connection to the database server.
@return mixed
@throws DatabaseConnectionException | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L70-L87 |
wigedev/farm | src/DataAccess/MsSQL.php | MsSQL.disconnect | public function disconnect() : void
{
if ($this->dbconn->inTransaction()) {
$this->dbconn->rollBack();
}
$this->dbconn = null;
$this->is_connected = false;
} | php | public function disconnect() : void
{
if ($this->dbconn->inTransaction()) {
$this->dbconn->rollBack();
}
$this->dbconn = null;
$this->is_connected = false;
} | Close the connection if it has been established. | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L92-L99 |
wigedev/farm | src/DataAccess/MsSQL.php | MsSQL.beginTransaction | public function beginTransaction() : bool
{
if ($this->dbconn->inTransaction()) {
throw new TransactionErrorException("A transaction has already been started.");
}
try {
return $this->dbconn->beginTransaction();
} catch (\PDOException $exception) {
throw new TransactionsNotSupportedException("Transactions are not supported in this database.");
}
} | php | public function beginTransaction() : bool
{
if ($this->dbconn->inTransaction()) {
throw new TransactionErrorException("A transaction has already been started.");
}
try {
return $this->dbconn->beginTransaction();
} catch (\PDOException $exception) {
throw new TransactionsNotSupportedException("Transactions are not supported in this database.");
}
} | Start a transaction.
@return bool
@throws TransactionErrorException if a transaction is already started
@throws TransactionsNotSupportedException if transactions are not supported | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L108-L118 |
wigedev/farm | src/DataAccess/MsSQL.php | MsSQL.query | public function query(string $query_string, array $params = [], array $options = []) : DAO
{
// Reset in case a previous query was attempted.
$this->query_succeeded = false;
// Connect to the database
if (!$this->is_connected) {
$this->connect();
}
// Get the query string and params
$query_params = array();
if (isset($options['params'])) {
$query_params = $options['params'];
}
try {
$stmt = $this->getStatement($query_string);
$this->stmt = $stmt;
$stmt->execute($query_params);
} catch (\Exception $e) {
throw new DatabaseQueryException($e->getMessage() . '|| QUERY: ' . $query_string . '|| PARAMS: ' . implode(';',
$query_params));
}
return $this;
} | php | public function query(string $query_string, array $params = [], array $options = []) : DAO
{
// Reset in case a previous query was attempted.
$this->query_succeeded = false;
// Connect to the database
if (!$this->is_connected) {
$this->connect();
}
// Get the query string and params
$query_params = array();
if (isset($options['params'])) {
$query_params = $options['params'];
}
try {
$stmt = $this->getStatement($query_string);
$this->stmt = $stmt;
$stmt->execute($query_params);
} catch (\Exception $e) {
throw new DatabaseQueryException($e->getMessage() . '|| QUERY: ' . $query_string . '|| PARAMS: ' . implode(';',
$query_params));
}
return $this;
} | Execute a query with the passed options. Typically the options array will include a params subarray to run the
query as a prepared statement.
@param string $query_string
@param array $params
@param array $options
@return DAO
@throws DatabaseQueryException | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L158-L184 |
wigedev/farm | src/DataAccess/MsSQL.php | MsSQL.toArray | public function toArray() : ?array
{
if (null === $this->stmt || false === $this->stmt) {
return null;
}
return $this->stmt->toArray();
} | php | public function toArray() : ?array
{
if (null === $this->stmt || false === $this->stmt) {
return null;
}
return $this->stmt->toArray();
} | Gets the results and a multidimensional array.
@return array|null The results as an array or null if this was not a select or if there was an error. | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L223-L229 |
wigedev/farm | src/DataAccess/MsSQL.php | MsSQL.generateSort | public function generateSort(array $column, ?string $prepend = null) : string
{
if (null === $prepend) {
$prepend = 'ORDER BY';
}
if ((bool)count(array_filter(array_keys($column), 'is_string'))) {
// Associative array
$return = array();
foreach ($column as $key => $col) {
$return[] = $key . ' ' . $col;
}
$return = implode(', ', $return);
} else {
// Simple array
$return = implode(', ', $column);
}
if ($return != '') {
$return = ' ' . $prepend . ' ' . $return;
}
return $return;
} | php | public function generateSort(array $column, ?string $prepend = null) : string
{
if (null === $prepend) {
$prepend = 'ORDER BY';
}
if ((bool)count(array_filter(array_keys($column), 'is_string'))) {
// Associative array
$return = array();
foreach ($column as $key => $col) {
$return[] = $key . ' ' . $col;
}
$return = implode(', ', $return);
} else {
// Simple array
$return = implode(', ', $column);
}
if ($return != '') {
$return = ' ' . $prepend . ' ' . $return;
}
return $return;
} | Generate a snippet of database engine specific sorting code, based on the passed $column and $direction.
Alternatively, an array of columns can be passed in that will be sorted according to the $direction, or an array
of colname => direction can be passed in.
@param string[] $column
@param string|null $prepend Text to add in front of the column list, if NULL adds the db default text
@return string | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataAccess/MsSQL.php#L275-L295 |
edwardstock/forker | src/helpers/ProcessHelper.php | ProcessHelper.setProcessTitle | public function setProcessTitle(string $title = null)
{
if ($title === null) {
return;
}
if (strlen($title) === 0) {
throw new \InvalidArgumentException('Process title cannot be empty');
}
// @codeCoverageIgnoreStart
if (!function_exists('cli_set_process_title')) {
$this->getLogger()->warning("function [cli_set_process_title] does not exists");
return;
}
// @codeCoverageIgnoreEnd
try {
cli_set_process_title($title);
} catch (\Throwable $e) {
if ($e->getCode() === 2) {
$this->getLogger()->warning($e->getMessage() . ". Probably, permission denied to set process title. Try again with privileged user");
} else {
throw $e;
}
}
} | php | public function setProcessTitle(string $title = null)
{
if ($title === null) {
return;
}
if (strlen($title) === 0) {
throw new \InvalidArgumentException('Process title cannot be empty');
}
// @codeCoverageIgnoreStart
if (!function_exists('cli_set_process_title')) {
$this->getLogger()->warning("function [cli_set_process_title] does not exists");
return;
}
// @codeCoverageIgnoreEnd
try {
cli_set_process_title($title);
} catch (\Throwable $e) {
if ($e->getCode() === 2) {
$this->getLogger()->warning($e->getMessage() . ". Probably, permission denied to set process title. Try again with privileged user");
} else {
throw $e;
}
}
} | @param string $title
@throws \Throwable | https://github.com/edwardstock/forker/blob/024a6d1d8a34a4fffb59717e066cad01a78141b5/src/helpers/ProcessHelper.php#L20-L48 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.next | public function next()
{
if ($this->offset !== null) {
$this->offset = $this->offset + 1;
return $this->collected[$this->offset];
}
return null;
} | php | public function next()
{
if ($this->offset !== null) {
$this->offset = $this->offset + 1;
return $this->collected[$this->offset];
}
return null;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L124-L132 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.last | public function last()
{
$this->offset = count($this->collected) - 1;
return $this->collected[$this->offset] ?? null;
} | php | public function last()
{
$this->offset = count($this->collected) - 1;
return $this->collected[$this->offset] ?? null;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L145-L150 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.only | public function only(...$columns)
{
if (!empty($columns) && !empty($this->collected)) {
// Map columns array to generate filtered columns.
$newCollection = array_map(function($collected) use ($columns) {
$collectedObject = new StdClass();
array_map(function($column) use ($collected, $collectedObject) {
if (isset($collected->$column)) {
$collectedObject->$column = $collected->$column;
}
}, $columns);
return $collectedObject;
}, $this->collected);
// Return new collection instance for collected columns.
return new self($newCollection, $this->statement);
}
return null;
} | php | public function only(...$columns)
{
if (!empty($columns) && !empty($this->collected)) {
// Map columns array to generate filtered columns.
$newCollection = array_map(function($collected) use ($columns) {
$collectedObject = new StdClass();
array_map(function($column) use ($collected, $collectedObject) {
if (isset($collected->$column)) {
$collectedObject->$column = $collected->$column;
}
}, $columns);
return $collectedObject;
}, $this->collected);
// Return new collection instance for collected columns.
return new self($newCollection, $this->statement);
}
return null;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L155-L176 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.remove | public function remove($key) : CollectionContract
{
if (isset($this->collected[$key])) {
unset($this->collected[$key]);
}
return $this;
} | php | public function remove($key) : CollectionContract
{
if (isset($this->collected[$key])) {
unset($this->collected[$key]);
}
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L198-L205 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.removeWhere | public function removeWhere(String $key, $value) : CollectionContract
{
if ($this->size() > 0) {
array_map(function($collected, $index) use ($key, $value) {
if (isset($collected->$key) && $collected->$key == $value) {
unset($this->collected[$index]);
}
}, $this->collected, array_keys($this->collected));
}
return $this;
} | php | public function removeWhere(String $key, $value) : CollectionContract
{
if ($this->size() > 0) {
array_map(function($collected, $index) use ($key, $value) {
if (isset($collected->$key) && $collected->$key == $value) {
unset($this->collected[$index]);
}
}, $this->collected, array_keys($this->collected));
}
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L210-L221 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.map | public function map(Array $elements, Closure $callback, Array $with=[]) : CollectionContract
{
array_map(function($element, $index) use ($callback, $elements, $with) {
$callbackArguments = [$element, $index, $this];
if (sizeof($with > 0)) {
$callbackArguments = array_merge($callbackArguments, $with);
}
return call_user_func_array(
$callback,
$callbackArguments
);
}, $elements, array_keys($elements));
return $this;
} | php | public function map(Array $elements, Closure $callback, Array $with=[]) : CollectionContract
{
array_map(function($element, $index) use ($callback, $elements, $with) {
$callbackArguments = [$element, $index, $this];
if (sizeof($with > 0)) {
$callbackArguments = array_merge($callbackArguments, $with);
}
return call_user_func_array(
$callback,
$callbackArguments
);
}, $elements, array_keys($elements));
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L226-L243 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.toArray | public function toArray(Array $elements=[]) : CollectionContract
{
if (sizeof($elements) > 0) {
$this->collected = $elements;
}
$list = array_map(function($element, $index) {
if ($element instanceof StdClass) {
return (Array) $element;
}
if (is_array($element)) {
// If it's an array, run a recursive function to convert all objects
// to array.
return $this->toArray($element)->all();
}
}, $this->collected, array_keys($this->collected));
$this->collected = $list;
return $this;
} | php | public function toArray(Array $elements=[]) : CollectionContract
{
if (sizeof($elements) > 0) {
$this->collected = $elements;
}
$list = array_map(function($element, $index) {
if ($element instanceof StdClass) {
return (Array) $element;
}
if (is_array($element)) {
// If it's an array, run a recursive function to convert all objects
// to array.
return $this->toArray($element)->all();
}
}, $this->collected, array_keys($this->collected));
$this->collected = $list;
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L248-L270 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.invoke | public function invoke(Array $elements, String $functionName) : CollectionContract
{
if (!function_exists($functionName)) {
throw new FunctionNotFoundException(sprintf("Function %s does not exist", $functionName));
}
$this->map($elements, function($element, $index) use ($functionName) {
call_user_func_array($functionName, [$element, $index]);
});
return $this;
} | php | public function invoke(Array $elements, String $functionName) : CollectionContract
{
if (!function_exists($functionName)) {
throw new FunctionNotFoundException(sprintf("Function %s does not exist", $functionName));
}
$this->map($elements, function($element, $index) use ($functionName) {
call_user_func_array($functionName, [$element, $index]);
});
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L275-L286 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.min | public function min($elements=[], String $with=null)
{
if ($elements instanceof CollectionContract) {
// If $elements is an instance of CollectionContract, we'll get the collected
// elements.
$elements = $elements->all();
}
if (sizeof($elements) > 0) {
$this->collected = $elements;
}
$list = array_map(function($element, $index) use ($with, $elements) {
// Is index an integer and element is not array or object? Is element a numeric indexed array?
if (is_int($index) || is_string($index)) {
if (!$with == null && isset($element[$with])) {
return $element[$with];
}else{
if (is_int($elements[$index])) {
return $elements[$index];
}
}
}
}, $this->collected, array_keys($this->collected));
return min($list);
} | php | public function min($elements=[], String $with=null)
{
if ($elements instanceof CollectionContract) {
// If $elements is an instance of CollectionContract, we'll get the collected
// elements.
$elements = $elements->all();
}
if (sizeof($elements) > 0) {
$this->collected = $elements;
}
$list = array_map(function($element, $index) use ($with, $elements) {
// Is index an integer and element is not array or object? Is element a numeric indexed array?
if (is_int($index) || is_string($index)) {
if (!$with == null && isset($element[$with])) {
return $element[$with];
}else{
if (is_int($elements[$index])) {
return $elements[$index];
}
}
}
}, $this->collected, array_keys($this->collected));
return min($list);
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L322-L348 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.groupBy | public function groupBy(String $key) : CollectionContract
{
if ($this->size() > 0) {
$list = [];
$newCollection = [];
foreach($this->all() as $index => $element) {
if (is_array($element) && isset($element[$key])) {
echo $element[$key];
continue;
}
if (is_object($element) && isset($element->$key)) {
// If element has already been added to group, append to the group
// with the same key.
if (isset($list[$element->$key])) {
// Save previous collected list(s)
$collected = $list[$element->$key];
$elementKey = $element->$key;
$newCollection[$elementKey][] = $element;
$newCollection[$elementKey][] = $collected;
continue;
}
$list[$element->$key] = $element;
$newCollection[$element->$key] = [$element];
continue;
}
}
}
$this->collected = $newCollection;
return $this;
} | php | public function groupBy(String $key) : CollectionContract
{
if ($this->size() > 0) {
$list = [];
$newCollection = [];
foreach($this->all() as $index => $element) {
if (is_array($element) && isset($element[$key])) {
echo $element[$key];
continue;
}
if (is_object($element) && isset($element->$key)) {
// If element has already been added to group, append to the group
// with the same key.
if (isset($list[$element->$key])) {
// Save previous collected list(s)
$collected = $list[$element->$key];
$elementKey = $element->$key;
$newCollection[$elementKey][] = $element;
$newCollection[$elementKey][] = $collected;
continue;
}
$list[$element->$key] = $element;
$newCollection[$element->$key] = [$element];
continue;
}
}
}
$this->collected = $newCollection;
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L353-L387 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.partition | public function partition(int $to) : CollectionContract
{
$this->collected = array_chunk($this->collected, $to);
return $this;
} | php | public function partition(int $to) : CollectionContract
{
$this->collected = array_chunk($this->collected, $to);
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L392-L396 |
PhoxPHP/Glider | src/Result/Collection.php | Collection.where | public function where(Array $conditions=[]) : CollectionContract
{
$clone = [];
if ($this->size() > 0) {
$this->toArray();
$condition = [];
foreach($this->collected as $index => $key) {
$element = $this->collected[$index];
$condition[$index] = [];
foreach (array_keys($conditions) as $i => $k) {
if (isset($element[$k]) && $element[$k] == $conditions[$k]) {
$condition[$index][] = 1;
continue;
}
$condition[$index][] = 0;
}
if (empty($condition[$index]) || in_array(0, $condition[$index])) {
continue;
}
$clone[] = $element;
}
}
$this->collected = $clone;
return $this;
} | php | public function where(Array $conditions=[]) : CollectionContract
{
$clone = [];
if ($this->size() > 0) {
$this->toArray();
$condition = [];
foreach($this->collected as $index => $key) {
$element = $this->collected[$index];
$condition[$index] = [];
foreach (array_keys($conditions) as $i => $k) {
if (isset($element[$k]) && $element[$k] == $conditions[$k]) {
$condition[$index][] = 1;
continue;
}
$condition[$index][] = 0;
}
if (empty($condition[$index]) || in_array(0, $condition[$index])) {
continue;
}
$clone[] = $element;
}
}
$this->collected = $clone;
return $this;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Result/Collection.php#L401-L431 |
BenGorFile/FileBundle | src/BenGorFile/FileBundle/DependencyInjection/Compiler/Application/Command/RemoveFileCommandBuilder.php | RemoveFileCommandBuilder.register | public function register($file)
{
$this->container->setDefinition(
$this->definitionName($file),
(new Definition(
RemoveFileHandler::class, [
$this->container->getDefinition(
'bengor.file.infrastructure.domain.model.' . $file . '_filesystem'
),
$this->container->getDefinition(
'bengor.file.infrastructure.persistence.' . $file . '_repository'
),
]
))->addTag(
'bengor_file_' . $file . '_command_bus_handler', [
'handles' => RemoveFileCommand::class,
]
)
);
} | php | public function register($file)
{
$this->container->setDefinition(
$this->definitionName($file),
(new Definition(
RemoveFileHandler::class, [
$this->container->getDefinition(
'bengor.file.infrastructure.domain.model.' . $file . '_filesystem'
),
$this->container->getDefinition(
'bengor.file.infrastructure.persistence.' . $file . '_repository'
),
]
))->addTag(
'bengor_file_' . $file . '_command_bus_handler', [
'handles' => RemoveFileCommand::class,
]
)
);
} | {@inheritdoc} | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/DependencyInjection/Compiler/Application/Command/RemoveFileCommandBuilder.php#L29-L48 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Form/Type/Theme/ComponentType.php | ComponentType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired('variation');
$resolver->setAllowedTypes('variation', Variation::class);
$resolver->setDefaults(array(
'data_class' => UpdateCommand::class,
));
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired('variation');
$resolver->setAllowedTypes('variation', Variation::class);
$resolver->setDefaults(array(
'data_class' => UpdateCommand::class,
));
} | {@inheritdoc} | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Form/Type/Theme/ComponentType.php#L42-L50 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Form/Type/Theme/ComponentType.php | ComponentType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->addModelTransformer($this)
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($builder, $options) {
$form = $event->getForm();
$component = $event->getData();
// Adds custom "data" component from component type
$form->add('data', $component->getComponentType()->getFormType(), array_replace_recursive(
$options['variation']->getConfiguration(
'components',
$component->getComponentType()->getName(),
'config',
array()
),
array(
'auto_initialize' => false,
'label' => false,
)
));
})
;
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->addModelTransformer($this)
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($builder, $options) {
$form = $event->getForm();
$component = $event->getData();
// Adds custom "data" component from component type
$form->add('data', $component->getComponentType()->getFormType(), array_replace_recursive(
$options['variation']->getConfiguration(
'components',
$component->getComponentType()->getName(),
'config',
array()
),
array(
'auto_initialize' => false,
'label' => false,
)
));
})
;
} | Page form prototype definition.
@see FormInterface::buildForm() | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Form/Type/Theme/ComponentType.php#L75-L98 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Form/Type/Theme/ComponentType.php | ComponentType.buildView | public function buildView(FormView $view, FormInterface $form, array $options)
{
$component = $form->getData();
$view->vars['label'] = ucfirst($component->getComponentType()->getName());
$view->vars['component_id'] = $component->getId();
} | php | public function buildView(FormView $view, FormInterface $form, array $options)
{
$component = $form->getData();
$view->vars['label'] = ucfirst($component->getComponentType()->getName());
$view->vars['component_id'] = $component->getId();
} | {@inheritdoc} | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Form/Type/Theme/ComponentType.php#L103-L109 |
amarcinkowski/hospitalplugin | src/utils/ExcelExport.php | ExcelExport.clearName | private static function clearName($string, $removeWords) {
$string = str_replace ( ' ', '-', $string );
$string = preg_replace ( '/[^A-Za-z0-9\-]/', '', $string );
foreach ( $removeWords as $word ) {
$string = str_replace ( $word, '', $string );
}
$string = substr ( $string, 0, 29 );
return $string;
} | php | private static function clearName($string, $removeWords) {
$string = str_replace ( ' ', '-', $string );
$string = preg_replace ( '/[^A-Za-z0-9\-]/', '', $string );
foreach ( $removeWords as $word ) {
$string = str_replace ( $word, '', $string );
}
$string = substr ( $string, 0, 29 );
return $string;
} | remove special chars and words from string
@param unknown $string | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/utils/ExcelExport.php#L94-L102 |
chilimatic/chilimatic-framework | lib/file/Upload.php | Upload.upload | public function upload($file = null)
{
if (empty($file) || !is_array($file)) return false;
$this->u_tmp_name = $file['tmp_name'];
$this->u_name = $file['name'];
$this->u_size = $file['size'];
$this->u_mime_type = $file['type'];
$this->u_error = isset($file['error']) ? $file['error'] : null;
if ($this->u_error) {
throw new FileException("File couldn't be uploaded reason " . FileException::$upload_errors[$this->u_error], Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__);
}
$this->_get_file_extension();
return true;
} | php | public function upload($file = null)
{
if (empty($file) || !is_array($file)) return false;
$this->u_tmp_name = $file['tmp_name'];
$this->u_name = $file['name'];
$this->u_size = $file['size'];
$this->u_mime_type = $file['type'];
$this->u_error = isset($file['error']) ? $file['error'] : null;
if ($this->u_error) {
throw new FileException("File couldn't be uploaded reason " . FileException::$upload_errors[$this->u_error], Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__);
}
$this->_get_file_extension();
return true;
} | current upload process
@param $file array
@return bool
@throws FileException | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Upload.php#L80-L98 |
chilimatic/chilimatic-framework | lib/file/Upload.php | Upload._get_file_extension | private function _get_file_extension()
{
if (empty($this->u_mime_type)) return false;
$tmp = explode('/', $this->u_mime_type);
$this->file_extension = array_pop($tmp);
unset($tmp);
return true;
} | php | private function _get_file_extension()
{
if (empty($this->u_mime_type)) return false;
$tmp = explode('/', $this->u_mime_type);
$this->file_extension = array_pop($tmp);
unset($tmp);
return true;
} | gets the suffix for the file that has been uploaded
@return bool | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Upload.php#L106-L117 |
chilimatic/chilimatic-framework | lib/file/Upload.php | Upload.save | public function save($path, $file_name = '', $delete_source = false)
{
try {
if (empty($path)) {
throw new FileException("No path has been given : $path", Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__);
}
$save_name = "$path/" . (empty($file_name) ? $this->u_name : $file_name);
$save_name = trim($save_name);
$save_name = (strpos($save_name, '.') === false) ? trim($save_name) . "." . trim($this->file_extension) : trim($save_name);
if (!copy($this->u_tmp_name, $save_name)) {
throw new FileException("Copy operation wasn't possible: $this->u_tmp_name, $save_name", Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__);
}
if ($delete_source === true) {
// delete the temporary file
unlink($this->u_tmp_name);
}
return $this->open($save_name);
} catch (FileException $e) {
throw $e;
}
} | php | public function save($path, $file_name = '', $delete_source = false)
{
try {
if (empty($path)) {
throw new FileException("No path has been given : $path", Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__);
}
$save_name = "$path/" . (empty($file_name) ? $this->u_name : $file_name);
$save_name = trim($save_name);
$save_name = (strpos($save_name, '.') === false) ? trim($save_name) . "." . trim($this->file_extension) : trim($save_name);
if (!copy($this->u_tmp_name, $save_name)) {
throw new FileException("Copy operation wasn't possible: $this->u_tmp_name, $save_name", Config::get('file_error'), Config::get('error_lvl_low'), __FILE__, __LINE__);
}
if ($delete_source === true) {
// delete the temporary file
unlink($this->u_tmp_name);
}
return $this->open($save_name);
} catch (FileException $e) {
throw $e;
}
} | Saves [copies] the file to the specific folder / directory
@param $path string
@param string $file_name
@param bool $delete_source
@throws \chilimatic\lib\exception\FileException
@throws \Exception
@internal param string $filename
@return bool | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Upload.php#L150-L176 |
inhere/php-library-plus | libs/Files/Picture.php | Picture.watermark | public function watermark($img, $outPath = '', $pos = '', $waterImg = '', $alpha = '', $text = '')
{
// 验证原图像 和 是否已有错误
if (false === $this->_checkImage($img) || $this->hasError()) {
return $this;
}
$imgInfo = pathinfo($img);
$imgType = $this->_handleImageType($imgInfo['extension']);
$outPath = $outPath ?: ($this->waterOptions['path'] ?: \dirname($img));
$pos = $pos ?: $this->waterOptions['pos'];
$alpha = $alpha ?: $this->waterOptions['alpha'];
$waterImg = $waterImg ?: $this->waterOptions['img'];
$waterImgType = $resWaterImg = null;
list($imgWidth, $imgHeight) = getimagesize($img);
if ($waterImg) {
// 验证水印图像
if (false === $this->_checkImage($waterImg)) {
return $this;
}
$waterImgType = $this->_handleImageType(pathinfo($waterImg, PATHINFO_EXTENSION));
list($waterWidth, $waterHeight) = getimagesize($waterImg);
if ($imgHeight < $waterHeight || $imgWidth < $waterWidth) {
$this->_error = 'The image is too small.';
return $this;
}
// create water image resource
$resWaterImg = \call_user_func("imagecreatefrom{$waterImgType}", $waterImg);
} else {
//水印文字
$text = $text ?: $this->waterOptions['text'];
if (!is_file($this->waterOptions['fontFile'])) {
throw new InvalidConfigException('请配置正确的水印文字资源路径');
}
if (!$text || \strlen($this->waterOptions['fontColor']) !== 6) {
throw new InvalidConfigException('The watermark font color length must equal to 6.');
}
$textInfo = imagettfbbox($this->waterOptions['fontSize'], 0, $this->waterOptions['fontFile'], $text);
$waterWidth = $textInfo[2] - $textInfo[6];
$waterHeight = $textInfo[3] - $textInfo[7];
}
// create image resource 建立原图资源
$method = "imagecreatefrom{$imgType}";
$resImg = $method($img);
//水印位置处理
list($x, $y) = $this->_calcWaterCoords($pos, $imgWidth, $waterWidth, $imgHeight, $waterHeight);
if ($waterImg && $resWaterImg && $waterImgType) {
// is png image. 'IMAGETYPE_PNG' === 3
if ($waterImgType === self::IMAGE_PNG) {
imagecopy($resImg, $resWaterImg, $x, $y, 0, 0, $waterWidth, $waterHeight);
} else {
imagecopymerge($resImg, $resWaterImg, $x, $y, 0, 0, $waterWidth, $waterHeight, $alpha);
}
} else {
$r = hexdec(substr($this->waterOptions['fontColor'], 0, 2));
$g = hexdec(substr($this->waterOptions['fontColor'], 2, 2));
$b = hexdec(substr($this->waterOptions['fontColor'], 4, 2));
$color = imagecolorallocate($resImg, $r, $g, $b);
$charset = 'UTF-8';
imagettftext(
$resImg, $this->waterOptions['fontSize'], 0, $x, $y,
$color, $this->waterOptions['fontFile'], iconv($charset, 'utf-8', $text)
);
}
if (!Directory::create($outPath)) {
$this->_error = 'Failed to create the output directory path!. OUT-PATH: ' . $outPath;
return $this;
}
$outFile = $outPath . '/' . $imgInfo['basename'];
if ($imgType === self::IMAGE_JPEG) {
imagejpeg($resImg, $outFile, $this->waterOptions['quality']);
} elseif ($imgType === self::IMAGE_PNG) {
imagepng($resImg, $outFile, ceil($this->waterOptions['quality'] / 10));
} else {
\call_user_func("image{$imgType}", $resImg, $outFile);
}
imagedestroy($resImg);
$this->working = [
'raw' => $img,
'out' => $outFile,
];
$this->_result['workWater']['rawFile'] = $img;
$this->_result['workWater']['outFile'] = $outFile;
return $this;
} | php | public function watermark($img, $outPath = '', $pos = '', $waterImg = '', $alpha = '', $text = '')
{
// 验证原图像 和 是否已有错误
if (false === $this->_checkImage($img) || $this->hasError()) {
return $this;
}
$imgInfo = pathinfo($img);
$imgType = $this->_handleImageType($imgInfo['extension']);
$outPath = $outPath ?: ($this->waterOptions['path'] ?: \dirname($img));
$pos = $pos ?: $this->waterOptions['pos'];
$alpha = $alpha ?: $this->waterOptions['alpha'];
$waterImg = $waterImg ?: $this->waterOptions['img'];
$waterImgType = $resWaterImg = null;
list($imgWidth, $imgHeight) = getimagesize($img);
if ($waterImg) {
// 验证水印图像
if (false === $this->_checkImage($waterImg)) {
return $this;
}
$waterImgType = $this->_handleImageType(pathinfo($waterImg, PATHINFO_EXTENSION));
list($waterWidth, $waterHeight) = getimagesize($waterImg);
if ($imgHeight < $waterHeight || $imgWidth < $waterWidth) {
$this->_error = 'The image is too small.';
return $this;
}
// create water image resource
$resWaterImg = \call_user_func("imagecreatefrom{$waterImgType}", $waterImg);
} else {
//水印文字
$text = $text ?: $this->waterOptions['text'];
if (!is_file($this->waterOptions['fontFile'])) {
throw new InvalidConfigException('请配置正确的水印文字资源路径');
}
if (!$text || \strlen($this->waterOptions['fontColor']) !== 6) {
throw new InvalidConfigException('The watermark font color length must equal to 6.');
}
$textInfo = imagettfbbox($this->waterOptions['fontSize'], 0, $this->waterOptions['fontFile'], $text);
$waterWidth = $textInfo[2] - $textInfo[6];
$waterHeight = $textInfo[3] - $textInfo[7];
}
// create image resource 建立原图资源
$method = "imagecreatefrom{$imgType}";
$resImg = $method($img);
//水印位置处理
list($x, $y) = $this->_calcWaterCoords($pos, $imgWidth, $waterWidth, $imgHeight, $waterHeight);
if ($waterImg && $resWaterImg && $waterImgType) {
// is png image. 'IMAGETYPE_PNG' === 3
if ($waterImgType === self::IMAGE_PNG) {
imagecopy($resImg, $resWaterImg, $x, $y, 0, 0, $waterWidth, $waterHeight);
} else {
imagecopymerge($resImg, $resWaterImg, $x, $y, 0, 0, $waterWidth, $waterHeight, $alpha);
}
} else {
$r = hexdec(substr($this->waterOptions['fontColor'], 0, 2));
$g = hexdec(substr($this->waterOptions['fontColor'], 2, 2));
$b = hexdec(substr($this->waterOptions['fontColor'], 4, 2));
$color = imagecolorallocate($resImg, $r, $g, $b);
$charset = 'UTF-8';
imagettftext(
$resImg, $this->waterOptions['fontSize'], 0, $x, $y,
$color, $this->waterOptions['fontFile'], iconv($charset, 'utf-8', $text)
);
}
if (!Directory::create($outPath)) {
$this->_error = 'Failed to create the output directory path!. OUT-PATH: ' . $outPath;
return $this;
}
$outFile = $outPath . '/' . $imgInfo['basename'];
if ($imgType === self::IMAGE_JPEG) {
imagejpeg($resImg, $outFile, $this->waterOptions['quality']);
} elseif ($imgType === self::IMAGE_PNG) {
imagepng($resImg, $outFile, ceil($this->waterOptions['quality'] / 10));
} else {
\call_user_func("image{$imgType}", $resImg, $outFile);
}
imagedestroy($resImg);
$this->working = [
'raw' => $img,
'out' => $outFile,
];
$this->_result['workWater']['rawFile'] = $img;
$this->_result['workWater']['outFile'] = $outFile;
return $this;
} | 水印处理
@param string $img 操作的图像
@param string $outPath 另存的图像
@param string $pos 水印位置
@param string $waterImg 水印图片
@param string $alpha 透明度
@param string $text 文字水印内容
@return Picture
@throws InvalidConfigException | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Picture.php#L161-L268 |
inhere/php-library-plus | libs/Files/Picture.php | Picture.thumbnail | public function thumbnail($img, $outPath = '', $outFilename = '', $thumbWidth = '', $thumbHeight = '', $thumbType = '')
{
if (!$this->_checkImage($img) || $this->hasError()) {
return $this;
}
$imgInfo = pathinfo($img);
$rawImgType = $imgInfo['extension'];
//基础配置
$thumbType = $thumbType ?: $this->thumbOptions['type'];
$thumbWidth = $thumbWidth ?: $this->thumbOptions['width'];
$thumbHeight = $thumbHeight ?: $this->thumbOptions['height'];
$outPath = $outPath ?: ($this->thumbOptions['path'] ?: \dirname($img));
//获得图像信息
list($imgWidth, $imgHeight) = getimagesize($img);
$imgType = $this->_handleImageType($rawImgType);
//获得相关尺寸
$thumbSize = $this->_calcThumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType);
//原始图像资源
// imagecreatefromgif() imagecreatefrompng() imagecreatefromjpeg() imagecreatefromwbmp()
$resImg = \call_user_func("imagecreatefrom{$imgType}", $img);
//缩略图的资源
if ($imgType === static::IMAGE_GIF) {
$resThumb = imagecreate($thumbSize[0], $thumbSize[1]);
$color = imagecolorallocate($resThumb, 255, 0, 0);
imagecolortransparent($resThumb, $color); //处理透明色
} else {
$resThumb = imagecreatetruecolor($thumbSize[0], $thumbSize[1]);
imagealphablending($resThumb, false); //关闭混色
imagesavealpha($resThumb, true); //储存透明通道
}
// 绘制缩略图X
if (\function_exists('imagecopyresampled')) {
imagecopyresampled($resThumb, $resImg, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $thumbSize[2], $thumbSize[3]);
} else {
imagecopyresized($resThumb, $resImg, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $thumbSize[2], $thumbSize[3]);
}
//配置输出文件名
$outFilename = $outFilename ?: $this->thumbOptions['prefix'] . $imgInfo['filename'] . $this->thumbOptions['suffix'] . '.' . $rawImgType;
$outFile = $outPath . DIRECTORY_SEPARATOR . $outFilename;
if (!Directory::create($outPath)) {
$this->_error = 'Failed to create the output directory path!. OUT-PATH: ' . $outPath;
return $this;
}
// generate image to dst file. imagepng(), imagegif(), imagejpeg(), imagewbmp()
\call_user_func("image{$imgType}", $resThumb, $outFile);
imagedestroy($resImg);
imagedestroy($resThumb);
$this->working = [
'raw' => $img,
'out' => $outFile,
];
$this->_result['workThumb']['rawFile'] = $img;
$this->_result['workThumb']['outFile'] = $outFile;
return $this;
} | php | public function thumbnail($img, $outPath = '', $outFilename = '', $thumbWidth = '', $thumbHeight = '', $thumbType = '')
{
if (!$this->_checkImage($img) || $this->hasError()) {
return $this;
}
$imgInfo = pathinfo($img);
$rawImgType = $imgInfo['extension'];
//基础配置
$thumbType = $thumbType ?: $this->thumbOptions['type'];
$thumbWidth = $thumbWidth ?: $this->thumbOptions['width'];
$thumbHeight = $thumbHeight ?: $this->thumbOptions['height'];
$outPath = $outPath ?: ($this->thumbOptions['path'] ?: \dirname($img));
//获得图像信息
list($imgWidth, $imgHeight) = getimagesize($img);
$imgType = $this->_handleImageType($rawImgType);
//获得相关尺寸
$thumbSize = $this->_calcThumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType);
//原始图像资源
// imagecreatefromgif() imagecreatefrompng() imagecreatefromjpeg() imagecreatefromwbmp()
$resImg = \call_user_func("imagecreatefrom{$imgType}", $img);
//缩略图的资源
if ($imgType === static::IMAGE_GIF) {
$resThumb = imagecreate($thumbSize[0], $thumbSize[1]);
$color = imagecolorallocate($resThumb, 255, 0, 0);
imagecolortransparent($resThumb, $color); //处理透明色
} else {
$resThumb = imagecreatetruecolor($thumbSize[0], $thumbSize[1]);
imagealphablending($resThumb, false); //关闭混色
imagesavealpha($resThumb, true); //储存透明通道
}
// 绘制缩略图X
if (\function_exists('imagecopyresampled')) {
imagecopyresampled($resThumb, $resImg, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $thumbSize[2], $thumbSize[3]);
} else {
imagecopyresized($resThumb, $resImg, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $thumbSize[2], $thumbSize[3]);
}
//配置输出文件名
$outFilename = $outFilename ?: $this->thumbOptions['prefix'] . $imgInfo['filename'] . $this->thumbOptions['suffix'] . '.' . $rawImgType;
$outFile = $outPath . DIRECTORY_SEPARATOR . $outFilename;
if (!Directory::create($outPath)) {
$this->_error = 'Failed to create the output directory path!. OUT-PATH: ' . $outPath;
return $this;
}
// generate image to dst file. imagepng(), imagegif(), imagejpeg(), imagewbmp()
\call_user_func("image{$imgType}", $resThumb, $outFile);
imagedestroy($resImg);
imagedestroy($resThumb);
$this->working = [
'raw' => $img,
'out' => $outFile,
];
$this->_result['workThumb']['rawFile'] = $img;
$this->_result['workThumb']['outFile'] = $outFile;
return $this;
} | 图片裁切处理(制作缩略图)
@param string $img 操作的图片文件路径(原图)
@param string $outPath 文件存放路径
@param string $outFilename 另存文件名
@param string $thumbWidth 缩略图宽度
@param string $thumbHeight 缩略图高度
@param string $thumbType 裁切图片的方式
@return static | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Picture.php#L298-L367 |
inhere/php-library-plus | libs/Files/Picture.php | Picture.show | public static function show($img)
{
if (!is_file($img) || !is_readable($img)) {
throw new FileSystemException('image file don\'t exists or file is not readable!');
}
$type = pathinfo($img, PATHINFO_EXTENSION);
$type = $type === self::IMAGE_JPG ? self::IMAGE_JPEG : $type;
if (!static::isSupportedType($type)) {
throw new InvalidArgumentException("image type [$type] is not supported!", 1);
}
/** @var resource $resImg */
$resImg = \call_user_func("imagecreatefrom{$type}", $img);
// 保持png图片的透明度
if ($type === self::IMAGE_PNG) {
// 设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息。
imagesavealpha($resImg, true);
}
header('Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate');
header('Content-type: image/' . $type . ';charset=utf8'); // 生成图片格式 png jpeg 。。。
ob_clean();
//生成图片,在浏览器中进行显示-格式 $type ,与上面的header声明对应
// e.g. imagepng($resImg);
$method = "image{$type}";
$success = $method($resImg);
// 已经显示图片后,可销毁,释放内存(可选)
imagedestroy($resImg);
return $success;
} | php | public static function show($img)
{
if (!is_file($img) || !is_readable($img)) {
throw new FileSystemException('image file don\'t exists or file is not readable!');
}
$type = pathinfo($img, PATHINFO_EXTENSION);
$type = $type === self::IMAGE_JPG ? self::IMAGE_JPEG : $type;
if (!static::isSupportedType($type)) {
throw new InvalidArgumentException("image type [$type] is not supported!", 1);
}
/** @var resource $resImg */
$resImg = \call_user_func("imagecreatefrom{$type}", $img);
// 保持png图片的透明度
if ($type === self::IMAGE_PNG) {
// 设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息。
imagesavealpha($resImg, true);
}
header('Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate');
header('Content-type: image/' . $type . ';charset=utf8'); // 生成图片格式 png jpeg 。。。
ob_clean();
//生成图片,在浏览器中进行显示-格式 $type ,与上面的header声明对应
// e.g. imagepng($resImg);
$method = "image{$type}";
$success = $method($resImg);
// 已经显示图片后,可销毁,释放内存(可选)
imagedestroy($resImg);
return $success;
} | 显示 image file 到浏览器
@param string $img 图片文件
@return bool
@throws FileSystemException
@throws InvalidArgumentException | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Picture.php#L376-L411 |
inhere/php-library-plus | libs/Files/Picture.php | Picture._checkImage | private function _checkImage($img)
{
if (!file_exists($img)) {
$this->_error = 'Image file dom\'t exists! file: ' . $img;
} elseif (!($type = pathinfo($img, PATHINFO_EXTENSION)) || !self::isSupportedType($type)) {
$this->_error = "Image type [$type] is not supported.";
}
return !$this->hasError();
} | php | private function _checkImage($img)
{
if (!file_exists($img)) {
$this->_error = 'Image file dom\'t exists! file: ' . $img;
} elseif (!($type = pathinfo($img, PATHINFO_EXTENSION)) || !self::isSupportedType($type)) {
$this->_error = "Image type [$type] is not supported.";
}
return !$this->hasError();
} | 验证
@param string $img 图像路径
@return bool | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Picture.php#L440-L449 |
inhere/php-library-plus | libs/Files/Picture.php | Picture._calcThumbSize | private function _calcThumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType)
{
//初始化缩略图尺寸
$w = $thumbWidth;
$h = $thumbHeight;
//初始化原图尺寸
$oldThumbWidth = $imgWidth;
$oldThumbHeight = $imgHeight;
// 原图比需要的缩略图还小
if ($imgWidth <= $thumbWidth && $imgHeight <= $thumbHeight) {
return [$imgWidth, $imgHeight, $oldThumbWidth, $oldThumbHeight];
}
switch ($thumbType) {
case 1 :
//固定宽度 高度自增
$h = $thumbWidth / $imgWidth * $imgHeight;
break;
case 2 :
//固定高度 宽度自增
$w = $thumbHeight / $imgHeight * $imgWidth;
break;
case 3 :
//固定宽度 高度裁切
$oldThumbHeight = $imgWidth / $thumbWidth * $thumbHeight;
break;
case 4 :
//固定高度 宽度裁切
$oldThumbWidth = $imgHeight / $thumbHeight * $thumbWidth;
break;
case 5 :
//缩放最大边 原图不裁切
if (($imgWidth / $thumbWidth) > ($imgHeight / $thumbHeight)) {
$h = $thumbWidth / $imgWidth * $imgHeight;
} else if (($imgWidth / $thumbWidth) < ($imgHeight / $thumbHeight)) {
$w = $thumbHeight / $imgHeight * $imgWidth;
} else {
$w = $thumbWidth;
$h = $thumbHeight;
}
break;
default:
//缩略图尺寸不变,自动裁切图片
if (($imgHeight / $thumbHeight) < ($imgWidth / $thumbWidth)) {
$oldThumbWidth = $imgHeight / $thumbHeight * $thumbWidth;
} else if (($imgHeight / $thumbHeight) > ($imgWidth / $thumbWidth)) {
$oldThumbHeight = $imgWidth / $thumbWidth * $thumbHeight;
}
}
return [$w, $h, $oldThumbWidth, $oldThumbHeight];
} | php | private function _calcThumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType)
{
//初始化缩略图尺寸
$w = $thumbWidth;
$h = $thumbHeight;
//初始化原图尺寸
$oldThumbWidth = $imgWidth;
$oldThumbHeight = $imgHeight;
// 原图比需要的缩略图还小
if ($imgWidth <= $thumbWidth && $imgHeight <= $thumbHeight) {
return [$imgWidth, $imgHeight, $oldThumbWidth, $oldThumbHeight];
}
switch ($thumbType) {
case 1 :
//固定宽度 高度自增
$h = $thumbWidth / $imgWidth * $imgHeight;
break;
case 2 :
//固定高度 宽度自增
$w = $thumbHeight / $imgHeight * $imgWidth;
break;
case 3 :
//固定宽度 高度裁切
$oldThumbHeight = $imgWidth / $thumbWidth * $thumbHeight;
break;
case 4 :
//固定高度 宽度裁切
$oldThumbWidth = $imgHeight / $thumbHeight * $thumbWidth;
break;
case 5 :
//缩放最大边 原图不裁切
if (($imgWidth / $thumbWidth) > ($imgHeight / $thumbHeight)) {
$h = $thumbWidth / $imgWidth * $imgHeight;
} else if (($imgWidth / $thumbWidth) < ($imgHeight / $thumbHeight)) {
$w = $thumbHeight / $imgHeight * $imgWidth;
} else {
$w = $thumbWidth;
$h = $thumbHeight;
}
break;
default:
//缩略图尺寸不变,自动裁切图片
if (($imgHeight / $thumbHeight) < ($imgWidth / $thumbWidth)) {
$oldThumbWidth = $imgHeight / $thumbHeight * $thumbWidth;
} else if (($imgHeight / $thumbHeight) > ($imgWidth / $thumbWidth)) {
$oldThumbHeight = $imgWidth / $thumbWidth * $thumbHeight;
}
}
return [$w, $h, $oldThumbWidth, $oldThumbHeight];
} | 计算获得缩略图的尺寸信息
@param string $imgWidth 原图宽度
@param string $imgHeight 原图高度
@param string $thumbWidth 缩略图宽度
@param string $thumbHeight 缩略图的高度
@param string $thumbType 处理方式
@return array | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Picture.php#L519-L572 |
inhere/php-library-plus | libs/Files/Picture.php | Picture.getWaterOption | public function getWaterOption($name, $default = null)
{
return array_key_exists($name, $this->waterOptions) ? $this->waterOptions[$name] : $default;
} | php | public function getWaterOption($name, $default = null)
{
return array_key_exists($name, $this->waterOptions) ? $this->waterOptions[$name] : $default;
} | getWaterOption
@param string $name
@param string|null $default
@return string | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Picture.php#L631-L634 |
inhere/php-library-plus | libs/Files/Picture.php | Picture.getThumbOption | public function getThumbOption($name, $default = null)
{
return array_key_exists($name, $this->thumbOptions) ? $this->thumbOptions[$name] : $default;
} | php | public function getThumbOption($name, $default = null)
{
return array_key_exists($name, $this->thumbOptions) ? $this->thumbOptions[$name] : $default;
} | getThumbOption
@param string $name
@param string|null $default
@return string | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Picture.php#L659-L662 |
smalldb/libSmalldb | class/Graph/ElementAttrIndex.php | ElementAttrIndex.rebuildAttrIndex | private function rebuildAttrIndex(string $key)
{
$this->index[$key] = [];
foreach ($this->elements as $id => $element) {
if ($element instanceof $this->elementClassName) {
$value = $element->getAttr($key);
$this->index[$key][$value][$id] = $element;
} else {
throw new \InvalidArgumentException("Indexed element must be instance of " . $this->elementClassName);
}
}
} | php | private function rebuildAttrIndex(string $key)
{
$this->index[$key] = [];
foreach ($this->elements as $id => $element) {
if ($element instanceof $this->elementClassName) {
$value = $element->getAttr($key);
$this->index[$key][$value][$id] = $element;
} else {
throw new \InvalidArgumentException("Indexed element must be instance of " . $this->elementClassName);
}
}
} | Rebuild the entire index from provided elements. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L85-L97 |
smalldb/libSmalldb | class/Graph/ElementAttrIndex.php | ElementAttrIndex.insertElement | public function insertElement(AbstractElement $element)
{
if (!($element instanceof $this->elementClassName)) {
throw new \InvalidArgumentException("Indexed element must be instance of " . $this->elementClassName);
}
$id = $element->getId();
if (isset($this->elements[$id])) {
throw new DuplicateElementException("Element \"$id\" already indexed.");
}
$this->elements[$id] = $element;
$indexedAttrs = array_intersect_key($element->getAttributes(), $this->index);
foreach ($indexedAttrs as $key => $newValue) {
$this->index[$key][$newValue][$id] = $element;
}
} | php | public function insertElement(AbstractElement $element)
{
if (!($element instanceof $this->elementClassName)) {
throw new \InvalidArgumentException("Indexed element must be instance of " . $this->elementClassName);
}
$id = $element->getId();
if (isset($this->elements[$id])) {
throw new DuplicateElementException("Element \"$id\" already indexed.");
}
$this->elements[$id] = $element;
$indexedAttrs = array_intersect_key($element->getAttributes(), $this->index);
foreach ($indexedAttrs as $key => $newValue) {
$this->index[$key][$newValue][$id] = $element;
}
} | Insert element into index (all keys has changed). | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L103-L121 |
smalldb/libSmalldb | class/Graph/ElementAttrIndex.php | ElementAttrIndex.removeElement | public function removeElement(AbstractElement $element)
{
$id = $element->getId();
if (!isset($this->elements[$id])) {
throw new MissingElementException("Element \"$id\" is not indexed.");
}
unset($this->elements[$id]);
$indexedAttrs = array_intersect_key($element->getAttributes(), $this->index);
foreach ($indexedAttrs as $key => $oldValue) {
unset($this->index[$key][$oldValue][$id]);
}
} | php | public function removeElement(AbstractElement $element)
{
$id = $element->getId();
if (!isset($this->elements[$id])) {
throw new MissingElementException("Element \"$id\" is not indexed.");
}
unset($this->elements[$id]);
$indexedAttrs = array_intersect_key($element->getAttributes(), $this->index);
foreach ($indexedAttrs as $key => $oldValue) {
unset($this->index[$key][$oldValue][$id]);
}
} | Remove element from index | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L127-L141 |
smalldb/libSmalldb | class/Graph/ElementAttrIndex.php | ElementAttrIndex.update | public function update(string $key, $oldValue, $newValue, AbstractElement $element)
{
if (!isset($this->index[$key])) {
throw new MissingAttrIndexException("Attribute index \"$key\" is not defined.");
}
$id = $element->getId();
if (isset($this->index[$key][$oldValue][$id])) {
unset($this->index[$key][$oldValue][$id]);
} else {
throw new MissingElementException("Old value of \"$id\" is not indexed.");
}
$this->index[$key][$newValue][$id] = $element;
} | php | public function update(string $key, $oldValue, $newValue, AbstractElement $element)
{
if (!isset($this->index[$key])) {
throw new MissingAttrIndexException("Attribute index \"$key\" is not defined.");
}
$id = $element->getId();
if (isset($this->index[$key][$oldValue][$id])) {
unset($this->index[$key][$oldValue][$id]);
} else {
throw new MissingElementException("Old value of \"$id\" is not indexed.");
}
$this->index[$key][$newValue][$id] = $element;
} | Update indices to match the changed attribute of the element | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L147-L162 |
smalldb/libSmalldb | class/Graph/ElementAttrIndex.php | ElementAttrIndex.getElements | public function getElements(string $key, $value): array
{
if (!isset($this->index[$key])) {
throw new MissingAttrIndexException("Attribute index \"$key\" is not defined.");
}
return $this->index[$key][$value] ?? [];
} | php | public function getElements(string $key, $value): array
{
if (!isset($this->index[$key])) {
throw new MissingAttrIndexException("Attribute index \"$key\" is not defined.");
}
return $this->index[$key][$value] ?? [];
} | Get elements by the value of the attribute | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/ElementAttrIndex.php#L179-L186 |
luoxiaojun1992/lb_framework | components/helpers/HtmlHelper.php | HtmlHelper.compress | public static function compress($html_code)
{
$segments = preg_split("/(<[^>]+?>)/si",$html_code, -1,PREG_SPLIT_NO_EMPTY| PREG_SPLIT_DELIM_CAPTURE);
$compressed = [];
$stack = [];
$tag = '';
$half_open = ['meta','input','link','img','br'];
$cannot_compress = ['pre','code','script','style'];
foreach ($segments as $seg) {
if (trim($seg) === '') {
continue;
}
if (preg_match("!<([a-z0-9]+)[^>]*?/>!si",$seg, $match) || preg_match("~<![^>]*>~", $seg)) {
//文档声明和注释,注释也不能删除,如<!--ie条件-->
$compressed[] = $seg;
} else if (preg_match("!</([a-z0-9]+)[^>]*?>!si",$seg,$match)) {
$tag = static::format_tag($match[1]);
if (count($stack) > 0 && $stack[count($stack)-1] == $tag) {
array_pop($stack);
$compressed[] = $seg;
}
//这里再最好加一段判断,可以用于修复错误的html
} else if (preg_match("!<([a-z0-9]+)[^>]*?>!si",$seg,$match)) {
$tag = static::format_tag($match[1]);
//半闭合标签不需要入栈,如<br/>,<img/>
if (!in_array($tag, $half_open)) {
array_push($stack,$tag);
}
$compressed[] = $seg;
} else {
$compressed[] = in_array($tag, $cannot_compress) ? $seg : preg_replace('!\s!', '', $seg);
}
}
return join('',$compressed);
} | php | public static function compress($html_code)
{
$segments = preg_split("/(<[^>]+?>)/si",$html_code, -1,PREG_SPLIT_NO_EMPTY| PREG_SPLIT_DELIM_CAPTURE);
$compressed = [];
$stack = [];
$tag = '';
$half_open = ['meta','input','link','img','br'];
$cannot_compress = ['pre','code','script','style'];
foreach ($segments as $seg) {
if (trim($seg) === '') {
continue;
}
if (preg_match("!<([a-z0-9]+)[^>]*?/>!si",$seg, $match) || preg_match("~<![^>]*>~", $seg)) {
//文档声明和注释,注释也不能删除,如<!--ie条件-->
$compressed[] = $seg;
} else if (preg_match("!</([a-z0-9]+)[^>]*?>!si",$seg,$match)) {
$tag = static::format_tag($match[1]);
if (count($stack) > 0 && $stack[count($stack)-1] == $tag) {
array_pop($stack);
$compressed[] = $seg;
}
//这里再最好加一段判断,可以用于修复错误的html
} else if (preg_match("!<([a-z0-9]+)[^>]*?>!si",$seg,$match)) {
$tag = static::format_tag($match[1]);
//半闭合标签不需要入栈,如<br/>,<img/>
if (!in_array($tag, $half_open)) {
array_push($stack,$tag);
}
$compressed[] = $seg;
} else {
$compressed[] = in_array($tag, $cannot_compress) ? $seg : preg_replace('!\s!', '', $seg);
}
}
return join('',$compressed);
} | Compress html
@param $html_code
@return string | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HtmlHelper.php#L18-L52 |
luoxiaojun1992/lb_framework | components/helpers/HtmlHelper.php | HtmlHelper.image | public static function image($src, $alt = '', $options = [])
{
$image_tag_tpl = '<img src="%s" alt="%s"%s />';
$cdnHost = Lb::app()->getCdnHost();
if ($cdnHost) {
if (!ValidationHelper::isUrl($src)) {
$src = $cdnHost . $src;
} else {
$src = preg_replace('/^(http|https):\/\/.+?\//i', $cdnHost . '/', $src);
}
}
return sprintf($image_tag_tpl, $src, $alt, self::assembleTagOptions($options));
} | php | public static function image($src, $alt = '', $options = [])
{
$image_tag_tpl = '<img src="%s" alt="%s"%s />';
$cdnHost = Lb::app()->getCdnHost();
if ($cdnHost) {
if (!ValidationHelper::isUrl($src)) {
$src = $cdnHost . $src;
} else {
$src = preg_replace('/^(http|https):\/\/.+?\//i', $cdnHost . '/', $src);
}
}
return sprintf($image_tag_tpl, $src, $alt, self::assembleTagOptions($options));
} | Generate image tag
@param $src
@param string $alt
@param array $options
@return string | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HtmlHelper.php#L84-L96 |
luoxiaojun1992/lb_framework | components/helpers/HtmlHelper.php | HtmlHelper.a | public static function a($href, $content = '', $title = '', $target = '', $options = [])
{
$a_tag_tpl = '<a href="%s" title="%s" target="%s"%s>%s</a>';
return sprintf($a_tag_tpl, $href, $title, $target, self::assembleTagOptions($options), $content);
} | php | public static function a($href, $content = '', $title = '', $target = '', $options = [])
{
$a_tag_tpl = '<a href="%s" title="%s" target="%s"%s>%s</a>';
return sprintf($a_tag_tpl, $href, $title, $target, self::assembleTagOptions($options), $content);
} | Generate a tag
@param $href
@param string $content
@param string $title
@param string $target
@param array $options
@return string | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HtmlHelper.php#L108-L112 |
luoxiaojun1992/lb_framework | components/helpers/HtmlHelper.php | HtmlHelper.purify | public static function purify($dirtyHtml)
{
if (self::$htmlPurifier && self::$htmlPurifier instanceof \HTMLPurifier) {
$purifier = self::$htmlPurifier;
} else {
$purifier = (self::$htmlPurifier = new \HTMLPurifier(\HTMLPurifier_Config::createDefault()));
}
return $purifier->purify($dirtyHtml);
} | php | public static function purify($dirtyHtml)
{
if (self::$htmlPurifier && self::$htmlPurifier instanceof \HTMLPurifier) {
$purifier = self::$htmlPurifier;
} else {
$purifier = (self::$htmlPurifier = new \HTMLPurifier(\HTMLPurifier_Config::createDefault()));
}
return $purifier->purify($dirtyHtml);
} | Purify dirty html
@param $dirtyHtml
@return mixed | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HtmlHelper.php#L120-L128 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.