id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
11,000
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient._getLogFileName
private function _getLogFileName() { static $logFileName = null; if (null == $logFileName) { $logFileName = $this->getUserHome().self::DEFAULT_LOG; } return $logFileName; }
php
private function _getLogFileName() { static $logFileName = null; if (null == $logFileName) { $logFileName = $this->getUserHome().self::DEFAULT_LOG; } return $logFileName; }
[ "private", "function", "_getLogFileName", "(", ")", "{", "static", "$", "logFileName", "=", "null", ";", "if", "(", "null", "==", "$", "logFileName", ")", "{", "$", "logFileName", "=", "$", "this", "->", "getUserHome", "(", ")", ".", "self", "::", "DEFAULT_LOG", ";", "}", "return", "$", "logFileName", ";", "}" ]
This method returns the path to the log file @return string
[ "This", "method", "returns", "the", "path", "to", "the", "log", "file" ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L356-L363
11,001
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient.createEnvironment
public function createEnvironment($name) { if (false == $this->vagrentExists($name)) { $msg = self::VAGRANT_FILE_NAME." not found in {$name}, skipping"; $this->printLn($msg, 'error'); return; } $environments = $this->getEnvironments(); $changed = false; if (false == $this->environmentExists($name)) { $environments[] = $name; $changed = true; $this->printLn("Environment {$name} created"); } if (true == $changed) { $this->setEnvironments($environments); $environments = array_reverse($environments); $this->setEnvironments($environments); } else { $message = "Environment {$name} already exists, skipping"; $this->printLn($message, 'notice', false); } return $this; }
php
public function createEnvironment($name) { if (false == $this->vagrentExists($name)) { $msg = self::VAGRANT_FILE_NAME." not found in {$name}, skipping"; $this->printLn($msg, 'error'); return; } $environments = $this->getEnvironments(); $changed = false; if (false == $this->environmentExists($name)) { $environments[] = $name; $changed = true; $this->printLn("Environment {$name} created"); } if (true == $changed) { $this->setEnvironments($environments); $environments = array_reverse($environments); $this->setEnvironments($environments); } else { $message = "Environment {$name} already exists, skipping"; $this->printLn($message, 'notice', false); } return $this; }
[ "public", "function", "createEnvironment", "(", "$", "name", ")", "{", "if", "(", "false", "==", "$", "this", "->", "vagrentExists", "(", "$", "name", ")", ")", "{", "$", "msg", "=", "self", "::", "VAGRANT_FILE_NAME", ".", "\" not found in {$name}, skipping\"", ";", "$", "this", "->", "printLn", "(", "$", "msg", ",", "'error'", ")", ";", "return", ";", "}", "$", "environments", "=", "$", "this", "->", "getEnvironments", "(", ")", ";", "$", "changed", "=", "false", ";", "if", "(", "false", "==", "$", "this", "->", "environmentExists", "(", "$", "name", ")", ")", "{", "$", "environments", "[", "]", "=", "$", "name", ";", "$", "changed", "=", "true", ";", "$", "this", "->", "printLn", "(", "\"Environment {$name} created\"", ")", ";", "}", "if", "(", "true", "==", "$", "changed", ")", "{", "$", "this", "->", "setEnvironments", "(", "$", "environments", ")", ";", "$", "environments", "=", "array_reverse", "(", "$", "environments", ")", ";", "$", "this", "->", "setEnvironments", "(", "$", "environments", ")", ";", "}", "else", "{", "$", "message", "=", "\"Environment {$name} already exists, skipping\"", ";", "$", "this", "->", "printLn", "(", "$", "message", ",", "'notice'", ",", "false", ")", ";", "}", "return", "$", "this", ";", "}" ]
This method adds the environment to storage if it is not already in storage. @param string $name is the name of the environment to create. @return $this
[ "This", "method", "adds", "the", "environment", "to", "storage", "if", "it", "is", "not", "already", "in", "storage", "." ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L420-L443
11,002
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient.removeEnvironment
public function removeEnvironment($name) { $removed = false; $environments = $this->getEnvironments(); if (true == in_array($name, $environments)) { if (($key = array_search($name, $environments)) !== false) { $this->printLn("Removing environment {$name}"); unset($environments[$key]); $removed = true; } } if (false == $removed) { $this->printLn("environment {$name} not found or removed"); } $this->setEnvironments($environments); return $this; }
php
public function removeEnvironment($name) { $removed = false; $environments = $this->getEnvironments(); if (true == in_array($name, $environments)) { if (($key = array_search($name, $environments)) !== false) { $this->printLn("Removing environment {$name}"); unset($environments[$key]); $removed = true; } } if (false == $removed) { $this->printLn("environment {$name} not found or removed"); } $this->setEnvironments($environments); return $this; }
[ "public", "function", "removeEnvironment", "(", "$", "name", ")", "{", "$", "removed", "=", "false", ";", "$", "environments", "=", "$", "this", "->", "getEnvironments", "(", ")", ";", "if", "(", "true", "==", "in_array", "(", "$", "name", ",", "$", "environments", ")", ")", "{", "if", "(", "(", "$", "key", "=", "array_search", "(", "$", "name", ",", "$", "environments", ")", ")", "!==", "false", ")", "{", "$", "this", "->", "printLn", "(", "\"Removing environment {$name}\"", ")", ";", "unset", "(", "$", "environments", "[", "$", "key", "]", ")", ";", "$", "removed", "=", "true", ";", "}", "}", "if", "(", "false", "==", "$", "removed", ")", "{", "$", "this", "->", "printLn", "(", "\"environment {$name} not found or removed\"", ")", ";", "}", "$", "this", "->", "setEnvironments", "(", "$", "environments", ")", ";", "return", "$", "this", ";", "}" ]
This method removed an environment from the system. The environment must match exactly to the path in storage. @param string $name Is the name of the environment to be removed @return $this
[ "This", "method", "removed", "an", "environment", "from", "the", "system", ".", "The", "environment", "must", "match", "exactly", "to", "the", "path", "in", "storage", "." ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L467-L483
11,003
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient.environmentsDown
protected function environmentsDown($ignoreCurrentEnvironment=false) { foreach ($this->getEnvironments() as $environment) { if (true == $ignoreCurrentEnvironment && $environment == $this->getCurrentEnvironment() ) { $this->printLn("Skipping current environment {$environment}"); } else if (true == file_exists($environment)) { chdir($environment); $this->printLn("Attempting shutdown down vagrant in {$environment}"); $output = ''; $return = ''; exec('vagrant halt', $output, $return); if (false == is_array($output)) { $output = array($output); } if (0 != $return) { $this->printLn("Error found, logged", 'warning'); $this->printLn(implode(', ', $output), 'warning', false); } else { $this->printLn(implode(', ', $output), 'notice'); } } else { $this->printLn("Dir not found {$environment}"); } } chdir($this->pwd); return $this; }
php
protected function environmentsDown($ignoreCurrentEnvironment=false) { foreach ($this->getEnvironments() as $environment) { if (true == $ignoreCurrentEnvironment && $environment == $this->getCurrentEnvironment() ) { $this->printLn("Skipping current environment {$environment}"); } else if (true == file_exists($environment)) { chdir($environment); $this->printLn("Attempting shutdown down vagrant in {$environment}"); $output = ''; $return = ''; exec('vagrant halt', $output, $return); if (false == is_array($output)) { $output = array($output); } if (0 != $return) { $this->printLn("Error found, logged", 'warning'); $this->printLn(implode(', ', $output), 'warning', false); } else { $this->printLn(implode(', ', $output), 'notice'); } } else { $this->printLn("Dir not found {$environment}"); } } chdir($this->pwd); return $this; }
[ "protected", "function", "environmentsDown", "(", "$", "ignoreCurrentEnvironment", "=", "false", ")", "{", "foreach", "(", "$", "this", "->", "getEnvironments", "(", ")", "as", "$", "environment", ")", "{", "if", "(", "true", "==", "$", "ignoreCurrentEnvironment", "&&", "$", "environment", "==", "$", "this", "->", "getCurrentEnvironment", "(", ")", ")", "{", "$", "this", "->", "printLn", "(", "\"Skipping current environment {$environment}\"", ")", ";", "}", "else", "if", "(", "true", "==", "file_exists", "(", "$", "environment", ")", ")", "{", "chdir", "(", "$", "environment", ")", ";", "$", "this", "->", "printLn", "(", "\"Attempting shutdown down vagrant in {$environment}\"", ")", ";", "$", "output", "=", "''", ";", "$", "return", "=", "''", ";", "exec", "(", "'vagrant halt'", ",", "$", "output", ",", "$", "return", ")", ";", "if", "(", "false", "==", "is_array", "(", "$", "output", ")", ")", "{", "$", "output", "=", "array", "(", "$", "output", ")", ";", "}", "if", "(", "0", "!=", "$", "return", ")", "{", "$", "this", "->", "printLn", "(", "\"Error found, logged\"", ",", "'warning'", ")", ";", "$", "this", "->", "printLn", "(", "implode", "(", "', '", ",", "$", "output", ")", ",", "'warning'", ",", "false", ")", ";", "}", "else", "{", "$", "this", "->", "printLn", "(", "implode", "(", "', '", ",", "$", "output", ")", ",", "'notice'", ")", ";", "}", "}", "else", "{", "$", "this", "->", "printLn", "(", "\"Dir not found {$environment}\"", ")", ";", "}", "}", "chdir", "(", "$", "this", "->", "pwd", ")", ";", "return", "$", "this", ";", "}" ]
This method halts every Vagrant environment. This is the only method which executes a command. @param bool $ignoreCurrentEnvironment tells the method to ignore the current environment and not call halt on it. @return $this;
[ "This", "method", "halts", "every", "Vagrant", "environment", ".", "This", "is", "the", "only", "method", "which", "executes", "a", "command", "." ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L494-L523
11,004
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient.printLn
protected function printLn($message, $type='general', $out=true) { if (null == $message) { return; } if (null != $this->output) { $message = (null == $type) ? $message : "<{$type}>{$message}</{$type}>"; if (true == $out) { $this->output->writeLn($message); } } $this->getLog()->addInfo($message, array('type' => $type)); }
php
protected function printLn($message, $type='general', $out=true) { if (null == $message) { return; } if (null != $this->output) { $message = (null == $type) ? $message : "<{$type}>{$message}</{$type}>"; if (true == $out) { $this->output->writeLn($message); } } $this->getLog()->addInfo($message, array('type' => $type)); }
[ "protected", "function", "printLn", "(", "$", "message", ",", "$", "type", "=", "'general'", ",", "$", "out", "=", "true", ")", "{", "if", "(", "null", "==", "$", "message", ")", "{", "return", ";", "}", "if", "(", "null", "!=", "$", "this", "->", "output", ")", "{", "$", "message", "=", "(", "null", "==", "$", "type", ")", "?", "$", "message", ":", "\"<{$type}>{$message}</{$type}>\"", ";", "if", "(", "true", "==", "$", "out", ")", "{", "$", "this", "->", "output", "->", "writeLn", "(", "$", "message", ")", ";", "}", "}", "$", "this", "->", "getLog", "(", ")", "->", "addInfo", "(", "$", "message", ",", "array", "(", "'type'", "=>", "$", "type", ")", ")", ";", "}" ]
This method prints a line to the terminal. @param string $message Is the message @param string $type Is the type of message (warning|notice|general) @param bool $out Tells the method to print to the terminal or just log @return void
[ "This", "method", "prints", "a", "line", "to", "the", "terminal", "." ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L534-L546
11,005
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient.cleanEnvironments
protected function cleanEnvironments() { $environmentsWhichExist = array(); foreach ($this->getEnvironments() as $key => $environment) { $msg = "Cleaning environment from storage {$environment}"; if (true == $this->vagrentExists($environment)) { $environmentsWhichExist[] = $environment; $msg = "Not cleaning from storage {$environment}"; } $this->printLn($msg); } $this->setEnvironments($environmentsWhichExist); return $this; }
php
protected function cleanEnvironments() { $environmentsWhichExist = array(); foreach ($this->getEnvironments() as $key => $environment) { $msg = "Cleaning environment from storage {$environment}"; if (true == $this->vagrentExists($environment)) { $environmentsWhichExist[] = $environment; $msg = "Not cleaning from storage {$environment}"; } $this->printLn($msg); } $this->setEnvironments($environmentsWhichExist); return $this; }
[ "protected", "function", "cleanEnvironments", "(", ")", "{", "$", "environmentsWhichExist", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getEnvironments", "(", ")", "as", "$", "key", "=>", "$", "environment", ")", "{", "$", "msg", "=", "\"Cleaning environment from storage {$environment}\"", ";", "if", "(", "true", "==", "$", "this", "->", "vagrentExists", "(", "$", "environment", ")", ")", "{", "$", "environmentsWhichExist", "[", "]", "=", "$", "environment", ";", "$", "msg", "=", "\"Not cleaning from storage {$environment}\"", ";", "}", "$", "this", "->", "printLn", "(", "$", "msg", ")", ";", "}", "$", "this", "->", "setEnvironments", "(", "$", "environmentsWhichExist", ")", ";", "return", "$", "this", ";", "}" ]
This method iterates over the _environments. If there is no VagrantFile within that environment then it is removed from the list of _environments. @return $this
[ "This", "method", "iterates", "over", "the", "_environments", ".", "If", "there", "is", "no", "VagrantFile", "within", "that", "environment", "then", "it", "is", "removed", "from", "the", "list", "of", "_environments", "." ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L589-L603
11,006
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient.migrateEnvironments
protected function migrateEnvironments($oldStore) { $currentStore = $this->getFileName(); //As a local cache if (false == file_exists($oldStore)) { $this->printLn("Old store not found at {$oldStore}", 'error'); } else { $this->printLn("Old store found {$oldStore}"); } $this->setFileName($oldStore); $this->loadEnvironments(); $this->printLn("Old environments loaded"); $oldEnvironments = $this->getEnvironments(); $this->setFileName($currentStore); $this->loadEnvironments(); foreach ($oldEnvironments as $oldEnvironment) { /* * Doing it this way validates the environment exists * before adding them to the store */ $this->createEnvironment($oldEnvironment); } $this->save(); $this->printLn("Old environments appended onto current store"); $this->getEnvironments(); }
php
protected function migrateEnvironments($oldStore) { $currentStore = $this->getFileName(); //As a local cache if (false == file_exists($oldStore)) { $this->printLn("Old store not found at {$oldStore}", 'error'); } else { $this->printLn("Old store found {$oldStore}"); } $this->setFileName($oldStore); $this->loadEnvironments(); $this->printLn("Old environments loaded"); $oldEnvironments = $this->getEnvironments(); $this->setFileName($currentStore); $this->loadEnvironments(); foreach ($oldEnvironments as $oldEnvironment) { /* * Doing it this way validates the environment exists * before adding them to the store */ $this->createEnvironment($oldEnvironment); } $this->save(); $this->printLn("Old environments appended onto current store"); $this->getEnvironments(); }
[ "protected", "function", "migrateEnvironments", "(", "$", "oldStore", ")", "{", "$", "currentStore", "=", "$", "this", "->", "getFileName", "(", ")", ";", "//As a local cache", "if", "(", "false", "==", "file_exists", "(", "$", "oldStore", ")", ")", "{", "$", "this", "->", "printLn", "(", "\"Old store not found at {$oldStore}\"", ",", "'error'", ")", ";", "}", "else", "{", "$", "this", "->", "printLn", "(", "\"Old store found {$oldStore}\"", ")", ";", "}", "$", "this", "->", "setFileName", "(", "$", "oldStore", ")", ";", "$", "this", "->", "loadEnvironments", "(", ")", ";", "$", "this", "->", "printLn", "(", "\"Old environments loaded\"", ")", ";", "$", "oldEnvironments", "=", "$", "this", "->", "getEnvironments", "(", ")", ";", "$", "this", "->", "setFileName", "(", "$", "currentStore", ")", ";", "$", "this", "->", "loadEnvironments", "(", ")", ";", "foreach", "(", "$", "oldEnvironments", "as", "$", "oldEnvironment", ")", "{", "/*\n * Doing it this way validates the environment exists\n * before adding them to the store\n */", "$", "this", "->", "createEnvironment", "(", "$", "oldEnvironment", ")", ";", "}", "$", "this", "->", "save", "(", ")", ";", "$", "this", "->", "printLn", "(", "\"Old environments appended onto current store\"", ")", ";", "$", "this", "->", "getEnvironments", "(", ")", ";", "}" ]
This method migrates an old store to a new store. It does however validate that the environment is valid before adding it to the store. @param string $oldStore Is the path to the old store @return array of new environments
[ "This", "method", "migrates", "an", "old", "store", "to", "a", "new", "store", ".", "It", "does", "however", "validate", "that", "the", "environment", "is", "valid", "before", "adding", "it", "to", "the", "store", "." ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L614-L638
11,007
philelson/VagrantTransient
src/VagrantTransient.php
VagrantTransient.getLog
public function getLog() { if (null == $this->log) { $handler = new StreamHandler($this->_getLogFileName(), Logger::INFO); $this->log = new Logger('VagrantTransient'); $this->log->pushHandler($handler); } return $this->log; }
php
public function getLog() { if (null == $this->log) { $handler = new StreamHandler($this->_getLogFileName(), Logger::INFO); $this->log = new Logger('VagrantTransient'); $this->log->pushHandler($handler); } return $this->log; }
[ "public", "function", "getLog", "(", ")", "{", "if", "(", "null", "==", "$", "this", "->", "log", ")", "{", "$", "handler", "=", "new", "StreamHandler", "(", "$", "this", "->", "_getLogFileName", "(", ")", ",", "Logger", "::", "INFO", ")", ";", "$", "this", "->", "log", "=", "new", "Logger", "(", "'VagrantTransient'", ")", ";", "$", "this", "->", "log", "->", "pushHandler", "(", "$", "handler", ")", ";", "}", "return", "$", "this", "->", "log", ";", "}" ]
This method returns a singleton instance of the logger class. @return Logger
[ "This", "method", "returns", "a", "singleton", "instance", "of", "the", "logger", "class", "." ]
cd82523e175ee3786c1a262fb7e75c38f24c0eb1
https://github.com/philelson/VagrantTransient/blob/cd82523e175ee3786c1a262fb7e75c38f24c0eb1/src/VagrantTransient.php#L658-L666
11,008
radphp/cake-orm-bundle
Event/CakeORMSubscriber.php
CakeORMSubscriber.loadTableRegistryMap
public function loadTableRegistryMap(Event $event) { foreach (Bundles::getLoaded() as $bundleName) { $mapDir = Bundles::getPath($bundleName) . DS . 'Domain' . DS . 'map'; if (is_file($mapDir . DS . 'table_registry_config.php')) { require_once $mapDir . DS . 'table_registry_config.php'; } } }
php
public function loadTableRegistryMap(Event $event) { foreach (Bundles::getLoaded() as $bundleName) { $mapDir = Bundles::getPath($bundleName) . DS . 'Domain' . DS . 'map'; if (is_file($mapDir . DS . 'table_registry_config.php')) { require_once $mapDir . DS . 'table_registry_config.php'; } } }
[ "public", "function", "loadTableRegistryMap", "(", "Event", "$", "event", ")", "{", "foreach", "(", "Bundles", "::", "getLoaded", "(", ")", "as", "$", "bundleName", ")", "{", "$", "mapDir", "=", "Bundles", "::", "getPath", "(", "$", "bundleName", ")", ".", "DS", ".", "'Domain'", ".", "DS", ".", "'map'", ";", "if", "(", "is_file", "(", "$", "mapDir", ".", "DS", ".", "'table_registry_config.php'", ")", ")", "{", "require_once", "$", "mapDir", ".", "DS", ".", "'table_registry_config.php'", ";", "}", "}", "}" ]
Load table registry map @param Event $event @throws \Rad\Core\Exception\MissingBundleException
[ "Load", "table", "registry", "map" ]
bb0c917ece97910739badc54a9020e0216e98820
https://github.com/radphp/cake-orm-bundle/blob/bb0c917ece97910739badc54a9020e0216e98820/Event/CakeORMSubscriber.php#L33-L42
11,009
gliverphp/helpers
src/Upload/UploadClass.php
UploadClass.setUploadpath
public function setUploadpath($dir_name) { //set the value of upload_path property //set the upload path if($dir_name === null) $this->upload_path = Registry::getConfig()['upload_path']; else $this->upload_path = $dir_name; return $this; }
php
public function setUploadpath($dir_name) { //set the value of upload_path property //set the upload path if($dir_name === null) $this->upload_path = Registry::getConfig()['upload_path']; else $this->upload_path = $dir_name; return $this; }
[ "public", "function", "setUploadpath", "(", "$", "dir_name", ")", "{", "//set the value of upload_path property", "//set the upload path", "if", "(", "$", "dir_name", "===", "null", ")", "$", "this", "->", "upload_path", "=", "Registry", "::", "getConfig", "(", ")", "[", "'upload_path'", "]", ";", "else", "$", "this", "->", "upload_path", "=", "$", "dir_name", ";", "return", "$", "this", ";", "}" ]
This method sets the upload file path @param string $dir_name The directory where to upload the file @return \Object $this instance
[ "This", "method", "sets", "the", "upload", "file", "path" ]
c5204df8169fad55f5b273422e45f56164373ab8
https://github.com/gliverphp/helpers/blob/c5204df8169fad55f5b273422e45f56164373ab8/src/Upload/UploadClass.php#L69-L78
11,010
gliverphp/helpers
src/Upload/UploadClass.php
UploadClass.setTargetdir
public function setTargetdir() { //set the target dir $this->target_dir = Path::base() . $this->upload_path; //check if the directory exists and create if not if( ! file_exists($this->target_dir)) mkdir($this->target_dir); return $this; }
php
public function setTargetdir() { //set the target dir $this->target_dir = Path::base() . $this->upload_path; //check if the directory exists and create if not if( ! file_exists($this->target_dir)) mkdir($this->target_dir); return $this; }
[ "public", "function", "setTargetdir", "(", ")", "{", "//set the target dir", "$", "this", "->", "target_dir", "=", "Path", "::", "base", "(", ")", ".", "$", "this", "->", "upload_path", ";", "//check if the directory exists and create if not", "if", "(", "!", "file_exists", "(", "$", "this", "->", "target_dir", ")", ")", "mkdir", "(", "$", "this", "->", "target_dir", ")", ";", "return", "$", "this", ";", "}" ]
This method sets the upload target directory @param null @return \Object $this instance
[ "This", "method", "sets", "the", "upload", "target", "directory" ]
c5204df8169fad55f5b273422e45f56164373ab8
https://github.com/gliverphp/helpers/blob/c5204df8169fad55f5b273422e45f56164373ab8/src/Upload/UploadClass.php#L100-L110
11,011
gliverphp/helpers
src/Upload/UploadClass.php
UploadClass.setTargetfilename
public function setTargetfilename() { //set the value of target file name $this->target_file_name = sprintf('%s.%s',sha1_file($_FILES[$this->file_name]['tmp_name']),$this->file_type); return $this; }
php
public function setTargetfilename() { //set the value of target file name $this->target_file_name = sprintf('%s.%s',sha1_file($_FILES[$this->file_name]['tmp_name']),$this->file_type); return $this; }
[ "public", "function", "setTargetfilename", "(", ")", "{", "//set the value of target file name", "$", "this", "->", "target_file_name", "=", "sprintf", "(", "'%s.%s'", ",", "sha1_file", "(", "$", "_FILES", "[", "$", "this", "->", "file_name", "]", "[", "'tmp_name'", "]", ")", ",", "$", "this", "->", "file_type", ")", ";", "return", "$", "this", ";", "}" ]
This method sets a unique target file name @param null @return \Object $this instance
[ "This", "method", "sets", "a", "unique", "target", "file", "name" ]
c5204df8169fad55f5b273422e45f56164373ab8
https://github.com/gliverphp/helpers/blob/c5204df8169fad55f5b273422e45f56164373ab8/src/Upload/UploadClass.php#L133-L140
11,012
gliverphp/helpers
src/Upload/UploadClass.php
UploadClass.setTargetfile
public function setTargetfile() { //set the upload_path_relative $this->upload_path_relative = $this->upload_path . $this->target_file_name; //set the full target file path $this->target_file = $this->target_dir . $this->target_file_name; return $this; }
php
public function setTargetfile() { //set the upload_path_relative $this->upload_path_relative = $this->upload_path . $this->target_file_name; //set the full target file path $this->target_file = $this->target_dir . $this->target_file_name; return $this; }
[ "public", "function", "setTargetfile", "(", ")", "{", "//set the upload_path_relative", "$", "this", "->", "upload_path_relative", "=", "$", "this", "->", "upload_path", ".", "$", "this", "->", "target_file_name", ";", "//set the full target file path", "$", "this", "->", "target_file", "=", "$", "this", "->", "target_dir", ".", "$", "this", "->", "target_file_name", ";", "return", "$", "this", ";", "}" ]
This method sets the target file name @param null @return \Object $this instance
[ "This", "method", "sets", "the", "target", "file", "name" ]
c5204df8169fad55f5b273422e45f56164373ab8
https://github.com/gliverphp/helpers/blob/c5204df8169fad55f5b273422e45f56164373ab8/src/Upload/UploadClass.php#L148-L158
11,013
Arbitracker/VCSWrapper
src/main/php/Arbit/VCSWrapper/CvsCli/Checkout.php
Checkout.initialize
public function initialize($url, $user = null, $password = null) { $count = substr_count($url, '#'); if ($count === 1) { $revision = null; list($repoUrl, $module) = explode('#', $url); } elseif ($count === 2) { list($repoUrl, $module, $revision) = explode('#', $url); } else { throw new \UnexpectedValueException("No valid VCS url $url"); } $process = new \Arbit\VCSWrapper\CvsCli\Process(); $process ->argument('-d') ->argument($repoUrl) ->argument('checkout') ->argument('-P') ->argument('-r') ->argument($revision) ->argument('-d') ->argument($this->root) ->argument($module) ->execute(); }
php
public function initialize($url, $user = null, $password = null) { $count = substr_count($url, '#'); if ($count === 1) { $revision = null; list($repoUrl, $module) = explode('#', $url); } elseif ($count === 2) { list($repoUrl, $module, $revision) = explode('#', $url); } else { throw new \UnexpectedValueException("No valid VCS url $url"); } $process = new \Arbit\VCSWrapper\CvsCli\Process(); $process ->argument('-d') ->argument($repoUrl) ->argument('checkout') ->argument('-P') ->argument('-r') ->argument($revision) ->argument('-d') ->argument($this->root) ->argument($module) ->execute(); }
[ "public", "function", "initialize", "(", "$", "url", ",", "$", "user", "=", "null", ",", "$", "password", "=", "null", ")", "{", "$", "count", "=", "substr_count", "(", "$", "url", ",", "'#'", ")", ";", "if", "(", "$", "count", "===", "1", ")", "{", "$", "revision", "=", "null", ";", "list", "(", "$", "repoUrl", ",", "$", "module", ")", "=", "explode", "(", "'#'", ",", "$", "url", ")", ";", "}", "elseif", "(", "$", "count", "===", "2", ")", "{", "list", "(", "$", "repoUrl", ",", "$", "module", ",", "$", "revision", ")", "=", "explode", "(", "'#'", ",", "$", "url", ")", ";", "}", "else", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "\"No valid VCS url $url\"", ")", ";", "}", "$", "process", "=", "new", "\\", "Arbit", "\\", "VCSWrapper", "\\", "CvsCli", "\\", "Process", "(", ")", ";", "$", "process", "->", "argument", "(", "'-d'", ")", "->", "argument", "(", "$", "repoUrl", ")", "->", "argument", "(", "'checkout'", ")", "->", "argument", "(", "'-P'", ")", "->", "argument", "(", "'-r'", ")", "->", "argument", "(", "$", "revision", ")", "->", "argument", "(", "'-d'", ")", "->", "argument", "(", "$", "this", "->", "root", ")", "->", "argument", "(", "$", "module", ")", "->", "execute", "(", ")", ";", "}" ]
Initializes fresh checkout Initialize repository from the given URL. Optionally username and password may be passed to the method, if required for the repository. @param string $url @param string $user @param string $password @return void
[ "Initializes", "fresh", "checkout" ]
64907c0c438600ce67d79a5d17f5155563f2bbf2
https://github.com/Arbitracker/VCSWrapper/blob/64907c0c438600ce67d79a5d17f5155563f2bbf2/src/main/php/Arbit/VCSWrapper/CvsCli/Checkout.php#L62-L86
11,014
webriq/core
module/Core/src/Grid/Core/Form/Package/Multisite.php
Multisite.transformValues
public function transformValues( array $values ) { if ( ! empty( $values['gridguyz-multisite']['defaultDomain'] ) ) { $values['gridguyz-multisite']['defaultDomain'] = trim( $values['gridguyz-multisite']['defaultDomain'], '.' ); } if ( ! empty( $values['gridguyz-multisite']['domainPostfix'] ) ) { $values['gridguyz-multisite']['domainPostfix'] = '.' . trim( $values['gridguyz-multisite']['domainPostfix'], '.' ); } return $values; }
php
public function transformValues( array $values ) { if ( ! empty( $values['gridguyz-multisite']['defaultDomain'] ) ) { $values['gridguyz-multisite']['defaultDomain'] = trim( $values['gridguyz-multisite']['defaultDomain'], '.' ); } if ( ! empty( $values['gridguyz-multisite']['domainPostfix'] ) ) { $values['gridguyz-multisite']['domainPostfix'] = '.' . trim( $values['gridguyz-multisite']['domainPostfix'], '.' ); } return $values; }
[ "public", "function", "transformValues", "(", "array", "$", "values", ")", "{", "if", "(", "!", "empty", "(", "$", "values", "[", "'gridguyz-multisite'", "]", "[", "'defaultDomain'", "]", ")", ")", "{", "$", "values", "[", "'gridguyz-multisite'", "]", "[", "'defaultDomain'", "]", "=", "trim", "(", "$", "values", "[", "'gridguyz-multisite'", "]", "[", "'defaultDomain'", "]", ",", "'.'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "values", "[", "'gridguyz-multisite'", "]", "[", "'domainPostfix'", "]", ")", ")", "{", "$", "values", "[", "'gridguyz-multisite'", "]", "[", "'domainPostfix'", "]", "=", "'.'", ".", "trim", "(", "$", "values", "[", "'gridguyz-multisite'", "]", "[", "'domainPostfix'", "]", ",", "'.'", ")", ";", "}", "return", "$", "values", ";", "}" ]
Transform form values @param array $values @return array
[ "Transform", "form", "values" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/Core/src/Grid/Core/Form/Package/Multisite.php#L22-L41
11,015
dothiv/DothivValueObjectBundle
Dothiv/ValueObject/PathValue.php
PathValue.addFilenameSuffix
public function addFilenameSuffix($suffix) { $path = $this->fi->getPath(); $ext = $this->fi->getExtension(); $nameWithoutExtension = preg_replace('/\.' . $ext . '$/', '', $this->fi->getFilename()); $this->fi = new \SplFileInfo(sprintf('%s/%s%s.%s', $path, $nameWithoutExtension, $suffix, $ext)); return $this; }
php
public function addFilenameSuffix($suffix) { $path = $this->fi->getPath(); $ext = $this->fi->getExtension(); $nameWithoutExtension = preg_replace('/\.' . $ext . '$/', '', $this->fi->getFilename()); $this->fi = new \SplFileInfo(sprintf('%s/%s%s.%s', $path, $nameWithoutExtension, $suffix, $ext)); return $this; }
[ "public", "function", "addFilenameSuffix", "(", "$", "suffix", ")", "{", "$", "path", "=", "$", "this", "->", "fi", "->", "getPath", "(", ")", ";", "$", "ext", "=", "$", "this", "->", "fi", "->", "getExtension", "(", ")", ";", "$", "nameWithoutExtension", "=", "preg_replace", "(", "'/\\.'", ".", "$", "ext", ".", "'$/'", ",", "''", ",", "$", "this", "->", "fi", "->", "getFilename", "(", ")", ")", ";", "$", "this", "->", "fi", "=", "new", "\\", "SplFileInfo", "(", "sprintf", "(", "'%s/%s%s.%s'", ",", "$", "path", ",", "$", "nameWithoutExtension", ",", "$", "suffix", ",", "$", "ext", ")", ")", ";", "return", "$", "this", ";", "}" ]
Adds a suffix the the filename. @param $suffix @return self
[ "Adds", "a", "suffix", "the", "the", "filename", "." ]
a4b63b358622efea756ffea605c9eb12f2f143e8
https://github.com/dothiv/DothivValueObjectBundle/blob/a4b63b358622efea756ffea605c9eb12f2f143e8/Dothiv/ValueObject/PathValue.php#L67-L74
11,016
flowcode/AmulenPageBundle
src/Flowcode/PageBundle/DependencyInjection/FlowcodePageExtension.php
FlowcodePageExtension.bindParameters
public function bindParameters(ContainerBuilder $container, $name, $config) { if (is_array($config) && empty($config[0])) { foreach ($config as $key => $value) { $this->bindParameters($container, $name . '.' . $key, $value); } } else { $container->setParameter($name, $config); } }
php
public function bindParameters(ContainerBuilder $container, $name, $config) { if (is_array($config) && empty($config[0])) { foreach ($config as $key => $value) { $this->bindParameters($container, $name . '.' . $key, $value); } } else { $container->setParameter($name, $config); } }
[ "public", "function", "bindParameters", "(", "ContainerBuilder", "$", "container", ",", "$", "name", ",", "$", "config", ")", "{", "if", "(", "is_array", "(", "$", "config", ")", "&&", "empty", "(", "$", "config", "[", "0", "]", ")", ")", "{", "foreach", "(", "$", "config", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "bindParameters", "(", "$", "container", ",", "$", "name", ".", "'.'", ".", "$", "key", ",", "$", "value", ")", ";", "}", "}", "else", "{", "$", "container", "->", "setParameter", "(", "$", "name", ",", "$", "config", ")", ";", "}", "}" ]
Binds the params from config @param ContainerBuilder $container Containerbuilder @param string $name Alias name @param array $config Configuration Array
[ "Binds", "the", "params", "from", "config" ]
41c90e1860d5f51aeda13cb42993b17cf14cf89f
https://github.com/flowcode/AmulenPageBundle/blob/41c90e1860d5f51aeda13cb42993b17cf14cf89f/src/Flowcode/PageBundle/DependencyInjection/FlowcodePageExtension.php#L42-L50
11,017
phPoirot/Http
Header/CollectionHeader.php
CollectionHeader.has
function has($label) { $r = $this->getIterator()->find( array('label' => strtolower($label)) ); foreach ($r as $v) return true; return false; }
php
function has($label) { $r = $this->getIterator()->find( array('label' => strtolower($label)) ); foreach ($r as $v) return true; return false; }
[ "function", "has", "(", "$", "label", ")", "{", "$", "r", "=", "$", "this", "->", "getIterator", "(", ")", "->", "find", "(", "array", "(", "'label'", "=>", "strtolower", "(", "$", "label", ")", ")", ")", ";", "foreach", "(", "$", "r", "as", "$", "v", ")", "return", "true", ";", "return", "false", ";", "}" ]
Has Header With Specific Label? ! headers label are case-insensitive @param string $label @return bool
[ "Has", "Header", "With", "Specific", "Label?" ]
3230b3555abf0e74c3d593fc49c8978758969736
https://github.com/phPoirot/Http/blob/3230b3555abf0e74c3d593fc49c8978758969736/Header/CollectionHeader.php#L86-L93
11,018
phPoirot/Http
Header/CollectionHeader.php
CollectionHeader.del
function del($label) { if (! $this->has($label) ) return $this; // .. $headers = $this->getIterator()->find( array('label' => strtolower($label)) ); foreach ($headers as $hash => $header) $this->getIterator()->del($hash); return $this; }
php
function del($label) { if (! $this->has($label) ) return $this; // .. $headers = $this->getIterator()->find( array('label' => strtolower($label)) ); foreach ($headers as $hash => $header) $this->getIterator()->del($hash); return $this; }
[ "function", "del", "(", "$", "label", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "label", ")", ")", "return", "$", "this", ";", "// ..", "$", "headers", "=", "$", "this", "->", "getIterator", "(", ")", "->", "find", "(", "array", "(", "'label'", "=>", "strtolower", "(", "$", "label", ")", ")", ")", ";", "foreach", "(", "$", "headers", "as", "$", "hash", "=>", "$", "header", ")", "$", "this", "->", "getIterator", "(", ")", "->", "del", "(", "$", "hash", ")", ";", "return", "$", "this", ";", "}" ]
Delete a Header With Label Name @param string $label @return CollectionHeader
[ "Delete", "a", "Header", "With", "Label", "Name" ]
3230b3555abf0e74c3d593fc49c8978758969736
https://github.com/phPoirot/Http/blob/3230b3555abf0e74c3d593fc49c8978758969736/Header/CollectionHeader.php#L102-L114
11,019
helloandre/pressing
src/File.php
File.render
private function render() { $parsed_data = Parser::parse($this->input_path); if ($parsed_data['frontmatter'] !== false && !$this->should_ignore()) { return Template::render($parsed_data['content'], $parsed_data['frontmatter']); } return $parsed_data['content']; }
php
private function render() { $parsed_data = Parser::parse($this->input_path); if ($parsed_data['frontmatter'] !== false && !$this->should_ignore()) { return Template::render($parsed_data['content'], $parsed_data['frontmatter']); } return $parsed_data['content']; }
[ "private", "function", "render", "(", ")", "{", "$", "parsed_data", "=", "Parser", "::", "parse", "(", "$", "this", "->", "input_path", ")", ";", "if", "(", "$", "parsed_data", "[", "'frontmatter'", "]", "!==", "false", "&&", "!", "$", "this", "->", "should_ignore", "(", ")", ")", "{", "return", "Template", "::", "render", "(", "$", "parsed_data", "[", "'content'", "]", ",", "$", "parsed_data", "[", "'frontmatter'", "]", ")", ";", "}", "return", "$", "parsed_data", "[", "'content'", "]", ";", "}" ]
run this file through our templating engine
[ "run", "this", "file", "through", "our", "templating", "engine" ]
e4244c7bbe90c38fa7d45e3c2da5d4b9153a0f54
https://github.com/helloandre/pressing/blob/e4244c7bbe90c38fa7d45e3c2da5d4b9153a0f54/src/File.php#L52-L60
11,020
helloandre/pressing
src/File.php
File.output
public function output() { $parts = explode('/', $this->output_path); // get rid of the filename array_pop($parts); $path = implode('/', $parts); if ($path && !file_exists($path)) { if (!mkdir($path, 0777, true)) { throw new \Exception("could not make directory $path"); } } if (!file_put_contents($this->output_path, $this->render())) { throw new \Exception("could not write $filename"); } }
php
public function output() { $parts = explode('/', $this->output_path); // get rid of the filename array_pop($parts); $path = implode('/', $parts); if ($path && !file_exists($path)) { if (!mkdir($path, 0777, true)) { throw new \Exception("could not make directory $path"); } } if (!file_put_contents($this->output_path, $this->render())) { throw new \Exception("could not write $filename"); } }
[ "public", "function", "output", "(", ")", "{", "$", "parts", "=", "explode", "(", "'/'", ",", "$", "this", "->", "output_path", ")", ";", "// get rid of the filename", "array_pop", "(", "$", "parts", ")", ";", "$", "path", "=", "implode", "(", "'/'", ",", "$", "parts", ")", ";", "if", "(", "$", "path", "&&", "!", "file_exists", "(", "$", "path", ")", ")", "{", "if", "(", "!", "mkdir", "(", "$", "path", ",", "0777", ",", "true", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"could not make directory $path\"", ")", ";", "}", "}", "if", "(", "!", "file_put_contents", "(", "$", "this", "->", "output_path", ",", "$", "this", "->", "render", "(", ")", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"could not write $filename\"", ")", ";", "}", "}" ]
this file now has it's contents and it parsed we just need to put it where it needs to go
[ "this", "file", "now", "has", "it", "s", "contents", "and", "it", "parsed", "we", "just", "need", "to", "put", "it", "where", "it", "needs", "to", "go" ]
e4244c7bbe90c38fa7d45e3c2da5d4b9153a0f54
https://github.com/helloandre/pressing/blob/e4244c7bbe90c38fa7d45e3c2da5d4b9153a0f54/src/File.php#L66-L81
11,021
helloandre/pressing
src/File.php
File.should_ignore
private function should_ignore() { $parts = explode('.', $this->relative_path); $ext = strtolower(end($parts)); return in_array($ext, $this->should_ignore_extensions); }
php
private function should_ignore() { $parts = explode('.', $this->relative_path); $ext = strtolower(end($parts)); return in_array($ext, $this->should_ignore_extensions); }
[ "private", "function", "should_ignore", "(", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "this", "->", "relative_path", ")", ";", "$", "ext", "=", "strtolower", "(", "end", "(", "$", "parts", ")", ")", ";", "return", "in_array", "(", "$", "ext", ",", "$", "this", "->", "should_ignore_extensions", ")", ";", "}" ]
and it should be run through our template renderer @return bool
[ "and", "it", "should", "be", "run", "through", "our", "template", "renderer" ]
e4244c7bbe90c38fa7d45e3c2da5d4b9153a0f54
https://github.com/helloandre/pressing/blob/e4244c7bbe90c38fa7d45e3c2da5d4b9153a0f54/src/File.php#L88-L92
11,022
shopery/view
src/Factory/CompositeViewFactory.php
CompositeViewFactory.createView
public function createView($object) { foreach ($this->factories as $factory) { $view = $factory->createView($object); if (null !== $view) { return $view; } } }
php
public function createView($object) { foreach ($this->factories as $factory) { $view = $factory->createView($object); if (null !== $view) { return $view; } } }
[ "public", "function", "createView", "(", "$", "object", ")", "{", "foreach", "(", "$", "this", "->", "factories", "as", "$", "factory", ")", "{", "$", "view", "=", "$", "factory", "->", "createView", "(", "$", "object", ")", ";", "if", "(", "null", "!==", "$", "view", ")", "{", "return", "$", "view", ";", "}", "}", "}" ]
Create a view for the object, delegating to inner factories @param $object @return View
[ "Create", "a", "view", "for", "the", "object", "delegating", "to", "inner", "factories" ]
cc38154a2b649ec99e7eb13f79b99cdf143bd4af
https://github.com/shopery/view/blob/cc38154a2b649ec99e7eb13f79b99cdf143bd4af/src/Factory/CompositeViewFactory.php#L52-L61
11,023
emaphp/eMapper
lib/eMapper/Statement/Builder/StatementBuilder.php
StatementBuilder.getExpression
protected function getExpression($property, $argn = 0) { $type = $this->entity->getProperty($property)->getType(); return isset($type) ? ('%{' . "$argn:$type" . '}') : ('%{' . $argn . '}') ; }
php
protected function getExpression($property, $argn = 0) { $type = $this->entity->getProperty($property)->getType(); return isset($type) ? ('%{' . "$argn:$type" . '}') : ('%{' . $argn . '}') ; }
[ "protected", "function", "getExpression", "(", "$", "property", ",", "$", "argn", "=", "0", ")", "{", "$", "type", "=", "$", "this", "->", "entity", "->", "getProperty", "(", "$", "property", ")", "->", "getType", "(", ")", ";", "return", "isset", "(", "$", "type", ")", "?", "(", "'%{'", ".", "\"$argn:$type\"", ".", "'}'", ")", ":", "(", "'%{'", ".", "$", "argn", ".", "'}'", ")", ";", "}" ]
Returns the argument expression for the given property @param string $property @param int $argn @return string
[ "Returns", "the", "argument", "expression", "for", "the", "given", "property" ]
df7100e601d2a1363d07028a786b6ceb22271829
https://github.com/emaphp/eMapper/blob/df7100e601d2a1363d07028a786b6ceb22271829/lib/eMapper/Statement/Builder/StatementBuilder.php#L60-L63
11,024
prooph/link-file-connector
src/Service/FileTypeAdapter/LeagueCsvTypeAdapter.php
LeagueCsvTypeAdapter.readDataForType
public function readDataForType($filename, Prototype $prototype, array &$metadata = []) { if ($prototype->typeDescription()->nativeType() !== NativeType::COLLECTION) throw new \InvalidArgumentException('The CsvReader can only handle collections'); $itemPrototype = $prototype->typeProperties()['item']->typePrototype(); $propertyNames = array_keys($itemPrototype->typeProperties()); $reader = Reader::createFromPath($filename); if (array_key_exists('delimiter', $metadata)) $reader->setDelimiter($metadata['delimiter']); if (array_key_exists('enclosure', $metadata)) $reader->setEnclosure($metadata['enclosure']); if (array_key_exists('escape', $metadata)) $reader->setEscape($metadata['escape']); if (array_key_exists('file_encoding', $metadata)) $reader->setEncodingFrom($metadata['file_encoding']); $firstRow = $reader->fetchOne(); $offset_or_keys = 0; $iteratorFilters = []; if ($this->isValidKeysRow($firstRow, $propertyNames)) { $iteratorFilters[] = function ($row, $rowIndex) { return $rowIndex != 0; }; } else { $offset_or_keys = $propertyNames; } //Filter empty rows $iteratorFilters[] = function($row) { if (! is_array($row)) return false; if (empty($row)) return false; if (count($row) === 1) { $value = current($row); return ! empty($value); } return true; }; foreach($iteratorFilters as $iteratorFilter) $reader->addFilter($iteratorFilter); $metadata['total_items'] = $reader->each(function() { return true; }); if (array_key_exists('offset', $metadata)) $reader->setOffset($metadata['offset']); if (array_key_exists('limit', $metadata)) $reader->setLimit($metadata['limit']); foreach($iteratorFilters as $iteratorFilter) $reader->addFilter($iteratorFilter); return array_map(function($row) use ($itemPrototype) { return $this->convertToItemData($row, $itemPrototype); }, $reader->fetchAssoc($offset_or_keys)); }
php
public function readDataForType($filename, Prototype $prototype, array &$metadata = []) { if ($prototype->typeDescription()->nativeType() !== NativeType::COLLECTION) throw new \InvalidArgumentException('The CsvReader can only handle collections'); $itemPrototype = $prototype->typeProperties()['item']->typePrototype(); $propertyNames = array_keys($itemPrototype->typeProperties()); $reader = Reader::createFromPath($filename); if (array_key_exists('delimiter', $metadata)) $reader->setDelimiter($metadata['delimiter']); if (array_key_exists('enclosure', $metadata)) $reader->setEnclosure($metadata['enclosure']); if (array_key_exists('escape', $metadata)) $reader->setEscape($metadata['escape']); if (array_key_exists('file_encoding', $metadata)) $reader->setEncodingFrom($metadata['file_encoding']); $firstRow = $reader->fetchOne(); $offset_or_keys = 0; $iteratorFilters = []; if ($this->isValidKeysRow($firstRow, $propertyNames)) { $iteratorFilters[] = function ($row, $rowIndex) { return $rowIndex != 0; }; } else { $offset_or_keys = $propertyNames; } //Filter empty rows $iteratorFilters[] = function($row) { if (! is_array($row)) return false; if (empty($row)) return false; if (count($row) === 1) { $value = current($row); return ! empty($value); } return true; }; foreach($iteratorFilters as $iteratorFilter) $reader->addFilter($iteratorFilter); $metadata['total_items'] = $reader->each(function() { return true; }); if (array_key_exists('offset', $metadata)) $reader->setOffset($metadata['offset']); if (array_key_exists('limit', $metadata)) $reader->setLimit($metadata['limit']); foreach($iteratorFilters as $iteratorFilter) $reader->addFilter($iteratorFilter); return array_map(function($row) use ($itemPrototype) { return $this->convertToItemData($row, $itemPrototype); }, $reader->fetchAssoc($offset_or_keys)); }
[ "public", "function", "readDataForType", "(", "$", "filename", ",", "Prototype", "$", "prototype", ",", "array", "&", "$", "metadata", "=", "[", "]", ")", "{", "if", "(", "$", "prototype", "->", "typeDescription", "(", ")", "->", "nativeType", "(", ")", "!==", "NativeType", "::", "COLLECTION", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'The CsvReader can only handle collections'", ")", ";", "$", "itemPrototype", "=", "$", "prototype", "->", "typeProperties", "(", ")", "[", "'item'", "]", "->", "typePrototype", "(", ")", ";", "$", "propertyNames", "=", "array_keys", "(", "$", "itemPrototype", "->", "typeProperties", "(", ")", ")", ";", "$", "reader", "=", "Reader", "::", "createFromPath", "(", "$", "filename", ")", ";", "if", "(", "array_key_exists", "(", "'delimiter'", ",", "$", "metadata", ")", ")", "$", "reader", "->", "setDelimiter", "(", "$", "metadata", "[", "'delimiter'", "]", ")", ";", "if", "(", "array_key_exists", "(", "'enclosure'", ",", "$", "metadata", ")", ")", "$", "reader", "->", "setEnclosure", "(", "$", "metadata", "[", "'enclosure'", "]", ")", ";", "if", "(", "array_key_exists", "(", "'escape'", ",", "$", "metadata", ")", ")", "$", "reader", "->", "setEscape", "(", "$", "metadata", "[", "'escape'", "]", ")", ";", "if", "(", "array_key_exists", "(", "'file_encoding'", ",", "$", "metadata", ")", ")", "$", "reader", "->", "setEncodingFrom", "(", "$", "metadata", "[", "'file_encoding'", "]", ")", ";", "$", "firstRow", "=", "$", "reader", "->", "fetchOne", "(", ")", ";", "$", "offset_or_keys", "=", "0", ";", "$", "iteratorFilters", "=", "[", "]", ";", "if", "(", "$", "this", "->", "isValidKeysRow", "(", "$", "firstRow", ",", "$", "propertyNames", ")", ")", "{", "$", "iteratorFilters", "[", "]", "=", "function", "(", "$", "row", ",", "$", "rowIndex", ")", "{", "return", "$", "rowIndex", "!=", "0", ";", "}", ";", "}", "else", "{", "$", "offset_or_keys", "=", "$", "propertyNames", ";", "}", "//Filter empty rows", "$", "iteratorFilters", "[", "]", "=", "function", "(", "$", "row", ")", "{", "if", "(", "!", "is_array", "(", "$", "row", ")", ")", "return", "false", ";", "if", "(", "empty", "(", "$", "row", ")", ")", "return", "false", ";", "if", "(", "count", "(", "$", "row", ")", "===", "1", ")", "{", "$", "value", "=", "current", "(", "$", "row", ")", ";", "return", "!", "empty", "(", "$", "value", ")", ";", "}", "return", "true", ";", "}", ";", "foreach", "(", "$", "iteratorFilters", "as", "$", "iteratorFilter", ")", "$", "reader", "->", "addFilter", "(", "$", "iteratorFilter", ")", ";", "$", "metadata", "[", "'total_items'", "]", "=", "$", "reader", "->", "each", "(", "function", "(", ")", "{", "return", "true", ";", "}", ")", ";", "if", "(", "array_key_exists", "(", "'offset'", ",", "$", "metadata", ")", ")", "$", "reader", "->", "setOffset", "(", "$", "metadata", "[", "'offset'", "]", ")", ";", "if", "(", "array_key_exists", "(", "'limit'", ",", "$", "metadata", ")", ")", "$", "reader", "->", "setLimit", "(", "$", "metadata", "[", "'limit'", "]", ")", ";", "foreach", "(", "$", "iteratorFilters", "as", "$", "iteratorFilter", ")", "$", "reader", "->", "addFilter", "(", "$", "iteratorFilter", ")", ";", "return", "array_map", "(", "function", "(", "$", "row", ")", "use", "(", "$", "itemPrototype", ")", "{", "return", "$", "this", "->", "convertToItemData", "(", "$", "row", ",", "$", "itemPrototype", ")", ";", "}", ",", "$", "reader", "->", "fetchAssoc", "(", "$", "offset_or_keys", ")", ")", ";", "}" ]
Use League\Csv\Reader to fetch data from csv file The reader checks if the first row of the file is the header row otherwise it uses the property names of the prototype item to match columns. In this case the order in the file must be the same as defined in the prototype item. The second scenario should be avoided because it can lead to silent errors. @param string $filename @param Prototype $prototype @param array $metadata @throws \InvalidArgumentException @return array
[ "Use", "League", "\\", "Csv", "\\", "Reader", "to", "fetch", "data", "from", "csv", "file" ]
531698a67efc3f1c2d12a456103f2f42bfb5980a
https://github.com/prooph/link-file-connector/blob/531698a67efc3f1c2d12a456103f2f42bfb5980a/src/Service/FileTypeAdapter/LeagueCsvTypeAdapter.php#L42-L95
11,025
jivoo/http
src/Route/AssetScheme.php
AssetScheme.handleError
public function handleError(\Jivoo\Http\ActionRequest $request, \Psr\Http\Message\ResponseInterface $response) { if (isset($this->errorHandler)) { return call_user_func($this->errorHandler, $request, $response); } return $response->withBody(new \Jivoo\Http\Message\StringStream('Asset not found')) ->withStatus(\Jivoo\Http\Message\Status::NOT_FOUND); }
php
public function handleError(\Jivoo\Http\ActionRequest $request, \Psr\Http\Message\ResponseInterface $response) { if (isset($this->errorHandler)) { return call_user_func($this->errorHandler, $request, $response); } return $response->withBody(new \Jivoo\Http\Message\StringStream('Asset not found')) ->withStatus(\Jivoo\Http\Message\Status::NOT_FOUND); }
[ "public", "function", "handleError", "(", "\\", "Jivoo", "\\", "Http", "\\", "ActionRequest", "$", "request", ",", "\\", "Psr", "\\", "Http", "\\", "Message", "\\", "ResponseInterface", "$", "response", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "errorHandler", ")", ")", "{", "return", "call_user_func", "(", "$", "this", "->", "errorHandler", ",", "$", "request", ",", "$", "response", ")", ";", "}", "return", "$", "response", "->", "withBody", "(", "new", "\\", "Jivoo", "\\", "Http", "\\", "Message", "\\", "StringStream", "(", "'Asset not found'", ")", ")", "->", "withStatus", "(", "\\", "Jivoo", "\\", "Http", "\\", "Message", "\\", "Status", "::", "NOT_FOUND", ")", ";", "}" ]
Create the error response. @param \Jivoo\Http\ActionRequest $request Request. @param \Psr\Http\Message\ResponseInterface $response Response. @return \Psr\Http\Message\ResponseInterface Error response.
[ "Create", "the", "error", "response", "." ]
3c1d8dba66978bc91fc2b324dd941e5da3b253bc
https://github.com/jivoo/http/blob/3c1d8dba66978bc91fc2b324dd941e5da3b253bc/src/Route/AssetScheme.php#L56-L63
11,026
jivoo/http
src/Route/AssetScheme.php
AssetScheme.addPath
public function addPath($namespace, $path, $priority = 5) { if ($path != '') { $path = rtrim($path, '/') . '/'; } $namespace = '/' . trim($namespace, '/'); if (! isset($this->paths[$namespace])) { $this->paths[$namespace] = []; } $this->paths[$namespace][] = [ 'path' => $path, 'priority' => $priority ]; usort($this->paths[$namespace], ['Jivoo\Utilities', 'prioritySorter']); }
php
public function addPath($namespace, $path, $priority = 5) { if ($path != '') { $path = rtrim($path, '/') . '/'; } $namespace = '/' . trim($namespace, '/'); if (! isset($this->paths[$namespace])) { $this->paths[$namespace] = []; } $this->paths[$namespace][] = [ 'path' => $path, 'priority' => $priority ]; usort($this->paths[$namespace], ['Jivoo\Utilities', 'prioritySorter']); }
[ "public", "function", "addPath", "(", "$", "namespace", ",", "$", "path", ",", "$", "priority", "=", "5", ")", "{", "if", "(", "$", "path", "!=", "''", ")", "{", "$", "path", "=", "rtrim", "(", "$", "path", ",", "'/'", ")", ".", "'/'", ";", "}", "$", "namespace", "=", "'/'", ".", "trim", "(", "$", "namespace", ",", "'/'", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "paths", "[", "$", "namespace", "]", ")", ")", "{", "$", "this", "->", "paths", "[", "$", "namespace", "]", "=", "[", "]", ";", "}", "$", "this", "->", "paths", "[", "$", "namespace", "]", "[", "]", "=", "[", "'path'", "=>", "$", "path", ",", "'priority'", "=>", "$", "priority", "]", ";", "usort", "(", "$", "this", "->", "paths", "[", "$", "namespace", "]", ",", "[", "'Jivoo\\Utilities'", ",", "'prioritySorter'", "]", ")", ";", "}" ]
Add an asset path. @param string $namespace Asset namespace. @param string $path Path. @param int $priority Path priority.
[ "Add", "an", "asset", "path", "." ]
3c1d8dba66978bc91fc2b324dd941e5da3b253bc
https://github.com/jivoo/http/blob/3c1d8dba66978bc91fc2b324dd941e5da3b253bc/src/Route/AssetScheme.php#L90-L105
11,027
jivoo/http
src/Route/AssetScheme.php
AssetScheme.find
public function find($asset) { $asset = trim($asset, '/'); $namespace = '/'; while (true) { $file = $this->findIn($asset, $namespace); if (isset($file)) { return $file; } $pos = strpos($asset, '/'); if ($pos === false) { break; } $namespace = rtrim($namespace, '/') . '/' . substr($asset, 0, $pos); $asset = substr($asset, $pos + 1); } return null; }
php
public function find($asset) { $asset = trim($asset, '/'); $namespace = '/'; while (true) { $file = $this->findIn($asset, $namespace); if (isset($file)) { return $file; } $pos = strpos($asset, '/'); if ($pos === false) { break; } $namespace = rtrim($namespace, '/') . '/' . substr($asset, 0, $pos); $asset = substr($asset, $pos + 1); } return null; }
[ "public", "function", "find", "(", "$", "asset", ")", "{", "$", "asset", "=", "trim", "(", "$", "asset", ",", "'/'", ")", ";", "$", "namespace", "=", "'/'", ";", "while", "(", "true", ")", "{", "$", "file", "=", "$", "this", "->", "findIn", "(", "$", "asset", ",", "$", "namespace", ")", ";", "if", "(", "isset", "(", "$", "file", ")", ")", "{", "return", "$", "file", ";", "}", "$", "pos", "=", "strpos", "(", "$", "asset", ",", "'/'", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "{", "break", ";", "}", "$", "namespace", "=", "rtrim", "(", "$", "namespace", ",", "'/'", ")", ".", "'/'", ".", "substr", "(", "$", "asset", ",", "0", ",", "$", "pos", ")", ";", "$", "asset", "=", "substr", "(", "$", "asset", ",", "$", "pos", "+", "1", ")", ";", "}", "return", "null", ";", "}" ]
Find an asset. @param string $asset Asset name. @return string|null Asset path on server, or null if not found.
[ "Find", "an", "asset", "." ]
3c1d8dba66978bc91fc2b324dd941e5da3b253bc
https://github.com/jivoo/http/blob/3c1d8dba66978bc91fc2b324dd941e5da3b253bc/src/Route/AssetScheme.php#L113-L130
11,028
jivoo/http
src/Route/AssetScheme.php
AssetScheme.findIn
public function findIn($asset, $namespace) { if (! isset($this->paths[$namespace])) { return null; } foreach ($this->paths[$namespace] as $path) { $file = $path['path'] . $asset; if (is_file($file)) { return $file; } } return null; }
php
public function findIn($asset, $namespace) { if (! isset($this->paths[$namespace])) { return null; } foreach ($this->paths[$namespace] as $path) { $file = $path['path'] . $asset; if (is_file($file)) { return $file; } } return null; }
[ "public", "function", "findIn", "(", "$", "asset", ",", "$", "namespace", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "paths", "[", "$", "namespace", "]", ")", ")", "{", "return", "null", ";", "}", "foreach", "(", "$", "this", "->", "paths", "[", "$", "namespace", "]", "as", "$", "path", ")", "{", "$", "file", "=", "$", "path", "[", "'path'", "]", ".", "$", "asset", ";", "if", "(", "is_file", "(", "$", "file", ")", ")", "{", "return", "$", "file", ";", "}", "}", "return", "null", ";", "}" ]
Find an asset in a namsepace. @param string $asset Asset name. @param string $namespace Namespace. @return string|null Asset path on server, or null if not found.
[ "Find", "an", "asset", "in", "a", "namsepace", "." ]
3c1d8dba66978bc91fc2b324dd941e5da3b253bc
https://github.com/jivoo/http/blob/3c1d8dba66978bc91fc2b324dd941e5da3b253bc/src/Route/AssetScheme.php#L139-L151
11,029
BapCat/Propifier
src/PropifierTrait.php
PropifierTrait.buildDependencies
private static function buildDependencies($obj): void { $name = get_class($obj); if(!array_key_exists($name, self::$method_map)) { try { $class = new ReflectionClass($obj); } catch(ReflectionException $e) { throw new RuntimeException("This shouldn't be possible", 0, $e); } $methods = $class->getMethods(ReflectionMethod::IS_PROTECTED); $properties = self::filterProperties($methods); $inflector = Inflector::get(); $method_map = self::remapProperties([$inflector, 'underscore'], $properties); self::$method_map[$name] = self::extractProperties($method_map); } }
php
private static function buildDependencies($obj): void { $name = get_class($obj); if(!array_key_exists($name, self::$method_map)) { try { $class = new ReflectionClass($obj); } catch(ReflectionException $e) { throw new RuntimeException("This shouldn't be possible", 0, $e); } $methods = $class->getMethods(ReflectionMethod::IS_PROTECTED); $properties = self::filterProperties($methods); $inflector = Inflector::get(); $method_map = self::remapProperties([$inflector, 'underscore'], $properties); self::$method_map[$name] = self::extractProperties($method_map); } }
[ "private", "static", "function", "buildDependencies", "(", "$", "obj", ")", ":", "void", "{", "$", "name", "=", "get_class", "(", "$", "obj", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "self", "::", "$", "method_map", ")", ")", "{", "try", "{", "$", "class", "=", "new", "ReflectionClass", "(", "$", "obj", ")", ";", "}", "catch", "(", "ReflectionException", "$", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"This shouldn't be possible\"", ",", "0", ",", "$", "e", ")", ";", "}", "$", "methods", "=", "$", "class", "->", "getMethods", "(", "ReflectionMethod", "::", "IS_PROTECTED", ")", ";", "$", "properties", "=", "self", "::", "filterProperties", "(", "$", "methods", ")", ";", "$", "inflector", "=", "Inflector", "::", "get", "(", ")", ";", "$", "method_map", "=", "self", "::", "remapProperties", "(", "[", "$", "inflector", ",", "'underscore'", "]", ",", "$", "properties", ")", ";", "self", "::", "$", "method_map", "[", "$", "name", "]", "=", "self", "::", "extractProperties", "(", "$", "method_map", ")", ";", "}", "}" ]
Builds and caches the properties for a given object, if not already cached @throws MismatchedPropertiesException If one property is an array property and the other isn't @throws InvalidPropertyException If a property has an invalid number of arguments @param object $obj The object to cache @return void
[ "Builds", "and", "caches", "the", "properties", "for", "a", "given", "object", "if", "not", "already", "cached" ]
a106b89585a32b2660076b635fb77a3729f8eeda
https://github.com/BapCat/Propifier/blob/a106b89585a32b2660076b635fb77a3729f8eeda/src/PropifierTrait.php#L32-L51
11,030
BapCat/Propifier
src/PropifierTrait.php
PropifierTrait.filterProperties
private static function filterProperties(array $methods): array { return array_filter($methods, function(ReflectionMethod $method) { return (strlen($method->name) > 3) && ( (strpos($method->name, 'get') === 0) || (strpos($method->name, 'set') === 0) || (strpos($method->name, 'itr') === 0) ) ; }); }
php
private static function filterProperties(array $methods): array { return array_filter($methods, function(ReflectionMethod $method) { return (strlen($method->name) > 3) && ( (strpos($method->name, 'get') === 0) || (strpos($method->name, 'set') === 0) || (strpos($method->name, 'itr') === 0) ) ; }); }
[ "private", "static", "function", "filterProperties", "(", "array", "$", "methods", ")", ":", "array", "{", "return", "array_filter", "(", "$", "methods", ",", "function", "(", "ReflectionMethod", "$", "method", ")", "{", "return", "(", "strlen", "(", "$", "method", "->", "name", ")", ">", "3", ")", "&&", "(", "(", "strpos", "(", "$", "method", "->", "name", ",", "'get'", ")", "===", "0", ")", "||", "(", "strpos", "(", "$", "method", "->", "name", ",", "'set'", ")", "===", "0", ")", "||", "(", "strpos", "(", "$", "method", "->", "name", ",", "'itr'", ")", "===", "0", ")", ")", ";", "}", ")", ";", "}" ]
Filters out all methods that don't match the property signatures @param ReflectionMethod[] $methods An array of methods to filter @return ReflectionMethod[] The methods after filtering out non-properties
[ "Filters", "out", "all", "methods", "that", "don", "t", "match", "the", "property", "signatures" ]
a106b89585a32b2660076b635fb77a3729f8eeda
https://github.com/BapCat/Propifier/blob/a106b89585a32b2660076b635fb77a3729f8eeda/src/PropifierTrait.php#L60-L70
11,031
BapCat/Propifier
src/PropifierTrait.php
PropifierTrait.remapProperties
private static function remapProperties(callable $inflector, array $properties): array { $mapped = []; foreach($properties as $property) { $prop_name = $inflector(substr($property->name, 3)); if(!isset($mapped[$prop_name])) { $mapped[$prop_name] = ['get' => null, 'set' => null, 'itr' => null]; } $mapped[$prop_name][substr($property->name, 0, 3)] = $property; } return $mapped; }
php
private static function remapProperties(callable $inflector, array $properties): array { $mapped = []; foreach($properties as $property) { $prop_name = $inflector(substr($property->name, 3)); if(!isset($mapped[$prop_name])) { $mapped[$prop_name] = ['get' => null, 'set' => null, 'itr' => null]; } $mapped[$prop_name][substr($property->name, 0, 3)] = $property; } return $mapped; }
[ "private", "static", "function", "remapProperties", "(", "callable", "$", "inflector", ",", "array", "$", "properties", ")", ":", "array", "{", "$", "mapped", "=", "[", "]", ";", "foreach", "(", "$", "properties", "as", "$", "property", ")", "{", "$", "prop_name", "=", "$", "inflector", "(", "substr", "(", "$", "property", "->", "name", ",", "3", ")", ")", ";", "if", "(", "!", "isset", "(", "$", "mapped", "[", "$", "prop_name", "]", ")", ")", "{", "$", "mapped", "[", "$", "prop_name", "]", "=", "[", "'get'", "=>", "null", ",", "'set'", "=>", "null", ",", "'itr'", "=>", "null", "]", ";", "}", "$", "mapped", "[", "$", "prop_name", "]", "[", "substr", "(", "$", "property", "->", "name", ",", "0", ",", "3", ")", "]", "=", "$", "property", ";", "}", "return", "$", "mapped", ";", "}" ]
Transforms property names and pairs them up where applicable @param callable $inflector An instance of Inflector to transform property names @param ReflectionMethod[] $properties The properties to transform @return ReflectionMethod[][] The properties after transformation and pairing
[ "Transforms", "property", "names", "and", "pairs", "them", "up", "where", "applicable" ]
a106b89585a32b2660076b635fb77a3729f8eeda
https://github.com/BapCat/Propifier/blob/a106b89585a32b2660076b635fb77a3729f8eeda/src/PropifierTrait.php#L80-L94
11,032
BapCat/Propifier
src/PropifierTrait.php
PropifierTrait._propifier_getMethod
private function _propifier_getMethod(string $name, string $prefix) { if($this->_propifier_hasMethod($name, $prefix)) { return self::$method_map[get_class($this)][$name][$prefix]; } throw new NoSuchPropertyException($name); }
php
private function _propifier_getMethod(string $name, string $prefix) { if($this->_propifier_hasMethod($name, $prefix)) { return self::$method_map[get_class($this)][$name][$prefix]; } throw new NoSuchPropertyException($name); }
[ "private", "function", "_propifier_getMethod", "(", "string", "$", "name", ",", "string", "$", "prefix", ")", "{", "if", "(", "$", "this", "->", "_propifier_hasMethod", "(", "$", "name", ",", "$", "prefix", ")", ")", "{", "return", "self", "::", "$", "method_map", "[", "get_class", "(", "$", "this", ")", "]", "[", "$", "name", "]", "[", "$", "prefix", "]", ";", "}", "throw", "new", "NoSuchPropertyException", "(", "$", "name", ")", ";", "}" ]
Gets the accessor or mutator for a given property. This method will build the cache if necessary. @throws NoSuchPropertyException If there is no accessor or mutator for the property @throws MismatchedPropertiesException If one property is an array property and the other isn't @throws InvalidPropertyException If a property has an invalid number of arguments @param string $name The name of the property @param string $prefix The type of property (ie. get, set) @return string|ArrayProperty|null The executable property
[ "Gets", "the", "accessor", "or", "mutator", "for", "a", "given", "property", ".", "This", "method", "will", "build", "the", "cache", "if", "necessary", "." ]
a106b89585a32b2660076b635fb77a3729f8eeda
https://github.com/BapCat/Propifier/blob/a106b89585a32b2660076b635fb77a3729f8eeda/src/PropifierTrait.php#L170-L176
11,033
BapCat/Propifier
src/PropifierTrait.php
PropifierTrait._propifier_hasMethod
private function _propifier_hasMethod(string $name, string $prefix): bool { self::buildDependencies($this); return isset(self::$method_map[get_class($this)][$name][$prefix]); }
php
private function _propifier_hasMethod(string $name, string $prefix): bool { self::buildDependencies($this); return isset(self::$method_map[get_class($this)][$name][$prefix]); }
[ "private", "function", "_propifier_hasMethod", "(", "string", "$", "name", ",", "string", "$", "prefix", ")", ":", "bool", "{", "self", "::", "buildDependencies", "(", "$", "this", ")", ";", "return", "isset", "(", "self", "::", "$", "method_map", "[", "get_class", "(", "$", "this", ")", "]", "[", "$", "name", "]", "[", "$", "prefix", "]", ")", ";", "}" ]
Checks if a given property exists. This method will build the cache if necessary. @throws MismatchedPropertiesException If one property is an array property and the other isn't @throws InvalidPropertyException If a property has an invalid number of arguments @param string $name The name of the property @param string $prefix The type of property (ie. get, set) @return bool True if the property exists, false otherwise
[ "Checks", "if", "a", "given", "property", "exists", ".", "This", "method", "will", "build", "the", "cache", "if", "necessary", "." ]
a106b89585a32b2660076b635fb77a3729f8eeda
https://github.com/BapCat/Propifier/blob/a106b89585a32b2660076b635fb77a3729f8eeda/src/PropifierTrait.php#L189-L193
11,034
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.createAttachmentSchema
protected function createAttachmentSchema(array $config) { $storage = $this->getStorage($config['storage']); return new AttachmentSchema($storage, $config['hash_callable'], $config['storage_depth']); }
php
protected function createAttachmentSchema(array $config) { $storage = $this->getStorage($config['storage']); return new AttachmentSchema($storage, $config['hash_callable'], $config['storage_depth']); }
[ "protected", "function", "createAttachmentSchema", "(", "array", "$", "config", ")", "{", "$", "storage", "=", "$", "this", "->", "getStorage", "(", "$", "config", "[", "'storage'", "]", ")", ";", "return", "new", "AttachmentSchema", "(", "$", "storage", ",", "$", "config", "[", "'hash_callable'", "]", ",", "$", "config", "[", "'storage_depth'", "]", ")", ";", "}" ]
Create AttachmentSchema object holding information about how to handle specific model classes and field names. @param array $config @throws StorageDoesNotExistException @return AttachmentSchema
[ "Create", "AttachmentSchema", "object", "holding", "information", "about", "how", "to", "handle", "specific", "model", "classes", "and", "field", "names", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L122-L127
11,035
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.storeAndAttachFile
public function storeAndAttachFile(File $file, AttachableObjectInterface $object, $fieldName = null, $deleteAfterCopy = null, $customFilename = null) { $this->checkAttachableObject($object); if (null === $deleteAfterCopy) { $deleteAfterCopy = $this->guessDeleteAfterCopy($file, $object, $fieldName); } $this->checkFile($file, $deleteAfterCopy); $fileKey = $this->generateKey($file, $object, $fieldName); $this->copyToStorage($file, $fileKey); $attachment = $this->saveToDatabase($file, $object, $fieldName, $fileKey, $customFilename); if ($deleteAfterCopy) { unlink($file->getRealPath()); } return $attachment; }
php
public function storeAndAttachFile(File $file, AttachableObjectInterface $object, $fieldName = null, $deleteAfterCopy = null, $customFilename = null) { $this->checkAttachableObject($object); if (null === $deleteAfterCopy) { $deleteAfterCopy = $this->guessDeleteAfterCopy($file, $object, $fieldName); } $this->checkFile($file, $deleteAfterCopy); $fileKey = $this->generateKey($file, $object, $fieldName); $this->copyToStorage($file, $fileKey); $attachment = $this->saveToDatabase($file, $object, $fieldName, $fileKey, $customFilename); if ($deleteAfterCopy) { unlink($file->getRealPath()); } return $attachment; }
[ "public", "function", "storeAndAttachFile", "(", "File", "$", "file", ",", "AttachableObjectInterface", "$", "object", ",", "$", "fieldName", "=", "null", ",", "$", "deleteAfterCopy", "=", "null", ",", "$", "customFilename", "=", "null", ")", "{", "$", "this", "->", "checkAttachableObject", "(", "$", "object", ")", ";", "if", "(", "null", "===", "$", "deleteAfterCopy", ")", "{", "$", "deleteAfterCopy", "=", "$", "this", "->", "guessDeleteAfterCopy", "(", "$", "file", ",", "$", "object", ",", "$", "fieldName", ")", ";", "}", "$", "this", "->", "checkFile", "(", "$", "file", ",", "$", "deleteAfterCopy", ")", ";", "$", "fileKey", "=", "$", "this", "->", "generateKey", "(", "$", "file", ",", "$", "object", ",", "$", "fieldName", ")", ";", "$", "this", "->", "copyToStorage", "(", "$", "file", ",", "$", "fileKey", ")", ";", "$", "attachment", "=", "$", "this", "->", "saveToDatabase", "(", "$", "file", ",", "$", "object", ",", "$", "fieldName", ",", "$", "fileKey", ",", "$", "customFilename", ")", ";", "if", "(", "$", "deleteAfterCopy", ")", "{", "unlink", "(", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "}", "return", "$", "attachment", ";", "}" ]
Store a new attachment file for the given object and optional object field name. There is no need for the field name to exist explicitly inside the object. @throws InputFileNotReadableException @throws InputFileNotWritableException @throws CouldNotWriteToStorageException @param File $file @param AttachableObjectInterface $object @param string $fieldName @param boolean $deleteAfterCopy Override default file deletion behavior @param string $customFilename Optional custom file name to use for the created link @return Attachment The created Attachment object
[ "Store", "a", "new", "attachment", "file", "for", "the", "given", "object", "and", "optional", "object", "field", "name", ".", "There", "is", "no", "need", "for", "the", "field", "name", "to", "exist", "explicitly", "inside", "the", "object", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L145-L167
11,036
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.checkFile
protected function checkFile(File $file, $deleteAfterCopy) { if (!$file->isReadable()) { throw new InputFileNotReadableException('File ' . $file->getRealPath() . ' is not readable'); } if ($deleteAfterCopy && !$file->isWritable()) { throw new InputFileNotWritableException('File ' . $file->getRealPath() . ' is not writable'); } return true; }
php
protected function checkFile(File $file, $deleteAfterCopy) { if (!$file->isReadable()) { throw new InputFileNotReadableException('File ' . $file->getRealPath() . ' is not readable'); } if ($deleteAfterCopy && !$file->isWritable()) { throw new InputFileNotWritableException('File ' . $file->getRealPath() . ' is not writable'); } return true; }
[ "protected", "function", "checkFile", "(", "File", "$", "file", ",", "$", "deleteAfterCopy", ")", "{", "if", "(", "!", "$", "file", "->", "isReadable", "(", ")", ")", "{", "throw", "new", "InputFileNotReadableException", "(", "'File '", ".", "$", "file", "->", "getRealPath", "(", ")", ".", "' is not readable'", ")", ";", "}", "if", "(", "$", "deleteAfterCopy", "&&", "!", "$", "file", "->", "isWritable", "(", ")", ")", "{", "throw", "new", "InputFileNotWritableException", "(", "'File '", ".", "$", "file", "->", "getRealPath", "(", ")", ".", "' is not writable'", ")", ";", "}", "return", "true", ";", "}" ]
Perform some checks to see if the given file is valid and ready to use. @throws InputFileNotReadableException @throws InputFileNotWritableException @param File $file @param boolean $deleteAfterCopy @return boolean
[ "Perform", "some", "checks", "to", "see", "if", "the", "given", "file", "is", "valid", "and", "ready", "to", "use", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L265-L278
11,037
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.generateKey
protected function generateKey(File $file, AttachableObjectInterface $object, $fieldName) { $schema = $this->getSchemaForObject($object, $fieldName); if ($file instanceof UploadedFile) { $extension = $file->getClientOriginalExtension(); } else { $extension = $file->getExtension(); } $hash = $this->generateFileHash($file, $schema); $fileKey = new $this->fileKeyClass(); $fileKey ->setHash($hash) ->setExtension($extension) ->setDepth($schema->getStorageDepth()) ->setClassName($object->getAttachableClassName()) ->setFieldName($fieldName) ->setStorageName($schema->getStorage()->getName()) ; // This triggers the generation inside the key. If there are any exceptions, we want them here for clarity. $fileKey->getKey(); return $fileKey; }
php
protected function generateKey(File $file, AttachableObjectInterface $object, $fieldName) { $schema = $this->getSchemaForObject($object, $fieldName); if ($file instanceof UploadedFile) { $extension = $file->getClientOriginalExtension(); } else { $extension = $file->getExtension(); } $hash = $this->generateFileHash($file, $schema); $fileKey = new $this->fileKeyClass(); $fileKey ->setHash($hash) ->setExtension($extension) ->setDepth($schema->getStorageDepth()) ->setClassName($object->getAttachableClassName()) ->setFieldName($fieldName) ->setStorageName($schema->getStorage()->getName()) ; // This triggers the generation inside the key. If there are any exceptions, we want them here for clarity. $fileKey->getKey(); return $fileKey; }
[ "protected", "function", "generateKey", "(", "File", "$", "file", ",", "AttachableObjectInterface", "$", "object", ",", "$", "fieldName", ")", "{", "$", "schema", "=", "$", "this", "->", "getSchemaForObject", "(", "$", "object", ",", "$", "fieldName", ")", ";", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "$", "extension", "=", "$", "file", "->", "getClientOriginalExtension", "(", ")", ";", "}", "else", "{", "$", "extension", "=", "$", "file", "->", "getExtension", "(", ")", ";", "}", "$", "hash", "=", "$", "this", "->", "generateFileHash", "(", "$", "file", ",", "$", "schema", ")", ";", "$", "fileKey", "=", "new", "$", "this", "->", "fileKeyClass", "(", ")", ";", "$", "fileKey", "->", "setHash", "(", "$", "hash", ")", "->", "setExtension", "(", "$", "extension", ")", "->", "setDepth", "(", "$", "schema", "->", "getStorageDepth", "(", ")", ")", "->", "setClassName", "(", "$", "object", "->", "getAttachableClassName", "(", ")", ")", "->", "setFieldName", "(", "$", "fieldName", ")", "->", "setStorageName", "(", "$", "schema", "->", "getStorage", "(", ")", "->", "getName", "(", ")", ")", ";", "// This triggers the generation inside the key. If there are any exceptions, we want them here for clarity.", "$", "fileKey", "->", "getKey", "(", ")", ";", "return", "$", "fileKey", ";", "}" ]
Generate the file key for the given file path and config. @param File $file @param AttachmentSchema $schema @return FileKey
[ "Generate", "the", "file", "key", "for", "the", "given", "file", "path", "and", "config", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L313-L342
11,038
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.generateFileHash
protected function generateFileHash(File $file, AttachmentSchema $schema) { return call_user_func($schema->getHashCallable(), $file->getRealPath()); }
php
protected function generateFileHash(File $file, AttachmentSchema $schema) { return call_user_func($schema->getHashCallable(), $file->getRealPath()); }
[ "protected", "function", "generateFileHash", "(", "File", "$", "file", ",", "AttachmentSchema", "$", "schema", ")", "{", "return", "call_user_func", "(", "$", "schema", "->", "getHashCallable", "(", ")", ",", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "}" ]
This generates the actual file hash by calling the hash callable, passing the file path. @param File $file @param AttachmentSchema $schema @return string
[ "This", "generates", "the", "actual", "file", "hash", "by", "calling", "the", "hash", "callable", "passing", "the", "file", "path", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L352-L355
11,039
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.getStorage
protected function getStorage($name) { if (!array_key_exists($name, $this->storages)) { throw new StorageDoesNotExistException('Invalid storage name: '.$name); } return $this->storages[$name]; }
php
protected function getStorage($name) { if (!array_key_exists($name, $this->storages)) { throw new StorageDoesNotExistException('Invalid storage name: '.$name); } return $this->storages[$name]; }
[ "protected", "function", "getStorage", "(", "$", "name", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "storages", ")", ")", "{", "throw", "new", "StorageDoesNotExistException", "(", "'Invalid storage name: '", ".", "$", "name", ")", ";", "}", "return", "$", "this", "->", "storages", "[", "$", "name", "]", ";", "}" ]
Get the storage with the given name @param string $name @return Storage
[ "Get", "the", "storage", "with", "the", "given", "name" ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L364-L372
11,040
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.copyToStorage
protected function copyToStorage(File $file, FileKey $fileKey) { $storage = $this->getStorage($fileKey->getStorageName()); $storagePath = $this->getStoragePath($storage, $fileKey); $filesystem = $storage->getFilesystem(); if (!$filesystem->has($storagePath)) { $size = $file->getSize(); $writtenSize = $filesystem->write($storagePath, file_get_contents($file->getRealPath())); if ($writtenSize != $size) { throw new CouldNotWriteToStorageException('Error copying file ' . $file->getRealPath() . ' to storage'); } } }
php
protected function copyToStorage(File $file, FileKey $fileKey) { $storage = $this->getStorage($fileKey->getStorageName()); $storagePath = $this->getStoragePath($storage, $fileKey); $filesystem = $storage->getFilesystem(); if (!$filesystem->has($storagePath)) { $size = $file->getSize(); $writtenSize = $filesystem->write($storagePath, file_get_contents($file->getRealPath())); if ($writtenSize != $size) { throw new CouldNotWriteToStorageException('Error copying file ' . $file->getRealPath() . ' to storage'); } } }
[ "protected", "function", "copyToStorage", "(", "File", "$", "file", ",", "FileKey", "$", "fileKey", ")", "{", "$", "storage", "=", "$", "this", "->", "getStorage", "(", "$", "fileKey", "->", "getStorageName", "(", ")", ")", ";", "$", "storagePath", "=", "$", "this", "->", "getStoragePath", "(", "$", "storage", ",", "$", "fileKey", ")", ";", "$", "filesystem", "=", "$", "storage", "->", "getFilesystem", "(", ")", ";", "if", "(", "!", "$", "filesystem", "->", "has", "(", "$", "storagePath", ")", ")", "{", "$", "size", "=", "$", "file", "->", "getSize", "(", ")", ";", "$", "writtenSize", "=", "$", "filesystem", "->", "write", "(", "$", "storagePath", ",", "file_get_contents", "(", "$", "file", "->", "getRealPath", "(", ")", ")", ")", ";", "if", "(", "$", "writtenSize", "!=", "$", "size", ")", "{", "throw", "new", "CouldNotWriteToStorageException", "(", "'Error copying file '", ".", "$", "file", "->", "getRealPath", "(", ")", ".", "' to storage'", ")", ";", "}", "}", "}" ]
Move the file to the storage as defined in the given file key. @param File $file @param string $fileKey
[ "Move", "the", "file", "to", "the", "storage", "as", "defined", "in", "the", "given", "file", "key", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L380-L396
11,041
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.getStoragePath
protected function getStoragePath(Storage $storage, FileKey $fileKey) { return ltrim($storage->getPathPrefix().'/'.$fileKey->getFilePath(), '/'); }
php
protected function getStoragePath(Storage $storage, FileKey $fileKey) { return ltrim($storage->getPathPrefix().'/'.$fileKey->getFilePath(), '/'); }
[ "protected", "function", "getStoragePath", "(", "Storage", "$", "storage", ",", "FileKey", "$", "fileKey", ")", "{", "return", "ltrim", "(", "$", "storage", "->", "getPathPrefix", "(", ")", ".", "'/'", ".", "$", "fileKey", "->", "getFilePath", "(", ")", ",", "'/'", ")", ";", "}" ]
Get the path inside the storage for the given Storage and FileKey. @param Storage $storage @param FileKey $fileKey @return string
[ "Get", "the", "path", "inside", "the", "storage", "for", "the", "given", "Storage", "and", "FileKey", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L406-L409
11,042
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.saveToDatabase
protected function saveToDatabase(File $file, AttachableObjectInterface $object, $fieldName, FileKey $fileKey, $customFilename = null) { $attachment = $this->getOrCreateAttachment($file, $object, $fieldName, $fileKey); $link = $this->createAttachmentLink($file, $object, $fieldName, $attachment, $customFilename); if (in_array($fieldName, $object->getAttachableFieldNames())) { $method = 'set'.$fieldName.'Attachment'; if (!method_exists($object, $method)) { throw new InvalidAttachableFieldNameException('Fieldname setter for '.$fieldName.' does not exist in '.get_class($object)); } $object->$method($attachment); $link->setIsCurrent(true); AttachmentLinkQuery::create() ->filterByAttachableObject($object) ->filterByModelField($fieldName) ->doUpdate(array('IsCurrent' => false), \Propel::getConnection()) ; } $link->save(); return $attachment; }
php
protected function saveToDatabase(File $file, AttachableObjectInterface $object, $fieldName, FileKey $fileKey, $customFilename = null) { $attachment = $this->getOrCreateAttachment($file, $object, $fieldName, $fileKey); $link = $this->createAttachmentLink($file, $object, $fieldName, $attachment, $customFilename); if (in_array($fieldName, $object->getAttachableFieldNames())) { $method = 'set'.$fieldName.'Attachment'; if (!method_exists($object, $method)) { throw new InvalidAttachableFieldNameException('Fieldname setter for '.$fieldName.' does not exist in '.get_class($object)); } $object->$method($attachment); $link->setIsCurrent(true); AttachmentLinkQuery::create() ->filterByAttachableObject($object) ->filterByModelField($fieldName) ->doUpdate(array('IsCurrent' => false), \Propel::getConnection()) ; } $link->save(); return $attachment; }
[ "protected", "function", "saveToDatabase", "(", "File", "$", "file", ",", "AttachableObjectInterface", "$", "object", ",", "$", "fieldName", ",", "FileKey", "$", "fileKey", ",", "$", "customFilename", "=", "null", ")", "{", "$", "attachment", "=", "$", "this", "->", "getOrCreateAttachment", "(", "$", "file", ",", "$", "object", ",", "$", "fieldName", ",", "$", "fileKey", ")", ";", "$", "link", "=", "$", "this", "->", "createAttachmentLink", "(", "$", "file", ",", "$", "object", ",", "$", "fieldName", ",", "$", "attachment", ",", "$", "customFilename", ")", ";", "if", "(", "in_array", "(", "$", "fieldName", ",", "$", "object", "->", "getAttachableFieldNames", "(", ")", ")", ")", "{", "$", "method", "=", "'set'", ".", "$", "fieldName", ".", "'Attachment'", ";", "if", "(", "!", "method_exists", "(", "$", "object", ",", "$", "method", ")", ")", "{", "throw", "new", "InvalidAttachableFieldNameException", "(", "'Fieldname setter for '", ".", "$", "fieldName", ".", "' does not exist in '", ".", "get_class", "(", "$", "object", ")", ")", ";", "}", "$", "object", "->", "$", "method", "(", "$", "attachment", ")", ";", "$", "link", "->", "setIsCurrent", "(", "true", ")", ";", "AttachmentLinkQuery", "::", "create", "(", ")", "->", "filterByAttachableObject", "(", "$", "object", ")", "->", "filterByModelField", "(", "$", "fieldName", ")", "->", "doUpdate", "(", "array", "(", "'IsCurrent'", "=>", "false", ")", ",", "\\", "Propel", "::", "getConnection", "(", ")", ")", ";", "}", "$", "link", "->", "save", "(", ")", ";", "return", "$", "attachment", ";", "}" ]
Perform filling and saving of attachment database object @throws InvalidAttachableFieldNameException @param File $file @param AttachableObjectInterface $object @param string $fieldName @param FileKey $fileKey @return Attachment
[ "Perform", "filling", "and", "saving", "of", "attachment", "database", "object" ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L423-L450
11,043
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.getOrCreateAttachment
protected function getOrCreateAttachment(File $file, AttachableObjectInterface $object, $fieldName, FileKey $fileKey) { $attachment = $this->getAttachment($fileKey->getKey()); if (null === $attachment) { $schema = $this->getSchemaForObject($object, $fieldName); $attachment = new Attachment(); $attachment ->setFileKey($fileKey->getKey()) ->setFileSize($file->getSize()) ->setFileType($file->getMimeType()) ->setStorageName($schema->getStorage()->getName()) ->setStorageDepth($schema->getStorageDepth()) ->setHashType($schema->getHashCallableAsString()) ; } return $attachment; }
php
protected function getOrCreateAttachment(File $file, AttachableObjectInterface $object, $fieldName, FileKey $fileKey) { $attachment = $this->getAttachment($fileKey->getKey()); if (null === $attachment) { $schema = $this->getSchemaForObject($object, $fieldName); $attachment = new Attachment(); $attachment ->setFileKey($fileKey->getKey()) ->setFileSize($file->getSize()) ->setFileType($file->getMimeType()) ->setStorageName($schema->getStorage()->getName()) ->setStorageDepth($schema->getStorageDepth()) ->setHashType($schema->getHashCallableAsString()) ; } return $attachment; }
[ "protected", "function", "getOrCreateAttachment", "(", "File", "$", "file", ",", "AttachableObjectInterface", "$", "object", ",", "$", "fieldName", ",", "FileKey", "$", "fileKey", ")", "{", "$", "attachment", "=", "$", "this", "->", "getAttachment", "(", "$", "fileKey", "->", "getKey", "(", ")", ")", ";", "if", "(", "null", "===", "$", "attachment", ")", "{", "$", "schema", "=", "$", "this", "->", "getSchemaForObject", "(", "$", "object", ",", "$", "fieldName", ")", ";", "$", "attachment", "=", "new", "Attachment", "(", ")", ";", "$", "attachment", "->", "setFileKey", "(", "$", "fileKey", "->", "getKey", "(", ")", ")", "->", "setFileSize", "(", "$", "file", "->", "getSize", "(", ")", ")", "->", "setFileType", "(", "$", "file", "->", "getMimeType", "(", ")", ")", "->", "setStorageName", "(", "$", "schema", "->", "getStorage", "(", ")", "->", "getName", "(", ")", ")", "->", "setStorageDepth", "(", "$", "schema", "->", "getStorageDepth", "(", ")", ")", "->", "setHashType", "(", "$", "schema", "->", "getHashCallableAsString", "(", ")", ")", ";", "}", "return", "$", "attachment", ";", "}" ]
Get a new Attachment object or an existing one if a file with the same key was already stored. @param File $file @param AttachableObjectInterface $object @param string $fieldName @param FileKey $fileKey @return Attachment
[ "Get", "a", "new", "Attachment", "object", "or", "an", "existing", "one", "if", "a", "file", "with", "the", "same", "key", "was", "already", "stored", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L462-L482
11,044
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.createAttachmentLink
protected function createAttachmentLink(File $file, AttachableObjectInterface $object, $fieldName, Attachment $attachment, $customFilename = null) { if ($file instanceof UploadedFile) { $extension = $file->getClientOriginalExtension(); $filename = $file->getClientOriginalName(); $basename = basename($filename, '.'.$extension); } else { $extension = $file->getExtension(); $filename = $file->getFilename(); $basename = $file->getBasename('.'.$extension); } if (null !== $customFilename) { $filename = $customFilename; $basename = basename($filename, '.'.$extension); } $link = new AttachmentLink(); $link ->setAttachment($attachment) ->setModelName($object->getAttachableClassName()) ->setModelId($object->getAttachableId()) ->setModelField($fieldName) ->setFileName($filename) ->setFileExtension($extension) ->setCustomName($basename) ; return $link; }
php
protected function createAttachmentLink(File $file, AttachableObjectInterface $object, $fieldName, Attachment $attachment, $customFilename = null) { if ($file instanceof UploadedFile) { $extension = $file->getClientOriginalExtension(); $filename = $file->getClientOriginalName(); $basename = basename($filename, '.'.$extension); } else { $extension = $file->getExtension(); $filename = $file->getFilename(); $basename = $file->getBasename('.'.$extension); } if (null !== $customFilename) { $filename = $customFilename; $basename = basename($filename, '.'.$extension); } $link = new AttachmentLink(); $link ->setAttachment($attachment) ->setModelName($object->getAttachableClassName()) ->setModelId($object->getAttachableId()) ->setModelField($fieldName) ->setFileName($filename) ->setFileExtension($extension) ->setCustomName($basename) ; return $link; }
[ "protected", "function", "createAttachmentLink", "(", "File", "$", "file", ",", "AttachableObjectInterface", "$", "object", ",", "$", "fieldName", ",", "Attachment", "$", "attachment", ",", "$", "customFilename", "=", "null", ")", "{", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "$", "extension", "=", "$", "file", "->", "getClientOriginalExtension", "(", ")", ";", "$", "filename", "=", "$", "file", "->", "getClientOriginalName", "(", ")", ";", "$", "basename", "=", "basename", "(", "$", "filename", ",", "'.'", ".", "$", "extension", ")", ";", "}", "else", "{", "$", "extension", "=", "$", "file", "->", "getExtension", "(", ")", ";", "$", "filename", "=", "$", "file", "->", "getFilename", "(", ")", ";", "$", "basename", "=", "$", "file", "->", "getBasename", "(", "'.'", ".", "$", "extension", ")", ";", "}", "if", "(", "null", "!==", "$", "customFilename", ")", "{", "$", "filename", "=", "$", "customFilename", ";", "$", "basename", "=", "basename", "(", "$", "filename", ",", "'.'", ".", "$", "extension", ")", ";", "}", "$", "link", "=", "new", "AttachmentLink", "(", ")", ";", "$", "link", "->", "setAttachment", "(", "$", "attachment", ")", "->", "setModelName", "(", "$", "object", "->", "getAttachableClassName", "(", ")", ")", "->", "setModelId", "(", "$", "object", "->", "getAttachableId", "(", ")", ")", "->", "setModelField", "(", "$", "fieldName", ")", "->", "setFileName", "(", "$", "filename", ")", "->", "setFileExtension", "(", "$", "extension", ")", "->", "setCustomName", "(", "$", "basename", ")", ";", "return", "$", "link", ";", "}" ]
Create new AttachmentLink object for the given parameters. @param File $file @param AttachableObjectInterface $object @param string $fieldName @param Attachment $attachment @return AttachmentLink
[ "Create", "new", "AttachmentLink", "object", "for", "the", "given", "parameters", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L494-L527
11,045
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.getFileKey
protected function getFileKey($key) { $key = (string) $key; if (!array_key_exists($key, $this->fileKeys)) { $this->fileKeys[$key] = new FileKey($key); } return $this->fileKeys[$key]; }
php
protected function getFileKey($key) { $key = (string) $key; if (!array_key_exists($key, $this->fileKeys)) { $this->fileKeys[$key] = new FileKey($key); } return $this->fileKeys[$key]; }
[ "protected", "function", "getFileKey", "(", "$", "key", ")", "{", "$", "key", "=", "(", "string", ")", "$", "key", ";", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "fileKeys", ")", ")", "{", "$", "this", "->", "fileKeys", "[", "$", "key", "]", "=", "new", "FileKey", "(", "$", "key", ")", ";", "}", "return", "$", "this", "->", "fileKeys", "[", "$", "key", "]", ";", "}" ]
Convert an existing string key to a FileKey object for further usage. @throws InvalidKeyException if the key cannot be parsed @param string $key @return FileKey
[ "Convert", "an", "existing", "string", "key", "to", "a", "FileKey", "object", "for", "further", "usage", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L538-L547
11,046
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.removeFile
protected function removeFile($key) { $fileKey = $this->getFileKey($key); $storage = $this->getStorage($fileKey->getStorageName()); return $storage->getFilesystem()->delete($this->getStoragePath($storage, $fileKey)); }
php
protected function removeFile($key) { $fileKey = $this->getFileKey($key); $storage = $this->getStorage($fileKey->getStorageName()); return $storage->getFilesystem()->delete($this->getStoragePath($storage, $fileKey)); }
[ "protected", "function", "removeFile", "(", "$", "key", ")", "{", "$", "fileKey", "=", "$", "this", "->", "getFileKey", "(", "$", "key", ")", ";", "$", "storage", "=", "$", "this", "->", "getStorage", "(", "$", "fileKey", "->", "getStorageName", "(", ")", ")", ";", "return", "$", "storage", "->", "getFilesystem", "(", ")", "->", "delete", "(", "$", "this", "->", "getStoragePath", "(", "$", "storage", ",", "$", "fileKey", ")", ")", ";", "}" ]
Remove the given file from the storage. @param string $key
[ "Remove", "the", "given", "file", "from", "the", "storage", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L569-L575
11,047
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.getFileUrl
public function getFileUrl($key) { $fileKey = $this->getFileKey($key); $storage = $this->getStorage($fileKey->getStorageName()); if (!$storage->hasBaseUrl()) { throw new MissingStorageConfigException('This storage does not have a configured base url!'); } return $storage->getBaseUrl().'/'.$this->getStoragePath($storage, $fileKey); }
php
public function getFileUrl($key) { $fileKey = $this->getFileKey($key); $storage = $this->getStorage($fileKey->getStorageName()); if (!$storage->hasBaseUrl()) { throw new MissingStorageConfigException('This storage does not have a configured base url!'); } return $storage->getBaseUrl().'/'.$this->getStoragePath($storage, $fileKey); }
[ "public", "function", "getFileUrl", "(", "$", "key", ")", "{", "$", "fileKey", "=", "$", "this", "->", "getFileKey", "(", "$", "key", ")", ";", "$", "storage", "=", "$", "this", "->", "getStorage", "(", "$", "fileKey", "->", "getStorageName", "(", ")", ")", ";", "if", "(", "!", "$", "storage", "->", "hasBaseUrl", "(", ")", ")", "{", "throw", "new", "MissingStorageConfigException", "(", "'This storage does not have a configured base url!'", ")", ";", "}", "return", "$", "storage", "->", "getBaseUrl", "(", ")", ".", "'/'", ".", "$", "this", "->", "getStoragePath", "(", "$", "storage", ",", "$", "fileKey", ")", ";", "}" ]
Get the URL for the given file key. @throws InvalidKeyException if the key cannot be parsed @throws StorageDoesNotExistException if the storage defined by the key is unknown @throws MissingStorageConfigException if the storage config for the key's storage does not contain a base url @param string $key @return $string
[ "Get", "the", "URL", "for", "the", "given", "file", "key", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L621-L632
11,048
vworldat/AttachmentBundle
Attachment/AttachmentHandler.php
AttachmentHandler.fileExists
public function fileExists($key) { $fileKey = $this->getFileKey($key); $storage = $this->getStorage($fileKey->getStorageName()); return $storage->getFilesystem()->has($this->getStoragePath($storage, $fileKey)); }
php
public function fileExists($key) { $fileKey = $this->getFileKey($key); $storage = $this->getStorage($fileKey->getStorageName()); return $storage->getFilesystem()->has($this->getStoragePath($storage, $fileKey)); }
[ "public", "function", "fileExists", "(", "$", "key", ")", "{", "$", "fileKey", "=", "$", "this", "->", "getFileKey", "(", "$", "key", ")", ";", "$", "storage", "=", "$", "this", "->", "getStorage", "(", "$", "fileKey", "->", "getStorageName", "(", ")", ")", ";", "return", "$", "storage", "->", "getFilesystem", "(", ")", "->", "has", "(", "$", "this", "->", "getStoragePath", "(", "$", "storage", ",", "$", "fileKey", ")", ")", ";", "}" ]
Check if the given file exists inside its storage. Actually you should never have to do this unless you are manipulating the storage by hand. @throws InvalidKeyException if the key cannot be parsed @throws StorageDoesNotExistException if the storage defined by the key is unknown @param string $key @return boolean
[ "Check", "if", "the", "given", "file", "exists", "inside", "its", "storage", ".", "Actually", "you", "should", "never", "have", "to", "do", "this", "unless", "you", "are", "manipulating", "the", "storage", "by", "hand", "." ]
fb179c913e135164e0d1ebc69dcaf8b4782370dd
https://github.com/vworldat/AttachmentBundle/blob/fb179c913e135164e0d1ebc69dcaf8b4782370dd/Attachment/AttachmentHandler.php#L669-L675
11,049
parfumix/laravel-translator
src/Translator.php
Translator.translate
public function translate($key, $translation, $locale = null, $driver = null) { $driver = ! is_null($driver) ? $this->getDriver($driver) : $this->driver(); return $driver->translate( $key, $translation, $locale ); }
php
public function translate($key, $translation, $locale = null, $driver = null) { $driver = ! is_null($driver) ? $this->getDriver($driver) : $this->driver(); return $driver->translate( $key, $translation, $locale ); }
[ "public", "function", "translate", "(", "$", "key", ",", "$", "translation", ",", "$", "locale", "=", "null", ",", "$", "driver", "=", "null", ")", "{", "$", "driver", "=", "!", "is_null", "(", "$", "driver", ")", "?", "$", "this", "->", "getDriver", "(", "$", "driver", ")", ":", "$", "this", "->", "driver", "(", ")", ";", "return", "$", "driver", "->", "translate", "(", "$", "key", ",", "$", "translation", ",", "$", "locale", ")", ";", "}" ]
Translate a key . @param $key @param $translation @param null $locale @param null $driver @return mixed
[ "Translate", "a", "key", "." ]
b85f17cbfebd4f35d1bfb817fbf13bff2c3f487e
https://github.com/parfumix/laravel-translator/blob/b85f17cbfebd4f35d1bfb817fbf13bff2c3f487e/src/Translator.php#L138-L144
11,050
rseyferth/chickenwire
src/ChickenWire/Controller.php
Controller._finish
protected function _finish() { // Check layout path $layoutPath = !is_null($this->request->route->module) ? $this->request->route->module->path . '/Layouts' : LAYOUT_PATH; // Layout set? if (!isset($this->_layout)) { // Layout in controller? if (!is_null(static::$layout)) { // Use that. $this->_layout = $layoutPath . '/' . static::$layout; } elseif (!is_null($this->request->route->module) && !is_null($this->request->route->module->defaultLayout)) { // Use that with module info $this->_layout = $layoutPath . '/' . $this->request->route->module->defaultLayout; } else { // Use app's default. $this->_layout = LAYOUT_PATH . '/' . Application::getConfiguration()->defaultLayout; } } // No layout? if ($this->_layout === false) { // Just output the content then. if (array_key_exists('main', $this->_renderedContent)) { echo $this->_renderedContent['main']; } } else { // Guess the extension $layoutFile = $this->_guessExtension($this->_layout); // Not found? if ($layoutFile === false) { throw new \Exception("Couldn't find layout for " . $this->_layout, 1); } $this->_layout = $layoutFile; // Create and render the layout $layout = new Layout($this->_layout, $this, $this->_renderedContent); } }
php
protected function _finish() { // Check layout path $layoutPath = !is_null($this->request->route->module) ? $this->request->route->module->path . '/Layouts' : LAYOUT_PATH; // Layout set? if (!isset($this->_layout)) { // Layout in controller? if (!is_null(static::$layout)) { // Use that. $this->_layout = $layoutPath . '/' . static::$layout; } elseif (!is_null($this->request->route->module) && !is_null($this->request->route->module->defaultLayout)) { // Use that with module info $this->_layout = $layoutPath . '/' . $this->request->route->module->defaultLayout; } else { // Use app's default. $this->_layout = LAYOUT_PATH . '/' . Application::getConfiguration()->defaultLayout; } } // No layout? if ($this->_layout === false) { // Just output the content then. if (array_key_exists('main', $this->_renderedContent)) { echo $this->_renderedContent['main']; } } else { // Guess the extension $layoutFile = $this->_guessExtension($this->_layout); // Not found? if ($layoutFile === false) { throw new \Exception("Couldn't find layout for " . $this->_layout, 1); } $this->_layout = $layoutFile; // Create and render the layout $layout = new Layout($this->_layout, $this, $this->_renderedContent); } }
[ "protected", "function", "_finish", "(", ")", "{", "// Check layout path", "$", "layoutPath", "=", "!", "is_null", "(", "$", "this", "->", "request", "->", "route", "->", "module", ")", "?", "$", "this", "->", "request", "->", "route", "->", "module", "->", "path", ".", "'/Layouts'", ":", "LAYOUT_PATH", ";", "// Layout set?", "if", "(", "!", "isset", "(", "$", "this", "->", "_layout", ")", ")", "{", "// Layout in controller?", "if", "(", "!", "is_null", "(", "static", "::", "$", "layout", ")", ")", "{", "// Use that.", "$", "this", "->", "_layout", "=", "$", "layoutPath", ".", "'/'", ".", "static", "::", "$", "layout", ";", "}", "elseif", "(", "!", "is_null", "(", "$", "this", "->", "request", "->", "route", "->", "module", ")", "&&", "!", "is_null", "(", "$", "this", "->", "request", "->", "route", "->", "module", "->", "defaultLayout", ")", ")", "{", "// Use that with module info", "$", "this", "->", "_layout", "=", "$", "layoutPath", ".", "'/'", ".", "$", "this", "->", "request", "->", "route", "->", "module", "->", "defaultLayout", ";", "}", "else", "{", "// Use app's default.", "$", "this", "->", "_layout", "=", "LAYOUT_PATH", ".", "'/'", ".", "Application", "::", "getConfiguration", "(", ")", "->", "defaultLayout", ";", "}", "}", "// No layout?", "if", "(", "$", "this", "->", "_layout", "===", "false", ")", "{", "// Just output the content then.", "if", "(", "array_key_exists", "(", "'main'", ",", "$", "this", "->", "_renderedContent", ")", ")", "{", "echo", "$", "this", "->", "_renderedContent", "[", "'main'", "]", ";", "}", "}", "else", "{", "// Guess the extension", "$", "layoutFile", "=", "$", "this", "->", "_guessExtension", "(", "$", "this", "->", "_layout", ")", ";", "// Not found?", "if", "(", "$", "layoutFile", "===", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Couldn't find layout for \"", ".", "$", "this", "->", "_layout", ",", "1", ")", ";", "}", "$", "this", "->", "_layout", "=", "$", "layoutFile", ";", "// Create and render the layout", "$", "layout", "=", "new", "Layout", "(", "$", "this", "->", "_layout", ",", "$", "this", ",", "$", "this", "->", "_renderedContent", ")", ";", "}", "}" ]
When the action has completed, the finish method will tie up loose ends @return void
[ "When", "the", "action", "has", "completed", "the", "finish", "method", "will", "tie", "up", "loose", "ends" ]
74921f0a0d489366602e25df43eda894719e43d3
https://github.com/rseyferth/chickenwire/blob/74921f0a0d489366602e25df43eda894719e43d3/src/ChickenWire/Controller.php#L227-L282
11,051
rseyferth/chickenwire
src/ChickenWire/Controller.php
Controller._guessExtension
private function _guessExtension($filename, $suffix = '.php') { // Content type chosen? $possibleExtensions = array(); $allAccepted = false; if (!is_null($this->contentType)) { // Get extensions $possibleExtensions = $this->contentType->getExtensions(); } else { // Collect extensions for all types foreach ($this->request->preferredContent as $type) { $possibleExtensions = array_merge($possibleExtensions, $type->getExtensions()); if ($type->type == Mime::ALL) { $allAccepted = true; } } } // See if any of 'em exist foreach ($possibleExtensions as $ext) { // Something there? $tryFilename = $filename . ".$ext$suffix"; if (file_exists($tryFilename)) { return $tryFilename; } } // Nothing found... Was */* one of accepted headers? if ($allAccepted) { // Check dir $dir = dirname($filename); if (!file_exists($dir) || !is_dir($dir)) { return false; } // File part $searchFor = substr($filename, strlen($dir) + 1); // Look in the directory $dh = opendir($dir); while (false !== ($file = readdir($dh))) { // Known content type? if (Str::getContentExtension($file)) // Starts with our template and ends with .php? if (is_file($dir . '/' . $file) && preg_match('/^' . preg_quote($searchFor) . '\.([a-z]+)' . preg_quote($suffix) . '$/', $file) && Mime::byExtension(Str::getContentExtension($file)) !== false) { // Well, we found a file with an extension, so let's serve it return $dir . '/' . $file; } } } // Nothing :( return false; }
php
private function _guessExtension($filename, $suffix = '.php') { // Content type chosen? $possibleExtensions = array(); $allAccepted = false; if (!is_null($this->contentType)) { // Get extensions $possibleExtensions = $this->contentType->getExtensions(); } else { // Collect extensions for all types foreach ($this->request->preferredContent as $type) { $possibleExtensions = array_merge($possibleExtensions, $type->getExtensions()); if ($type->type == Mime::ALL) { $allAccepted = true; } } } // See if any of 'em exist foreach ($possibleExtensions as $ext) { // Something there? $tryFilename = $filename . ".$ext$suffix"; if (file_exists($tryFilename)) { return $tryFilename; } } // Nothing found... Was */* one of accepted headers? if ($allAccepted) { // Check dir $dir = dirname($filename); if (!file_exists($dir) || !is_dir($dir)) { return false; } // File part $searchFor = substr($filename, strlen($dir) + 1); // Look in the directory $dh = opendir($dir); while (false !== ($file = readdir($dh))) { // Known content type? if (Str::getContentExtension($file)) // Starts with our template and ends with .php? if (is_file($dir . '/' . $file) && preg_match('/^' . preg_quote($searchFor) . '\.([a-z]+)' . preg_quote($suffix) . '$/', $file) && Mime::byExtension(Str::getContentExtension($file)) !== false) { // Well, we found a file with an extension, so let's serve it return $dir . '/' . $file; } } } // Nothing :( return false; }
[ "private", "function", "_guessExtension", "(", "$", "filename", ",", "$", "suffix", "=", "'.php'", ")", "{", "// Content type chosen?", "$", "possibleExtensions", "=", "array", "(", ")", ";", "$", "allAccepted", "=", "false", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "contentType", ")", ")", "{", "// Get extensions", "$", "possibleExtensions", "=", "$", "this", "->", "contentType", "->", "getExtensions", "(", ")", ";", "}", "else", "{", "// Collect extensions for all types", "foreach", "(", "$", "this", "->", "request", "->", "preferredContent", "as", "$", "type", ")", "{", "$", "possibleExtensions", "=", "array_merge", "(", "$", "possibleExtensions", ",", "$", "type", "->", "getExtensions", "(", ")", ")", ";", "if", "(", "$", "type", "->", "type", "==", "Mime", "::", "ALL", ")", "{", "$", "allAccepted", "=", "true", ";", "}", "}", "}", "// See if any of 'em exist", "foreach", "(", "$", "possibleExtensions", "as", "$", "ext", ")", "{", "// Something there?", "$", "tryFilename", "=", "$", "filename", ".", "\".$ext$suffix\"", ";", "if", "(", "file_exists", "(", "$", "tryFilename", ")", ")", "{", "return", "$", "tryFilename", ";", "}", "}", "// Nothing found... Was */* one of accepted headers?", "if", "(", "$", "allAccepted", ")", "{", "// Check dir", "$", "dir", "=", "dirname", "(", "$", "filename", ")", ";", "if", "(", "!", "file_exists", "(", "$", "dir", ")", "||", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "return", "false", ";", "}", "// File part", "$", "searchFor", "=", "substr", "(", "$", "filename", ",", "strlen", "(", "$", "dir", ")", "+", "1", ")", ";", "// Look in the directory\t\t\t\t", "$", "dh", "=", "opendir", "(", "$", "dir", ")", ";", "while", "(", "false", "!==", "(", "$", "file", "=", "readdir", "(", "$", "dh", ")", ")", ")", "{", "// Known content type?", "if", "(", "Str", "::", "getContentExtension", "(", "$", "file", ")", ")", "// Starts with our template and ends with .php?", "if", "(", "is_file", "(", "$", "dir", ".", "'/'", ".", "$", "file", ")", "&&", "preg_match", "(", "'/^'", ".", "preg_quote", "(", "$", "searchFor", ")", ".", "'\\.([a-z]+)'", ".", "preg_quote", "(", "$", "suffix", ")", ".", "'$/'", ",", "$", "file", ")", "&&", "Mime", "::", "byExtension", "(", "Str", "::", "getContentExtension", "(", "$", "file", ")", ")", "!==", "false", ")", "{", "// Well, we found a file with an extension, so let's serve it", "return", "$", "dir", ".", "'/'", ".", "$", "file", ";", "}", "}", "}", "// Nothing :(", "return", "false", ";", "}" ]
Guess a file extension for the given extensionless filename, based on the request headers, or chosen content type. @param string $filename The filename without extension to complete. This already needs to be complete path. @param string $suffix (default '.php') Suffix to put at then end of every filename to try. @return string|false The completed filename, when a suitable file was found, or false if not.
[ "Guess", "a", "file", "extension", "for", "the", "given", "extensionless", "filename", "based", "on", "the", "request", "headers", "or", "chosen", "content", "type", "." ]
74921f0a0d489366602e25df43eda894719e43d3
https://github.com/rseyferth/chickenwire/blob/74921f0a0d489366602e25df43eda894719e43d3/src/ChickenWire/Controller.php#L795-L867
11,052
rseyferth/chickenwire
src/ChickenWire/Controller.php
Controller._interpretOptionsWithinView
private function _interpretOptionsWithinView(&$options) { // Nut'n? if (is_null($options)) { throw new \Exception("Cannot execute an empty render inside a view.", 1); } // A simple string? if (is_string($options)) { $options = array("partial" => $options); } // Not an array? if (!is_array($options)) { $options = array($options); } // Empty? if (count($options) == 0) { // Render nothing. $options = array("nothing" => true); return; } // Determine my view path $viewPath = !is_null($this->request->route->module) ? $this->request->route->module->path . "/Views/" : VIEW_PATH . "/"; // Model instances (or empty array)? if (isset($options[0]) && is_object($options[0]) && is_subclass_of($options[0], "\\ChickenWire\\Model")) { // Get class name $modelClass = $options[0]->getClass(); // Do a partial render for the record set $options = array( "partial" => strtolower($modelClass), "collection" => $options ); } // Partial? if (array_key_exists("partial", $options)) { // An object? if (array_key_exists("object", $options)) { $options['collection'] = array($options['object']); unset($options['object']); } // Collection? if (array_key_exists("collection", $options) && !array_key_exists("as", $options)) { /// Get class name $modelClass = $options['collection'][0]->getClass(); $options['as'] = strtolower($modelClass); } // A slashed location? if (strstr($options['partial'], '/')) { } else { // Does this route have a model? if (is_null($this->request->route->models)) { throw new \Exception("This route does not have a model linked to it, so you have to define a template, instead of an action.", 1); } // Remove namespace $model = $this->request->route->models[count($this->request->route->models) - 1]; $model = Str::removeNamespace($model); // Convert it to a full template $options['partial'] = Str::pluralize($model) . "/" . $options['partial']; } // Add _ to filename if (!preg_match('/\/_[a-z]+$/', $options['partial'])) { // Add _ $options['partial'] = substr($options['partial'], 0, strrpos($options['partial'], "/")) . '/_' . substr($options['partial'], strrpos($options['partial'], "/") + 1); } // Add view path $options['partial'] = $viewPath . $options['partial']; } // Any other options..? }
php
private function _interpretOptionsWithinView(&$options) { // Nut'n? if (is_null($options)) { throw new \Exception("Cannot execute an empty render inside a view.", 1); } // A simple string? if (is_string($options)) { $options = array("partial" => $options); } // Not an array? if (!is_array($options)) { $options = array($options); } // Empty? if (count($options) == 0) { // Render nothing. $options = array("nothing" => true); return; } // Determine my view path $viewPath = !is_null($this->request->route->module) ? $this->request->route->module->path . "/Views/" : VIEW_PATH . "/"; // Model instances (or empty array)? if (isset($options[0]) && is_object($options[0]) && is_subclass_of($options[0], "\\ChickenWire\\Model")) { // Get class name $modelClass = $options[0]->getClass(); // Do a partial render for the record set $options = array( "partial" => strtolower($modelClass), "collection" => $options ); } // Partial? if (array_key_exists("partial", $options)) { // An object? if (array_key_exists("object", $options)) { $options['collection'] = array($options['object']); unset($options['object']); } // Collection? if (array_key_exists("collection", $options) && !array_key_exists("as", $options)) { /// Get class name $modelClass = $options['collection'][0]->getClass(); $options['as'] = strtolower($modelClass); } // A slashed location? if (strstr($options['partial'], '/')) { } else { // Does this route have a model? if (is_null($this->request->route->models)) { throw new \Exception("This route does not have a model linked to it, so you have to define a template, instead of an action.", 1); } // Remove namespace $model = $this->request->route->models[count($this->request->route->models) - 1]; $model = Str::removeNamespace($model); // Convert it to a full template $options['partial'] = Str::pluralize($model) . "/" . $options['partial']; } // Add _ to filename if (!preg_match('/\/_[a-z]+$/', $options['partial'])) { // Add _ $options['partial'] = substr($options['partial'], 0, strrpos($options['partial'], "/")) . '/_' . substr($options['partial'], strrpos($options['partial'], "/") + 1); } // Add view path $options['partial'] = $viewPath . $options['partial']; } // Any other options..? }
[ "private", "function", "_interpretOptionsWithinView", "(", "&", "$", "options", ")", "{", "// Nut'n?", "if", "(", "is_null", "(", "$", "options", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Cannot execute an empty render inside a view.\"", ",", "1", ")", ";", "}", "// A simple string?", "if", "(", "is_string", "(", "$", "options", ")", ")", "{", "$", "options", "=", "array", "(", "\"partial\"", "=>", "$", "options", ")", ";", "}", "// Not an array?", "if", "(", "!", "is_array", "(", "$", "options", ")", ")", "{", "$", "options", "=", "array", "(", "$", "options", ")", ";", "}", "// Empty?", "if", "(", "count", "(", "$", "options", ")", "==", "0", ")", "{", "// Render nothing.", "$", "options", "=", "array", "(", "\"nothing\"", "=>", "true", ")", ";", "return", ";", "}", "// Determine my view path", "$", "viewPath", "=", "!", "is_null", "(", "$", "this", "->", "request", "->", "route", "->", "module", ")", "?", "$", "this", "->", "request", "->", "route", "->", "module", "->", "path", ".", "\"/Views/\"", ":", "VIEW_PATH", ".", "\"/\"", ";", "// Model instances (or empty array)?", "if", "(", "isset", "(", "$", "options", "[", "0", "]", ")", "&&", "is_object", "(", "$", "options", "[", "0", "]", ")", "&&", "is_subclass_of", "(", "$", "options", "[", "0", "]", ",", "\"\\\\ChickenWire\\\\Model\"", ")", ")", "{", "// Get class name", "$", "modelClass", "=", "$", "options", "[", "0", "]", "->", "getClass", "(", ")", ";", "// Do a partial render for the record set", "$", "options", "=", "array", "(", "\"partial\"", "=>", "strtolower", "(", "$", "modelClass", ")", ",", "\"collection\"", "=>", "$", "options", ")", ";", "}", "// Partial?", "if", "(", "array_key_exists", "(", "\"partial\"", ",", "$", "options", ")", ")", "{", "// An object?", "if", "(", "array_key_exists", "(", "\"object\"", ",", "$", "options", ")", ")", "{", "$", "options", "[", "'collection'", "]", "=", "array", "(", "$", "options", "[", "'object'", "]", ")", ";", "unset", "(", "$", "options", "[", "'object'", "]", ")", ";", "}", "// Collection?", "if", "(", "array_key_exists", "(", "\"collection\"", ",", "$", "options", ")", "&&", "!", "array_key_exists", "(", "\"as\"", ",", "$", "options", ")", ")", "{", "/// Get class name", "$", "modelClass", "=", "$", "options", "[", "'collection'", "]", "[", "0", "]", "->", "getClass", "(", ")", ";", "$", "options", "[", "'as'", "]", "=", "strtolower", "(", "$", "modelClass", ")", ";", "}", "// A slashed location?", "if", "(", "strstr", "(", "$", "options", "[", "'partial'", "]", ",", "'/'", ")", ")", "{", "}", "else", "{", "// Does this route have a model?", "if", "(", "is_null", "(", "$", "this", "->", "request", "->", "route", "->", "models", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"This route does not have a model linked to it, so you have to define a template, instead of an action.\"", ",", "1", ")", ";", "}", "// Remove namespace", "$", "model", "=", "$", "this", "->", "request", "->", "route", "->", "models", "[", "count", "(", "$", "this", "->", "request", "->", "route", "->", "models", ")", "-", "1", "]", ";", "$", "model", "=", "Str", "::", "removeNamespace", "(", "$", "model", ")", ";", "// Convert it to a full template\t\t\t\t", "$", "options", "[", "'partial'", "]", "=", "Str", "::", "pluralize", "(", "$", "model", ")", ".", "\"/\"", ".", "$", "options", "[", "'partial'", "]", ";", "}", "// Add _ to filename", "if", "(", "!", "preg_match", "(", "'/\\/_[a-z]+$/'", ",", "$", "options", "[", "'partial'", "]", ")", ")", "{", "// Add _", "$", "options", "[", "'partial'", "]", "=", "substr", "(", "$", "options", "[", "'partial'", "]", ",", "0", ",", "strrpos", "(", "$", "options", "[", "'partial'", "]", ",", "\"/\"", ")", ")", ".", "'/_'", ".", "substr", "(", "$", "options", "[", "'partial'", "]", ",", "strrpos", "(", "$", "options", "[", "'partial'", "]", ",", "\"/\"", ")", "+", "1", ")", ";", "}", "// Add view path", "$", "options", "[", "'partial'", "]", "=", "$", "viewPath", ".", "$", "options", "[", "'partial'", "]", ";", "}", "// Any other options..?", "}" ]
Interpret the options given to a render call inside a view. @param array The options to interpret by reference. @return void
[ "Interpret", "the", "options", "given", "to", "a", "render", "call", "inside", "a", "view", "." ]
74921f0a0d489366602e25df43eda894719e43d3
https://github.com/rseyferth/chickenwire/blob/74921f0a0d489366602e25df43eda894719e43d3/src/ChickenWire/Controller.php#L875-L974
11,053
rseyferth/chickenwire
src/ChickenWire/Controller.php
Controller._checkAuth
private function _checkAuth() { // Not needed? if (!isset(static::$requiresAuth) || is_null(static::$requiresAuth) || empty(static::$requiresAuth)) { return true; } // Get auth $auth = static::$requiresAuth; // Is there an except clause? if (is_array($auth) && array_key_exists("except", $auth)) { // Is my method in it? if (in_array($this->route->action, $auth['except'])) { return true; } } // Is there an only clause? if (is_array($auth) && array_key_exists("only", $auth)) { // Is it an array? if (!is_array($auth['only'])) { $auth['only'] = array($auth['only']); } // Is my method in it? if (!in_array($this->route->action, $auth['only'])) { return true; } } // Get auth name $authName = is_array($auth) ? $auth[0] : $auth; // Find auth object $this->auth = Auth::get($authName); // Is it authenticated? if ($this->auth->isAuthenticated() !== true) { // Store last page :) $this->auth->rememberPage($this->request->uri); // Redirect to login page if (!is_null($this->auth->loginAction)) { $this->_invokeAuthLoginAction(); } else { $this->redirect($this->auth->loginUri); } return false; } else { // We're in! return true; } }
php
private function _checkAuth() { // Not needed? if (!isset(static::$requiresAuth) || is_null(static::$requiresAuth) || empty(static::$requiresAuth)) { return true; } // Get auth $auth = static::$requiresAuth; // Is there an except clause? if (is_array($auth) && array_key_exists("except", $auth)) { // Is my method in it? if (in_array($this->route->action, $auth['except'])) { return true; } } // Is there an only clause? if (is_array($auth) && array_key_exists("only", $auth)) { // Is it an array? if (!is_array($auth['only'])) { $auth['only'] = array($auth['only']); } // Is my method in it? if (!in_array($this->route->action, $auth['only'])) { return true; } } // Get auth name $authName = is_array($auth) ? $auth[0] : $auth; // Find auth object $this->auth = Auth::get($authName); // Is it authenticated? if ($this->auth->isAuthenticated() !== true) { // Store last page :) $this->auth->rememberPage($this->request->uri); // Redirect to login page if (!is_null($this->auth->loginAction)) { $this->_invokeAuthLoginAction(); } else { $this->redirect($this->auth->loginUri); } return false; } else { // We're in! return true; } }
[ "private", "function", "_checkAuth", "(", ")", "{", "// Not needed?", "if", "(", "!", "isset", "(", "static", "::", "$", "requiresAuth", ")", "||", "is_null", "(", "static", "::", "$", "requiresAuth", ")", "||", "empty", "(", "static", "::", "$", "requiresAuth", ")", ")", "{", "return", "true", ";", "}", "// Get auth", "$", "auth", "=", "static", "::", "$", "requiresAuth", ";", "// Is there an except clause?", "if", "(", "is_array", "(", "$", "auth", ")", "&&", "array_key_exists", "(", "\"except\"", ",", "$", "auth", ")", ")", "{", "// Is my method in it?", "if", "(", "in_array", "(", "$", "this", "->", "route", "->", "action", ",", "$", "auth", "[", "'except'", "]", ")", ")", "{", "return", "true", ";", "}", "}", "// Is there an only clause?", "if", "(", "is_array", "(", "$", "auth", ")", "&&", "array_key_exists", "(", "\"only\"", ",", "$", "auth", ")", ")", "{", "// Is it an array?", "if", "(", "!", "is_array", "(", "$", "auth", "[", "'only'", "]", ")", ")", "{", "$", "auth", "[", "'only'", "]", "=", "array", "(", "$", "auth", "[", "'only'", "]", ")", ";", "}", "// Is my method in it?", "if", "(", "!", "in_array", "(", "$", "this", "->", "route", "->", "action", ",", "$", "auth", "[", "'only'", "]", ")", ")", "{", "return", "true", ";", "}", "}", "// Get auth name", "$", "authName", "=", "is_array", "(", "$", "auth", ")", "?", "$", "auth", "[", "0", "]", ":", "$", "auth", ";", "// Find auth object", "$", "this", "->", "auth", "=", "Auth", "::", "get", "(", "$", "authName", ")", ";", "// Is it authenticated?", "if", "(", "$", "this", "->", "auth", "->", "isAuthenticated", "(", ")", "!==", "true", ")", "{", "// Store last page :)", "$", "this", "->", "auth", "->", "rememberPage", "(", "$", "this", "->", "request", "->", "uri", ")", ";", "// Redirect to login page", "if", "(", "!", "is_null", "(", "$", "this", "->", "auth", "->", "loginAction", ")", ")", "{", "$", "this", "->", "_invokeAuthLoginAction", "(", ")", ";", "}", "else", "{", "$", "this", "->", "redirect", "(", "$", "this", "->", "auth", "->", "loginUri", ")", ";", "}", "return", "false", ";", "}", "else", "{", "// We're in!", "return", "true", ";", "}", "}" ]
Check if current action needs authentication, and if it is validated @return boolean Whether authentication passed
[ "Check", "if", "current", "action", "needs", "authentication", "and", "if", "it", "is", "validated" ]
74921f0a0d489366602e25df43eda894719e43d3
https://github.com/rseyferth/chickenwire/blob/74921f0a0d489366602e25df43eda894719e43d3/src/ChickenWire/Controller.php#L1167-L1231
11,054
rseyferth/chickenwire
src/ChickenWire/Controller.php
Controller._invokeAuthLoginAction
private function _invokeAuthLoginAction() { // Try to instatiate the login controller (without executing the request) $login = new $this->auth->loginController($this->request, false); // Does it have the method? if (method_exists($login, $this->auth->loginAction)) { // Is it public? $reflection = new \ReflectionMethod($login, $this->auth->loginAction); if (!$reflection->isPublic()) { throw new \Exception("The method '" . $this->auth->loginAction . "' on " . get_class($login) . " is not public.", 1); } // Send not auth! Http::sendStatus(401); // Call action $reflection->invoke($login); } else { throw new \Exception("There is no method '" . $this->auth->loginAction . "' on " . get_class($login), 1); } }
php
private function _invokeAuthLoginAction() { // Try to instatiate the login controller (without executing the request) $login = new $this->auth->loginController($this->request, false); // Does it have the method? if (method_exists($login, $this->auth->loginAction)) { // Is it public? $reflection = new \ReflectionMethod($login, $this->auth->loginAction); if (!$reflection->isPublic()) { throw new \Exception("The method '" . $this->auth->loginAction . "' on " . get_class($login) . " is not public.", 1); } // Send not auth! Http::sendStatus(401); // Call action $reflection->invoke($login); } else { throw new \Exception("There is no method '" . $this->auth->loginAction . "' on " . get_class($login), 1); } }
[ "private", "function", "_invokeAuthLoginAction", "(", ")", "{", "// Try to instatiate the login controller (without executing the request)", "$", "login", "=", "new", "$", "this", "->", "auth", "->", "loginController", "(", "$", "this", "->", "request", ",", "false", ")", ";", "// Does it have the method?", "if", "(", "method_exists", "(", "$", "login", ",", "$", "this", "->", "auth", "->", "loginAction", ")", ")", "{", "// Is it public?", "$", "reflection", "=", "new", "\\", "ReflectionMethod", "(", "$", "login", ",", "$", "this", "->", "auth", "->", "loginAction", ")", ";", "if", "(", "!", "$", "reflection", "->", "isPublic", "(", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"The method '\"", ".", "$", "this", "->", "auth", "->", "loginAction", ".", "\"' on \"", ".", "get_class", "(", "$", "login", ")", ".", "\" is not public.\"", ",", "1", ")", ";", "}", "// Send not auth!", "Http", "::", "sendStatus", "(", "401", ")", ";", "// Call action", "$", "reflection", "->", "invoke", "(", "$", "login", ")", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "\"There is no method '\"", ".", "$", "this", "->", "auth", "->", "loginAction", ".", "\"' on \"", ".", "get_class", "(", "$", "login", ")", ",", "1", ")", ";", "}", "}" ]
Invoke the Login action for the Controller's Auth object @return void
[ "Invoke", "the", "Login", "action", "for", "the", "Controller", "s", "Auth", "object" ]
74921f0a0d489366602e25df43eda894719e43d3
https://github.com/rseyferth/chickenwire/blob/74921f0a0d489366602e25df43eda894719e43d3/src/ChickenWire/Controller.php#L1314-L1345
11,055
rseyferth/chickenwire
src/ChickenWire/Controller.php
Controller.show404
protected function show404() { //@TODO Real implementation... Http::sendStatus(404); if (class_exists("\\Application\\Controllers\\ErrorController")) { $controller = new \Application\Controllers\ErrorController($this->request, false); $controller->show(404); } else { echo ("404 Page not found"); } die; }
php
protected function show404() { //@TODO Real implementation... Http::sendStatus(404); if (class_exists("\\Application\\Controllers\\ErrorController")) { $controller = new \Application\Controllers\ErrorController($this->request, false); $controller->show(404); } else { echo ("404 Page not found"); } die; }
[ "protected", "function", "show404", "(", ")", "{", "//@TODO Real implementation...", "Http", "::", "sendStatus", "(", "404", ")", ";", "if", "(", "class_exists", "(", "\"\\\\Application\\\\Controllers\\\\ErrorController\"", ")", ")", "{", "$", "controller", "=", "new", "\\", "Application", "\\", "Controllers", "\\", "ErrorController", "(", "$", "this", "->", "request", ",", "false", ")", ";", "$", "controller", "->", "show", "(", "404", ")", ";", "}", "else", "{", "echo", "(", "\"404 Page not found\"", ")", ";", "}", "die", ";", "}" ]
Send a 404 error to the client @return void
[ "Send", "a", "404", "error", "to", "the", "client" ]
74921f0a0d489366602e25df43eda894719e43d3
https://github.com/rseyferth/chickenwire/blob/74921f0a0d489366602e25df43eda894719e43d3/src/ChickenWire/Controller.php#L1487-L1506
11,056
monomelodies/ornament
src/Model.php
Model.save
public function save() { if ($this instanceof Immutable) { throw new Exception\Immutable($this); } $errors = []; if (method_exists($this, 'notify')) { $notify = clone $this; } foreach ($this->__adapters as $model) { if ($model->isDirty()) { if ($model->isNew() && $this instanceof Uncreateable) { throw new Exception\Uncreateable($this); } if (!$model->save()) { $errors[] = true; } } } $annotations = $this->annotations()['properties']; foreach ($annotations as $prop => $anns) { if (isset($anns['Private']) || $prop{0} == '_') { continue; } $value = $this->$prop; if (is_object($value)) { if ($value instanceof Collection && $value->isDirty()) { if ($error = $value->save()) { $errors = array_merge($errors, $error); } } elseif ($save = Helper::modelSaveMethod($value) and !method_exists($value, 'isDirty') || $value->isDirty() ) { if (!$value->$save()) { $errors[] = true; } } } } if (isset($notify)) { $notify->notify(); } $this->markClean(); return $errors ? $errors : null; }
php
public function save() { if ($this instanceof Immutable) { throw new Exception\Immutable($this); } $errors = []; if (method_exists($this, 'notify')) { $notify = clone $this; } foreach ($this->__adapters as $model) { if ($model->isDirty()) { if ($model->isNew() && $this instanceof Uncreateable) { throw new Exception\Uncreateable($this); } if (!$model->save()) { $errors[] = true; } } } $annotations = $this->annotations()['properties']; foreach ($annotations as $prop => $anns) { if (isset($anns['Private']) || $prop{0} == '_') { continue; } $value = $this->$prop; if (is_object($value)) { if ($value instanceof Collection && $value->isDirty()) { if ($error = $value->save()) { $errors = array_merge($errors, $error); } } elseif ($save = Helper::modelSaveMethod($value) and !method_exists($value, 'isDirty') || $value->isDirty() ) { if (!$value->$save()) { $errors[] = true; } } } } if (isset($notify)) { $notify->notify(); } $this->markClean(); return $errors ? $errors : null; }
[ "public", "function", "save", "(", ")", "{", "if", "(", "$", "this", "instanceof", "Immutable", ")", "{", "throw", "new", "Exception", "\\", "Immutable", "(", "$", "this", ")", ";", "}", "$", "errors", "=", "[", "]", ";", "if", "(", "method_exists", "(", "$", "this", ",", "'notify'", ")", ")", "{", "$", "notify", "=", "clone", "$", "this", ";", "}", "foreach", "(", "$", "this", "->", "__adapters", "as", "$", "model", ")", "{", "if", "(", "$", "model", "->", "isDirty", "(", ")", ")", "{", "if", "(", "$", "model", "->", "isNew", "(", ")", "&&", "$", "this", "instanceof", "Uncreateable", ")", "{", "throw", "new", "Exception", "\\", "Uncreateable", "(", "$", "this", ")", ";", "}", "if", "(", "!", "$", "model", "->", "save", "(", ")", ")", "{", "$", "errors", "[", "]", "=", "true", ";", "}", "}", "}", "$", "annotations", "=", "$", "this", "->", "annotations", "(", ")", "[", "'properties'", "]", ";", "foreach", "(", "$", "annotations", "as", "$", "prop", "=>", "$", "anns", ")", "{", "if", "(", "isset", "(", "$", "anns", "[", "'Private'", "]", ")", "||", "$", "prop", "{", "0", "}", "==", "'_'", ")", "{", "continue", ";", "}", "$", "value", "=", "$", "this", "->", "$", "prop", ";", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "if", "(", "$", "value", "instanceof", "Collection", "&&", "$", "value", "->", "isDirty", "(", ")", ")", "{", "if", "(", "$", "error", "=", "$", "value", "->", "save", "(", ")", ")", "{", "$", "errors", "=", "array_merge", "(", "$", "errors", ",", "$", "error", ")", ";", "}", "}", "elseif", "(", "$", "save", "=", "Helper", "::", "modelSaveMethod", "(", "$", "value", ")", "and", "!", "method_exists", "(", "$", "value", ",", "'isDirty'", ")", "||", "$", "value", "->", "isDirty", "(", ")", ")", "{", "if", "(", "!", "$", "value", "->", "$", "save", "(", ")", ")", "{", "$", "errors", "[", "]", "=", "true", ";", "}", "}", "}", "}", "if", "(", "isset", "(", "$", "notify", ")", ")", "{", "$", "notify", "->", "notify", "(", ")", ";", "}", "$", "this", "->", "markClean", "(", ")", ";", "return", "$", "errors", "?", "$", "errors", ":", "null", ";", "}" ]
Persists the model back to storage based on the specified adapters. If an adapter supports transactions, you are encouraged to use them; but you should do so in your own code. @return null|array null on success, or an array of errors encountered. @throws Ornament\Exception\Immutable if the model implements the Immutable interface and is thus immutable. @throws Ornament\Exception\Uncreateable if the model is new and implemnts the Uncreatable interface and can therefor not be created programmatically.
[ "Persists", "the", "model", "back", "to", "storage", "based", "on", "the", "specified", "adapters", ".", "If", "an", "adapter", "supports", "transactions", "you", "are", "encouraged", "to", "use", "them", ";", "but", "you", "should", "do", "so", "in", "your", "own", "code", "." ]
d7d070ad11f5731be141cf55c2756accaaf51402
https://github.com/monomelodies/ornament/blob/d7d070ad11f5731be141cf55c2756accaaf51402/src/Model.php#L244-L288
11,057
monomelodies/ornament
src/Model.php
Model.delete
public function delete() { if (method_exists($this, 'notify')) { $notify = clone $this; } if ($this instanceof Undeleteable) { throw new Exception\Undeleteable($this); } $errors = []; foreach ($this->__adapters as $adapter) { if ($error = $adapter->delete($this)) { $errors[] = $error; } else { $adapter->markDeleted(); } } if (isset($notify)) { $notify->notify(); } $this->__state = 'deleted'; return $errors ? $errors : null; }
php
public function delete() { if (method_exists($this, 'notify')) { $notify = clone $this; } if ($this instanceof Undeleteable) { throw new Exception\Undeleteable($this); } $errors = []; foreach ($this->__adapters as $adapter) { if ($error = $adapter->delete($this)) { $errors[] = $error; } else { $adapter->markDeleted(); } } if (isset($notify)) { $notify->notify(); } $this->__state = 'deleted'; return $errors ? $errors : null; }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "method_exists", "(", "$", "this", ",", "'notify'", ")", ")", "{", "$", "notify", "=", "clone", "$", "this", ";", "}", "if", "(", "$", "this", "instanceof", "Undeleteable", ")", "{", "throw", "new", "Exception", "\\", "Undeleteable", "(", "$", "this", ")", ";", "}", "$", "errors", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "__adapters", "as", "$", "adapter", ")", "{", "if", "(", "$", "error", "=", "$", "adapter", "->", "delete", "(", "$", "this", ")", ")", "{", "$", "errors", "[", "]", "=", "$", "error", ";", "}", "else", "{", "$", "adapter", "->", "markDeleted", "(", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "notify", ")", ")", "{", "$", "notify", "->", "notify", "(", ")", ";", "}", "$", "this", "->", "__state", "=", "'deleted'", ";", "return", "$", "errors", "?", "$", "errors", ":", "null", ";", "}" ]
Deletes the current model from storage based on the specified adapters. If an adapter supports transactions, you are encouraged to use them; but you should do so in your own code. @return null|array null on success, or an array of errors encountered. @throw Ornament\Exception\Undeleteable if the model implements the Undeleteable interface and is hence "protected".
[ "Deletes", "the", "current", "model", "from", "storage", "based", "on", "the", "specified", "adapters", ".", "If", "an", "adapter", "supports", "transactions", "you", "are", "encouraged", "to", "use", "them", ";", "but", "you", "should", "do", "so", "in", "your", "own", "code", "." ]
d7d070ad11f5731be141cf55c2756accaaf51402
https://github.com/monomelodies/ornament/blob/d7d070ad11f5731be141cf55c2756accaaf51402/src/Model.php#L299-L320
11,058
monomelodies/ornament
src/Model.php
Model.markClean
public function markClean() { foreach ($this->__adapters as $model) { $model->markClean(); } $annotations = $this->annotations()['properties']; foreach ($annotations as $prop => $anns) { if (isset($anns['Private']) || $prop{0} == '_') { continue; } $value = $this->$prop; if (is_object($value) and method_exists($value, 'markClean')) { $value->markClean(); } } $this->__state = 'clean'; }
php
public function markClean() { foreach ($this->__adapters as $model) { $model->markClean(); } $annotations = $this->annotations()['properties']; foreach ($annotations as $prop => $anns) { if (isset($anns['Private']) || $prop{0} == '_') { continue; } $value = $this->$prop; if (is_object($value) and method_exists($value, 'markClean')) { $value->markClean(); } } $this->__state = 'clean'; }
[ "public", "function", "markClean", "(", ")", "{", "foreach", "(", "$", "this", "->", "__adapters", "as", "$", "model", ")", "{", "$", "model", "->", "markClean", "(", ")", ";", "}", "$", "annotations", "=", "$", "this", "->", "annotations", "(", ")", "[", "'properties'", "]", ";", "foreach", "(", "$", "annotations", "as", "$", "prop", "=>", "$", "anns", ")", "{", "if", "(", "isset", "(", "$", "anns", "[", "'Private'", "]", ")", "||", "$", "prop", "{", "0", "}", "==", "'_'", ")", "{", "continue", ";", "}", "$", "value", "=", "$", "this", "->", "$", "prop", ";", "if", "(", "is_object", "(", "$", "value", ")", "and", "method_exists", "(", "$", "value", ",", "'markClean'", ")", ")", "{", "$", "value", "->", "markClean", "(", ")", ";", "}", "}", "$", "this", "->", "__state", "=", "'clean'", ";", "}" ]
Mark the current model as 'clean', i.e. not dirty. Useful if you manually set values after loading from storage that shouldn't count towards "dirtiness". Called automatically after saving. @return void
[ "Mark", "the", "current", "model", "as", "clean", "i", ".", "e", ".", "not", "dirty", ".", "Useful", "if", "you", "manually", "set", "values", "after", "loading", "from", "storage", "that", "shouldn", "t", "count", "towards", "dirtiness", ".", "Called", "automatically", "after", "saving", "." ]
d7d070ad11f5731be141cf55c2756accaaf51402
https://github.com/monomelodies/ornament/blob/d7d070ad11f5731be141cf55c2756accaaf51402/src/Model.php#L348-L364
11,059
ironedgesoftware/graphs
src/Export/Writer/GraphvizWriter.php
GraphvizWriter.getUtils
public function getUtils(): Utils { if ($this->_utils === null) { $this->_utils = new Utils($this->getSystemService()); } return $this->_utils; }
php
public function getUtils(): Utils { if ($this->_utils === null) { $this->_utils = new Utils($this->getSystemService()); } return $this->_utils; }
[ "public", "function", "getUtils", "(", ")", ":", "Utils", "{", "if", "(", "$", "this", "->", "_utils", "===", "null", ")", "{", "$", "this", "->", "_utils", "=", "new", "Utils", "(", "$", "this", "->", "getSystemService", "(", ")", ")", ";", "}", "return", "$", "this", "->", "_utils", ";", "}" ]
Returns the value of field _utils. @return Utils
[ "Returns", "the", "value", "of", "field", "_utils", "." ]
c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0
https://github.com/ironedgesoftware/graphs/blob/c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0/src/Export/Writer/GraphvizWriter.php#L58-L65
11,060
ironedgesoftware/graphs
src/Export/Writer/GraphvizWriter.php
GraphvizWriter.write
public function write(array $data, array $options) { if (!$this->getUtils()->isDotInstalled()) { throw ExportException::create( 'Can\'t export to a Graphviz image because "dot" binary is not available. Verify that the ' . '"graphviz" package is installed on your system.' ); } if (!isset($data['node']) || !($data['node'] instanceof NodeInterface)) { throw ValidationException::create( 'Data attribute "node" must be an instance of IronEdge\Component\Graphs\Node\NodeInterface.' ); } if (!isset($options['path']) || !is_string($options['path']) || $options['path'] === '') { throw ValidationException::create( 'To be able to export this graph to a graphviz image, you must set option "path" with a string ' . 'with the path to the target file.' ); } /** @var NodeInterface $graph */ $graph = $data['node']; $file = $options['path']; $graphvizCode = 'digraph ' . $graph->getId() . ' {' . PHP_EOL; $graphAttributes = $graph->getMetadataAttr('graphviz.nodeAttributes', []); if ($graphAttributes) { foreach ($graphAttributes as $k => $v) { $graphvizCode .= ' ' . $k . '=' . $v . ';' . PHP_EOL; } $graphvizCode .= PHP_EOL; } $graphvizCode .= $this->generateNodeCode($graph); $graphvizCode .= '}'; $this->generateGraphvizOutputFile($graphvizCode, $file, ['targetType' => 'png']); }
php
public function write(array $data, array $options) { if (!$this->getUtils()->isDotInstalled()) { throw ExportException::create( 'Can\'t export to a Graphviz image because "dot" binary is not available. Verify that the ' . '"graphviz" package is installed on your system.' ); } if (!isset($data['node']) || !($data['node'] instanceof NodeInterface)) { throw ValidationException::create( 'Data attribute "node" must be an instance of IronEdge\Component\Graphs\Node\NodeInterface.' ); } if (!isset($options['path']) || !is_string($options['path']) || $options['path'] === '') { throw ValidationException::create( 'To be able to export this graph to a graphviz image, you must set option "path" with a string ' . 'with the path to the target file.' ); } /** @var NodeInterface $graph */ $graph = $data['node']; $file = $options['path']; $graphvizCode = 'digraph ' . $graph->getId() . ' {' . PHP_EOL; $graphAttributes = $graph->getMetadataAttr('graphviz.nodeAttributes', []); if ($graphAttributes) { foreach ($graphAttributes as $k => $v) { $graphvizCode .= ' ' . $k . '=' . $v . ';' . PHP_EOL; } $graphvizCode .= PHP_EOL; } $graphvizCode .= $this->generateNodeCode($graph); $graphvizCode .= '}'; $this->generateGraphvizOutputFile($graphvizCode, $file, ['targetType' => 'png']); }
[ "public", "function", "write", "(", "array", "$", "data", ",", "array", "$", "options", ")", "{", "if", "(", "!", "$", "this", "->", "getUtils", "(", ")", "->", "isDotInstalled", "(", ")", ")", "{", "throw", "ExportException", "::", "create", "(", "'Can\\'t export to a Graphviz image because \"dot\" binary is not available. Verify that the '", ".", "'\"graphviz\" package is installed on your system.'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "'node'", "]", ")", "||", "!", "(", "$", "data", "[", "'node'", "]", "instanceof", "NodeInterface", ")", ")", "{", "throw", "ValidationException", "::", "create", "(", "'Data attribute \"node\" must be an instance of IronEdge\\Component\\Graphs\\Node\\NodeInterface.'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "options", "[", "'path'", "]", ")", "||", "!", "is_string", "(", "$", "options", "[", "'path'", "]", ")", "||", "$", "options", "[", "'path'", "]", "===", "''", ")", "{", "throw", "ValidationException", "::", "create", "(", "'To be able to export this graph to a graphviz image, you must set option \"path\" with a string '", ".", "'with the path to the target file.'", ")", ";", "}", "/** @var NodeInterface $graph */", "$", "graph", "=", "$", "data", "[", "'node'", "]", ";", "$", "file", "=", "$", "options", "[", "'path'", "]", ";", "$", "graphvizCode", "=", "'digraph '", ".", "$", "graph", "->", "getId", "(", ")", ".", "' {'", ".", "PHP_EOL", ";", "$", "graphAttributes", "=", "$", "graph", "->", "getMetadataAttr", "(", "'graphviz.nodeAttributes'", ",", "[", "]", ")", ";", "if", "(", "$", "graphAttributes", ")", "{", "foreach", "(", "$", "graphAttributes", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "graphvizCode", ".=", "' '", ".", "$", "k", ".", "'='", ".", "$", "v", ".", "';'", ".", "PHP_EOL", ";", "}", "$", "graphvizCode", ".=", "PHP_EOL", ";", "}", "$", "graphvizCode", ".=", "$", "this", "->", "generateNodeCode", "(", "$", "graph", ")", ";", "$", "graphvizCode", ".=", "'}'", ";", "$", "this", "->", "generateGraphvizOutputFile", "(", "$", "graphvizCode", ",", "$", "file", ",", "[", "'targetType'", "=>", "'png'", "]", ")", ";", "}" ]
Writes the data into a graphviz image. @param array $data - Data. @param array $options - Options. @throws ValidationException @throws ExportException @return void
[ "Writes", "the", "data", "into", "a", "graphviz", "image", "." ]
c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0
https://github.com/ironedgesoftware/graphs/blob/c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0/src/Export/Writer/GraphvizWriter.php#L120-L162
11,061
ironedgesoftware/graphs
src/Export/Writer/GraphvizWriter.php
GraphvizWriter.generateGraphvizOutputFile
protected function generateGraphvizOutputFile( string $graphvizCode, string $targetFile, array $graphvizOptions = [] ): GraphvizWriter { $graphvizOptions = array_replace_recursive( [ 'targetType' => 'png' ], $graphvizOptions ); $tmpFile = $targetFile.'.tmp'; $this->removeFile($targetFile) ->removeFile($tmpFile); $this->writeFile($graphvizCode, $tmpFile); exec('dot -T'.$graphvizOptions['targetType'].' '.$tmpFile.' -o '.$targetFile, $output, $status); if ($status) { throw ExportException::create( 'Couldn\'t generate Graphviz image. Exit Code: '.$status.' - Output: '.print_r($output, true) ); } $this->removeFile($tmpFile); return $this; }
php
protected function generateGraphvizOutputFile( string $graphvizCode, string $targetFile, array $graphvizOptions = [] ): GraphvizWriter { $graphvizOptions = array_replace_recursive( [ 'targetType' => 'png' ], $graphvizOptions ); $tmpFile = $targetFile.'.tmp'; $this->removeFile($targetFile) ->removeFile($tmpFile); $this->writeFile($graphvizCode, $tmpFile); exec('dot -T'.$graphvizOptions['targetType'].' '.$tmpFile.' -o '.$targetFile, $output, $status); if ($status) { throw ExportException::create( 'Couldn\'t generate Graphviz image. Exit Code: '.$status.' - Output: '.print_r($output, true) ); } $this->removeFile($tmpFile); return $this; }
[ "protected", "function", "generateGraphvizOutputFile", "(", "string", "$", "graphvizCode", ",", "string", "$", "targetFile", ",", "array", "$", "graphvizOptions", "=", "[", "]", ")", ":", "GraphvizWriter", "{", "$", "graphvizOptions", "=", "array_replace_recursive", "(", "[", "'targetType'", "=>", "'png'", "]", ",", "$", "graphvizOptions", ")", ";", "$", "tmpFile", "=", "$", "targetFile", ".", "'.tmp'", ";", "$", "this", "->", "removeFile", "(", "$", "targetFile", ")", "->", "removeFile", "(", "$", "tmpFile", ")", ";", "$", "this", "->", "writeFile", "(", "$", "graphvizCode", ",", "$", "tmpFile", ")", ";", "exec", "(", "'dot -T'", ".", "$", "graphvizOptions", "[", "'targetType'", "]", ".", "' '", ".", "$", "tmpFile", ".", "' -o '", ".", "$", "targetFile", ",", "$", "output", ",", "$", "status", ")", ";", "if", "(", "$", "status", ")", "{", "throw", "ExportException", "::", "create", "(", "'Couldn\\'t generate Graphviz image. Exit Code: '", ".", "$", "status", ".", "' - Output: '", ".", "print_r", "(", "$", "output", ",", "true", ")", ")", ";", "}", "$", "this", "->", "removeFile", "(", "$", "tmpFile", ")", ";", "return", "$", "this", ";", "}" ]
Exports a graphviz code to a file. @param string $graphvizCode - Graphviz code. @param string $targetFile - Target file. @param array $graphvizOptions - Graphviz options. @throws ExportException @return GraphvizWriter
[ "Exports", "a", "graphviz", "code", "to", "a", "file", "." ]
c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0
https://github.com/ironedgesoftware/graphs/blob/c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0/src/Export/Writer/GraphvizWriter.php#L259-L289
11,062
ironedgesoftware/graphs
src/Export/Writer/GraphvizWriter.php
GraphvizWriter.writeFile
protected function writeFile(string $contents, string $file): GraphvizWriter { if (!file_put_contents($file, $contents)) { throw ExportException::create( 'Couldn\'t write to file "'.$file.'".' ); } return $this; }
php
protected function writeFile(string $contents, string $file): GraphvizWriter { if (!file_put_contents($file, $contents)) { throw ExportException::create( 'Couldn\'t write to file "'.$file.'".' ); } return $this; }
[ "protected", "function", "writeFile", "(", "string", "$", "contents", ",", "string", "$", "file", ")", ":", "GraphvizWriter", "{", "if", "(", "!", "file_put_contents", "(", "$", "file", ",", "$", "contents", ")", ")", "{", "throw", "ExportException", "::", "create", "(", "'Couldn\\'t write to file \"'", ".", "$", "file", ".", "'\".'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Writes contents to a file. @param string $contents - File contents. @param string $file - File. @throws ExportException @return GraphvizWriter
[ "Writes", "contents", "to", "a", "file", "." ]
c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0
https://github.com/ironedgesoftware/graphs/blob/c1cc2347e7ba1935fe6b06356a74f0cf3101f5a0/src/Export/Writer/GraphvizWriter.php#L315-L324
11,063
smeeckaert/di
src/Decorator/Builder.php
Builder.checkParams
protected function checkParams($params) { foreach ($params as $type) { if ($type instanceof Decorator) { $this->errors[] = "Parameter is not well instantiated [" . (string)$type . "]"; } } }
php
protected function checkParams($params) { foreach ($params as $type) { if ($type instanceof Decorator) { $this->errors[] = "Parameter is not well instantiated [" . (string)$type . "]"; } } }
[ "protected", "function", "checkParams", "(", "$", "params", ")", "{", "foreach", "(", "$", "params", "as", "$", "type", ")", "{", "if", "(", "$", "type", "instanceof", "Decorator", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "\"Parameter is not well instantiated [\"", ".", "(", "string", ")", "$", "type", ".", "\"]\"", ";", "}", "}", "}" ]
Check if parameters are usable Mainly if parameters are still decorators it will break the injection @param $params
[ "Check", "if", "parameters", "are", "usable", "Mainly", "if", "parameters", "are", "still", "decorators", "it", "will", "break", "the", "injection" ]
3d5e3ed20038bed9a42fcd2821970f77112b8d3c
https://github.com/smeeckaert/di/blob/3d5e3ed20038bed9a42fcd2821970f77112b8d3c/src/Decorator/Builder.php#L75-L82
11,064
smeeckaert/di
src/Decorator/Builder.php
Builder.setParams
protected function setParams($position, $required, $param) { if (!empty($required['class']) && !is_a($param, $required['class'])) { $this->errors[] = sprintf("You can't put an instance of %s in the parameter #%s $%s of type %s", get_class($param), $position, $required['name'], $required['class']); return false; } $this->methodParams[$position] = $param; }
php
protected function setParams($position, $required, $param) { if (!empty($required['class']) && !is_a($param, $required['class'])) { $this->errors[] = sprintf("You can't put an instance of %s in the parameter #%s $%s of type %s", get_class($param), $position, $required['name'], $required['class']); return false; } $this->methodParams[$position] = $param; }
[ "protected", "function", "setParams", "(", "$", "position", ",", "$", "required", ",", "$", "param", ")", "{", "if", "(", "!", "empty", "(", "$", "required", "[", "'class'", "]", ")", "&&", "!", "is_a", "(", "$", "param", ",", "$", "required", "[", "'class'", "]", ")", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "sprintf", "(", "\"You can't put an instance of %s in the parameter #%s $%s of type %s\"", ",", "get_class", "(", "$", "param", ")", ",", "$", "position", ",", "$", "required", "[", "'name'", "]", ",", "$", "required", "[", "'class'", "]", ")", ";", "return", "false", ";", "}", "$", "this", "->", "methodParams", "[", "$", "position", "]", "=", "$", "param", ";", "}" ]
Set into the methodParams array the correct param for the position @param $position @param $required @param $param @return bool
[ "Set", "into", "the", "methodParams", "array", "the", "correct", "param", "for", "the", "position" ]
3d5e3ed20038bed9a42fcd2821970f77112b8d3c
https://github.com/smeeckaert/di/blob/3d5e3ed20038bed9a42fcd2821970f77112b8d3c/src/Decorator/Builder.php#L91-L99
11,065
neradp/SNPClient
src/bTd/SNP/Protocol/Message.php
Message.addToContent
public function addToContent(string $param, string $value): void { $this->content[$param] = $value; }
php
public function addToContent(string $param, string $value): void { $this->content[$param] = $value; }
[ "public", "function", "addToContent", "(", "string", "$", "param", ",", "string", "$", "value", ")", ":", "void", "{", "$", "this", "->", "content", "[", "$", "param", "]", "=", "$", "value", ";", "}" ]
Add a named value to the content part of message. @param string $param Name. @param string $value Value. @return void
[ "Add", "a", "named", "value", "to", "the", "content", "part", "of", "message", "." ]
68a7ddf0fe7c0a5b64417cb27aed190c029fcfcc
https://github.com/neradp/SNPClient/blob/68a7ddf0fe7c0a5b64417cb27aed190c029fcfcc/src/bTd/SNP/Protocol/Message.php#L70-L74
11,066
novuso/common
src/Application/Messaging/Event/ServiceAwareEventDispatcher.php
ServiceAwareEventDispatcher.registerService
public function registerService(string $className, string $serviceId): void { assert( Validate::implementsInterface($className, EventSubscriber::class), sprintf('Invalid subscriber class: %s', $className) ); /** @var EventSubscriber $className The subscriber class name */ foreach ($className::eventRegistration() as $eventType => $params) { $eventType = ClassName::underscore($eventType); if (is_string($params)) { $this->addHandlerService($eventType, $serviceId, $params); } elseif (is_string($params[0])) { $priority = isset($params[1]) ? (int) $params[1] : 0; $this->addHandlerService($eventType, $serviceId, $params[0], $priority); } else { foreach ($params as $handler) { $priority = isset($handler[1]) ? (int) $handler[1] : 0; $this->addHandlerService($eventType, $serviceId, $handler[0], $priority); } } } }
php
public function registerService(string $className, string $serviceId): void { assert( Validate::implementsInterface($className, EventSubscriber::class), sprintf('Invalid subscriber class: %s', $className) ); /** @var EventSubscriber $className The subscriber class name */ foreach ($className::eventRegistration() as $eventType => $params) { $eventType = ClassName::underscore($eventType); if (is_string($params)) { $this->addHandlerService($eventType, $serviceId, $params); } elseif (is_string($params[0])) { $priority = isset($params[1]) ? (int) $params[1] : 0; $this->addHandlerService($eventType, $serviceId, $params[0], $priority); } else { foreach ($params as $handler) { $priority = isset($handler[1]) ? (int) $handler[1] : 0; $this->addHandlerService($eventType, $serviceId, $handler[0], $priority); } } } }
[ "public", "function", "registerService", "(", "string", "$", "className", ",", "string", "$", "serviceId", ")", ":", "void", "{", "assert", "(", "Validate", "::", "implementsInterface", "(", "$", "className", ",", "EventSubscriber", "::", "class", ")", ",", "sprintf", "(", "'Invalid subscriber class: %s'", ",", "$", "className", ")", ")", ";", "/** @var EventSubscriber $className The subscriber class name */", "foreach", "(", "$", "className", "::", "eventRegistration", "(", ")", "as", "$", "eventType", "=>", "$", "params", ")", "{", "$", "eventType", "=", "ClassName", "::", "underscore", "(", "$", "eventType", ")", ";", "if", "(", "is_string", "(", "$", "params", ")", ")", "{", "$", "this", "->", "addHandlerService", "(", "$", "eventType", ",", "$", "serviceId", ",", "$", "params", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "params", "[", "0", "]", ")", ")", "{", "$", "priority", "=", "isset", "(", "$", "params", "[", "1", "]", ")", "?", "(", "int", ")", "$", "params", "[", "1", "]", ":", "0", ";", "$", "this", "->", "addHandlerService", "(", "$", "eventType", ",", "$", "serviceId", ",", "$", "params", "[", "0", "]", ",", "$", "priority", ")", ";", "}", "else", "{", "foreach", "(", "$", "params", "as", "$", "handler", ")", "{", "$", "priority", "=", "isset", "(", "$", "handler", "[", "1", "]", ")", "?", "(", "int", ")", "$", "handler", "[", "1", "]", ":", "0", ";", "$", "this", "->", "addHandlerService", "(", "$", "eventType", ",", "$", "serviceId", ",", "$", "handler", "[", "0", "]", ",", "$", "priority", ")", ";", "}", "}", "}", "}" ]
Registers a subscriber service to handle events The subscriber class must implement: Novuso\Common\Domain\Messaging\Event\EventSubscriber @param string $className The subscriber class name @param string $serviceId The subscriber service ID @return void
[ "Registers", "a", "subscriber", "service", "to", "handle", "events" ]
7d0e5a4f4c79c9622e068efc8b7c70815c460863
https://github.com/novuso/common/blob/7d0e5a4f4c79c9622e068efc8b7c70815c460863/src/Application/Messaging/Event/ServiceAwareEventDispatcher.php#L62-L83
11,067
novuso/common
src/Application/Messaging/Event/ServiceAwareEventDispatcher.php
ServiceAwareEventDispatcher.addHandlerService
public function addHandlerService(string $eventType, string $serviceId, string $method, int $priority = 0): void { if (!isset($this->serviceIds[$eventType])) { $this->serviceIds[$eventType] = []; } $this->serviceIds[$eventType][] = [$serviceId, $method, $priority]; }
php
public function addHandlerService(string $eventType, string $serviceId, string $method, int $priority = 0): void { if (!isset($this->serviceIds[$eventType])) { $this->serviceIds[$eventType] = []; } $this->serviceIds[$eventType][] = [$serviceId, $method, $priority]; }
[ "public", "function", "addHandlerService", "(", "string", "$", "eventType", ",", "string", "$", "serviceId", ",", "string", "$", "method", ",", "int", "$", "priority", "=", "0", ")", ":", "void", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "serviceIds", "[", "$", "eventType", "]", ")", ")", "{", "$", "this", "->", "serviceIds", "[", "$", "eventType", "]", "=", "[", "]", ";", "}", "$", "this", "->", "serviceIds", "[", "$", "eventType", "]", "[", "]", "=", "[", "$", "serviceId", ",", "$", "method", ",", "$", "priority", "]", ";", "}" ]
Adds a handler service for a specific event @param string $eventType The event type @param string $serviceId The handler service ID @param string $method The name of the method to invoke @param int $priority Higher priority handlers are called first @return void
[ "Adds", "a", "handler", "service", "for", "a", "specific", "event" ]
7d0e5a4f4c79c9622e068efc8b7c70815c460863
https://github.com/novuso/common/blob/7d0e5a4f4c79c9622e068efc8b7c70815c460863/src/Application/Messaging/Event/ServiceAwareEventDispatcher.php#L95-L102
11,068
novuso/common
src/Application/Messaging/Event/ServiceAwareEventDispatcher.php
ServiceAwareEventDispatcher.lazyLoad
protected function lazyLoad(string $eventType): void { if (isset($this->serviceIds[$eventType])) { foreach ($this->serviceIds[$eventType] as $args) { list($serviceId, $method, $priority) = $args; $service = $this->container->get($serviceId); $key = sprintf('%s.%s', $serviceId, $method); if (!isset($this->services[$eventType][$key])) { $this->addHandler($eventType, [$service, $method], $priority); } elseif ($service !== $this->services[$eventType][$key]) { parent::removeHandler($eventType, [$this->services[$eventType][$key], $method]); $this->addHandler($eventType, [$service, $method], $priority); } $this->services[$eventType][$key] = $service; } } }
php
protected function lazyLoad(string $eventType): void { if (isset($this->serviceIds[$eventType])) { foreach ($this->serviceIds[$eventType] as $args) { list($serviceId, $method, $priority) = $args; $service = $this->container->get($serviceId); $key = sprintf('%s.%s', $serviceId, $method); if (!isset($this->services[$eventType][$key])) { $this->addHandler($eventType, [$service, $method], $priority); } elseif ($service !== $this->services[$eventType][$key]) { parent::removeHandler($eventType, [$this->services[$eventType][$key], $method]); $this->addHandler($eventType, [$service, $method], $priority); } $this->services[$eventType][$key] = $service; } } }
[ "protected", "function", "lazyLoad", "(", "string", "$", "eventType", ")", ":", "void", "{", "if", "(", "isset", "(", "$", "this", "->", "serviceIds", "[", "$", "eventType", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "serviceIds", "[", "$", "eventType", "]", "as", "$", "args", ")", "{", "list", "(", "$", "serviceId", ",", "$", "method", ",", "$", "priority", ")", "=", "$", "args", ";", "$", "service", "=", "$", "this", "->", "container", "->", "get", "(", "$", "serviceId", ")", ";", "$", "key", "=", "sprintf", "(", "'%s.%s'", ",", "$", "serviceId", ",", "$", "method", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "services", "[", "$", "eventType", "]", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "addHandler", "(", "$", "eventType", ",", "[", "$", "service", ",", "$", "method", "]", ",", "$", "priority", ")", ";", "}", "elseif", "(", "$", "service", "!==", "$", "this", "->", "services", "[", "$", "eventType", "]", "[", "$", "key", "]", ")", "{", "parent", "::", "removeHandler", "(", "$", "eventType", ",", "[", "$", "this", "->", "services", "[", "$", "eventType", "]", "[", "$", "key", "]", ",", "$", "method", "]", ")", ";", "$", "this", "->", "addHandler", "(", "$", "eventType", ",", "[", "$", "service", ",", "$", "method", "]", ",", "$", "priority", ")", ";", "}", "$", "this", "->", "services", "[", "$", "eventType", "]", "[", "$", "key", "]", "=", "$", "service", ";", "}", "}", "}" ]
Lazy loads event handlers from the service container @param string $eventType The event type @return void
[ "Lazy", "loads", "event", "handlers", "from", "the", "service", "container" ]
7d0e5a4f4c79c9622e068efc8b7c70815c460863
https://github.com/novuso/common/blob/7d0e5a4f4c79c9622e068efc8b7c70815c460863/src/Application/Messaging/Event/ServiceAwareEventDispatcher.php#L181-L197
11,069
nozerrat/daniia
Daniia/Daniia.php
Daniia.connection
private function connection() { $this->apply_config_db(); try { if ( @$_ENV["daniia_connection"] && !$this->id_conn ) { $this->id_conn = $_ENV["daniia_connection"]; } elseif ( !$this->id_conn ) { $this->id_conn = new \PDO($this->dsn, $this->user, $this->pass); } } catch (\PDOException $e) { die("Error: " . $e->getMessage() . "<br/>"); } $this->get_instance(); return $this; }
php
private function connection() { $this->apply_config_db(); try { if ( @$_ENV["daniia_connection"] && !$this->id_conn ) { $this->id_conn = $_ENV["daniia_connection"]; } elseif ( !$this->id_conn ) { $this->id_conn = new \PDO($this->dsn, $this->user, $this->pass); } } catch (\PDOException $e) { die("Error: " . $e->getMessage() . "<br/>"); } $this->get_instance(); return $this; }
[ "private", "function", "connection", "(", ")", "{", "$", "this", "->", "apply_config_db", "(", ")", ";", "try", "{", "if", "(", "@", "$", "_ENV", "[", "\"daniia_connection\"", "]", "&&", "!", "$", "this", "->", "id_conn", ")", "{", "$", "this", "->", "id_conn", "=", "$", "_ENV", "[", "\"daniia_connection\"", "]", ";", "}", "elseif", "(", "!", "$", "this", "->", "id_conn", ")", "{", "$", "this", "->", "id_conn", "=", "new", "\\", "PDO", "(", "$", "this", "->", "dsn", ",", "$", "this", "->", "user", ",", "$", "this", "->", "pass", ")", ";", "}", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "die", "(", "\"Error: \"", ".", "$", "e", "->", "getMessage", "(", ")", ".", "\"<br/>\"", ")", ";", "}", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}" ]
Establese la coneccion a la Base de Datdos @author Carlos Garcia @return Object
[ "Establese", "la", "coneccion", "a", "la", "Base", "de", "Datdos" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L292-L307
11,070
nozerrat/daniia
Daniia/Daniia.php
Daniia.reset
private function reset() { $this->select = " SELECT * "; $this->from = " FROM _table_ "; $this->join = " "; $this->on = " "; $this->where = " "; $this->groupBy = " "; $this->having = " "; $this->orderBy = " "; $this->limit = " "; $this->offset = " "; $this->union = " "; $this->case = ""; $this->when = ""; $this->else = ""; $this->rows = [] ; $this->placeholder_data = [] ; $_ENV["daniia_daniia"] = null; $this->get_instance(); return $this; }
php
private function reset() { $this->select = " SELECT * "; $this->from = " FROM _table_ "; $this->join = " "; $this->on = " "; $this->where = " "; $this->groupBy = " "; $this->having = " "; $this->orderBy = " "; $this->limit = " "; $this->offset = " "; $this->union = " "; $this->case = ""; $this->when = ""; $this->else = ""; $this->rows = [] ; $this->placeholder_data = [] ; $_ENV["daniia_daniia"] = null; $this->get_instance(); return $this; }
[ "private", "function", "reset", "(", ")", "{", "$", "this", "->", "select", "=", "\" SELECT * \"", ";", "$", "this", "->", "from", "=", "\" FROM _table_ \"", ";", "$", "this", "->", "join", "=", "\" \"", ";", "$", "this", "->", "on", "=", "\" \"", ";", "$", "this", "->", "where", "=", "\" \"", ";", "$", "this", "->", "groupBy", "=", "\" \"", ";", "$", "this", "->", "having", "=", "\" \"", ";", "$", "this", "->", "orderBy", "=", "\" \"", ";", "$", "this", "->", "limit", "=", "\" \"", ";", "$", "this", "->", "offset", "=", "\" \"", ";", "$", "this", "->", "union", "=", "\" \"", ";", "$", "this", "->", "case", "=", "\"\"", ";", "$", "this", "->", "when", "=", "\"\"", ";", "$", "this", "->", "else", "=", "\"\"", ";", "$", "this", "->", "rows", "=", "[", "]", ";", "$", "this", "->", "placeholder_data", "=", "[", "]", ";", "$", "_ENV", "[", "\"daniia_daniia\"", "]", "=", "null", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}" ]
resetea todas las variables de la clase por defecto @author Carlos Garcia @return Object
[ "resetea", "todas", "las", "variables", "de", "la", "clase", "por", "defecto" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L314-L335
11,071
nozerrat/daniia
Daniia/Daniia.php
Daniia.query
final public function query( string $sql, $closure=NULL ) { $this->connection(); $this->last_sql = $this->sql = $sql; $this->fetch(); $this->data = $this->rows; $this->reset(); if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
php
final public function query( string $sql, $closure=NULL ) { $this->connection(); $this->last_sql = $this->sql = $sql; $this->fetch(); $this->data = $this->rows; $this->reset(); if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
[ "final", "public", "function", "query", "(", "string", "$", "sql", ",", "$", "closure", "=", "NULL", ")", "{", "$", "this", "->", "connection", "(", ")", ";", "$", "this", "->", "last_sql", "=", "$", "this", "->", "sql", "=", "$", "sql", ";", "$", "this", "->", "fetch", "(", ")", ";", "$", "this", "->", "data", "=", "$", "this", "->", "rows", ";", "$", "this", "->", "reset", "(", ")", ";", "if", "(", "$", "closure", "instanceof", "\\", "Closure", ")", "{", "$", "this", "->", "data", "=", "$", "closure", "(", "$", "this", "->", "data", ",", "$", "this", ")", ";", "}", "return", "$", "this", "->", "data", "?", ":", "[", "]", ";", "}" ]
Ejecuta una sentencia SQL, devolviendo un conjunto de resultados como un objeto @author Carlos Garcia @param String $sql @return Array
[ "Ejecuta", "una", "sentencia", "SQL", "devolviendo", "un", "conjunto", "de", "resultados", "como", "un", "objeto" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L502-L512
11,072
nozerrat/daniia
Daniia/Daniia.php
Daniia.queryArray
final public function queryArray( string $sql, $closure=NULL ) { $type_fetch = $this->type_fetch; $this->type_fetch = 'assoc'; $this->query( $sql ); $this->type_fetch = $type_fetch; // $this->data = array_map(function($v){return(array)$v;},$this->data); if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
php
final public function queryArray( string $sql, $closure=NULL ) { $type_fetch = $this->type_fetch; $this->type_fetch = 'assoc'; $this->query( $sql ); $this->type_fetch = $type_fetch; // $this->data = array_map(function($v){return(array)$v;},$this->data); if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
[ "final", "public", "function", "queryArray", "(", "string", "$", "sql", ",", "$", "closure", "=", "NULL", ")", "{", "$", "type_fetch", "=", "$", "this", "->", "type_fetch", ";", "$", "this", "->", "type_fetch", "=", "'assoc'", ";", "$", "this", "->", "query", "(", "$", "sql", ")", ";", "$", "this", "->", "type_fetch", "=", "$", "type_fetch", ";", "// $this->data = array_map(function($v){return(array)$v;},$this->data);", "if", "(", "$", "closure", "instanceof", "\\", "Closure", ")", "{", "$", "this", "->", "data", "=", "$", "closure", "(", "$", "this", "->", "data", ",", "$", "this", ")", ";", "}", "return", "$", "this", "->", "data", "?", ":", "[", "]", ";", "}" ]
Ejecuta una sentencia SQL, devolviendo un conjunto de resultados como un Array @author Carlos Garcia @param Closure $closure @return Array
[ "Ejecuta", "una", "sentencia", "SQL", "devolviendo", "un", "conjunto", "de", "resultados", "como", "un", "Array" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L520-L530
11,073
nozerrat/daniia
Daniia/Daniia.php
Daniia.get
final public function get($closure=NULL) { $this->connection(); if ($this->table===NULL) { if ( !preg_match('/^ *FROM +\(/', $this->from) ) { $this->from = ''; } } else { if (preg_match('/\./', $this->table) || !$this->schema ) { $this->from = str_replace("_table_", $this->table, $this->from); } else { $this->from = str_replace("_table_", $this->schema.'.'.$this->table, $this->from); } } $this->last_sql = $this->sql = $this->select.' '.$this->from.' '.$this->join.' '.$this->where.' '.$this->union.' '.$this->groupBy.' '.$this->having.' '.$this->orderBy.' '.$this->limit.' '.$this->offset; if ($closure===FALSE) return $this->sql; $this->fetch(); $this->data = $this->rows; $this->reset(); if ( $this->tableOrig!==NULL ) { $this->table = $this->tableOrig; } if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
php
final public function get($closure=NULL) { $this->connection(); if ($this->table===NULL) { if ( !preg_match('/^ *FROM +\(/', $this->from) ) { $this->from = ''; } } else { if (preg_match('/\./', $this->table) || !$this->schema ) { $this->from = str_replace("_table_", $this->table, $this->from); } else { $this->from = str_replace("_table_", $this->schema.'.'.$this->table, $this->from); } } $this->last_sql = $this->sql = $this->select.' '.$this->from.' '.$this->join.' '.$this->where.' '.$this->union.' '.$this->groupBy.' '.$this->having.' '.$this->orderBy.' '.$this->limit.' '.$this->offset; if ($closure===FALSE) return $this->sql; $this->fetch(); $this->data = $this->rows; $this->reset(); if ( $this->tableOrig!==NULL ) { $this->table = $this->tableOrig; } if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
[ "final", "public", "function", "get", "(", "$", "closure", "=", "NULL", ")", "{", "$", "this", "->", "connection", "(", ")", ";", "if", "(", "$", "this", "->", "table", "===", "NULL", ")", "{", "if", "(", "!", "preg_match", "(", "'/^ *FROM +\\(/'", ",", "$", "this", "->", "from", ")", ")", "{", "$", "this", "->", "from", "=", "''", ";", "}", "}", "else", "{", "if", "(", "preg_match", "(", "'/\\./'", ",", "$", "this", "->", "table", ")", "||", "!", "$", "this", "->", "schema", ")", "{", "$", "this", "->", "from", "=", "str_replace", "(", "\"_table_\"", ",", "$", "this", "->", "table", ",", "$", "this", "->", "from", ")", ";", "}", "else", "{", "$", "this", "->", "from", "=", "str_replace", "(", "\"_table_\"", ",", "$", "this", "->", "schema", ".", "'.'", ".", "$", "this", "->", "table", ",", "$", "this", "->", "from", ")", ";", "}", "}", "$", "this", "->", "last_sql", "=", "$", "this", "->", "sql", "=", "$", "this", "->", "select", ".", "' '", ".", "$", "this", "->", "from", ".", "' '", ".", "$", "this", "->", "join", ".", "' '", ".", "$", "this", "->", "where", ".", "' '", ".", "$", "this", "->", "union", ".", "' '", ".", "$", "this", "->", "groupBy", ".", "' '", ".", "$", "this", "->", "having", ".", "' '", ".", "$", "this", "->", "orderBy", ".", "' '", ".", "$", "this", "->", "limit", ".", "' '", ".", "$", "this", "->", "offset", ";", "if", "(", "$", "closure", "===", "FALSE", ")", "return", "$", "this", "->", "sql", ";", "$", "this", "->", "fetch", "(", ")", ";", "$", "this", "->", "data", "=", "$", "this", "->", "rows", ";", "$", "this", "->", "reset", "(", ")", ";", "if", "(", "$", "this", "->", "tableOrig", "!==", "NULL", ")", "{", "$", "this", "->", "table", "=", "$", "this", "->", "tableOrig", ";", "}", "if", "(", "$", "closure", "instanceof", "\\", "Closure", ")", "{", "$", "this", "->", "data", "=", "$", "closure", "(", "$", "this", "->", "data", ",", "$", "this", ")", ";", "}", "return", "$", "this", "->", "data", "?", ":", "[", "]", ";", "}" ]
Retorna los datos consultados @author Carlos Garcia @param Closure $closure @return Array|object
[ "Retorna", "los", "datos", "consultados" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L540-L575
11,074
nozerrat/daniia
Daniia/Daniia.php
Daniia.getArray
final public function getArray($closure=NULL) { $type_fetch = $this->type_fetch; $this->type_fetch = 'assoc'; $this->get(); $this->type_fetch = $type_fetch; // $this->data = array_map(function($v){return(array)$v;},$this->data); if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
php
final public function getArray($closure=NULL) { $type_fetch = $this->type_fetch; $this->type_fetch = 'assoc'; $this->get(); $this->type_fetch = $type_fetch; // $this->data = array_map(function($v){return(array)$v;},$this->data); if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this->data ?: []; }
[ "final", "public", "function", "getArray", "(", "$", "closure", "=", "NULL", ")", "{", "$", "type_fetch", "=", "$", "this", "->", "type_fetch", ";", "$", "this", "->", "type_fetch", "=", "'assoc'", ";", "$", "this", "->", "get", "(", ")", ";", "$", "this", "->", "type_fetch", "=", "$", "type_fetch", ";", "// $this->data = array_map(function($v){return(array)$v;},$this->data);", "if", "(", "$", "closure", "instanceof", "\\", "Closure", ")", "{", "$", "this", "->", "data", "=", "$", "closure", "(", "$", "this", "->", "data", ",", "$", "this", ")", ";", "}", "return", "$", "this", "->", "data", "?", ":", "[", "]", ";", "}" ]
Retorna los datos consultados en formato Array @author Carlos Garcia @param Closure $closure @return Array
[ "Retorna", "los", "datos", "consultados", "en", "formato", "Array" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L583-L593
11,075
nozerrat/daniia
Daniia/Daniia.php
Daniia.find
final public function find($ids=[]) { if (func_num_args()>0) { if (func_num_args()===1) { if (!is_array($ids)) { $ids = (array) $ids ; } } else { $ids = func_get_args(); } } $closure = NULL; if ( count(func_get_args())>1 ) { if ( $ids[count($ids)-1] instanceof \Closure ) { $closure = array_pop($ids); } if (is_array($ids[0])) { $ids = $ids[0]; } } $this->find_first_data = $this->find_save_data = $this->find_delete_data = TRUE; if ( count($ids) && !(@$ids[0] instanceof \Closure) ) { if ( $this->is_assoc( $ids ) ) { $this->where( $ids ); } else { $this->where( $this->primaryKey, 'in', $ids ); } } $this->get(); if (count($ids)===1 && count($this->data)===1) { $this->data = $this->data[0]; } if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this; }
php
final public function find($ids=[]) { if (func_num_args()>0) { if (func_num_args()===1) { if (!is_array($ids)) { $ids = (array) $ids ; } } else { $ids = func_get_args(); } } $closure = NULL; if ( count(func_get_args())>1 ) { if ( $ids[count($ids)-1] instanceof \Closure ) { $closure = array_pop($ids); } if (is_array($ids[0])) { $ids = $ids[0]; } } $this->find_first_data = $this->find_save_data = $this->find_delete_data = TRUE; if ( count($ids) && !(@$ids[0] instanceof \Closure) ) { if ( $this->is_assoc( $ids ) ) { $this->where( $ids ); } else { $this->where( $this->primaryKey, 'in', $ids ); } } $this->get(); if (count($ids)===1 && count($this->data)===1) { $this->data = $this->data[0]; } if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } return $this; }
[ "final", "public", "function", "find", "(", "$", "ids", "=", "[", "]", ")", "{", "if", "(", "func_num_args", "(", ")", ">", "0", ")", "{", "if", "(", "func_num_args", "(", ")", "===", "1", ")", "{", "if", "(", "!", "is_array", "(", "$", "ids", ")", ")", "{", "$", "ids", "=", "(", "array", ")", "$", "ids", ";", "}", "}", "else", "{", "$", "ids", "=", "func_get_args", "(", ")", ";", "}", "}", "$", "closure", "=", "NULL", ";", "if", "(", "count", "(", "func_get_args", "(", ")", ")", ">", "1", ")", "{", "if", "(", "$", "ids", "[", "count", "(", "$", "ids", ")", "-", "1", "]", "instanceof", "\\", "Closure", ")", "{", "$", "closure", "=", "array_pop", "(", "$", "ids", ")", ";", "}", "if", "(", "is_array", "(", "$", "ids", "[", "0", "]", ")", ")", "{", "$", "ids", "=", "$", "ids", "[", "0", "]", ";", "}", "}", "$", "this", "->", "find_first_data", "=", "$", "this", "->", "find_save_data", "=", "$", "this", "->", "find_delete_data", "=", "TRUE", ";", "if", "(", "count", "(", "$", "ids", ")", "&&", "!", "(", "@", "$", "ids", "[", "0", "]", "instanceof", "\\", "Closure", ")", ")", "{", "if", "(", "$", "this", "->", "is_assoc", "(", "$", "ids", ")", ")", "{", "$", "this", "->", "where", "(", "$", "ids", ")", ";", "}", "else", "{", "$", "this", "->", "where", "(", "$", "this", "->", "primaryKey", ",", "'in'", ",", "$", "ids", ")", ";", "}", "}", "$", "this", "->", "get", "(", ")", ";", "if", "(", "count", "(", "$", "ids", ")", "===", "1", "&&", "count", "(", "$", "this", "->", "data", ")", "===", "1", ")", "{", "$", "this", "->", "data", "=", "$", "this", "->", "data", "[", "0", "]", ";", "}", "if", "(", "$", "closure", "instanceof", "\\", "Closure", ")", "{", "$", "this", "->", "data", "=", "$", "closure", "(", "$", "this", "->", "data", ",", "$", "this", ")", ";", "}", "return", "$", "this", ";", "}" ]
Busca uno o varios registros en la Base de Datos @author Carlos Garcia @param Array $ids @return Array|Object
[ "Busca", "uno", "o", "varios", "registros", "en", "la", "Base", "de", "Datos" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L723-L767
11,076
nozerrat/daniia
Daniia/Daniia.php
Daniia.save
final public function save($closure=NULL) { $updated = FALSE; if ($this->find_save_data && @$this->data->{$this->primaryKey}) { $updated = $this->update((array)$this->data); } $last_id = NULL; if (($this->find_save_data && !@$this->data->{$this->primaryKey}) || !$updated) { $last_id = $this->insertGetId((array)$this->data); } $this->find_save_data = FALSE; $lastQuery = $this->lastQuery(); $error = $this->error(); if ( $error['message'] ) { return FALSE; } if ( $last_id ) { $this->where( $this->primaryKey, $last_id ); $this->get(); $this->last_sql = $lastQuery ."\n". $this->lastQuery(); } if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } $error = $this->error(); return $error['message'] ? FALSE : TRUE; }
php
final public function save($closure=NULL) { $updated = FALSE; if ($this->find_save_data && @$this->data->{$this->primaryKey}) { $updated = $this->update((array)$this->data); } $last_id = NULL; if (($this->find_save_data && !@$this->data->{$this->primaryKey}) || !$updated) { $last_id = $this->insertGetId((array)$this->data); } $this->find_save_data = FALSE; $lastQuery = $this->lastQuery(); $error = $this->error(); if ( $error['message'] ) { return FALSE; } if ( $last_id ) { $this->where( $this->primaryKey, $last_id ); $this->get(); $this->last_sql = $lastQuery ."\n". $this->lastQuery(); } if ($closure instanceof \Closure) { $this->data = $closure( $this->data, $this ); } $error = $this->error(); return $error['message'] ? FALSE : TRUE; }
[ "final", "public", "function", "save", "(", "$", "closure", "=", "NULL", ")", "{", "$", "updated", "=", "FALSE", ";", "if", "(", "$", "this", "->", "find_save_data", "&&", "@", "$", "this", "->", "data", "->", "{", "$", "this", "->", "primaryKey", "}", ")", "{", "$", "updated", "=", "$", "this", "->", "update", "(", "(", "array", ")", "$", "this", "->", "data", ")", ";", "}", "$", "last_id", "=", "NULL", ";", "if", "(", "(", "$", "this", "->", "find_save_data", "&&", "!", "@", "$", "this", "->", "data", "->", "{", "$", "this", "->", "primaryKey", "}", ")", "||", "!", "$", "updated", ")", "{", "$", "last_id", "=", "$", "this", "->", "insertGetId", "(", "(", "array", ")", "$", "this", "->", "data", ")", ";", "}", "$", "this", "->", "find_save_data", "=", "FALSE", ";", "$", "lastQuery", "=", "$", "this", "->", "lastQuery", "(", ")", ";", "$", "error", "=", "$", "this", "->", "error", "(", ")", ";", "if", "(", "$", "error", "[", "'message'", "]", ")", "{", "return", "FALSE", ";", "}", "if", "(", "$", "last_id", ")", "{", "$", "this", "->", "where", "(", "$", "this", "->", "primaryKey", ",", "$", "last_id", ")", ";", "$", "this", "->", "get", "(", ")", ";", "$", "this", "->", "last_sql", "=", "$", "lastQuery", ".", "\"\\n\"", ".", "$", "this", "->", "lastQuery", "(", ")", ";", "}", "if", "(", "$", "closure", "instanceof", "\\", "Closure", ")", "{", "$", "this", "->", "data", "=", "$", "closure", "(", "$", "this", "->", "data", ",", "$", "this", ")", ";", "}", "$", "error", "=", "$", "this", "->", "error", "(", ")", ";", "return", "$", "error", "[", "'message'", "]", "?", "FALSE", ":", "TRUE", ";", "}" ]
actualiza o crea un registro en la base de datos @author Carlos Garcia @return boolean
[ "actualiza", "o", "crea", "un", "registro", "en", "la", "base", "de", "datos" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L774-L806
11,077
nozerrat/daniia
Daniia/Daniia.php
Daniia.truncate
final public function truncate() { $this->connection(); $this->sql = "TRUNCATE TABLE {$this->table};"; if($this->driver=='firebird'||$this->driver=='sqlite') $this->sql = "DELETE FROM {$this->table};"; // $this->fetch(false); $this->fetch(); return $this->resultset?true:false; }
php
final public function truncate() { $this->connection(); $this->sql = "TRUNCATE TABLE {$this->table};"; if($this->driver=='firebird'||$this->driver=='sqlite') $this->sql = "DELETE FROM {$this->table};"; // $this->fetch(false); $this->fetch(); return $this->resultset?true:false; }
[ "final", "public", "function", "truncate", "(", ")", "{", "$", "this", "->", "connection", "(", ")", ";", "$", "this", "->", "sql", "=", "\"TRUNCATE TABLE {$this->table};\"", ";", "if", "(", "$", "this", "->", "driver", "==", "'firebird'", "||", "$", "this", "->", "driver", "==", "'sqlite'", ")", "$", "this", "->", "sql", "=", "\"DELETE FROM {$this->table};\"", ";", "// $this->fetch(false);", "$", "this", "->", "fetch", "(", ")", ";", "return", "$", "this", "->", "resultset", "?", "true", ":", "false", ";", "}" ]
elimina todos los datos de una tabla @author Carlos Garcia @return boolean
[ "elimina", "todos", "los", "datos", "de", "una", "tabla" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L893-L904
11,078
nozerrat/daniia
Daniia/Daniia.php
Daniia.table
final public function table($table) { $this->connection(); if (func_num_args()>1) $table = func_get_args(); else if(is_string($table)) $table = [$table]; $schema = ''; if ($this->driver=='pgsql' && $this->schema) $schema = $this->schema ? $this->schema.'.' : ''; $tmp_table = []; foreach($table as $table) { if (preg_match('/\./', $table)) { $tmp_table[] = $table; } else { $tmp_table[] = $schema.$table; } } $table = implode(",", $tmp_table); if ($this->extended) { if ( $this->table ) { $this->table = $schema.$this->table.",".$table; } else { $this->table = $table; } } else { $this->table = $table; } $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; }
php
final public function table($table) { $this->connection(); if (func_num_args()>1) $table = func_get_args(); else if(is_string($table)) $table = [$table]; $schema = ''; if ($this->driver=='pgsql' && $this->schema) $schema = $this->schema ? $this->schema.'.' : ''; $tmp_table = []; foreach($table as $table) { if (preg_match('/\./', $table)) { $tmp_table[] = $table; } else { $tmp_table[] = $schema.$table; } } $table = implode(",", $tmp_table); if ($this->extended) { if ( $this->table ) { $this->table = $schema.$this->table.",".$table; } else { $this->table = $table; } } else { $this->table = $table; } $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; }
[ "final", "public", "function", "table", "(", "$", "table", ")", "{", "$", "this", "->", "connection", "(", ")", ";", "if", "(", "func_num_args", "(", ")", ">", "1", ")", "$", "table", "=", "func_get_args", "(", ")", ";", "else", "if", "(", "is_string", "(", "$", "table", ")", ")", "$", "table", "=", "[", "$", "table", "]", ";", "$", "schema", "=", "''", ";", "if", "(", "$", "this", "->", "driver", "==", "'pgsql'", "&&", "$", "this", "->", "schema", ")", "$", "schema", "=", "$", "this", "->", "schema", "?", "$", "this", "->", "schema", ".", "'.'", ":", "''", ";", "$", "tmp_table", "=", "[", "]", ";", "foreach", "(", "$", "table", "as", "$", "table", ")", "{", "if", "(", "preg_match", "(", "'/\\./'", ",", "$", "table", ")", ")", "{", "$", "tmp_table", "[", "]", "=", "$", "table", ";", "}", "else", "{", "$", "tmp_table", "[", "]", "=", "$", "schema", ".", "$", "table", ";", "}", "}", "$", "table", "=", "implode", "(", "\",\"", ",", "$", "tmp_table", ")", ";", "if", "(", "$", "this", "->", "extended", ")", "{", "if", "(", "$", "this", "->", "table", ")", "{", "$", "this", "->", "table", "=", "$", "schema", ".", "$", "this", "->", "table", ".", "\",\"", ".", "$", "table", ";", "}", "else", "{", "$", "this", "->", "table", "=", "$", "table", ";", "}", "}", "else", "{", "$", "this", "->", "table", "=", "$", "table", ";", "}", "$", "this", "->", "find_first_data", "=", "$", "this", "->", "find_save_data", "=", "$", "this", "->", "find_delete_data", "=", "FALSE", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}" ]
Establese el nombre de la tabla @author Carlos Garcia @param $tables String @return Object
[ "Establese", "el", "nombre", "de", "la", "tabla" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L912-L950
11,079
nozerrat/daniia
Daniia/Daniia.php
Daniia.select
final public function select($select = "*") { $this->connection(); if (func_num_args()>1) $select = func_get_args(); else if(is_string($select)) { $select = [$select]; } $select_tmp = []; foreach ($select as $value) { if ( $value===NULL ) $select_tmp[] = ' NULL '; elseif ( gettype( $value )==='boolean' ) $select_tmp[] = $value ? ' TRUE ' : ' FALSE '; elseif ($value instanceof \Closure) { $value(new \Daniia\Daniia()); if (preg_match("/^CASE/", $_ENV['daniia_daniia']->case)) { $select_tmp[] = '( '.$_ENV['daniia_daniia']->case.' '.$_ENV['daniia_daniia']->when.' '.$_ENV['daniia_daniia']->else.' END )'; $_ENV['daniia_daniia']->case = NULL; } else { $select_tmp[] = $_ENV['daniia_daniia']->get_sql(); $_ENV['daniia_daniia'] = null; } } elseif ( in_array(strtolower(trim($value)), $this->columnsData, true) ) $select_tmp[] = $value; else { $select_tmp[] = $value; } } $select = implode(",", $select_tmp); $this->select = str_replace("*", $select, $this->select); $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; }
php
final public function select($select = "*") { $this->connection(); if (func_num_args()>1) $select = func_get_args(); else if(is_string($select)) { $select = [$select]; } $select_tmp = []; foreach ($select as $value) { if ( $value===NULL ) $select_tmp[] = ' NULL '; elseif ( gettype( $value )==='boolean' ) $select_tmp[] = $value ? ' TRUE ' : ' FALSE '; elseif ($value instanceof \Closure) { $value(new \Daniia\Daniia()); if (preg_match("/^CASE/", $_ENV['daniia_daniia']->case)) { $select_tmp[] = '( '.$_ENV['daniia_daniia']->case.' '.$_ENV['daniia_daniia']->when.' '.$_ENV['daniia_daniia']->else.' END )'; $_ENV['daniia_daniia']->case = NULL; } else { $select_tmp[] = $_ENV['daniia_daniia']->get_sql(); $_ENV['daniia_daniia'] = null; } } elseif ( in_array(strtolower(trim($value)), $this->columnsData, true) ) $select_tmp[] = $value; else { $select_tmp[] = $value; } } $select = implode(",", $select_tmp); $this->select = str_replace("*", $select, $this->select); $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; }
[ "final", "public", "function", "select", "(", "$", "select", "=", "\"*\"", ")", "{", "$", "this", "->", "connection", "(", ")", ";", "if", "(", "func_num_args", "(", ")", ">", "1", ")", "$", "select", "=", "func_get_args", "(", ")", ";", "else", "if", "(", "is_string", "(", "$", "select", ")", ")", "{", "$", "select", "=", "[", "$", "select", "]", ";", "}", "$", "select_tmp", "=", "[", "]", ";", "foreach", "(", "$", "select", "as", "$", "value", ")", "{", "if", "(", "$", "value", "===", "NULL", ")", "$", "select_tmp", "[", "]", "=", "' NULL '", ";", "elseif", "(", "gettype", "(", "$", "value", ")", "===", "'boolean'", ")", "$", "select_tmp", "[", "]", "=", "$", "value", "?", "' TRUE '", ":", "' FALSE '", ";", "elseif", "(", "$", "value", "instanceof", "\\", "Closure", ")", "{", "$", "value", "(", "new", "\\", "Daniia", "\\", "Daniia", "(", ")", ")", ";", "if", "(", "preg_match", "(", "\"/^CASE/\"", ",", "$", "_ENV", "[", "'daniia_daniia'", "]", "->", "case", ")", ")", "{", "$", "select_tmp", "[", "]", "=", "'( '", ".", "$", "_ENV", "[", "'daniia_daniia'", "]", "->", "case", ".", "' '", ".", "$", "_ENV", "[", "'daniia_daniia'", "]", "->", "when", ".", "' '", ".", "$", "_ENV", "[", "'daniia_daniia'", "]", "->", "else", ".", "' END )'", ";", "$", "_ENV", "[", "'daniia_daniia'", "]", "->", "case", "=", "NULL", ";", "}", "else", "{", "$", "select_tmp", "[", "]", "=", "$", "_ENV", "[", "'daniia_daniia'", "]", "->", "get_sql", "(", ")", ";", "$", "_ENV", "[", "'daniia_daniia'", "]", "=", "null", ";", "}", "}", "elseif", "(", "in_array", "(", "strtolower", "(", "trim", "(", "$", "value", ")", ")", ",", "$", "this", "->", "columnsData", ",", "true", ")", ")", "$", "select_tmp", "[", "]", "=", "$", "value", ";", "else", "{", "$", "select_tmp", "[", "]", "=", "$", "value", ";", "}", "}", "$", "select", "=", "implode", "(", "\",\"", ",", "$", "select_tmp", ")", ";", "$", "this", "->", "select", "=", "str_replace", "(", "\"*\"", ",", "$", "select", ",", "$", "this", "->", "select", ")", ";", "$", "this", "->", "find_first_data", "=", "$", "this", "->", "find_save_data", "=", "$", "this", "->", "find_delete_data", "=", "FALSE", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}" ]
Establese los nombres dee las columnas a consultar @author Carlos Garcia @param string $select @return Object
[ "Establese", "los", "nombres", "dee", "las", "columnas", "a", "consultar" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L958-L999
11,080
nozerrat/daniia
Daniia/Daniia.php
Daniia.from
final public function from($table="",$aliasFrom="") { $this->connection(); $sql = ""; $closure = false; // si es un closure lo ejecutamos if ($table instanceof \Closure) { // el resultado resuelto es almacenado en la variable $_ENV["daniia_from"] // para luego terminar de agruparlo $table(new \Daniia\Daniia()); $sql = $_ENV["daniia_daniia"]->get_sql(); $_ENV["daniia_daniia"] = null; $sql.= " AS ".($aliasFrom ? $aliasFrom : " _alias_ "); $closure = true; } else { if (func_num_args()>1){ $table = func_get_args(); } elseif(is_string($table)) { $table = [$table]; } $schema = ''; if ($this->driver=='pgsql' && $this->schema) { $schema = $this->schema ? $this->schema.'.' : ''; } $tmp_table = []; foreach($table as $val) { if (preg_match('/\./', $val)) { $tmp_table[] = $val; } else { $tmp_table[] = $schema.$val; } } $table = implode(",", $tmp_table); } if ($this->extended && is_string($table) && !$closure) { $table = $schema.$this->table.",".$table; } if (!$this->bool_group) { if ( !$this->table && gettype( $table )==='string') { $this->table = $table; } $this->from = str_replace("_table_", ($closure ? $sql : ($table ?: $this->table)), $this->from); } $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; }
php
final public function from($table="",$aliasFrom="") { $this->connection(); $sql = ""; $closure = false; // si es un closure lo ejecutamos if ($table instanceof \Closure) { // el resultado resuelto es almacenado en la variable $_ENV["daniia_from"] // para luego terminar de agruparlo $table(new \Daniia\Daniia()); $sql = $_ENV["daniia_daniia"]->get_sql(); $_ENV["daniia_daniia"] = null; $sql.= " AS ".($aliasFrom ? $aliasFrom : " _alias_ "); $closure = true; } else { if (func_num_args()>1){ $table = func_get_args(); } elseif(is_string($table)) { $table = [$table]; } $schema = ''; if ($this->driver=='pgsql' && $this->schema) { $schema = $this->schema ? $this->schema.'.' : ''; } $tmp_table = []; foreach($table as $val) { if (preg_match('/\./', $val)) { $tmp_table[] = $val; } else { $tmp_table[] = $schema.$val; } } $table = implode(",", $tmp_table); } if ($this->extended && is_string($table) && !$closure) { $table = $schema.$this->table.",".$table; } if (!$this->bool_group) { if ( !$this->table && gettype( $table )==='string') { $this->table = $table; } $this->from = str_replace("_table_", ($closure ? $sql : ($table ?: $this->table)), $this->from); } $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; }
[ "final", "public", "function", "from", "(", "$", "table", "=", "\"\"", ",", "$", "aliasFrom", "=", "\"\"", ")", "{", "$", "this", "->", "connection", "(", ")", ";", "$", "sql", "=", "\"\"", ";", "$", "closure", "=", "false", ";", "// si es un closure lo ejecutamos", "if", "(", "$", "table", "instanceof", "\\", "Closure", ")", "{", "// el resultado resuelto es almacenado en la variable $_ENV[\"daniia_from\"]", "// para luego terminar de agruparlo", "$", "table", "(", "new", "\\", "Daniia", "\\", "Daniia", "(", ")", ")", ";", "$", "sql", "=", "$", "_ENV", "[", "\"daniia_daniia\"", "]", "->", "get_sql", "(", ")", ";", "$", "_ENV", "[", "\"daniia_daniia\"", "]", "=", "null", ";", "$", "sql", ".=", "\" AS \"", ".", "(", "$", "aliasFrom", "?", "$", "aliasFrom", ":", "\" _alias_ \"", ")", ";", "$", "closure", "=", "true", ";", "}", "else", "{", "if", "(", "func_num_args", "(", ")", ">", "1", ")", "{", "$", "table", "=", "func_get_args", "(", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "table", ")", ")", "{", "$", "table", "=", "[", "$", "table", "]", ";", "}", "$", "schema", "=", "''", ";", "if", "(", "$", "this", "->", "driver", "==", "'pgsql'", "&&", "$", "this", "->", "schema", ")", "{", "$", "schema", "=", "$", "this", "->", "schema", "?", "$", "this", "->", "schema", ".", "'.'", ":", "''", ";", "}", "$", "tmp_table", "=", "[", "]", ";", "foreach", "(", "$", "table", "as", "$", "val", ")", "{", "if", "(", "preg_match", "(", "'/\\./'", ",", "$", "val", ")", ")", "{", "$", "tmp_table", "[", "]", "=", "$", "val", ";", "}", "else", "{", "$", "tmp_table", "[", "]", "=", "$", "schema", ".", "$", "val", ";", "}", "}", "$", "table", "=", "implode", "(", "\",\"", ",", "$", "tmp_table", ")", ";", "}", "if", "(", "$", "this", "->", "extended", "&&", "is_string", "(", "$", "table", ")", "&&", "!", "$", "closure", ")", "{", "$", "table", "=", "$", "schema", ".", "$", "this", "->", "table", ".", "\",\"", ".", "$", "table", ";", "}", "if", "(", "!", "$", "this", "->", "bool_group", ")", "{", "if", "(", "!", "$", "this", "->", "table", "&&", "gettype", "(", "$", "table", ")", "===", "'string'", ")", "{", "$", "this", "->", "table", "=", "$", "table", ";", "}", "$", "this", "->", "from", "=", "str_replace", "(", "\"_table_\"", ",", "(", "$", "closure", "?", "$", "sql", ":", "(", "$", "table", "?", ":", "$", "this", "->", "table", ")", ")", ",", "$", "this", "->", "from", ")", ";", "}", "$", "this", "->", "find_first_data", "=", "$", "this", "->", "find_save_data", "=", "$", "this", "->", "find_delete_data", "=", "FALSE", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}" ]
Establece el nombre de la tabla a consultar @author Carlos Garcia @param $table String|Closure @param $alias String @return Object
[ "Establece", "el", "nombre", "de", "la", "tabla", "a", "consultar" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1008-L1065
11,081
nozerrat/daniia
Daniia/Daniia.php
Daniia.insert
final public function insert(array $datas, bool $returning_id = false) { if (is_array($datas) && count($datas)) { if (!is_array(@$datas[0])) $datas = [$datas]; $this->connection(); $this->columns(); $placeholders = []; $this->placeholder_data = []; foreach ($datas as $data) { $placeholder = []; foreach($this->columnsData as $column) { if(isset($data[$column])) { $placeholder[$column] = "NULL"; if ( gettype($data[$column])==='boolean' ) $placeholder[$column] = $data[$column] ? 'TRUE' : 'FALSE'; elseif ( $data[$column]!=='' && $data[$column]!==NULL ) { $placeholder[$column] = "?"; $this->placeholder_data[] = $data[$column]; } } } $placeholders[] = "(".implode(",", $placeholder).")"; } $columns = "(".implode(",", array_keys($placeholder)).")"; $placeholders = implode(",", $placeholders); $schema = ''; $returning = ''; if ($this->driver=='pgsql' && $this->schema) { if (!preg_match('/\./', $this->table)) { $schema = $this->schema ? $this->schema.'.' : ''; } $returning = $returning_id ? 'RETURNING '.$this->primaryKey : ''; } $this->last_sql = $this->sql = "INSERT INTO {$schema}{$this->table} {$columns} VALUES {$placeholders} {$returning};"; $this->fetch(); $this->data = $this->rows; $this->reset(); if ( $this->tableOrig!==NULL ) { $this->table = $this->tableOrig; } $error = $this->error(); return $error['message'] ? FALSE : TRUE; } return FALSE; }
php
final public function insert(array $datas, bool $returning_id = false) { if (is_array($datas) && count($datas)) { if (!is_array(@$datas[0])) $datas = [$datas]; $this->connection(); $this->columns(); $placeholders = []; $this->placeholder_data = []; foreach ($datas as $data) { $placeholder = []; foreach($this->columnsData as $column) { if(isset($data[$column])) { $placeholder[$column] = "NULL"; if ( gettype($data[$column])==='boolean' ) $placeholder[$column] = $data[$column] ? 'TRUE' : 'FALSE'; elseif ( $data[$column]!=='' && $data[$column]!==NULL ) { $placeholder[$column] = "?"; $this->placeholder_data[] = $data[$column]; } } } $placeholders[] = "(".implode(",", $placeholder).")"; } $columns = "(".implode(",", array_keys($placeholder)).")"; $placeholders = implode(",", $placeholders); $schema = ''; $returning = ''; if ($this->driver=='pgsql' && $this->schema) { if (!preg_match('/\./', $this->table)) { $schema = $this->schema ? $this->schema.'.' : ''; } $returning = $returning_id ? 'RETURNING '.$this->primaryKey : ''; } $this->last_sql = $this->sql = "INSERT INTO {$schema}{$this->table} {$columns} VALUES {$placeholders} {$returning};"; $this->fetch(); $this->data = $this->rows; $this->reset(); if ( $this->tableOrig!==NULL ) { $this->table = $this->tableOrig; } $error = $this->error(); return $error['message'] ? FALSE : TRUE; } return FALSE; }
[ "final", "public", "function", "insert", "(", "array", "$", "datas", ",", "bool", "$", "returning_id", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "datas", ")", "&&", "count", "(", "$", "datas", ")", ")", "{", "if", "(", "!", "is_array", "(", "@", "$", "datas", "[", "0", "]", ")", ")", "$", "datas", "=", "[", "$", "datas", "]", ";", "$", "this", "->", "connection", "(", ")", ";", "$", "this", "->", "columns", "(", ")", ";", "$", "placeholders", "=", "[", "]", ";", "$", "this", "->", "placeholder_data", "=", "[", "]", ";", "foreach", "(", "$", "datas", "as", "$", "data", ")", "{", "$", "placeholder", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "columnsData", "as", "$", "column", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "$", "column", "]", ")", ")", "{", "$", "placeholder", "[", "$", "column", "]", "=", "\"NULL\"", ";", "if", "(", "gettype", "(", "$", "data", "[", "$", "column", "]", ")", "===", "'boolean'", ")", "$", "placeholder", "[", "$", "column", "]", "=", "$", "data", "[", "$", "column", "]", "?", "'TRUE'", ":", "'FALSE'", ";", "elseif", "(", "$", "data", "[", "$", "column", "]", "!==", "''", "&&", "$", "data", "[", "$", "column", "]", "!==", "NULL", ")", "{", "$", "placeholder", "[", "$", "column", "]", "=", "\"?\"", ";", "$", "this", "->", "placeholder_data", "[", "]", "=", "$", "data", "[", "$", "column", "]", ";", "}", "}", "}", "$", "placeholders", "[", "]", "=", "\"(\"", ".", "implode", "(", "\",\"", ",", "$", "placeholder", ")", ".", "\")\"", ";", "}", "$", "columns", "=", "\"(\"", ".", "implode", "(", "\",\"", ",", "array_keys", "(", "$", "placeholder", ")", ")", ".", "\")\"", ";", "$", "placeholders", "=", "implode", "(", "\",\"", ",", "$", "placeholders", ")", ";", "$", "schema", "=", "''", ";", "$", "returning", "=", "''", ";", "if", "(", "$", "this", "->", "driver", "==", "'pgsql'", "&&", "$", "this", "->", "schema", ")", "{", "if", "(", "!", "preg_match", "(", "'/\\./'", ",", "$", "this", "->", "table", ")", ")", "{", "$", "schema", "=", "$", "this", "->", "schema", "?", "$", "this", "->", "schema", ".", "'.'", ":", "''", ";", "}", "$", "returning", "=", "$", "returning_id", "?", "'RETURNING '", ".", "$", "this", "->", "primaryKey", ":", "''", ";", "}", "$", "this", "->", "last_sql", "=", "$", "this", "->", "sql", "=", "\"INSERT INTO {$schema}{$this->table} {$columns} VALUES {$placeholders} {$returning};\"", ";", "$", "this", "->", "fetch", "(", ")", ";", "$", "this", "->", "data", "=", "$", "this", "->", "rows", ";", "$", "this", "->", "reset", "(", ")", ";", "if", "(", "$", "this", "->", "tableOrig", "!==", "NULL", ")", "{", "$", "this", "->", "table", "=", "$", "this", "->", "tableOrig", ";", "}", "$", "error", "=", "$", "this", "->", "error", "(", ")", ";", "return", "$", "error", "[", "'message'", "]", "?", "FALSE", ":", "TRUE", ";", "}", "return", "FALSE", ";", "}" ]
inserta datos en la base de datos @author Carlos Garcia @param $datas Array @param $returning_id Boolean @return Boolean
[ "inserta", "datos", "en", "la", "base", "de", "datos" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1074-L1131
11,082
nozerrat/daniia
Daniia/Daniia.php
Daniia.insertGetId
final public function insertGetId(array $datas) { $this->connection(); $this->last_id = NULL; if ( $this->driver=='pgsql' ) { $this->insert( $datas, TRUE ); if ( @$this->data[0] ) { $this->last_id = @$this->data[0]->{$this->primaryKey}; } } else { $this->insert( $datas ); $this->last_id = $this->id_conn->lastInsertId(); } return (int) $this->last_id; }
php
final public function insertGetId(array $datas) { $this->connection(); $this->last_id = NULL; if ( $this->driver=='pgsql' ) { $this->insert( $datas, TRUE ); if ( @$this->data[0] ) { $this->last_id = @$this->data[0]->{$this->primaryKey}; } } else { $this->insert( $datas ); $this->last_id = $this->id_conn->lastInsertId(); } return (int) $this->last_id; }
[ "final", "public", "function", "insertGetId", "(", "array", "$", "datas", ")", "{", "$", "this", "->", "connection", "(", ")", ";", "$", "this", "->", "last_id", "=", "NULL", ";", "if", "(", "$", "this", "->", "driver", "==", "'pgsql'", ")", "{", "$", "this", "->", "insert", "(", "$", "datas", ",", "TRUE", ")", ";", "if", "(", "@", "$", "this", "->", "data", "[", "0", "]", ")", "{", "$", "this", "->", "last_id", "=", "@", "$", "this", "->", "data", "[", "0", "]", "->", "{", "$", "this", "->", "primaryKey", "}", ";", "}", "}", "else", "{", "$", "this", "->", "insert", "(", "$", "datas", ")", ";", "$", "this", "->", "last_id", "=", "$", "this", "->", "id_conn", "->", "lastInsertId", "(", ")", ";", "}", "return", "(", "int", ")", "$", "this", "->", "last_id", ";", "}" ]
inserta y luego retorna la clave primaria del registro @author Carlos Garcia @param $datas Array @return integer
[ "inserta", "y", "luego", "retorna", "la", "clave", "primaria", "del", "registro" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1139-L1153
11,083
nozerrat/daniia
Daniia/Daniia.php
Daniia.delete
final public function delete( $ids = [] ) { if (func_num_args()>0) { if (func_num_args()==1) { if (!is_array($ids)) { $ids = (array) $ids; } } else { $ids = func_get_args(); } } $this->connection(); if ( $this->find_delete_data ) { if(is_object($this->data) && $this->data) { $ids[] = $this->data->{$this->primaryKey}; } if(is_array($this->data) && $this->data) { foreach($this->data as $data) $ids[] = $data->{$this->primaryKey}; } $this->find_delete_data = FALSE; if (!count( $ids )) { return FALSE; } } if ( $this->is_assoc( $ids ) ) { $this->where( $ids ); $ids = NULL; } else { $this->placeholder_data = $ids; $placeholder = $this->get_placeholder($ids); } $where = ''; if ( $ids ) { if (preg_match("/WHERE/", $this->where)) $where = " {$this->where} AND {$this->primaryKey} IN({$placeholder}) "; else $where = " WHERE {$this->primaryKey} IN({$placeholder}) "; } else { if (preg_match("/WHERE/", $this->where)) $where = $this->where; } $schema = ''; if($this->driver=='pgsql' && $this->schema) { if (!preg_match('/\./', $this->table)) { $schema = $this->schema ? $this->schema.'.' : ''; } } $this->last_sql = $this->sql = "DELETE FROM {$schema}{$this->table} {$where}"; // $this->fetch(false); $this->fetch(); $this->reset(); if ( $this->tableOrig!==null ) { $this->table = $this->tableOrig; } $error = $this->error(); return $error['message'] ? false : true; }
php
final public function delete( $ids = [] ) { if (func_num_args()>0) { if (func_num_args()==1) { if (!is_array($ids)) { $ids = (array) $ids; } } else { $ids = func_get_args(); } } $this->connection(); if ( $this->find_delete_data ) { if(is_object($this->data) && $this->data) { $ids[] = $this->data->{$this->primaryKey}; } if(is_array($this->data) && $this->data) { foreach($this->data as $data) $ids[] = $data->{$this->primaryKey}; } $this->find_delete_data = FALSE; if (!count( $ids )) { return FALSE; } } if ( $this->is_assoc( $ids ) ) { $this->where( $ids ); $ids = NULL; } else { $this->placeholder_data = $ids; $placeholder = $this->get_placeholder($ids); } $where = ''; if ( $ids ) { if (preg_match("/WHERE/", $this->where)) $where = " {$this->where} AND {$this->primaryKey} IN({$placeholder}) "; else $where = " WHERE {$this->primaryKey} IN({$placeholder}) "; } else { if (preg_match("/WHERE/", $this->where)) $where = $this->where; } $schema = ''; if($this->driver=='pgsql' && $this->schema) { if (!preg_match('/\./', $this->table)) { $schema = $this->schema ? $this->schema.'.' : ''; } } $this->last_sql = $this->sql = "DELETE FROM {$schema}{$this->table} {$where}"; // $this->fetch(false); $this->fetch(); $this->reset(); if ( $this->tableOrig!==null ) { $this->table = $this->tableOrig; } $error = $this->error(); return $error['message'] ? false : true; }
[ "final", "public", "function", "delete", "(", "$", "ids", "=", "[", "]", ")", "{", "if", "(", "func_num_args", "(", ")", ">", "0", ")", "{", "if", "(", "func_num_args", "(", ")", "==", "1", ")", "{", "if", "(", "!", "is_array", "(", "$", "ids", ")", ")", "{", "$", "ids", "=", "(", "array", ")", "$", "ids", ";", "}", "}", "else", "{", "$", "ids", "=", "func_get_args", "(", ")", ";", "}", "}", "$", "this", "->", "connection", "(", ")", ";", "if", "(", "$", "this", "->", "find_delete_data", ")", "{", "if", "(", "is_object", "(", "$", "this", "->", "data", ")", "&&", "$", "this", "->", "data", ")", "{", "$", "ids", "[", "]", "=", "$", "this", "->", "data", "->", "{", "$", "this", "->", "primaryKey", "}", ";", "}", "if", "(", "is_array", "(", "$", "this", "->", "data", ")", "&&", "$", "this", "->", "data", ")", "{", "foreach", "(", "$", "this", "->", "data", "as", "$", "data", ")", "$", "ids", "[", "]", "=", "$", "data", "->", "{", "$", "this", "->", "primaryKey", "}", ";", "}", "$", "this", "->", "find_delete_data", "=", "FALSE", ";", "if", "(", "!", "count", "(", "$", "ids", ")", ")", "{", "return", "FALSE", ";", "}", "}", "if", "(", "$", "this", "->", "is_assoc", "(", "$", "ids", ")", ")", "{", "$", "this", "->", "where", "(", "$", "ids", ")", ";", "$", "ids", "=", "NULL", ";", "}", "else", "{", "$", "this", "->", "placeholder_data", "=", "$", "ids", ";", "$", "placeholder", "=", "$", "this", "->", "get_placeholder", "(", "$", "ids", ")", ";", "}", "$", "where", "=", "''", ";", "if", "(", "$", "ids", ")", "{", "if", "(", "preg_match", "(", "\"/WHERE/\"", ",", "$", "this", "->", "where", ")", ")", "$", "where", "=", "\" {$this->where} AND {$this->primaryKey} IN({$placeholder}) \"", ";", "else", "$", "where", "=", "\" WHERE {$this->primaryKey} IN({$placeholder}) \"", ";", "}", "else", "{", "if", "(", "preg_match", "(", "\"/WHERE/\"", ",", "$", "this", "->", "where", ")", ")", "$", "where", "=", "$", "this", "->", "where", ";", "}", "$", "schema", "=", "''", ";", "if", "(", "$", "this", "->", "driver", "==", "'pgsql'", "&&", "$", "this", "->", "schema", ")", "{", "if", "(", "!", "preg_match", "(", "'/\\./'", ",", "$", "this", "->", "table", ")", ")", "{", "$", "schema", "=", "$", "this", "->", "schema", "?", "$", "this", "->", "schema", ".", "'.'", ":", "''", ";", "}", "}", "$", "this", "->", "last_sql", "=", "$", "this", "->", "sql", "=", "\"DELETE FROM {$schema}{$this->table} {$where}\"", ";", "// $this->fetch(false);", "$", "this", "->", "fetch", "(", ")", ";", "$", "this", "->", "reset", "(", ")", ";", "if", "(", "$", "this", "->", "tableOrig", "!==", "null", ")", "{", "$", "this", "->", "table", "=", "$", "this", "->", "tableOrig", ";", "}", "$", "error", "=", "$", "this", "->", "error", "(", ")", ";", "return", "$", "error", "[", "'message'", "]", "?", "false", ":", "true", ";", "}" ]
elimina un registro en la base de datos @author Carlos Garcia @param $ids mixed @return boolean
[ "elimina", "un", "registro", "en", "la", "base", "de", "datos" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1252-L1324
11,084
nozerrat/daniia
Daniia/Daniia.php
Daniia.orderBy
final public function orderBy($fields) { if (func_num_args()>0) { if (func_num_args()==1) { if (!is_array($fields)) { $fields = (array) $fields; } }else{ $fields = func_get_args(); } $order = ''; if(strtoupper($fields[count($fields)-1])=='ASC'||strtoupper($fields[count($fields)-1])=='DESC'){ $order = $fields[count($fields)-1]; unset($fields[count($fields)-1]); } $this->orderBy = " ORDER BY ".implode(',',$fields).' '.strtoupper($order); $this->get_instance(); return $this; } return null; }
php
final public function orderBy($fields) { if (func_num_args()>0) { if (func_num_args()==1) { if (!is_array($fields)) { $fields = (array) $fields; } }else{ $fields = func_get_args(); } $order = ''; if(strtoupper($fields[count($fields)-1])=='ASC'||strtoupper($fields[count($fields)-1])=='DESC'){ $order = $fields[count($fields)-1]; unset($fields[count($fields)-1]); } $this->orderBy = " ORDER BY ".implode(',',$fields).' '.strtoupper($order); $this->get_instance(); return $this; } return null; }
[ "final", "public", "function", "orderBy", "(", "$", "fields", ")", "{", "if", "(", "func_num_args", "(", ")", ">", "0", ")", "{", "if", "(", "func_num_args", "(", ")", "==", "1", ")", "{", "if", "(", "!", "is_array", "(", "$", "fields", ")", ")", "{", "$", "fields", "=", "(", "array", ")", "$", "fields", ";", "}", "}", "else", "{", "$", "fields", "=", "func_get_args", "(", ")", ";", "}", "$", "order", "=", "''", ";", "if", "(", "strtoupper", "(", "$", "fields", "[", "count", "(", "$", "fields", ")", "-", "1", "]", ")", "==", "'ASC'", "||", "strtoupper", "(", "$", "fields", "[", "count", "(", "$", "fields", ")", "-", "1", "]", ")", "==", "'DESC'", ")", "{", "$", "order", "=", "$", "fields", "[", "count", "(", "$", "fields", ")", "-", "1", "]", ";", "unset", "(", "$", "fields", "[", "count", "(", "$", "fields", ")", "-", "1", "]", ")", ";", "}", "$", "this", "->", "orderBy", "=", "\" ORDER BY \"", ".", "implode", "(", "','", ",", "$", "fields", ")", ".", "' '", ".", "strtoupper", "(", "$", "order", ")", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}", "return", "null", ";", "}" ]
agrega el query ORDER BY basico @author Carlos Garcia @param String|Array $fields @return Object
[ "agrega", "el", "query", "ORDER", "BY", "basico" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1804-L1825
11,085
nozerrat/daniia
Daniia/Daniia.php
Daniia.groupBy
final public function groupBy($fields) { if (func_num_args()>0) { if (func_num_args()==1) { if (!is_array($fields)) { $fields = (array) $fields; } }else{ $fields = func_get_args(); } $this->groupBy = " GROUP BY ".implode(',',$fields); $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; } return null; }
php
final public function groupBy($fields) { if (func_num_args()>0) { if (func_num_args()==1) { if (!is_array($fields)) { $fields = (array) $fields; } }else{ $fields = func_get_args(); } $this->groupBy = " GROUP BY ".implode(',',$fields); $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; } return null; }
[ "final", "public", "function", "groupBy", "(", "$", "fields", ")", "{", "if", "(", "func_num_args", "(", ")", ">", "0", ")", "{", "if", "(", "func_num_args", "(", ")", "==", "1", ")", "{", "if", "(", "!", "is_array", "(", "$", "fields", ")", ")", "{", "$", "fields", "=", "(", "array", ")", "$", "fields", ";", "}", "}", "else", "{", "$", "fields", "=", "func_get_args", "(", ")", ";", "}", "$", "this", "->", "groupBy", "=", "\" GROUP BY \"", ".", "implode", "(", "','", ",", "$", "fields", ")", ";", "$", "this", "->", "find_first_data", "=", "$", "this", "->", "find_save_data", "=", "$", "this", "->", "find_delete_data", "=", "FALSE", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}", "return", "null", ";", "}" ]
agrega el query GROUP BY basico @author Carlos Garcia @param String|Array $fields @return mixed.
[ "agrega", "el", "query", "GROUP", "BY", "basico" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1833-L1851
11,086
nozerrat/daniia
Daniia/Daniia.php
Daniia.limit
final public function limit($limit,$offset=null) { if (is_numeric($limit) || is_array($limit)) { if(is_array($limit)) { $temp = $limit; $limit = $temp[0]; $offset = @$temp[1]; } $this->limit = " LIMIT {$limit} "; if(is_numeric($offset)) { $this->offset( $offset ); } $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; } return null; }
php
final public function limit($limit,$offset=null) { if (is_numeric($limit) || is_array($limit)) { if(is_array($limit)) { $temp = $limit; $limit = $temp[0]; $offset = @$temp[1]; } $this->limit = " LIMIT {$limit} "; if(is_numeric($offset)) { $this->offset( $offset ); } $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; } return null; }
[ "final", "public", "function", "limit", "(", "$", "limit", ",", "$", "offset", "=", "null", ")", "{", "if", "(", "is_numeric", "(", "$", "limit", ")", "||", "is_array", "(", "$", "limit", ")", ")", "{", "if", "(", "is_array", "(", "$", "limit", ")", ")", "{", "$", "temp", "=", "$", "limit", ";", "$", "limit", "=", "$", "temp", "[", "0", "]", ";", "$", "offset", "=", "@", "$", "temp", "[", "1", "]", ";", "}", "$", "this", "->", "limit", "=", "\" LIMIT {$limit} \"", ";", "if", "(", "is_numeric", "(", "$", "offset", ")", ")", "{", "$", "this", "->", "offset", "(", "$", "offset", ")", ";", "}", "$", "this", "->", "find_first_data", "=", "$", "this", "->", "find_save_data", "=", "$", "this", "->", "find_delete_data", "=", "FALSE", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}", "return", "null", ";", "}" ]
agrega el query basico LIMIT @author Carlos Garcia @param Integer|Array $limit @param Integer $offset @return Object
[ "agrega", "el", "query", "basico", "LIMIT" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1860-L1880
11,087
nozerrat/daniia
Daniia/Daniia.php
Daniia.offset
final public function offset($offset) { if (is_numeric($offset)) { $this->offset = " OFFSET {$offset} "; $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; } return null; }
php
final public function offset($offset) { if (is_numeric($offset)) { $this->offset = " OFFSET {$offset} "; $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE; $this->get_instance(); return $this; } return null; }
[ "final", "public", "function", "offset", "(", "$", "offset", ")", "{", "if", "(", "is_numeric", "(", "$", "offset", ")", ")", "{", "$", "this", "->", "offset", "=", "\" OFFSET {$offset} \"", ";", "$", "this", "->", "find_first_data", "=", "$", "this", "->", "find_save_data", "=", "$", "this", "->", "find_delete_data", "=", "FALSE", ";", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}", "return", "null", ";", "}" ]
agrega el query basico OFFSET @author Carlos Garcia @param Integer|Array $limit @param Integer $offset @return Object
[ "agrega", "el", "query", "basico", "OFFSET" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1889-L1900
11,088
nozerrat/daniia
Daniia/Daniia.php
Daniia.union
final public function union($closure) { // si es un closure lo ejecutamos if ($closure instanceof \Closure) { // el resultado resuelto es almacenado en la variable $_ENV["daniia_union"] // para luego terminar de agruparlo $closure(new \Daniia\Daniia()); $str = $_ENV["daniia_daniia"]->get_sql(); $_ENV["daniia_daniia"] = null; $this->union .= ' UNION ' . $str; } $this->get_instance(); return $this; }
php
final public function union($closure) { // si es un closure lo ejecutamos if ($closure instanceof \Closure) { // el resultado resuelto es almacenado en la variable $_ENV["daniia_union"] // para luego terminar de agruparlo $closure(new \Daniia\Daniia()); $str = $_ENV["daniia_daniia"]->get_sql(); $_ENV["daniia_daniia"] = null; $this->union .= ' UNION ' . $str; } $this->get_instance(); return $this; }
[ "final", "public", "function", "union", "(", "$", "closure", ")", "{", "// si es un closure lo ejecutamos", "if", "(", "$", "closure", "instanceof", "\\", "Closure", ")", "{", "// el resultado resuelto es almacenado en la variable $_ENV[\"daniia_union\"]", "// para luego terminar de agruparlo", "$", "closure", "(", "new", "\\", "Daniia", "\\", "Daniia", "(", ")", ")", ";", "$", "str", "=", "$", "_ENV", "[", "\"daniia_daniia\"", "]", "->", "get_sql", "(", ")", ";", "$", "_ENV", "[", "\"daniia_daniia\"", "]", "=", "null", ";", "$", "this", "->", "union", ".=", "' UNION '", ".", "$", "str", ";", "}", "$", "this", "->", "get_instance", "(", ")", ";", "return", "$", "this", ";", "}" ]
genera una lista dependiendo de los datos consultados @author Carlos Garcia @param Closure $closure @return mixed
[ "genera", "una", "lista", "dependiendo", "de", "los", "datos", "consultados" ]
d1e33c8e00d73e8a82724365856fb88ae008f57a
https://github.com/nozerrat/daniia/blob/d1e33c8e00d73e8a82724365856fb88ae008f57a/Daniia/Daniia.php#L1908-L1921
11,089
sasedev/extra-tools-bundle
src/Sasedev/ExtraToolsBundle/Twig/TwigExtension.php
TwigExtension.countryFilter
public function countryFilter($country, $default = '', $locale = null) { $locale = $locale == null ? \Locale::getDefault() : $locale; $countries = Intl::getRegionBundle()->getCountryNames($locale); return array_key_exists($country, $countries) ? $countries[$country] : $default; }
php
public function countryFilter($country, $default = '', $locale = null) { $locale = $locale == null ? \Locale::getDefault() : $locale; $countries = Intl::getRegionBundle()->getCountryNames($locale); return array_key_exists($country, $countries) ? $countries[$country] : $default; }
[ "public", "function", "countryFilter", "(", "$", "country", ",", "$", "default", "=", "''", ",", "$", "locale", "=", "null", ")", "{", "$", "locale", "=", "$", "locale", "==", "null", "?", "\\", "Locale", "::", "getDefault", "(", ")", ":", "$", "locale", ";", "$", "countries", "=", "Intl", "::", "getRegionBundle", "(", ")", "->", "getCountryNames", "(", "$", "locale", ")", ";", "return", "array_key_exists", "(", "$", "country", ",", "$", "countries", ")", "?", "$", "countries", "[", "$", "country", "]", ":", "$", "default", ";", "}" ]
Translate a country indicator to its locale full name Uses default system locale by default. Pass another locale string to force a different translation @param string $country The contry indicator @param string $default The default value is the country does not exist (optionnal) @param mixed $locale @return string The localized string
[ "Translate", "a", "country", "indicator", "to", "its", "locale", "full", "name", "Uses", "default", "system", "locale", "by", "default", ".", "Pass", "another", "locale", "string", "to", "force", "a", "different", "translation" ]
14037d6b5c8ba9520ffe33f26057e2e53bea7a75
https://github.com/sasedev/extra-tools-bundle/blob/14037d6b5c8ba9520ffe33f26057e2e53bea7a75/src/Sasedev/ExtraToolsBundle/Twig/TwigExtension.php#L51-L57
11,090
sasedev/extra-tools-bundle
src/Sasedev/ExtraToolsBundle/Twig/TwigExtension.php
TwigExtension.convertFilter
public function convertFilter($value, $sourceUnit, $destinationUnit, $unitName, $locale = null) { if (null !== $value) { $translatedUnitName = $this->translator->trans($unitName, array(), 'SasedevExtraToolsBundle'); $value = $this->converter->convert($value, $sourceUnit, $destinationUnit, $locale); $value = $value . ' ' . $translatedUnitName; } return $value; }
php
public function convertFilter($value, $sourceUnit, $destinationUnit, $unitName, $locale = null) { if (null !== $value) { $translatedUnitName = $this->translator->trans($unitName, array(), 'SasedevExtraToolsBundle'); $value = $this->converter->convert($value, $sourceUnit, $destinationUnit, $locale); $value = $value . ' ' . $translatedUnitName; } return $value; }
[ "public", "function", "convertFilter", "(", "$", "value", ",", "$", "sourceUnit", ",", "$", "destinationUnit", ",", "$", "unitName", ",", "$", "locale", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "value", ")", "{", "$", "translatedUnitName", "=", "$", "this", "->", "translator", "->", "trans", "(", "$", "unitName", ",", "array", "(", ")", ",", "'SasedevExtraToolsBundle'", ")", ";", "$", "value", "=", "$", "this", "->", "converter", "->", "convert", "(", "$", "value", ",", "$", "sourceUnit", ",", "$", "destinationUnit", ",", "$", "locale", ")", ";", "$", "value", "=", "$", "value", ".", "' '", ".", "$", "translatedUnitName", ";", "}", "return", "$", "value", ";", "}" ]
Convert a value into another unit. Returns null if fails or not supported. @param mixed $value @param string $sourceUnit @param string $destinationUnit @param string the locale (optional) @return string|null The converted value
[ "Convert", "a", "value", "into", "another", "unit", ".", "Returns", "null", "if", "fails", "or", "not", "supported", "." ]
14037d6b5c8ba9520ffe33f26057e2e53bea7a75
https://github.com/sasedev/extra-tools-bundle/blob/14037d6b5c8ba9520ffe33f26057e2e53bea7a75/src/Sasedev/ExtraToolsBundle/Twig/TwigExtension.php#L92-L102
11,091
coolms/common
src/View/Helper/Hierarchy.php
Hierarchy.render
public function render(HierarchyInterface $node = null, $criteria = null, $options = [], $includeNode = null) { return $this->getMapper()->childrenHierarchy( $node, // if node is null starting from root nodes null === $criteria ? $this->direct() : $criteria, // true: load all children, false: only direct, array: criteria array_replace_recursive($this->getOptions(), $options), null === $includeNode ? $this->includeNode() : $includeNode ); }
php
public function render(HierarchyInterface $node = null, $criteria = null, $options = [], $includeNode = null) { return $this->getMapper()->childrenHierarchy( $node, // if node is null starting from root nodes null === $criteria ? $this->direct() : $criteria, // true: load all children, false: only direct, array: criteria array_replace_recursive($this->getOptions(), $options), null === $includeNode ? $this->includeNode() : $includeNode ); }
[ "public", "function", "render", "(", "HierarchyInterface", "$", "node", "=", "null", ",", "$", "criteria", "=", "null", ",", "$", "options", "=", "[", "]", ",", "$", "includeNode", "=", "null", ")", "{", "return", "$", "this", "->", "getMapper", "(", ")", "->", "childrenHierarchy", "(", "$", "node", ",", "// if node is null starting from root nodes", "null", "===", "$", "criteria", "?", "$", "this", "->", "direct", "(", ")", ":", "$", "criteria", ",", "// true: load all children, false: only direct, array: criteria", "array_replace_recursive", "(", "$", "this", "->", "getOptions", "(", ")", ",", "$", "options", ")", ",", "null", "===", "$", "includeNode", "?", "$", "this", "->", "includeNode", "(", ")", ":", "$", "includeNode", ")", ";", "}" ]
Render node's hierarchy @param HierarchyInterface $node @param array|bool $criteria @param array $options @param bool $includeNode @return string
[ "Render", "node", "s", "hierarchy" ]
3572993cdcdb2898cdde396a2f1de9864b193660
https://github.com/coolms/common/blob/3572993cdcdb2898cdde396a2f1de9864b193660/src/View/Helper/Hierarchy.php#L83-L91
11,092
canis-io/yii2-canis-lib
lib/base/ClassManager.php
ClassManager.setClasses
public function setClasses($classes, $override = true) { foreach ($classes as $key => $class) { if ($override || !isset($this->_classes[$key])) { $this->_classes[$key] = $class; } } }
php
public function setClasses($classes, $override = true) { foreach ($classes as $key => $class) { if ($override || !isset($this->_classes[$key])) { $this->_classes[$key] = $class; } } }
[ "public", "function", "setClasses", "(", "$", "classes", ",", "$", "override", "=", "true", ")", "{", "foreach", "(", "$", "classes", "as", "$", "key", "=>", "$", "class", ")", "{", "if", "(", "$", "override", "||", "!", "isset", "(", "$", "this", "->", "_classes", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "_classes", "[", "$", "key", "]", "=", "$", "class", ";", "}", "}", "}" ]
Set classes. @param [[@doctodo param_type:classes]] $classes [[@doctodo param_description:classes]] @param boolean $override [[@doctodo param_description:override]] [optional]
[ "Set", "classes", "." ]
97d533521f65b084dc805c5f312c364b469142d2
https://github.com/canis-io/yii2-canis-lib/blob/97d533521f65b084dc805c5f312c364b469142d2/lib/base/ClassManager.php#L64-L71
11,093
prooph/link-sql-connector
src/Service/TableConnectorGenerator.php
TableConnectorGenerator.replaceProcessingTypes
private function replaceProcessingTypes($dbname, $table, Connection $connection) { $dbNsName = $this->titleize($dbname); $rowClassName = $this->titleize($table); $collectionClassName = $rowClassName . "Collection"; $namespace = 'Prooph\Link\Application\DataType\SqlConnector\\' . $dbNsName; $this->dataTypeLocation->addDataTypeClass( $namespace . '\\' . $rowClassName, $this->generateRowTypeClass($namespace, $rowClassName, $table, $connection), $forceReplace = true ); $this->dataTypeLocation->addDataTypeClass( $namespace . '\\' . $collectionClassName, $this->generateRowCollectionTypeClass($namespace, $collectionClassName, $rowClassName), $forceReplace = true ); return [ $namespace . '\\' . $rowClassName, $namespace . '\\' . $collectionClassName ]; }
php
private function replaceProcessingTypes($dbname, $table, Connection $connection) { $dbNsName = $this->titleize($dbname); $rowClassName = $this->titleize($table); $collectionClassName = $rowClassName . "Collection"; $namespace = 'Prooph\Link\Application\DataType\SqlConnector\\' . $dbNsName; $this->dataTypeLocation->addDataTypeClass( $namespace . '\\' . $rowClassName, $this->generateRowTypeClass($namespace, $rowClassName, $table, $connection), $forceReplace = true ); $this->dataTypeLocation->addDataTypeClass( $namespace . '\\' . $collectionClassName, $this->generateRowCollectionTypeClass($namespace, $collectionClassName, $rowClassName), $forceReplace = true ); return [ $namespace . '\\' . $rowClassName, $namespace . '\\' . $collectionClassName ]; }
[ "private", "function", "replaceProcessingTypes", "(", "$", "dbname", ",", "$", "table", ",", "Connection", "$", "connection", ")", "{", "$", "dbNsName", "=", "$", "this", "->", "titleize", "(", "$", "dbname", ")", ";", "$", "rowClassName", "=", "$", "this", "->", "titleize", "(", "$", "table", ")", ";", "$", "collectionClassName", "=", "$", "rowClassName", ".", "\"Collection\"", ";", "$", "namespace", "=", "'Prooph\\Link\\Application\\DataType\\SqlConnector\\\\'", ".", "$", "dbNsName", ";", "$", "this", "->", "dataTypeLocation", "->", "addDataTypeClass", "(", "$", "namespace", ".", "'\\\\'", ".", "$", "rowClassName", ",", "$", "this", "->", "generateRowTypeClass", "(", "$", "namespace", ",", "$", "rowClassName", ",", "$", "table", ",", "$", "connection", ")", ",", "$", "forceReplace", "=", "true", ")", ";", "$", "this", "->", "dataTypeLocation", "->", "addDataTypeClass", "(", "$", "namespace", ".", "'\\\\'", ".", "$", "collectionClassName", ",", "$", "this", "->", "generateRowCollectionTypeClass", "(", "$", "namespace", ",", "$", "collectionClassName", ",", "$", "rowClassName", ")", ",", "$", "forceReplace", "=", "true", ")", ";", "return", "[", "$", "namespace", ".", "'\\\\'", ".", "$", "rowClassName", ",", "$", "namespace", ".", "'\\\\'", ".", "$", "collectionClassName", "]", ";", "}" ]
Does the same like generateProcessingTypesIfNotExist but overrides any existing type classes. Use this method with care. @param string $dbname @param string $table @param Connection $connection @return array
[ "Does", "the", "same", "like", "generateProcessingTypesIfNotExist", "but", "overrides", "any", "existing", "type", "classes", ".", "Use", "this", "method", "with", "care", "." ]
8846d6abf18c2df809e150794f12efdfbe467933
https://github.com/prooph/link-sql-connector/blob/8846d6abf18c2df809e150794f12efdfbe467933/src/Service/TableConnectorGenerator.php#L237-L260
11,094
prooph/link-sql-connector
src/Service/TableConnectorGenerator.php
TableConnectorGenerator.loadPropertiesForTable
private function loadPropertiesForTable($table, Connection $connection) { $columns = $connection->getSchemaManager()->listTableColumns($table); $props = []; foreach ($columns as $name => $column) { $processingType = $this->doctrineColumnToProcessingType($column); $props[$name] = [ 'processing_type' => $processingType, 'doctrine_type' => $column->getType()->getName(), ]; } return $props; }
php
private function loadPropertiesForTable($table, Connection $connection) { $columns = $connection->getSchemaManager()->listTableColumns($table); $props = []; foreach ($columns as $name => $column) { $processingType = $this->doctrineColumnToProcessingType($column); $props[$name] = [ 'processing_type' => $processingType, 'doctrine_type' => $column->getType()->getName(), ]; } return $props; }
[ "private", "function", "loadPropertiesForTable", "(", "$", "table", ",", "Connection", "$", "connection", ")", "{", "$", "columns", "=", "$", "connection", "->", "getSchemaManager", "(", ")", "->", "listTableColumns", "(", "$", "table", ")", ";", "$", "props", "=", "[", "]", ";", "foreach", "(", "$", "columns", "as", "$", "name", "=>", "$", "column", ")", "{", "$", "processingType", "=", "$", "this", "->", "doctrineColumnToProcessingType", "(", "$", "column", ")", ";", "$", "props", "[", "$", "name", "]", "=", "[", "'processing_type'", "=>", "$", "processingType", ",", "'doctrine_type'", "=>", "$", "column", "->", "getType", "(", ")", "->", "getName", "(", ")", ",", "]", ";", "}", "return", "$", "props", ";", "}" ]
Inspect given table and creates a map containing the mapped processing type and the original doctrine type The map is indexed by column names which become the property names @param string $table @param Connection $connection @return array
[ "Inspect", "given", "table", "and", "creates", "a", "map", "containing", "the", "mapped", "processing", "type", "and", "the", "original", "doctrine", "type", "The", "map", "is", "indexed", "by", "column", "names", "which", "become", "the", "property", "names" ]
8846d6abf18c2df809e150794f12efdfbe467933
https://github.com/prooph/link-sql-connector/blob/8846d6abf18c2df809e150794f12efdfbe467933/src/Service/TableConnectorGenerator.php#L283-L300
11,095
prooph/link-sql-connector
src/Service/TableConnectorGenerator.php
TableConnectorGenerator.loadPrimaryKeyforTable
private function loadPrimaryKeyforTable($table, Connection $connection) { $indexes = $connection->getSchemaManager()->listTableIndexes($table); $primaryKey = null; foreach ($indexes as $index) { if ($index->isPrimary()) { $columns = $index->getColumns(); $primaryKey = implode("_", $columns); break; } } return $primaryKey; }
php
private function loadPrimaryKeyforTable($table, Connection $connection) { $indexes = $connection->getSchemaManager()->listTableIndexes($table); $primaryKey = null; foreach ($indexes as $index) { if ($index->isPrimary()) { $columns = $index->getColumns(); $primaryKey = implode("_", $columns); break; } } return $primaryKey; }
[ "private", "function", "loadPrimaryKeyforTable", "(", "$", "table", ",", "Connection", "$", "connection", ")", "{", "$", "indexes", "=", "$", "connection", "->", "getSchemaManager", "(", ")", "->", "listTableIndexes", "(", "$", "table", ")", ";", "$", "primaryKey", "=", "null", ";", "foreach", "(", "$", "indexes", "as", "$", "index", ")", "{", "if", "(", "$", "index", "->", "isPrimary", "(", ")", ")", "{", "$", "columns", "=", "$", "index", "->", "getColumns", "(", ")", ";", "$", "primaryKey", "=", "implode", "(", "\"_\"", ",", "$", "columns", ")", ";", "break", ";", "}", "}", "return", "$", "primaryKey", ";", "}" ]
If table has a primary key this becomes the identifier of the row type. If primary key consists of more then one column, the name of the identifier is generated by concatenating the column names with a underscore. Such a row type needs to be manually adjusted to deal with the identifier! @param $table @param Connection $connection @return null|string
[ "If", "table", "has", "a", "primary", "key", "this", "becomes", "the", "identifier", "of", "the", "row", "type", ".", "If", "primary", "key", "consists", "of", "more", "then", "one", "column", "the", "name", "of", "the", "identifier", "is", "generated", "by", "concatenating", "the", "column", "names", "with", "a", "underscore", ".", "Such", "a", "row", "type", "needs", "to", "be", "manually", "adjusted", "to", "deal", "with", "the", "identifier!" ]
8846d6abf18c2df809e150794f12efdfbe467933
https://github.com/prooph/link-sql-connector/blob/8846d6abf18c2df809e150794f12efdfbe467933/src/Service/TableConnectorGenerator.php#L312-L328
11,096
gossi/trixionary
src/domain/base/ObjectDomainTrait.php
ObjectDomainTrait.removeSkills
public function removeSkills($id, $data) { // find $model = $this->get($id); if ($model === null) { return new NotFound(['message' => 'Object not found.']); } // pass remove to internal logic try { $this->doRemoveSkills($model, $data); } catch (ErrorsException $e) { return new NotValid(['errors' => $e->getErrors()]); } // save and dispatch events $this->dispatch(ObjectEvent::PRE_SKILLS_REMOVE, $model, $data); $this->dispatch(ObjectEvent::PRE_SAVE, $model, $data); $rows = $model->save(); $this->dispatch(ObjectEvent::POST_SKILLS_REMOVE, $model, $data); $this->dispatch(ObjectEvent::POST_SAVE, $model, $data); if ($rows > 0) { return Updated(['model' => $model]); } return NotUpdated(['model' => $model]); }
php
public function removeSkills($id, $data) { // find $model = $this->get($id); if ($model === null) { return new NotFound(['message' => 'Object not found.']); } // pass remove to internal logic try { $this->doRemoveSkills($model, $data); } catch (ErrorsException $e) { return new NotValid(['errors' => $e->getErrors()]); } // save and dispatch events $this->dispatch(ObjectEvent::PRE_SKILLS_REMOVE, $model, $data); $this->dispatch(ObjectEvent::PRE_SAVE, $model, $data); $rows = $model->save(); $this->dispatch(ObjectEvent::POST_SKILLS_REMOVE, $model, $data); $this->dispatch(ObjectEvent::POST_SAVE, $model, $data); if ($rows > 0) { return Updated(['model' => $model]); } return NotUpdated(['model' => $model]); }
[ "public", "function", "removeSkills", "(", "$", "id", ",", "$", "data", ")", "{", "// find", "$", "model", "=", "$", "this", "->", "get", "(", "$", "id", ")", ";", "if", "(", "$", "model", "===", "null", ")", "{", "return", "new", "NotFound", "(", "[", "'message'", "=>", "'Object not found.'", "]", ")", ";", "}", "// pass remove to internal logic", "try", "{", "$", "this", "->", "doRemoveSkills", "(", "$", "model", ",", "$", "data", ")", ";", "}", "catch", "(", "ErrorsException", "$", "e", ")", "{", "return", "new", "NotValid", "(", "[", "'errors'", "=>", "$", "e", "->", "getErrors", "(", ")", "]", ")", ";", "}", "// save and dispatch events", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "PRE_SKILLS_REMOVE", ",", "$", "model", ",", "$", "data", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "PRE_SAVE", ",", "$", "model", ",", "$", "data", ")", ";", "$", "rows", "=", "$", "model", "->", "save", "(", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "POST_SKILLS_REMOVE", ",", "$", "model", ",", "$", "data", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "POST_SAVE", ",", "$", "model", ",", "$", "data", ")", ";", "if", "(", "$", "rows", ">", "0", ")", "{", "return", "Updated", "(", "[", "'model'", "=>", "$", "model", "]", ")", ";", "}", "return", "NotUpdated", "(", "[", "'model'", "=>", "$", "model", "]", ")", ";", "}" ]
Removes Skills from Object @param mixed $id @param mixed $data @return PayloadInterface
[ "Removes", "Skills", "from", "Object" ]
221a6c5322473d7d7f8e322958a3ee46d87da150
https://github.com/gossi/trixionary/blob/221a6c5322473d7d7f8e322958a3ee46d87da150/src/domain/base/ObjectDomainTrait.php#L189-L216
11,097
gossi/trixionary
src/domain/base/ObjectDomainTrait.php
ObjectDomainTrait.setSportId
public function setSportId($id, $relatedId) { // find $model = $this->get($id); if ($model === null) { return new NotFound(['message' => 'Object not found.']); } // update if ($this->doSetSportId($model, $relatedId)) { $this->dispatch(ObjectEvent::PRE_SPORT_UPDATE, $model); $this->dispatch(ObjectEvent::PRE_SAVE, $model); $model->save(); $this->dispatch(ObjectEvent::POST_SPORT_UPDATE, $model); $this->dispatch(ObjectEvent::POST_SAVE, $model); return Updated(['model' => $model]); } return NotUpdated(['model' => $model]); }
php
public function setSportId($id, $relatedId) { // find $model = $this->get($id); if ($model === null) { return new NotFound(['message' => 'Object not found.']); } // update if ($this->doSetSportId($model, $relatedId)) { $this->dispatch(ObjectEvent::PRE_SPORT_UPDATE, $model); $this->dispatch(ObjectEvent::PRE_SAVE, $model); $model->save(); $this->dispatch(ObjectEvent::POST_SPORT_UPDATE, $model); $this->dispatch(ObjectEvent::POST_SAVE, $model); return Updated(['model' => $model]); } return NotUpdated(['model' => $model]); }
[ "public", "function", "setSportId", "(", "$", "id", ",", "$", "relatedId", ")", "{", "// find", "$", "model", "=", "$", "this", "->", "get", "(", "$", "id", ")", ";", "if", "(", "$", "model", "===", "null", ")", "{", "return", "new", "NotFound", "(", "[", "'message'", "=>", "'Object not found.'", "]", ")", ";", "}", "// update", "if", "(", "$", "this", "->", "doSetSportId", "(", "$", "model", ",", "$", "relatedId", ")", ")", "{", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "PRE_SPORT_UPDATE", ",", "$", "model", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "PRE_SAVE", ",", "$", "model", ")", ";", "$", "model", "->", "save", "(", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "POST_SPORT_UPDATE", ",", "$", "model", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "POST_SAVE", ",", "$", "model", ")", ";", "return", "Updated", "(", "[", "'model'", "=>", "$", "model", "]", ")", ";", "}", "return", "NotUpdated", "(", "[", "'model'", "=>", "$", "model", "]", ")", ";", "}" ]
Sets the Sport id @param mixed $id @param mixed $relatedId @return PayloadInterface
[ "Sets", "the", "Sport", "id" ]
221a6c5322473d7d7f8e322958a3ee46d87da150
https://github.com/gossi/trixionary/blob/221a6c5322473d7d7f8e322958a3ee46d87da150/src/domain/base/ObjectDomainTrait.php#L225-L245
11,098
gossi/trixionary
src/domain/base/ObjectDomainTrait.php
ObjectDomainTrait.update
public function update($id, $data) { // find $model = $this->get($id); if ($model === null) { return new NotFound(['message' => 'Object not found.']); } // hydrate $serializer = Object::getSerializer(); $model = $serializer->hydrate($model, $data); $this->hydrateRelationships($model, $data); // dispatch pre save hooks $this->dispatch(ObjectEvent::PRE_UPDATE, $model, $data); $this->dispatch(ObjectEvent::PRE_SAVE, $model, $data); // validate $validator = $this->getValidator(); if ($validator !== null && !$validator->validate($model)) { return new NotValid([ 'errors' => $validator->getValidationFailures() ]); } // save and dispath post save hooks $rows = $model->save(); $this->dispatch(ObjectEvent::POST_UPDATE, $model, $data); $this->dispatch(ObjectEvent::POST_SAVE, $model, $data); $payload = ['model' => $model]; if ($rows === 0) { return new NotUpdated($payload); } return new Updated($payload); }
php
public function update($id, $data) { // find $model = $this->get($id); if ($model === null) { return new NotFound(['message' => 'Object not found.']); } // hydrate $serializer = Object::getSerializer(); $model = $serializer->hydrate($model, $data); $this->hydrateRelationships($model, $data); // dispatch pre save hooks $this->dispatch(ObjectEvent::PRE_UPDATE, $model, $data); $this->dispatch(ObjectEvent::PRE_SAVE, $model, $data); // validate $validator = $this->getValidator(); if ($validator !== null && !$validator->validate($model)) { return new NotValid([ 'errors' => $validator->getValidationFailures() ]); } // save and dispath post save hooks $rows = $model->save(); $this->dispatch(ObjectEvent::POST_UPDATE, $model, $data); $this->dispatch(ObjectEvent::POST_SAVE, $model, $data); $payload = ['model' => $model]; if ($rows === 0) { return new NotUpdated($payload); } return new Updated($payload); }
[ "public", "function", "update", "(", "$", "id", ",", "$", "data", ")", "{", "// find", "$", "model", "=", "$", "this", "->", "get", "(", "$", "id", ")", ";", "if", "(", "$", "model", "===", "null", ")", "{", "return", "new", "NotFound", "(", "[", "'message'", "=>", "'Object not found.'", "]", ")", ";", "}", "// hydrate", "$", "serializer", "=", "Object", "::", "getSerializer", "(", ")", ";", "$", "model", "=", "$", "serializer", "->", "hydrate", "(", "$", "model", ",", "$", "data", ")", ";", "$", "this", "->", "hydrateRelationships", "(", "$", "model", ",", "$", "data", ")", ";", "// dispatch pre save hooks", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "PRE_UPDATE", ",", "$", "model", ",", "$", "data", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "PRE_SAVE", ",", "$", "model", ",", "$", "data", ")", ";", "// validate", "$", "validator", "=", "$", "this", "->", "getValidator", "(", ")", ";", "if", "(", "$", "validator", "!==", "null", "&&", "!", "$", "validator", "->", "validate", "(", "$", "model", ")", ")", "{", "return", "new", "NotValid", "(", "[", "'errors'", "=>", "$", "validator", "->", "getValidationFailures", "(", ")", "]", ")", ";", "}", "// save and dispath post save hooks", "$", "rows", "=", "$", "model", "->", "save", "(", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "POST_UPDATE", ",", "$", "model", ",", "$", "data", ")", ";", "$", "this", "->", "dispatch", "(", "ObjectEvent", "::", "POST_SAVE", ",", "$", "model", ",", "$", "data", ")", ";", "$", "payload", "=", "[", "'model'", "=>", "$", "model", "]", ";", "if", "(", "$", "rows", "===", "0", ")", "{", "return", "new", "NotUpdated", "(", "$", "payload", ")", ";", "}", "return", "new", "Updated", "(", "$", "payload", ")", ";", "}" ]
Updates a Object with the given idand the provided data @param mixed $id @param mixed $data @return PayloadInterface
[ "Updates", "a", "Object", "with", "the", "given", "idand", "the", "provided", "data" ]
221a6c5322473d7d7f8e322958a3ee46d87da150
https://github.com/gossi/trixionary/blob/221a6c5322473d7d7f8e322958a3ee46d87da150/src/domain/base/ObjectDomainTrait.php#L254-L291
11,099
gossi/trixionary
src/domain/base/ObjectDomainTrait.php
ObjectDomainTrait.doUpdateSkills
protected function doUpdateSkills(Object $model, $data) { // remove all relationships before SkillQuery::create()->filterByObject($model)->delete(); // add them $errors = []; foreach ($data as $entry) { if (!isset($entry['id'])) { $errors[] = 'Missing id for Skill'; } else { $related = SkillQuery::create()->findOneById($entry['id']); $model->addSkill($related); } } if (count($errors) > 0) { throw new ErrorsException($errors); } }
php
protected function doUpdateSkills(Object $model, $data) { // remove all relationships before SkillQuery::create()->filterByObject($model)->delete(); // add them $errors = []; foreach ($data as $entry) { if (!isset($entry['id'])) { $errors[] = 'Missing id for Skill'; } else { $related = SkillQuery::create()->findOneById($entry['id']); $model->addSkill($related); } } if (count($errors) > 0) { throw new ErrorsException($errors); } }
[ "protected", "function", "doUpdateSkills", "(", "Object", "$", "model", ",", "$", "data", ")", "{", "// remove all relationships before", "SkillQuery", "::", "create", "(", ")", "->", "filterByObject", "(", "$", "model", ")", "->", "delete", "(", ")", ";", "// add them", "$", "errors", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "entry", ")", "{", "if", "(", "!", "isset", "(", "$", "entry", "[", "'id'", "]", ")", ")", "{", "$", "errors", "[", "]", "=", "'Missing id for Skill'", ";", "}", "else", "{", "$", "related", "=", "SkillQuery", "::", "create", "(", ")", "->", "findOneById", "(", "$", "entry", "[", "'id'", "]", ")", ";", "$", "model", "->", "addSkill", "(", "$", "related", ")", ";", "}", "}", "if", "(", "count", "(", "$", "errors", ")", ">", "0", ")", "{", "throw", "new", "ErrorsException", "(", "$", "errors", ")", ";", "}", "}" ]
Internal update mechanism of Skills on Object @param Object $model @param mixed $data
[ "Internal", "update", "mechanism", "of", "Skills", "on", "Object" ]
221a6c5322473d7d7f8e322958a3ee46d87da150
https://github.com/gossi/trixionary/blob/221a6c5322473d7d7f8e322958a3ee46d87da150/src/domain/base/ObjectDomainTrait.php#L467-L485