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
partition
stringclasses
1 value
PenoaksDev/Milky-Framework
src/Milky/Pagination/Paginator.php
Paginator.checkForMorePages
protected function checkForMorePages() { $this->hasMore = count( $this->items ) > ( $this->perPage ); $this->items = $this->items->slice( 0, $this->perPage ); }
php
protected function checkForMorePages() { $this->hasMore = count( $this->items ) > ( $this->perPage ); $this->items = $this->items->slice( 0, $this->perPage ); }
[ "protected", "function", "checkForMorePages", "(", ")", "{", "$", "this", "->", "hasMore", "=", "count", "(", "$", "this", "->", "items", ")", ">", "(", "$", "this", "->", "perPage", ")", ";", "$", "this", "->", "items", "=", "$", "this", "->", "items", "->", "slice", "(", "0", ",", "$", "this", "->", "perPage", ")", ";", "}" ]
Check for more pages. The last item will be sliced off. @return void
[ "Check", "for", "more", "pages", ".", "The", "last", "item", "will", "be", "sliced", "off", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Pagination/Paginator.php#L62-L67
train
OxfordInfoLabs/kinikit-core
src/Util/SerialisableArrayUtils.php
SerialisableArrayUtils.getMemberValueArrayForObjects
public static function getMemberValueArrayForObjects($member, $objects) { $returnValues = array(); foreach ($objects as $key => $value) { if (is_object($value)) { if ($value instanceof SerialisableObject) { $returnValues[$key] = $value->__getSerialisablePropertyValue($member); } else { throw new ClassNotSerialisableException(get_class($value)); } } } return $returnValues; }
php
public static function getMemberValueArrayForObjects($member, $objects) { $returnValues = array(); foreach ($objects as $key => $value) { if (is_object($value)) { if ($value instanceof SerialisableObject) { $returnValues[$key] = $value->__getSerialisablePropertyValue($member); } else { throw new ClassNotSerialisableException(get_class($value)); } } } return $returnValues; }
[ "public", "static", "function", "getMemberValueArrayForObjects", "(", "$", "member", ",", "$", "objects", ")", "{", "$", "returnValues", "=", "array", "(", ")", ";", "foreach", "(", "$", "objects", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "if", "(", "$", "value", "instanceof", "SerialisableObject", ")", "{", "$", "returnValues", "[", "$", "key", "]", "=", "$", "value", "->", "__getSerialisablePropertyValue", "(", "$", "member", ")", ";", "}", "else", "{", "throw", "new", "ClassNotSerialisableException", "(", "get_class", "(", "$", "value", ")", ")", ";", "}", "}", "}", "return", "$", "returnValues", ";", "}" ]
Get an array of member values for a given member for the array of objects passed using the same indexing system as the passed objects. @static @param $member @param $objects
[ "Get", "an", "array", "of", "member", "values", "for", "a", "given", "member", "for", "the", "array", "of", "objects", "passed", "using", "the", "same", "indexing", "system", "as", "the", "passed", "objects", "." ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/SerialisableArrayUtils.php#L30-L47
train
OxfordInfoLabs/kinikit-core
src/Util/SerialisableArrayUtils.php
SerialisableArrayUtils.indexArrayOfObjectsByMember
public static function indexArrayOfObjectsByMember($member, $objects) { $returnValues = array(); foreach ($objects as $object) { if ($object instanceof SerialisableObject) { $returnValues[$object->__getSerialisablePropertyValue($member)] = $object; } else { throw new ClassNotSerialisableException(get_class($object)); } } return $returnValues; }
php
public static function indexArrayOfObjectsByMember($member, $objects) { $returnValues = array(); foreach ($objects as $object) { if ($object instanceof SerialisableObject) { $returnValues[$object->__getSerialisablePropertyValue($member)] = $object; } else { throw new ClassNotSerialisableException(get_class($object)); } } return $returnValues; }
[ "public", "static", "function", "indexArrayOfObjectsByMember", "(", "$", "member", ",", "$", "objects", ")", "{", "$", "returnValues", "=", "array", "(", ")", ";", "foreach", "(", "$", "objects", "as", "$", "object", ")", "{", "if", "(", "$", "object", "instanceof", "SerialisableObject", ")", "{", "$", "returnValues", "[", "$", "object", "->", "__getSerialisablePropertyValue", "(", "$", "member", ")", "]", "=", "$", "object", ";", "}", "else", "{", "throw", "new", "ClassNotSerialisableException", "(", "get_class", "(", "$", "object", ")", ")", ";", "}", "}", "return", "$", "returnValues", ";", "}" ]
Index the array of passed objects by the supplied member, returning an associative array. @param $member @param $objects
[ "Index", "the", "array", "of", "passed", "objects", "by", "the", "supplied", "member", "returning", "an", "associative", "array", "." ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/SerialisableArrayUtils.php#L56-L70
train
OxfordInfoLabs/kinikit-core
src/Util/SerialisableArrayUtils.php
SerialisableArrayUtils.filterArrayOfObjectsByMember
public static function filterArrayOfObjectsByMember($member, $objects, $filterValue) { $filterValues = is_array($filterValue) ? $filterValue : array($filterValue); $filteredObjects = array(); foreach ($objects as $object) { if ($object instanceof SerialisableObject) { foreach ($filterValues as $value) { if ($value == $object->__getSerialisablePropertyValue($member)) { $filteredObjects[] = $object; break; } } } else { throw new ClassNotSerialisableException(get_class($object)); } } return $filteredObjects; }
php
public static function filterArrayOfObjectsByMember($member, $objects, $filterValue) { $filterValues = is_array($filterValue) ? $filterValue : array($filterValue); $filteredObjects = array(); foreach ($objects as $object) { if ($object instanceof SerialisableObject) { foreach ($filterValues as $value) { if ($value == $object->__getSerialisablePropertyValue($member)) { $filteredObjects[] = $object; break; } } } else { throw new ClassNotSerialisableException(get_class($object)); } } return $filteredObjects; }
[ "public", "static", "function", "filterArrayOfObjectsByMember", "(", "$", "member", ",", "$", "objects", ",", "$", "filterValue", ")", "{", "$", "filterValues", "=", "is_array", "(", "$", "filterValue", ")", "?", "$", "filterValue", ":", "array", "(", "$", "filterValue", ")", ";", "$", "filteredObjects", "=", "array", "(", ")", ";", "foreach", "(", "$", "objects", "as", "$", "object", ")", "{", "if", "(", "$", "object", "instanceof", "SerialisableObject", ")", "{", "foreach", "(", "$", "filterValues", "as", "$", "value", ")", "{", "if", "(", "$", "value", "==", "$", "object", "->", "__getSerialisablePropertyValue", "(", "$", "member", ")", ")", "{", "$", "filteredObjects", "[", "]", "=", "$", "object", ";", "break", ";", "}", "}", "}", "else", "{", "throw", "new", "ClassNotSerialisableException", "(", "get_class", "(", "$", "object", ")", ")", ";", "}", "}", "return", "$", "filteredObjects", ";", "}" ]
Filter an array of objects by a specified member. Perhaps in the future extend to multiple match types. @param $member @param $objects @param $filterValue
[ "Filter", "an", "array", "of", "objects", "by", "a", "specified", "member", ".", "Perhaps", "in", "the", "future", "extend", "to", "multiple", "match", "types", "." ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/SerialisableArrayUtils.php#L81-L102
train
OxfordInfoLabs/kinikit-core
src/Util/SerialisableArrayUtils.php
SerialisableArrayUtils.groupArrayOfObjectsByMember
public static function groupArrayOfObjectsByMember($member, $objects) { if (!is_array($member)) $member = array($member); $leafMember = array_pop($member); $groupedObjects = new AssociativeArray(); foreach ($objects as $object) { $rootNode = $groupedObjects; foreach ($member as $memberComponent) { $groupValue = $object->__getSerialisablePropertyValue($memberComponent); if (!$groupValue && !is_numeric($groupValue)) $groupValue = "NULL"; if (!isset($rootNode[$groupValue])) $rootNode[$groupValue] = new AssociativeArray(); $rootNode = $rootNode[$groupValue]; } $leafValue = $object->__getSerialisablePropertyValue($leafMember); if (!$leafValue && !is_numeric($leafValue)) $leafValue = "NULL"; if (!$rootNode[$leafValue]) $rootNode[$leafValue] = array(); $leafValues = $rootNode[$leafValue]; $leafValues[] = $object; $rootNode[$leafValue] = $leafValues; } return $groupedObjects->toArray(); }
php
public static function groupArrayOfObjectsByMember($member, $objects) { if (!is_array($member)) $member = array($member); $leafMember = array_pop($member); $groupedObjects = new AssociativeArray(); foreach ($objects as $object) { $rootNode = $groupedObjects; foreach ($member as $memberComponent) { $groupValue = $object->__getSerialisablePropertyValue($memberComponent); if (!$groupValue && !is_numeric($groupValue)) $groupValue = "NULL"; if (!isset($rootNode[$groupValue])) $rootNode[$groupValue] = new AssociativeArray(); $rootNode = $rootNode[$groupValue]; } $leafValue = $object->__getSerialisablePropertyValue($leafMember); if (!$leafValue && !is_numeric($leafValue)) $leafValue = "NULL"; if (!$rootNode[$leafValue]) $rootNode[$leafValue] = array(); $leafValues = $rootNode[$leafValue]; $leafValues[] = $object; $rootNode[$leafValue] = $leafValues; } return $groupedObjects->toArray(); }
[ "public", "static", "function", "groupArrayOfObjectsByMember", "(", "$", "member", ",", "$", "objects", ")", "{", "if", "(", "!", "is_array", "(", "$", "member", ")", ")", "$", "member", "=", "array", "(", "$", "member", ")", ";", "$", "leafMember", "=", "array_pop", "(", "$", "member", ")", ";", "$", "groupedObjects", "=", "new", "AssociativeArray", "(", ")", ";", "foreach", "(", "$", "objects", "as", "$", "object", ")", "{", "$", "rootNode", "=", "$", "groupedObjects", ";", "foreach", "(", "$", "member", "as", "$", "memberComponent", ")", "{", "$", "groupValue", "=", "$", "object", "->", "__getSerialisablePropertyValue", "(", "$", "memberComponent", ")", ";", "if", "(", "!", "$", "groupValue", "&&", "!", "is_numeric", "(", "$", "groupValue", ")", ")", "$", "groupValue", "=", "\"NULL\"", ";", "if", "(", "!", "isset", "(", "$", "rootNode", "[", "$", "groupValue", "]", ")", ")", "$", "rootNode", "[", "$", "groupValue", "]", "=", "new", "AssociativeArray", "(", ")", ";", "$", "rootNode", "=", "$", "rootNode", "[", "$", "groupValue", "]", ";", "}", "$", "leafValue", "=", "$", "object", "->", "__getSerialisablePropertyValue", "(", "$", "leafMember", ")", ";", "if", "(", "!", "$", "leafValue", "&&", "!", "is_numeric", "(", "$", "leafValue", ")", ")", "$", "leafValue", "=", "\"NULL\"", ";", "if", "(", "!", "$", "rootNode", "[", "$", "leafValue", "]", ")", "$", "rootNode", "[", "$", "leafValue", "]", "=", "array", "(", ")", ";", "$", "leafValues", "=", "$", "rootNode", "[", "$", "leafValue", "]", ";", "$", "leafValues", "[", "]", "=", "$", "object", ";", "$", "rootNode", "[", "$", "leafValue", "]", "=", "$", "leafValues", ";", "}", "return", "$", "groupedObjects", "->", "toArray", "(", ")", ";", "}" ]
Group an array of objects by a given member. @param $member @param $objects
[ "Group", "an", "array", "of", "objects", "by", "a", "given", "member", "." ]
edc1b2e6ffabd595c4c7d322279b3dd1e59ef359
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/SerialisableArrayUtils.php#L111-L146
train
praxigento/mobi_mod_pv
Controller/Adminhtml/Transfers/Upload/Save.php
Save.saveFile
private function saveFile() { $dirMedia = $this->filesystem->getDirectoryWrite(ADirList::MEDIA); $dirTarget = $dirMedia->getAbsolutePath(self::MEDIA_SUBFOLDER); $fileId = self::FIELDSET . '[' . self::FIELD_CSV_FILE . ']'; // $fileId = self::FIELD_CSV_FILE; // $fileId = self::FIELDSET; $uploader = $this->factUploader->create(['fileId' => $fileId]); $uploader->setAllowRenameFiles(true); $result = $uploader->save($dirTarget); if (isset($result['path']) && isset($result['file'])) { $fullpath = $result['path'] . $result['file']; $this->logger->info("Uploaded file is saved into '$fullpath'."); } return $result; }
php
private function saveFile() { $dirMedia = $this->filesystem->getDirectoryWrite(ADirList::MEDIA); $dirTarget = $dirMedia->getAbsolutePath(self::MEDIA_SUBFOLDER); $fileId = self::FIELDSET . '[' . self::FIELD_CSV_FILE . ']'; // $fileId = self::FIELD_CSV_FILE; // $fileId = self::FIELDSET; $uploader = $this->factUploader->create(['fileId' => $fileId]); $uploader->setAllowRenameFiles(true); $result = $uploader->save($dirTarget); if (isset($result['path']) && isset($result['file'])) { $fullpath = $result['path'] . $result['file']; $this->logger->info("Uploaded file is saved into '$fullpath'."); } return $result; }
[ "private", "function", "saveFile", "(", ")", "{", "$", "dirMedia", "=", "$", "this", "->", "filesystem", "->", "getDirectoryWrite", "(", "ADirList", "::", "MEDIA", ")", ";", "$", "dirTarget", "=", "$", "dirMedia", "->", "getAbsolutePath", "(", "self", "::", "MEDIA_SUBFOLDER", ")", ";", "$", "fileId", "=", "self", "::", "FIELDSET", ".", "'['", ".", "self", "::", "FIELD_CSV_FILE", ".", "']'", ";", "// $fileId = self::FIELD_CSV_FILE;", "// $fileId = self::FIELDSET;", "$", "uploader", "=", "$", "this", "->", "factUploader", "->", "create", "(", "[", "'fileId'", "=>", "$", "fileId", "]", ")", ";", "$", "uploader", "->", "setAllowRenameFiles", "(", "true", ")", ";", "$", "result", "=", "$", "uploader", "->", "save", "(", "$", "dirTarget", ")", ";", "if", "(", "isset", "(", "$", "result", "[", "'path'", "]", ")", "&&", "isset", "(", "$", "result", "[", "'file'", "]", ")", ")", "{", "$", "fullpath", "=", "$", "result", "[", "'path'", "]", ".", "$", "result", "[", "'file'", "]", ";", "$", "this", "->", "logger", "->", "info", "(", "\"Uploaded file is saved into '$fullpath'.\"", ")", ";", "}", "return", "$", "result", ";", "}" ]
Save uploading file to the 'media' folder @return array @throws \Magento\Framework\Exception\FileSystemException
[ "Save", "uploading", "file", "to", "the", "media", "folder" ]
d1540b7e94264527006e8b9fa68904a72a63928e
https://github.com/praxigento/mobi_mod_pv/blob/d1540b7e94264527006e8b9fa68904a72a63928e/Controller/Adminhtml/Transfers/Upload/Save.php#L121-L136
train
t3v/t3v_core
Classes/Service/PageService.php
PageService.getBackendLayoutForPage
public function getBackendLayoutForPage(int $uid) { $rootLine = $this->pageRepository->getRootLine($uid); if ($rootLine) { $index = -1; foreach($rootLine as $page) { $index++; $backendLayout = $page['backend_layout']; $hasBackendLayout = false; $backendLayoutNextLevel = $page['backend_layout_next_level']; $hasBackendLayoutNextLevel = false; if (!empty($backendLayout)) { $backendLayout = str_replace(self::BACKEND_LAYOUT_PREFIX, '', $backendLayout); } if (!empty($backendLayout) && $backendLayout != '-1') { $hasBackendLayout = true; } if (!empty($backendLayoutNextLevel)) { $backendLayoutNextLevel = str_replace(self::BACKEND_LAYOUT_PREFIX, '', $backendLayoutNextLevel); } if (!empty($backendLayoutNextLevel) && $backendLayoutNextLevel != '-1') { $hasBackendLayoutNextLevel = true; } if ($index == 0 && $hasBackendLayout) { return $backendLayout; } elseif ($index > 0 && $hasBackendLayoutNextLevel) { return $backendLayoutNextLevel; } } } return null; }
php
public function getBackendLayoutForPage(int $uid) { $rootLine = $this->pageRepository->getRootLine($uid); if ($rootLine) { $index = -1; foreach($rootLine as $page) { $index++; $backendLayout = $page['backend_layout']; $hasBackendLayout = false; $backendLayoutNextLevel = $page['backend_layout_next_level']; $hasBackendLayoutNextLevel = false; if (!empty($backendLayout)) { $backendLayout = str_replace(self::BACKEND_LAYOUT_PREFIX, '', $backendLayout); } if (!empty($backendLayout) && $backendLayout != '-1') { $hasBackendLayout = true; } if (!empty($backendLayoutNextLevel)) { $backendLayoutNextLevel = str_replace(self::BACKEND_LAYOUT_PREFIX, '', $backendLayoutNextLevel); } if (!empty($backendLayoutNextLevel) && $backendLayoutNextLevel != '-1') { $hasBackendLayoutNextLevel = true; } if ($index == 0 && $hasBackendLayout) { return $backendLayout; } elseif ($index > 0 && $hasBackendLayoutNextLevel) { return $backendLayoutNextLevel; } } } return null; }
[ "public", "function", "getBackendLayoutForPage", "(", "int", "$", "uid", ")", "{", "$", "rootLine", "=", "$", "this", "->", "pageRepository", "->", "getRootLine", "(", "$", "uid", ")", ";", "if", "(", "$", "rootLine", ")", "{", "$", "index", "=", "-", "1", ";", "foreach", "(", "$", "rootLine", "as", "$", "page", ")", "{", "$", "index", "++", ";", "$", "backendLayout", "=", "$", "page", "[", "'backend_layout'", "]", ";", "$", "hasBackendLayout", "=", "false", ";", "$", "backendLayoutNextLevel", "=", "$", "page", "[", "'backend_layout_next_level'", "]", ";", "$", "hasBackendLayoutNextLevel", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "backendLayout", ")", ")", "{", "$", "backendLayout", "=", "str_replace", "(", "self", "::", "BACKEND_LAYOUT_PREFIX", ",", "''", ",", "$", "backendLayout", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "backendLayout", ")", "&&", "$", "backendLayout", "!=", "'-1'", ")", "{", "$", "hasBackendLayout", "=", "true", ";", "}", "if", "(", "!", "empty", "(", "$", "backendLayoutNextLevel", ")", ")", "{", "$", "backendLayoutNextLevel", "=", "str_replace", "(", "self", "::", "BACKEND_LAYOUT_PREFIX", ",", "''", ",", "$", "backendLayoutNextLevel", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "backendLayoutNextLevel", ")", "&&", "$", "backendLayoutNextLevel", "!=", "'-1'", ")", "{", "$", "hasBackendLayoutNextLevel", "=", "true", ";", "}", "if", "(", "$", "index", "==", "0", "&&", "$", "hasBackendLayout", ")", "{", "return", "$", "backendLayout", ";", "}", "elseif", "(", "$", "index", ">", "0", "&&", "$", "hasBackendLayoutNextLevel", ")", "{", "return", "$", "backendLayoutNextLevel", ";", "}", "}", "}", "return", "null", ";", "}" ]
Gets the backend layout for a page. @param int $uid The UID of the page @return string|null The backend layout or null if no backend layout was found
[ "Gets", "the", "backend", "layout", "for", "a", "page", "." ]
8c04b7688cc2773f11fcc87fda3f7cd53d80a980
https://github.com/t3v/t3v_core/blob/8c04b7688cc2773f11fcc87fda3f7cd53d80a980/Classes/Service/PageService.php#L205-L244
train
ekyna/MediaBundle
Browser/Generator.php
Generator.generateThumbUrl
public function generateThumbUrl(MediaInterface $media) { $path = null; if ($media->getType() === MediaTypes::IMAGE) { $path = $this->cacheManager->getBrowserPath($media->getPath(), 'media_thumb'); } else { $path = $this->generateFileThumb($media); } if (null === $path) { $path = '/bundles/ekynamedia/img/file.jpg'; } return $path; }
php
public function generateThumbUrl(MediaInterface $media) { $path = null; if ($media->getType() === MediaTypes::IMAGE) { $path = $this->cacheManager->getBrowserPath($media->getPath(), 'media_thumb'); } else { $path = $this->generateFileThumb($media); } if (null === $path) { $path = '/bundles/ekynamedia/img/file.jpg'; } return $path; }
[ "public", "function", "generateThumbUrl", "(", "MediaInterface", "$", "media", ")", "{", "$", "path", "=", "null", ";", "if", "(", "$", "media", "->", "getType", "(", ")", "===", "MediaTypes", "::", "IMAGE", ")", "{", "$", "path", "=", "$", "this", "->", "cacheManager", "->", "getBrowserPath", "(", "$", "media", "->", "getPath", "(", ")", ",", "'media_thumb'", ")", ";", "}", "else", "{", "$", "path", "=", "$", "this", "->", "generateFileThumb", "(", "$", "media", ")", ";", "}", "if", "(", "null", "===", "$", "path", ")", "{", "$", "path", "=", "'/bundles/ekynamedia/img/file.jpg'", ";", "}", "return", "$", "path", ";", "}" ]
Generates a thumb for the given media. @param MediaInterface $media @return string
[ "Generates", "a", "thumb", "for", "the", "given", "media", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Browser/Generator.php#L89-L104
train
ekyna/MediaBundle
Browser/Generator.php
Generator.generateFrontUrl
public function generateFrontUrl(MediaInterface $media) { $path = null; if ($media->getType() === MediaTypes::IMAGE) { $path = $this->cacheManager->getBrowserPath($media->getPath(), 'media_front'); } elseif (in_array($media->getType(), [MediaTypes::VIDEO, MediaTypes::AUDIO, MediaTypes::FLASH])) { $path = $this->urlGenerator->generate('ekyna_media_player', ['key' => $media->getPath()], true); } else { $path = $this->urlGenerator->generate('ekyna_media_download', ['key' => $media->getPath()], true); } return $path; }
php
public function generateFrontUrl(MediaInterface $media) { $path = null; if ($media->getType() === MediaTypes::IMAGE) { $path = $this->cacheManager->getBrowserPath($media->getPath(), 'media_front'); } elseif (in_array($media->getType(), [MediaTypes::VIDEO, MediaTypes::AUDIO, MediaTypes::FLASH])) { $path = $this->urlGenerator->generate('ekyna_media_player', ['key' => $media->getPath()], true); } else { $path = $this->urlGenerator->generate('ekyna_media_download', ['key' => $media->getPath()], true); } return $path; }
[ "public", "function", "generateFrontUrl", "(", "MediaInterface", "$", "media", ")", "{", "$", "path", "=", "null", ";", "if", "(", "$", "media", "->", "getType", "(", ")", "===", "MediaTypes", "::", "IMAGE", ")", "{", "$", "path", "=", "$", "this", "->", "cacheManager", "->", "getBrowserPath", "(", "$", "media", "->", "getPath", "(", ")", ",", "'media_front'", ")", ";", "}", "elseif", "(", "in_array", "(", "$", "media", "->", "getType", "(", ")", ",", "[", "MediaTypes", "::", "VIDEO", ",", "MediaTypes", "::", "AUDIO", ",", "MediaTypes", "::", "FLASH", "]", ")", ")", "{", "$", "path", "=", "$", "this", "->", "urlGenerator", "->", "generate", "(", "'ekyna_media_player'", ",", "[", "'key'", "=>", "$", "media", "->", "getPath", "(", ")", "]", ",", "true", ")", ";", "}", "else", "{", "$", "path", "=", "$", "this", "->", "urlGenerator", "->", "generate", "(", "'ekyna_media_download'", ",", "[", "'key'", "=>", "$", "media", "->", "getPath", "(", ")", "]", ",", "true", ")", ";", "}", "return", "$", "path", ";", "}" ]
Generates the default front url. @param MediaInterface $media @return string
[ "Generates", "the", "default", "front", "url", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Browser/Generator.php#L112-L125
train
ekyna/MediaBundle
Browser/Generator.php
Generator.generateFileThumb
private function generateFileThumb(MediaInterface $media) { $extension = $media->guessExtension(); $thumbPath = sprintf('/%s/%s.jpg', $this->thumbsDirectory, $extension); $destination = $this->webRootDirectory . $thumbPath; if (file_exists($destination)) { return $thumbPath; } $backgroundColor = MediaTypes::getColor($media->getType()); $iconPath = sprintf('%s/%s.png', $this->iconsSourcePath, $extension); if (! file_exists($iconPath)) { $iconPath = $this->iconsSourcePath.'/default.png'; } $this->checkDir(dirname($destination)); try { $palette = new RGB(); $thumb = $this->imagine->create(new Box(120, 90), $palette->color($backgroundColor)); $icon = $this->imagine->open($iconPath); $iconSize = $icon->getSize(); $start = new Point(120/2 - $iconSize->getWidth()/2, 90/2 - $iconSize->getHeight()/2); $thumb->paste($icon, $start); $thumb->save($destination); return $thumbPath; } catch (ImagineException $e) { // Image thumb generation failed } return null; }
php
private function generateFileThumb(MediaInterface $media) { $extension = $media->guessExtension(); $thumbPath = sprintf('/%s/%s.jpg', $this->thumbsDirectory, $extension); $destination = $this->webRootDirectory . $thumbPath; if (file_exists($destination)) { return $thumbPath; } $backgroundColor = MediaTypes::getColor($media->getType()); $iconPath = sprintf('%s/%s.png', $this->iconsSourcePath, $extension); if (! file_exists($iconPath)) { $iconPath = $this->iconsSourcePath.'/default.png'; } $this->checkDir(dirname($destination)); try { $palette = new RGB(); $thumb = $this->imagine->create(new Box(120, 90), $palette->color($backgroundColor)); $icon = $this->imagine->open($iconPath); $iconSize = $icon->getSize(); $start = new Point(120/2 - $iconSize->getWidth()/2, 90/2 - $iconSize->getHeight()/2); $thumb->paste($icon, $start); $thumb->save($destination); return $thumbPath; } catch (ImagineException $e) { // Image thumb generation failed } return null; }
[ "private", "function", "generateFileThumb", "(", "MediaInterface", "$", "media", ")", "{", "$", "extension", "=", "$", "media", "->", "guessExtension", "(", ")", ";", "$", "thumbPath", "=", "sprintf", "(", "'/%s/%s.jpg'", ",", "$", "this", "->", "thumbsDirectory", ",", "$", "extension", ")", ";", "$", "destination", "=", "$", "this", "->", "webRootDirectory", ".", "$", "thumbPath", ";", "if", "(", "file_exists", "(", "$", "destination", ")", ")", "{", "return", "$", "thumbPath", ";", "}", "$", "backgroundColor", "=", "MediaTypes", "::", "getColor", "(", "$", "media", "->", "getType", "(", ")", ")", ";", "$", "iconPath", "=", "sprintf", "(", "'%s/%s.png'", ",", "$", "this", "->", "iconsSourcePath", ",", "$", "extension", ")", ";", "if", "(", "!", "file_exists", "(", "$", "iconPath", ")", ")", "{", "$", "iconPath", "=", "$", "this", "->", "iconsSourcePath", ".", "'/default.png'", ";", "}", "$", "this", "->", "checkDir", "(", "dirname", "(", "$", "destination", ")", ")", ";", "try", "{", "$", "palette", "=", "new", "RGB", "(", ")", ";", "$", "thumb", "=", "$", "this", "->", "imagine", "->", "create", "(", "new", "Box", "(", "120", ",", "90", ")", ",", "$", "palette", "->", "color", "(", "$", "backgroundColor", ")", ")", ";", "$", "icon", "=", "$", "this", "->", "imagine", "->", "open", "(", "$", "iconPath", ")", ";", "$", "iconSize", "=", "$", "icon", "->", "getSize", "(", ")", ";", "$", "start", "=", "new", "Point", "(", "120", "/", "2", "-", "$", "iconSize", "->", "getWidth", "(", ")", "/", "2", ",", "90", "/", "2", "-", "$", "iconSize", "->", "getHeight", "(", ")", "/", "2", ")", ";", "$", "thumb", "->", "paste", "(", "$", "icon", ",", "$", "start", ")", ";", "$", "thumb", "->", "save", "(", "$", "destination", ")", ";", "return", "$", "thumbPath", ";", "}", "catch", "(", "ImagineException", "$", "e", ")", "{", "// Image thumb generation failed", "}", "return", "null", ";", "}" ]
Generates thumb for non-image elements. @param MediaInterface $media @return null|string
[ "Generates", "thumb", "for", "non", "-", "image", "elements", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Browser/Generator.php#L133-L168
train
ekyna/MediaBundle
Browser/Generator.php
Generator.checkDir
private function checkDir($dir) { if (! $this->fs->exists($dir)) { $this->fs->mkdir($dir); } }
php
private function checkDir($dir) { if (! $this->fs->exists($dir)) { $this->fs->mkdir($dir); } }
[ "private", "function", "checkDir", "(", "$", "dir", ")", "{", "if", "(", "!", "$", "this", "->", "fs", "->", "exists", "(", "$", "dir", ")", ")", "{", "$", "this", "->", "fs", "->", "mkdir", "(", "$", "dir", ")", ";", "}", "}" ]
Creates the directory if it does not exists. @param $dir
[ "Creates", "the", "directory", "if", "it", "does", "not", "exists", "." ]
512cf86c801a130a9f17eba8b48d646d23acdbab
https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/Browser/Generator.php#L195-L200
train
matthiasmoritz/cake-isbn
src/Controller/Component/IsbnComponent.php
IsbnComponent.splitIsbn
public function splitIsbn($isbn) { if (!$this->validateIsbn($isbn)) { return false; } $prefix = substr($isbn, 0,3); $groupnumber = $this->getGroupNumber($isbn); $pubnumber = $this->getPublisherNumber($isbn); $prenumbers = strlen($groupnumber)+strlen($pubnumber)+3; $articleNumber = substr($isbn, $prenumbers, -1); $checkdigit = substr($isbn, -1); return (array($prefix, $groupnumber, $pubnumber, $articleNumber, $checkdigit)); }
php
public function splitIsbn($isbn) { if (!$this->validateIsbn($isbn)) { return false; } $prefix = substr($isbn, 0,3); $groupnumber = $this->getGroupNumber($isbn); $pubnumber = $this->getPublisherNumber($isbn); $prenumbers = strlen($groupnumber)+strlen($pubnumber)+3; $articleNumber = substr($isbn, $prenumbers, -1); $checkdigit = substr($isbn, -1); return (array($prefix, $groupnumber, $pubnumber, $articleNumber, $checkdigit)); }
[ "public", "function", "splitIsbn", "(", "$", "isbn", ")", "{", "if", "(", "!", "$", "this", "->", "validateIsbn", "(", "$", "isbn", ")", ")", "{", "return", "false", ";", "}", "$", "prefix", "=", "substr", "(", "$", "isbn", ",", "0", ",", "3", ")", ";", "$", "groupnumber", "=", "$", "this", "->", "getGroupNumber", "(", "$", "isbn", ")", ";", "$", "pubnumber", "=", "$", "this", "->", "getPublisherNumber", "(", "$", "isbn", ")", ";", "$", "prenumbers", "=", "strlen", "(", "$", "groupnumber", ")", "+", "strlen", "(", "$", "pubnumber", ")", "+", "3", ";", "$", "articleNumber", "=", "substr", "(", "$", "isbn", ",", "$", "prenumbers", ",", "-", "1", ")", ";", "$", "checkdigit", "=", "substr", "(", "$", "isbn", ",", "-", "1", ")", ";", "return", "(", "array", "(", "$", "prefix", ",", "$", "groupnumber", ",", "$", "pubnumber", ",", "$", "articleNumber", ",", "$", "checkdigit", ")", ")", ";", "}" ]
Splits a valid ISBN-13 Number in its components @param string $input The ISBN Numeber. @return array['bookland']['publisherNumber']['ArticleNumber']['Checksum'] @access public @throws NO ERROR HANDLING
[ "Splits", "a", "valid", "ISBN", "-", "13", "Number", "in", "its", "components" ]
aba4147bcc714bc1f6db057587f0372cd5b3bff1
https://github.com/matthiasmoritz/cake-isbn/blob/aba4147bcc714bc1f6db057587f0372cd5b3bff1/src/Controller/Component/IsbnComponent.php#L88-L101
train
matthiasmoritz/cake-isbn
src/Controller/Component/IsbnComponent.php
IsbnComponent.validateIsbn
public function validateIsbn($check) { $ean = strval($check); $code = substr($ean, 0, -1); $key = $this->calculateCheckdigit13($code); // in key steht die prüfziffer - an den code anhängen $code .= $key; if ($code == $ean) { return true; }else { return false; } }
php
public function validateIsbn($check) { $ean = strval($check); $code = substr($ean, 0, -1); $key = $this->calculateCheckdigit13($code); // in key steht die prüfziffer - an den code anhängen $code .= $key; if ($code == $ean) { return true; }else { return false; } }
[ "public", "function", "validateIsbn", "(", "$", "check", ")", "{", "$", "ean", "=", "strval", "(", "$", "check", ")", ";", "$", "code", "=", "substr", "(", "$", "ean", ",", "0", ",", "-", "1", ")", ";", "$", "key", "=", "$", "this", "->", "calculateCheckdigit13", "(", "$", "code", ")", ";", "// in key steht die prüfziffer - an den code anhängen", "$", "code", ".=", "$", "key", ";", "if", "(", "$", "code", "==", "$", "ean", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Validates an ISBN-13 Number @param string $input The ISBN Numeber. @returnbool
[ "Validates", "an", "ISBN", "-", "13", "Number" ]
aba4147bcc714bc1f6db057587f0372cd5b3bff1
https://github.com/matthiasmoritz/cake-isbn/blob/aba4147bcc714bc1f6db057587f0372cd5b3bff1/src/Controller/Component/IsbnComponent.php#L109-L124
train
rawphp/RawRequest
src/RawPHP/RawRequest/Request.php
Request.init
public function init( $config = [ ] ) { if ( isset( $_SERVER[ 'HTTP_USER_AGENT' ] ) ) { $this->userAgent = $_SERVER[ 'HTTP_USER_AGENT' ]; } if ( isset( $_SERVER[ 'SERVER_NAME' ] ) ) { $this->server = $_SERVER[ 'SERVER_NAME' ]; } if ( isset( $_SERVER[ 'SERVER_PORT' ] ) ) { $this->port = $_SERVER[ 'SERVER_PORT' ]; } if ( isset( $_SERVER[ 'REQUEST_METHOD' ] ) ) { $this->method = $_SERVER[ 'REQUEST_METHOD' ]; } if ( isset( $_SERVER[ 'QUERY_STRING' ] ) ) { $this->query = $_SERVER[ 'QUERY_STRING' ]; } if ( isset( $_SERVER[ 'SCRIPT_NAME' ] ) ) { $this->script = $_SERVER[ 'SCRIPT_NAME' ]; } if ( isset( $_SERVER[ 'REQUEST_URI' ] ) ) { $this->requestUri = $_SERVER[ 'REQUEST_URI' ]; } if ( isset( $_SERVER[ 'REQUEST_SCHEME' ] ) ) { $this->scheme = $_SERVER[ 'REQUEST_SCHEME' ]; } $request = str_replace( $_SERVER[ 'SCRIPT_NAME' ], '', $this->requestUri ); $elements = explode( '/', $request ); if ( '' === $elements[ 0 ] ) { array_shift( $elements ); } if ( 2 <= count( $elements ) ) { $this->route = $elements[ 0 ] . '/' . $elements[ 1 ]; array_shift( $elements ); array_shift( $elements ); if ( 0 < count( $elements ) ) { $this->params = $elements; } } else if ( 1 === count( $elements ) ) { $this->route = $elements[ 0 ]; array_shift( $elements ); } }
php
public function init( $config = [ ] ) { if ( isset( $_SERVER[ 'HTTP_USER_AGENT' ] ) ) { $this->userAgent = $_SERVER[ 'HTTP_USER_AGENT' ]; } if ( isset( $_SERVER[ 'SERVER_NAME' ] ) ) { $this->server = $_SERVER[ 'SERVER_NAME' ]; } if ( isset( $_SERVER[ 'SERVER_PORT' ] ) ) { $this->port = $_SERVER[ 'SERVER_PORT' ]; } if ( isset( $_SERVER[ 'REQUEST_METHOD' ] ) ) { $this->method = $_SERVER[ 'REQUEST_METHOD' ]; } if ( isset( $_SERVER[ 'QUERY_STRING' ] ) ) { $this->query = $_SERVER[ 'QUERY_STRING' ]; } if ( isset( $_SERVER[ 'SCRIPT_NAME' ] ) ) { $this->script = $_SERVER[ 'SCRIPT_NAME' ]; } if ( isset( $_SERVER[ 'REQUEST_URI' ] ) ) { $this->requestUri = $_SERVER[ 'REQUEST_URI' ]; } if ( isset( $_SERVER[ 'REQUEST_SCHEME' ] ) ) { $this->scheme = $_SERVER[ 'REQUEST_SCHEME' ]; } $request = str_replace( $_SERVER[ 'SCRIPT_NAME' ], '', $this->requestUri ); $elements = explode( '/', $request ); if ( '' === $elements[ 0 ] ) { array_shift( $elements ); } if ( 2 <= count( $elements ) ) { $this->route = $elements[ 0 ] . '/' . $elements[ 1 ]; array_shift( $elements ); array_shift( $elements ); if ( 0 < count( $elements ) ) { $this->params = $elements; } } else if ( 1 === count( $elements ) ) { $this->route = $elements[ 0 ]; array_shift( $elements ); } }
[ "public", "function", "init", "(", "$", "config", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ")", ")", "{", "$", "this", "->", "userAgent", "=", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ")", ")", "{", "$", "this", "->", "server", "=", "$", "_SERVER", "[", "'SERVER_NAME'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'SERVER_PORT'", "]", ")", ")", "{", "$", "this", "->", "port", "=", "$", "_SERVER", "[", "'SERVER_PORT'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ")", ")", "{", "$", "this", "->", "method", "=", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'QUERY_STRING'", "]", ")", ")", "{", "$", "this", "->", "query", "=", "$", "_SERVER", "[", "'QUERY_STRING'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'SCRIPT_NAME'", "]", ")", ")", "{", "$", "this", "->", "script", "=", "$", "_SERVER", "[", "'SCRIPT_NAME'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ")", "{", "$", "this", "->", "requestUri", "=", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ";", "}", "if", "(", "isset", "(", "$", "_SERVER", "[", "'REQUEST_SCHEME'", "]", ")", ")", "{", "$", "this", "->", "scheme", "=", "$", "_SERVER", "[", "'REQUEST_SCHEME'", "]", ";", "}", "$", "request", "=", "str_replace", "(", "$", "_SERVER", "[", "'SCRIPT_NAME'", "]", ",", "''", ",", "$", "this", "->", "requestUri", ")", ";", "$", "elements", "=", "explode", "(", "'/'", ",", "$", "request", ")", ";", "if", "(", "''", "===", "$", "elements", "[", "0", "]", ")", "{", "array_shift", "(", "$", "elements", ")", ";", "}", "if", "(", "2", "<=", "count", "(", "$", "elements", ")", ")", "{", "$", "this", "->", "route", "=", "$", "elements", "[", "0", "]", ".", "'/'", ".", "$", "elements", "[", "1", "]", ";", "array_shift", "(", "$", "elements", ")", ";", "array_shift", "(", "$", "elements", ")", ";", "if", "(", "0", "<", "count", "(", "$", "elements", ")", ")", "{", "$", "this", "->", "params", "=", "$", "elements", ";", "}", "}", "else", "if", "(", "1", "===", "count", "(", "$", "elements", ")", ")", "{", "$", "this", "->", "route", "=", "$", "elements", "[", "0", "]", ";", "array_shift", "(", "$", "elements", ")", ";", "}", "}" ]
Initialises the request. @param array $config optional configuration array
[ "Initialises", "the", "request", "." ]
89b596f1fb035f1acd5fa89b58a6f4a3d56a5ffe
https://github.com/rawphp/RawRequest/blob/89b596f1fb035f1acd5fa89b58a6f4a3d56a5ffe/src/RawPHP/RawRequest/Request.php#L82-L144
train
rawphp/RawRequest
src/RawPHP/RawRequest/Request.php
Request.createUrl
public function createUrl( $route, $params = [ ], $absolute = FALSE ) { $url = $this->script . '/' . $route; if ( file_exists( TEST_LOCK_FILE ) ) { $url = $route; } if ( !empty( $params ) ) { foreach ( $params as $value ) { $url .= "/$value"; } } if ( $absolute ) { if ( !file_exists( TEST_LOCK_FILE ) ) { $url = $this->scheme . '://' . $this->server . $url; } else { $url = BASE_URL . $url; } } return $url; }
php
public function createUrl( $route, $params = [ ], $absolute = FALSE ) { $url = $this->script . '/' . $route; if ( file_exists( TEST_LOCK_FILE ) ) { $url = $route; } if ( !empty( $params ) ) { foreach ( $params as $value ) { $url .= "/$value"; } } if ( $absolute ) { if ( !file_exists( TEST_LOCK_FILE ) ) { $url = $this->scheme . '://' . $this->server . $url; } else { $url = BASE_URL . $url; } } return $url; }
[ "public", "function", "createUrl", "(", "$", "route", ",", "$", "params", "=", "[", "]", ",", "$", "absolute", "=", "FALSE", ")", "{", "$", "url", "=", "$", "this", "->", "script", ".", "'/'", ".", "$", "route", ";", "if", "(", "file_exists", "(", "TEST_LOCK_FILE", ")", ")", "{", "$", "url", "=", "$", "route", ";", "}", "if", "(", "!", "empty", "(", "$", "params", ")", ")", "{", "foreach", "(", "$", "params", "as", "$", "value", ")", "{", "$", "url", ".=", "\"/$value\"", ";", "}", "}", "if", "(", "$", "absolute", ")", "{", "if", "(", "!", "file_exists", "(", "TEST_LOCK_FILE", ")", ")", "{", "$", "url", "=", "$", "this", "->", "scheme", ".", "'://'", ".", "$", "this", "->", "server", ".", "$", "url", ";", "}", "else", "{", "$", "url", "=", "BASE_URL", ".", "$", "url", ";", "}", "}", "return", "$", "url", ";", "}" ]
Creates a http url. This method has a dependency on two defines 1. TEST_LOCK_FILE - test lock file, define it as '/path/to/site/root/test.lock' 2. BASE_URL - this is the base url of your application, e.g, http://rawphp.org @param string $route the route @param array $params list of parameters (in the correct order) @param bool $absolute whether the url should be absolute @return string the url
[ "Creates", "a", "http", "url", "." ]
89b596f1fb035f1acd5fa89b58a6f4a3d56a5ffe
https://github.com/rawphp/RawRequest/blob/89b596f1fb035f1acd5fa89b58a6f4a3d56a5ffe/src/RawPHP/RawRequest/Request.php#L359-L389
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/controllers/AbstractController.php
AbstractController.handleDatasource
public function handleDatasource($name, $method, array $preloadedData, array &$templateVariables) { $this->name = $name; $datasource = ActionUtils::createActionDatasource($name,$method); // set the variables for use $this->templateVars =& $templateVariables; $this->currentDatasource = $datasource; // set the current datasource $this->currentActionOrDatasource = $datasource; $methodResolved = ActionUtils::parseMethod($method); $this->currentMethod = $methodResolved; //if(LOG_ENABLE) System::log(self::$logType, 'Datasource: ['.$datasource.']'); // if we did an action and the datasource is already set, use it if(self::$actionBoundDatasource == $datasource) return $this; if(!method_exists($this, $methodResolved)) throw new Exception('Method ['.$methodResolved.'] does not exist on class ['.get_class($this).']'); // clear the data first $this->setData(null); // set preloaded data (from Renderer) if(!empty($preloadedData)) $this->setData($preloadedData); $this->preDatasource(); //if(LOG_ENABLE) System::log(self::$logType, 'Executing method ['.$methodResolved.']'); $result = null; $result = $this->$methodResolved(); if($result == null) $result = array(); // bind to datasource $this->setData($result); $this->postDatasource(); return $this; // for chaining }
php
public function handleDatasource($name, $method, array $preloadedData, array &$templateVariables) { $this->name = $name; $datasource = ActionUtils::createActionDatasource($name,$method); // set the variables for use $this->templateVars =& $templateVariables; $this->currentDatasource = $datasource; // set the current datasource $this->currentActionOrDatasource = $datasource; $methodResolved = ActionUtils::parseMethod($method); $this->currentMethod = $methodResolved; //if(LOG_ENABLE) System::log(self::$logType, 'Datasource: ['.$datasource.']'); // if we did an action and the datasource is already set, use it if(self::$actionBoundDatasource == $datasource) return $this; if(!method_exists($this, $methodResolved)) throw new Exception('Method ['.$methodResolved.'] does not exist on class ['.get_class($this).']'); // clear the data first $this->setData(null); // set preloaded data (from Renderer) if(!empty($preloadedData)) $this->setData($preloadedData); $this->preDatasource(); //if(LOG_ENABLE) System::log(self::$logType, 'Executing method ['.$methodResolved.']'); $result = null; $result = $this->$methodResolved(); if($result == null) $result = array(); // bind to datasource $this->setData($result); $this->postDatasource(); return $this; // for chaining }
[ "public", "function", "handleDatasource", "(", "$", "name", ",", "$", "method", ",", "array", "$", "preloadedData", ",", "array", "&", "$", "templateVariables", ")", "{", "$", "this", "->", "name", "=", "$", "name", ";", "$", "datasource", "=", "ActionUtils", "::", "createActionDatasource", "(", "$", "name", ",", "$", "method", ")", ";", "// set the variables for use", "$", "this", "->", "templateVars", "=", "&", "$", "templateVariables", ";", "$", "this", "->", "currentDatasource", "=", "$", "datasource", ";", "// set the current datasource", "$", "this", "->", "currentActionOrDatasource", "=", "$", "datasource", ";", "$", "methodResolved", "=", "ActionUtils", "::", "parseMethod", "(", "$", "method", ")", ";", "$", "this", "->", "currentMethod", "=", "$", "methodResolved", ";", "//if(LOG_ENABLE) System::log(self::$logType, 'Datasource: ['.$datasource.']');", "// if we did an action and the datasource is already set, use it", "if", "(", "self", "::", "$", "actionBoundDatasource", "==", "$", "datasource", ")", "return", "$", "this", ";", "if", "(", "!", "method_exists", "(", "$", "this", ",", "$", "methodResolved", ")", ")", "throw", "new", "Exception", "(", "'Method ['", ".", "$", "methodResolved", ".", "'] does not exist on class ['", ".", "get_class", "(", "$", "this", ")", ".", "']'", ")", ";", "// clear the data first", "$", "this", "->", "setData", "(", "null", ")", ";", "// set preloaded data (from Renderer)", "if", "(", "!", "empty", "(", "$", "preloadedData", ")", ")", "$", "this", "->", "setData", "(", "$", "preloadedData", ")", ";", "$", "this", "->", "preDatasource", "(", ")", ";", "//if(LOG_ENABLE) System::log(self::$logType, 'Executing method ['.$methodResolved.']');", "$", "result", "=", "null", ";", "$", "result", "=", "$", "this", "->", "$", "methodResolved", "(", ")", ";", "if", "(", "$", "result", "==", "null", ")", "$", "result", "=", "array", "(", ")", ";", "// bind to datasource", "$", "this", "->", "setData", "(", "$", "result", ")", ";", "$", "this", "->", "postDatasource", "(", ")", ";", "return", "$", "this", ";", "// for chaining", "}" ]
this is used by the RenderModule when loading data from an element
[ "this", "is", "used", "by", "the", "RenderModule", "when", "loading", "data", "from", "an", "element" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/controllers/AbstractController.php#L208-L259
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/controllers/AbstractController.php
AbstractController.getTemplateVariable
protected function getTemplateVariable($name, $default = null) { return array_key_exists($name, $this->templateVars)?$this->templateVars[$name]:$default; }
php
protected function getTemplateVariable($name, $default = null) { return array_key_exists($name, $this->templateVars)?$this->templateVars[$name]:$default; }
[ "protected", "function", "getTemplateVariable", "(", "$", "name", ",", "$", "default", "=", "null", ")", "{", "return", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "templateVars", ")", "?", "$", "this", "->", "templateVars", "[", "$", "name", "]", ":", "$", "default", ";", "}" ]
Used in datasource methods @param string $name @param mixed $default @return mixed
[ "Used", "in", "datasource", "methods" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/controllers/AbstractController.php#L399-L402
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/controllers/AbstractController.php
AbstractController.getRequiredTemplateVariable
protected function getRequiredTemplateVariable($name) { if(!array_key_exists($name, $this->templateVars)) throw new ControllerException('Required template variable ['.$name.'] is missing'); return $this->templateVars[$name]; }
php
protected function getRequiredTemplateVariable($name) { if(!array_key_exists($name, $this->templateVars)) throw new ControllerException('Required template variable ['.$name.'] is missing'); return $this->templateVars[$name]; }
[ "protected", "function", "getRequiredTemplateVariable", "(", "$", "name", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "templateVars", ")", ")", "throw", "new", "ControllerException", "(", "'Required template variable ['", ".", "$", "name", ".", "'] is missing'", ")", ";", "return", "$", "this", "->", "templateVars", "[", "$", "name", "]", ";", "}" ]
Used in datasource methods, throws ControllerException when value is missing @param $name @return mixed
[ "Used", "in", "datasource", "methods", "throws", "ControllerException", "when", "value", "is", "missing" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/controllers/AbstractController.php#L420-L426
train
bandama-framework/bandama-framework
src/foundation/session/Flash.php
Flash.get
public function get($type = 'success') { $key = self::BANDAMA_FLASH_KEY.'_'.$type; $flash = $this->session->get($key); $this->session->delete($key); return $flash; }
php
public function get($type = 'success') { $key = self::BANDAMA_FLASH_KEY.'_'.$type; $flash = $this->session->get($key); $this->session->delete($key); return $flash; }
[ "public", "function", "get", "(", "$", "type", "=", "'success'", ")", "{", "$", "key", "=", "self", "::", "BANDAMA_FLASH_KEY", ".", "'_'", ".", "$", "type", ";", "$", "flash", "=", "$", "this", "->", "session", "->", "get", "(", "$", "key", ")", ";", "$", "this", "->", "session", "->", "delete", "(", "$", "key", ")", ";", "return", "$", "flash", ";", "}" ]
Get flash message @return mixed
[ "Get", "flash", "message" ]
234ed703baf9e31268941c9d5f6d5e004cc53066
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/session/Flash.php#L62-L68
train
zenapply/php-peoplematter
src/PeopleMatter.php
PeopleMatter.getClient
public function getClient() { if (!$this->client instanceof Client) { $this->client = new Client([ "cookies" => true ]); } return $this->client; }
php
public function getClient() { if (!$this->client instanceof Client) { $this->client = new Client([ "cookies" => true ]); } return $this->client; }
[ "public", "function", "getClient", "(", ")", "{", "if", "(", "!", "$", "this", "->", "client", "instanceof", "Client", ")", "{", "$", "this", "->", "client", "=", "new", "Client", "(", "[", "\"cookies\"", "=>", "true", "]", ")", ";", "}", "return", "$", "this", "->", "client", ";", "}" ]
Returns the Client instance @return Client
[ "Returns", "the", "Client", "instance" ]
141e01f6b2e68741358995643e61c88864a4a165
https://github.com/zenapply/php-peoplematter/blob/141e01f6b2e68741358995643e61c88864a4a165/src/PeopleMatter.php#L264-L272
train
zenapply/php-peoplematter
src/PeopleMatter.php
PeopleMatter.request
protected function request($method, $url, $options = []) { $client = $this->getClient(); try { $response = $client->request($method, $url, $options); } catch (\GuzzleHttp\Exception\ClientException $e) { $response = $e->getResponse(); throw new PeopleMatterException($response->getStatusCode().": ".$response->getReasonPhrase(), 1, $e); } $body = $response->getBody(); if (!is_array($body)) { $json = json_decode($body, true); } else { $json = $body; } if (!empty($json["ErrorMessage"])) { throw new PeopleMatterException($json["ErrorMessage"], $json["ErrorCode"]); } return $json; }
php
protected function request($method, $url, $options = []) { $client = $this->getClient(); try { $response = $client->request($method, $url, $options); } catch (\GuzzleHttp\Exception\ClientException $e) { $response = $e->getResponse(); throw new PeopleMatterException($response->getStatusCode().": ".$response->getReasonPhrase(), 1, $e); } $body = $response->getBody(); if (!is_array($body)) { $json = json_decode($body, true); } else { $json = $body; } if (!empty($json["ErrorMessage"])) { throw new PeopleMatterException($json["ErrorMessage"], $json["ErrorCode"]); } return $json; }
[ "protected", "function", "request", "(", "$", "method", ",", "$", "url", ",", "$", "options", "=", "[", "]", ")", "{", "$", "client", "=", "$", "this", "->", "getClient", "(", ")", ";", "try", "{", "$", "response", "=", "$", "client", "->", "request", "(", "$", "method", ",", "$", "url", ",", "$", "options", ")", ";", "}", "catch", "(", "\\", "GuzzleHttp", "\\", "Exception", "\\", "ClientException", "$", "e", ")", "{", "$", "response", "=", "$", "e", "->", "getResponse", "(", ")", ";", "throw", "new", "PeopleMatterException", "(", "$", "response", "->", "getStatusCode", "(", ")", ".", "\": \"", ".", "$", "response", "->", "getReasonPhrase", "(", ")", ",", "1", ",", "$", "e", ")", ";", "}", "$", "body", "=", "$", "response", "->", "getBody", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "body", ")", ")", "{", "$", "json", "=", "json_decode", "(", "$", "body", ",", "true", ")", ";", "}", "else", "{", "$", "json", "=", "$", "body", ";", "}", "if", "(", "!", "empty", "(", "$", "json", "[", "\"ErrorMessage\"", "]", ")", ")", "{", "throw", "new", "PeopleMatterException", "(", "$", "json", "[", "\"ErrorMessage\"", "]", ",", "$", "json", "[", "\"ErrorCode\"", "]", ")", ";", "}", "return", "$", "json", ";", "}" ]
Executes a request to the PeopleMatter API @param string $method The request type @param string $url The url to request @param array $options An array of options for the request @return array The response as an array
[ "Executes", "a", "request", "to", "the", "PeopleMatter", "API" ]
141e01f6b2e68741358995643e61c88864a4a165
https://github.com/zenapply/php-peoplematter/blob/141e01f6b2e68741358995643e61c88864a4a165/src/PeopleMatter.php#L281-L303
train
makinacorpus/drupal-apubsub
src/Backend/AbstractDrupalCursor.php
AbstractDrupalCursor.applyOperator
final protected function applyOperator(\SelectQueryInterface $query, $statement, $value) { // Check if $value contains an operator (i.e. if is associative array) if (is_array($value) && !Misc::isIndexed($value)) { // First key will be the operator $keys = array_keys($value); $operator = $keys[0]; $value = $value[$operator]; switch ($operator) { case '<>': if (is_array($value)) { $query->condition($statement, $value, 'NOT IN'); } else { $query->condition($statement, $value, '<>'); } break; case 'exists': $query->exists($value); break; case 'in': $query->condition($statement, $value, 'IN'); break; default: $query->condition($statement, $value, $operator); break; } } else if (null === $value) { $query->isNull($statement); } else { $query->condition($statement, $value); } }
php
final protected function applyOperator(\SelectQueryInterface $query, $statement, $value) { // Check if $value contains an operator (i.e. if is associative array) if (is_array($value) && !Misc::isIndexed($value)) { // First key will be the operator $keys = array_keys($value); $operator = $keys[0]; $value = $value[$operator]; switch ($operator) { case '<>': if (is_array($value)) { $query->condition($statement, $value, 'NOT IN'); } else { $query->condition($statement, $value, '<>'); } break; case 'exists': $query->exists($value); break; case 'in': $query->condition($statement, $value, 'IN'); break; default: $query->condition($statement, $value, $operator); break; } } else if (null === $value) { $query->isNull($statement); } else { $query->condition($statement, $value); } }
[ "final", "protected", "function", "applyOperator", "(", "\\", "SelectQueryInterface", "$", "query", ",", "$", "statement", ",", "$", "value", ")", "{", "// Check if $value contains an operator (i.e. if is associative array)", "if", "(", "is_array", "(", "$", "value", ")", "&&", "!", "Misc", "::", "isIndexed", "(", "$", "value", ")", ")", "{", "// First key will be the operator", "$", "keys", "=", "array_keys", "(", "$", "value", ")", ";", "$", "operator", "=", "$", "keys", "[", "0", "]", ";", "$", "value", "=", "$", "value", "[", "$", "operator", "]", ";", "switch", "(", "$", "operator", ")", "{", "case", "'<>'", ":", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "query", "->", "condition", "(", "$", "statement", ",", "$", "value", ",", "'NOT IN'", ")", ";", "}", "else", "{", "$", "query", "->", "condition", "(", "$", "statement", ",", "$", "value", ",", "'<>'", ")", ";", "}", "break", ";", "case", "'exists'", ":", "$", "query", "->", "exists", "(", "$", "value", ")", ";", "break", ";", "case", "'in'", ":", "$", "query", "->", "condition", "(", "$", "statement", ",", "$", "value", ",", "'IN'", ")", ";", "break", ";", "default", ":", "$", "query", "->", "condition", "(", "$", "statement", ",", "$", "value", ",", "$", "operator", ")", ";", "break", ";", "}", "}", "else", "if", "(", "null", "===", "$", "value", ")", "{", "$", "query", "->", "isNull", "(", "$", "statement", ")", ";", "}", "else", "{", "$", "query", "->", "condition", "(", "$", "statement", ",", "$", "value", ")", ";", "}", "}" ]
Apply the operator onto the query @param \SelectQueryInterface $query @param string $statement @param string $value
[ "Apply", "the", "operator", "onto", "the", "query" ]
534fbecf67c880996ae02210c0bfdb3e0d3699b6
https://github.com/makinacorpus/drupal-apubsub/blob/534fbecf67c880996ae02210c0bfdb3e0d3699b6/src/Backend/AbstractDrupalCursor.php#L163-L200
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.attach
public function attach( Base $entity, &$restingPlace = null ) { if( !$this->makeableSafetyCheck() ) { return null; } // check type if( !is_a( $entity, $this->entityClass ) ) { throw new EntityNotCompatibleWithRepositoryException( $entity, $this ); } // At the moment something is new if it doesn't have a key set. // This is still a work in progress if( $key = $entity->keyGet( $entity ) ) { // check we've not got a collision already if( isset( $this->instancesPersisted[$key] ) ) { throw new \RuntimeException( "Repository entity merging not yet coded (but I'm not exactly sure why you need this). You've probably got a logic bug somewhere. What you are asking is, well, odd."); } $this->instancesPersisted[$key] = $entity; $restingPlace = self::PERSISTED; } else { // debugging check to find where something is being double attached if( false !== array_search( $entity, $this->instancesUnpersisted, true ) ) { d_pr( sane_debug_backtrace() ); die(); } $this->instancesUnpersisted[] = $entity; $restingPlace = self::UNPERSISTED; } return true; }
php
public function attach( Base $entity, &$restingPlace = null ) { if( !$this->makeableSafetyCheck() ) { return null; } // check type if( !is_a( $entity, $this->entityClass ) ) { throw new EntityNotCompatibleWithRepositoryException( $entity, $this ); } // At the moment something is new if it doesn't have a key set. // This is still a work in progress if( $key = $entity->keyGet( $entity ) ) { // check we've not got a collision already if( isset( $this->instancesPersisted[$key] ) ) { throw new \RuntimeException( "Repository entity merging not yet coded (but I'm not exactly sure why you need this). You've probably got a logic bug somewhere. What you are asking is, well, odd."); } $this->instancesPersisted[$key] = $entity; $restingPlace = self::PERSISTED; } else { // debugging check to find where something is being double attached if( false !== array_search( $entity, $this->instancesUnpersisted, true ) ) { d_pr( sane_debug_backtrace() ); die(); } $this->instancesUnpersisted[] = $entity; $restingPlace = self::UNPERSISTED; } return true; }
[ "public", "function", "attach", "(", "Base", "$", "entity", ",", "&", "$", "restingPlace", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "makeableSafetyCheck", "(", ")", ")", "{", "return", "null", ";", "}", "// check type", "if", "(", "!", "is_a", "(", "$", "entity", ",", "$", "this", "->", "entityClass", ")", ")", "{", "throw", "new", "EntityNotCompatibleWithRepositoryException", "(", "$", "entity", ",", "$", "this", ")", ";", "}", "// At the moment something is new if it doesn't have a key set.", "// This is still a work in progress", "if", "(", "$", "key", "=", "$", "entity", "->", "keyGet", "(", "$", "entity", ")", ")", "{", "// check we've not got a collision already", "if", "(", "isset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Repository entity merging not yet coded (but I'm not exactly sure why you need this). You've probably got a logic bug somewhere. What you are asking is, well, odd.\"", ")", ";", "}", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", "=", "$", "entity", ";", "$", "restingPlace", "=", "self", "::", "PERSISTED", ";", "}", "else", "{", "// debugging check to find where something is being double attached", "if", "(", "false", "!==", "array_search", "(", "$", "entity", ",", "$", "this", "->", "instancesUnpersisted", ",", "true", ")", ")", "{", "d_pr", "(", "sane_debug_backtrace", "(", ")", ")", ";", "die", "(", ")", ";", "}", "$", "this", "->", "instancesUnpersisted", "[", "]", "=", "$", "entity", ";", "$", "restingPlace", "=", "self", "::", "UNPERSISTED", ";", "}", "return", "true", ";", "}" ]
Add a entity into the multiton array @param Entity\Base @param mixed If successful attachment the location of the new attachment @return bool. Successful attachment?
[ "Add", "a", "entity", "into", "the", "multiton", "array" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L61-L100
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.isAttached
public function isAttached( Base $entity ) { return false !== array_search( $entity, $this->instancesPersisted, true ) || false !== array_search( $entity, $this->instancesUnpersisted, true ); }
php
public function isAttached( Base $entity ) { return false !== array_search( $entity, $this->instancesPersisted, true ) || false !== array_search( $entity, $this->instancesUnpersisted, true ); }
[ "public", "function", "isAttached", "(", "Base", "$", "entity", ")", "{", "return", "false", "!==", "array_search", "(", "$", "entity", ",", "$", "this", "->", "instancesPersisted", ",", "true", ")", "||", "false", "!==", "array_search", "(", "$", "entity", ",", "$", "this", "->", "instancesUnpersisted", ",", "true", ")", ";", "}" ]
Is in multiton store. @return bool
[ "Is", "in", "multiton", "store", "." ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L106-L110
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.detach
public function detach( Base $entity, &$detachedFrom = null ) { $detachedFrom = null; foreach( array( 'Persisted', 'Unpersisted') as $type ) { $cache = "instances{$type}"; $cache =& $this->$cache; if( false !== $key = array_search( $entity, $cache, true ) ) { unset( $cache[$key] ); $detachedFrom = $this->constantGet( strtoupper( $type ) ); return true; } unset( $cache ); } return false; }
php
public function detach( Base $entity, &$detachedFrom = null ) { $detachedFrom = null; foreach( array( 'Persisted', 'Unpersisted') as $type ) { $cache = "instances{$type}"; $cache =& $this->$cache; if( false !== $key = array_search( $entity, $cache, true ) ) { unset( $cache[$key] ); $detachedFrom = $this->constantGet( strtoupper( $type ) ); return true; } unset( $cache ); } return false; }
[ "public", "function", "detach", "(", "Base", "$", "entity", ",", "&", "$", "detachedFrom", "=", "null", ")", "{", "$", "detachedFrom", "=", "null", ";", "foreach", "(", "array", "(", "'Persisted'", ",", "'Unpersisted'", ")", "as", "$", "type", ")", "{", "$", "cache", "=", "\"instances{$type}\"", ";", "$", "cache", "=", "&", "$", "this", "->", "$", "cache", ";", "if", "(", "false", "!==", "$", "key", "=", "array_search", "(", "$", "entity", ",", "$", "cache", ",", "true", ")", ")", "{", "unset", "(", "$", "cache", "[", "$", "key", "]", ")", ";", "$", "detachedFrom", "=", "$", "this", "->", "constantGet", "(", "strtoupper", "(", "$", "type", ")", ")", ";", "return", "true", ";", "}", "unset", "(", "$", "cache", ")", ";", "}", "return", "false", ";", "}" ]
Detach a entity from the multiton @param Entity\Base @return bool Successful detachement?
[ "Detach", "a", "entity", "from", "the", "multiton" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L117-L139
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.rekey
public function rekey( Base $entity ) { if( false !== $key = array_search( $entity, $this->instancesPersisted, true ) ) { $newKey = $entity->keyGet( $entity ); if( isset( $this->instancesPersisted[$newKey] ) and $entity !== $this->instancesPersisted[$newKey] ) { throw new \RuntimeException( "Different object already exists with this same `key`. Clear collision." ); } unset( $this->instancesPersisted[$key] ); $this->instancesPersisted[$newKey] = $entity; return true; } return false; }
php
public function rekey( Base $entity ) { if( false !== $key = array_search( $entity, $this->instancesPersisted, true ) ) { $newKey = $entity->keyGet( $entity ); if( isset( $this->instancesPersisted[$newKey] ) and $entity !== $this->instancesPersisted[$newKey] ) { throw new \RuntimeException( "Different object already exists with this same `key`. Clear collision." ); } unset( $this->instancesPersisted[$key] ); $this->instancesPersisted[$newKey] = $entity; return true; } return false; }
[ "public", "function", "rekey", "(", "Base", "$", "entity", ")", "{", "if", "(", "false", "!==", "$", "key", "=", "array_search", "(", "$", "entity", ",", "$", "this", "->", "instancesPersisted", ",", "true", ")", ")", "{", "$", "newKey", "=", "$", "entity", "->", "keyGet", "(", "$", "entity", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "newKey", "]", ")", "and", "$", "entity", "!==", "$", "this", "->", "instancesPersisted", "[", "$", "newKey", "]", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Different object already exists with this same `key`. Clear collision.\"", ")", ";", "}", "unset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", ")", ";", "$", "this", "->", "instancesPersisted", "[", "$", "newKey", "]", "=", "$", "entity", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
A entity's key has changed. If it is in the repository this'll need rekeying @param Base $entity
[ "A", "entity", "s", "key", "has", "changed", ".", "If", "it", "is", "in", "the", "repository", "this", "ll", "need", "rekeying" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L145-L164
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.find
public function find( $key, $disableLateLoading = null, $cache = true ) { // $disableLateLoading default value management if( !is_bool( $disableLateLoading ) ) { $disableLateLoading = false; } // have we switched off the multiton? if( !$cache ) { return parent::find( $key, $disableLateLoading ); } // determine the multitonKey if( is_null( $key ) ) { return null; } elseif( is_scalar( $key ) ) { $multitonKey = $key; } elseif( is_array( $key ) ) { $multitonKey = call_user_func( "{$this->entityClass}::keyGet", $key ); } else { return null; } // do we have this? if( !isset( $this->instancesPersisted[$multitonKey] ) ) { $obj = parent::find( $key, $disableLateLoading ); // not got anything? if( !$obj ) { return null; } $this->garbageCollect(); $this->instancesPersisted[$multitonKey] = $obj; // disable late loading } elseif( $disableLateLoading ) { $this->instancesPersisted[$multitonKey]->load(); } return $this->instancesPersisted[$multitonKey]; }
php
public function find( $key, $disableLateLoading = null, $cache = true ) { // $disableLateLoading default value management if( !is_bool( $disableLateLoading ) ) { $disableLateLoading = false; } // have we switched off the multiton? if( !$cache ) { return parent::find( $key, $disableLateLoading ); } // determine the multitonKey if( is_null( $key ) ) { return null; } elseif( is_scalar( $key ) ) { $multitonKey = $key; } elseif( is_array( $key ) ) { $multitonKey = call_user_func( "{$this->entityClass}::keyGet", $key ); } else { return null; } // do we have this? if( !isset( $this->instancesPersisted[$multitonKey] ) ) { $obj = parent::find( $key, $disableLateLoading ); // not got anything? if( !$obj ) { return null; } $this->garbageCollect(); $this->instancesPersisted[$multitonKey] = $obj; // disable late loading } elseif( $disableLateLoading ) { $this->instancesPersisted[$multitonKey]->load(); } return $this->instancesPersisted[$multitonKey]; }
[ "public", "function", "find", "(", "$", "key", ",", "$", "disableLateLoading", "=", "null", ",", "$", "cache", "=", "true", ")", "{", "// $disableLateLoading default value management", "if", "(", "!", "is_bool", "(", "$", "disableLateLoading", ")", ")", "{", "$", "disableLateLoading", "=", "false", ";", "}", "// have we switched off the multiton?", "if", "(", "!", "$", "cache", ")", "{", "return", "parent", "::", "find", "(", "$", "key", ",", "$", "disableLateLoading", ")", ";", "}", "// determine the multitonKey", "if", "(", "is_null", "(", "$", "key", ")", ")", "{", "return", "null", ";", "}", "elseif", "(", "is_scalar", "(", "$", "key", ")", ")", "{", "$", "multitonKey", "=", "$", "key", ";", "}", "elseif", "(", "is_array", "(", "$", "key", ")", ")", "{", "$", "multitonKey", "=", "call_user_func", "(", "\"{$this->entityClass}::keyGet\"", ",", "$", "key", ")", ";", "}", "else", "{", "return", "null", ";", "}", "// do we have this?", "if", "(", "!", "isset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "multitonKey", "]", ")", ")", "{", "$", "obj", "=", "parent", "::", "find", "(", "$", "key", ",", "$", "disableLateLoading", ")", ";", "// not got anything?", "if", "(", "!", "$", "obj", ")", "{", "return", "null", ";", "}", "$", "this", "->", "garbageCollect", "(", ")", ";", "$", "this", "->", "instancesPersisted", "[", "$", "multitonKey", "]", "=", "$", "obj", ";", "// disable late loading", "}", "elseif", "(", "$", "disableLateLoading", ")", "{", "$", "this", "->", "instancesPersisted", "[", "$", "multitonKey", "]", "->", "load", "(", ")", ";", "}", "return", "$", "this", "->", "instancesPersisted", "[", "$", "multitonKey", "]", ";", "}" ]
Multiton. Fuck yeah! @param $key scalar. This key will be used to key the multiton array and instance the multiton. @param bool $disableLateLoading @param bool $cache default false. Is is now possible to create a object that doesn't exist in the multion.
[ "Multiton", ".", "Fuck", "yeah!" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L173-L219
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.make
public function make( array $data = null ) { $obj = parent::make( $data ); $this->instancesUnpersisted[] = $obj; return $obj; }
php
public function make( array $data = null ) { $obj = parent::make( $data ); $this->instancesUnpersisted[] = $obj; return $obj; }
[ "public", "function", "make", "(", "array", "$", "data", "=", "null", ")", "{", "$", "obj", "=", "parent", "::", "make", "(", "$", "data", ")", ";", "$", "this", "->", "instancesUnpersisted", "[", "]", "=", "$", "obj", ";", "return", "$", "obj", ";", "}" ]
Make a new entity @inheritDoc()
[ "Make", "a", "new", "entity" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L338-L343
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.initByData
public function initByData( array $data = null ) { if( !$data ) { return null; } // table inheritance - ghetto? /* if( isset( $data['tableoid'] ) ) { if( $data['tableoid'] != static::OID ) { $repo = Repository::init( $data['tableoid'] ); return $repo->initByData( $data ); } unset( $data['tableoid'] ); } */ $key = call_user_func( array( $this->entityClass, 'keyGet' ), $data ); // is this already in the cache? Are we initalising something we've already loaded? if( isset( $this->instancesPersisted[$key] ) ) { // Late loading? Don't need this anymore. $obj = $this->instancesPersisted[$key]; $obj->__construct( $data ); return $obj; } $obj = parent::initByData($data); $this->instancesPersisted[$key] = $obj; return $obj; }
php
public function initByData( array $data = null ) { if( !$data ) { return null; } // table inheritance - ghetto? /* if( isset( $data['tableoid'] ) ) { if( $data['tableoid'] != static::OID ) { $repo = Repository::init( $data['tableoid'] ); return $repo->initByData( $data ); } unset( $data['tableoid'] ); } */ $key = call_user_func( array( $this->entityClass, 'keyGet' ), $data ); // is this already in the cache? Are we initalising something we've already loaded? if( isset( $this->instancesPersisted[$key] ) ) { // Late loading? Don't need this anymore. $obj = $this->instancesPersisted[$key]; $obj->__construct( $data ); return $obj; } $obj = parent::initByData($data); $this->instancesPersisted[$key] = $obj; return $obj; }
[ "public", "function", "initByData", "(", "array", "$", "data", "=", "null", ")", "{", "if", "(", "!", "$", "data", ")", "{", "return", "null", ";", "}", "// table inheritance - ghetto?", "/*\n if( isset( $data['tableoid'] ) ) {\n if( $data['tableoid'] != static::OID ) {\n $repo = Repository::init( $data['tableoid'] );\n return $repo->initByData( $data );\n }\n unset( $data['tableoid'] );\n }\n */", "$", "key", "=", "call_user_func", "(", "array", "(", "$", "this", "->", "entityClass", ",", "'keyGet'", ")", ",", "$", "data", ")", ";", "// is this already in the cache? Are we initalising something we've already loaded?", "if", "(", "isset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", ")", ")", "{", "// Late loading? Don't need this anymore.", "$", "obj", "=", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", ";", "$", "obj", "->", "__construct", "(", "$", "data", ")", ";", "return", "$", "obj", ";", "}", "$", "obj", "=", "parent", "::", "initByData", "(", "$", "data", ")", ";", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", "=", "$", "obj", ";", "return", "$", "obj", ";", "}" ]
Entry point for objects where you've got the data array and you wish to instantiate a object and add to the cache. @param array $data @return Bond\Entity
[ "Entry", "point", "for", "objects", "where", "you", "ve", "got", "the", "data", "array", "and", "you", "wish", "to", "instantiate", "a", "object", "and", "add", "to", "the", "cache", "." ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L352-L390
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.isCached
public function isCached( Base $entity, $source = self::PERSISTED ) { switch( $source ) { case self::PERSISTED: return false !== array_search( $entity, $this->instancesPersisted, true ); case self::UNPERSISTED: return false !== array_search( $entity, $this->instancesUnpersisted, true ); case self::ALL: return $this->isCached( $entity, self::PERSISTED ) || $this->isCached( $entity, self::UNPERSISTED ); } throw new \InvalidArgumentException("Bad source `{$source}` passed to " . __FUNCTION__); }
php
public function isCached( Base $entity, $source = self::PERSISTED ) { switch( $source ) { case self::PERSISTED: return false !== array_search( $entity, $this->instancesPersisted, true ); case self::UNPERSISTED: return false !== array_search( $entity, $this->instancesUnpersisted, true ); case self::ALL: return $this->isCached( $entity, self::PERSISTED ) || $this->isCached( $entity, self::UNPERSISTED ); } throw new \InvalidArgumentException("Bad source `{$source}` passed to " . __FUNCTION__); }
[ "public", "function", "isCached", "(", "Base", "$", "entity", ",", "$", "source", "=", "self", "::", "PERSISTED", ")", "{", "switch", "(", "$", "source", ")", "{", "case", "self", "::", "PERSISTED", ":", "return", "false", "!==", "array_search", "(", "$", "entity", ",", "$", "this", "->", "instancesPersisted", ",", "true", ")", ";", "case", "self", "::", "UNPERSISTED", ":", "return", "false", "!==", "array_search", "(", "$", "entity", ",", "$", "this", "->", "instancesUnpersisted", ",", "true", ")", ";", "case", "self", "::", "ALL", ":", "return", "$", "this", "->", "isCached", "(", "$", "entity", ",", "self", "::", "PERSISTED", ")", "||", "$", "this", "->", "isCached", "(", "$", "entity", ",", "self", "::", "UNPERSISTED", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Bad source `{$source}` passed to \"", ".", "__FUNCTION__", ")", ";", "}" ]
Is this object in the multiton cache @return bool;
[ "Is", "this", "object", "in", "the", "multiton", "cache" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L490-L501
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.cacheSize
public function cacheSize( $type = self::PERSISTED ) { switch( $type ) { case self::PERSISTED: return count( $this->instancesPersisted ); case self::UNPERSISTED: return count( $this->instancesUnpersisted ); case self::ALL: return $this->cacheSize( self::PERSISTED ) + $this->cacheSize( self::UNPERSISTED ); } throw new \InvalidArgumentException("Bad source `{$source}` passed to " . __FUNCTION__); }
php
public function cacheSize( $type = self::PERSISTED ) { switch( $type ) { case self::PERSISTED: return count( $this->instancesPersisted ); case self::UNPERSISTED: return count( $this->instancesUnpersisted ); case self::ALL: return $this->cacheSize( self::PERSISTED ) + $this->cacheSize( self::UNPERSISTED ); } throw new \InvalidArgumentException("Bad source `{$source}` passed to " . __FUNCTION__); }
[ "public", "function", "cacheSize", "(", "$", "type", "=", "self", "::", "PERSISTED", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "self", "::", "PERSISTED", ":", "return", "count", "(", "$", "this", "->", "instancesPersisted", ")", ";", "case", "self", "::", "UNPERSISTED", ":", "return", "count", "(", "$", "this", "->", "instancesUnpersisted", ")", ";", "case", "self", "::", "ALL", ":", "return", "$", "this", "->", "cacheSize", "(", "self", "::", "PERSISTED", ")", "+", "$", "this", "->", "cacheSize", "(", "self", "::", "UNPERSISTED", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Bad source `{$source}` passed to \"", ".", "__FUNCTION__", ")", ";", "}" ]
Returns the number of cached items @return int Number of instances stored
[ "Returns", "the", "number", "of", "cached", "items" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L507-L518
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.cacheInvalidate
public function cacheInvalidate( $type = self::ALL ) { switch( $type ) { case self::PERSISTED: $return = count( $this->instancesPersisted ); $this->instancesPersisted = array(); return $return; case self::UNPERSISTED: $return = count( $this->instancesUnpersisted ); $this->instancesUnpersisted = array(); return $return; case self::ALL: $return = count( $this->instancesPersisted ) + count( $this->instancesUnpersisted ); $this->instancesPersisted = array(); $this->instancesUnpersisted = array(); return $return; } throw new \InvalidArgumentException("Bad source `{$source}` passed to " . __FUNCTION__); }
php
public function cacheInvalidate( $type = self::ALL ) { switch( $type ) { case self::PERSISTED: $return = count( $this->instancesPersisted ); $this->instancesPersisted = array(); return $return; case self::UNPERSISTED: $return = count( $this->instancesUnpersisted ); $this->instancesUnpersisted = array(); return $return; case self::ALL: $return = count( $this->instancesPersisted ) + count( $this->instancesUnpersisted ); $this->instancesPersisted = array(); $this->instancesUnpersisted = array(); return $return; } throw new \InvalidArgumentException("Bad source `{$source}` passed to " . __FUNCTION__); }
[ "public", "function", "cacheInvalidate", "(", "$", "type", "=", "self", "::", "ALL", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "self", "::", "PERSISTED", ":", "$", "return", "=", "count", "(", "$", "this", "->", "instancesPersisted", ")", ";", "$", "this", "->", "instancesPersisted", "=", "array", "(", ")", ";", "return", "$", "return", ";", "case", "self", "::", "UNPERSISTED", ":", "$", "return", "=", "count", "(", "$", "this", "->", "instancesUnpersisted", ")", ";", "$", "this", "->", "instancesUnpersisted", "=", "array", "(", ")", ";", "return", "$", "return", ";", "case", "self", "::", "ALL", ":", "$", "return", "=", "count", "(", "$", "this", "->", "instancesPersisted", ")", "+", "count", "(", "$", "this", "->", "instancesUnpersisted", ")", ";", "$", "this", "->", "instancesPersisted", "=", "array", "(", ")", ";", "$", "this", "->", "instancesUnpersisted", "=", "array", "(", ")", ";", "return", "$", "return", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Bad source `{$source}` passed to \"", ".", "__FUNCTION__", ")", ";", "}" ]
Invalidate cache. Returns multiton to it's vanilla state. Required for unit testing.
[ "Invalidate", "cache", ".", "Returns", "multiton", "to", "it", "s", "vanilla", "state", ".", "Required", "for", "unit", "testing", "." ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L523-L541
train
squareproton/Bond
src/Bond/Repository/Multiton.php
Multiton.garbageCollect
public function garbageCollect( $keyOrObject = null ) { // we're going to be doing the $this->instancesPersisted_max_allowed check first if( $keyOrObject == null ) { // auto garbage collection is disabled. if( !is_int( $this->instancesMaxAllowed ) ) { return 0; } $removed = 0; reset( $this->instancesPersisted ); // iterate over the instances starting oldest first while we've got too many while( count( $this->instancesPersisted ) >= $this->instancesMaxAllowed && list( $key, $obj ) = each( $this->instancesPersisted ) ) { if( !$obj->isChanged() ) { unset( $this->instancesPersisted[$key] ); $removed++; } } return $removed; } if( is_object( $keyOrObject ) ) { foreach( $this->instancesPersisted as $key => $obj ) { if( $keyOrObject === $obj ) { if( $obj->isChanged() ) { return 0; } else { unset( $this->instancesPersisted[$key] ); return 1; } } } // remove from static unpersisted if( false !== $_key = array_search( $keyOrObject, $this->instancesUnpersisted, true ) ) { unset( $this->instancesUnpersisted[$_key] ); } } elseif( is_scalar( $keyOrObject ) && isset( $this->instancesPersisted[$keyOrObject] ) ) { if( $this->instancesPersisted[$keyOrObject]->isChanged() ) { return 0; } else { unset( $this->instancesPersisted[$keyOrObject] ); return 1; } } return 0; }
php
public function garbageCollect( $keyOrObject = null ) { // we're going to be doing the $this->instancesPersisted_max_allowed check first if( $keyOrObject == null ) { // auto garbage collection is disabled. if( !is_int( $this->instancesMaxAllowed ) ) { return 0; } $removed = 0; reset( $this->instancesPersisted ); // iterate over the instances starting oldest first while we've got too many while( count( $this->instancesPersisted ) >= $this->instancesMaxAllowed && list( $key, $obj ) = each( $this->instancesPersisted ) ) { if( !$obj->isChanged() ) { unset( $this->instancesPersisted[$key] ); $removed++; } } return $removed; } if( is_object( $keyOrObject ) ) { foreach( $this->instancesPersisted as $key => $obj ) { if( $keyOrObject === $obj ) { if( $obj->isChanged() ) { return 0; } else { unset( $this->instancesPersisted[$key] ); return 1; } } } // remove from static unpersisted if( false !== $_key = array_search( $keyOrObject, $this->instancesUnpersisted, true ) ) { unset( $this->instancesUnpersisted[$_key] ); } } elseif( is_scalar( $keyOrObject ) && isset( $this->instancesPersisted[$keyOrObject] ) ) { if( $this->instancesPersisted[$keyOrObject]->isChanged() ) { return 0; } else { unset( $this->instancesPersisted[$keyOrObject] ); return 1; } } return 0; }
[ "public", "function", "garbageCollect", "(", "$", "keyOrObject", "=", "null", ")", "{", "// we're going to be doing the $this->instancesPersisted_max_allowed check first", "if", "(", "$", "keyOrObject", "==", "null", ")", "{", "// auto garbage collection is disabled.", "if", "(", "!", "is_int", "(", "$", "this", "->", "instancesMaxAllowed", ")", ")", "{", "return", "0", ";", "}", "$", "removed", "=", "0", ";", "reset", "(", "$", "this", "->", "instancesPersisted", ")", ";", "// iterate over the instances starting oldest first while we've got too many", "while", "(", "count", "(", "$", "this", "->", "instancesPersisted", ")", ">=", "$", "this", "->", "instancesMaxAllowed", "&&", "list", "(", "$", "key", ",", "$", "obj", ")", "=", "each", "(", "$", "this", "->", "instancesPersisted", ")", ")", "{", "if", "(", "!", "$", "obj", "->", "isChanged", "(", ")", ")", "{", "unset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", ")", ";", "$", "removed", "++", ";", "}", "}", "return", "$", "removed", ";", "}", "if", "(", "is_object", "(", "$", "keyOrObject", ")", ")", "{", "foreach", "(", "$", "this", "->", "instancesPersisted", "as", "$", "key", "=>", "$", "obj", ")", "{", "if", "(", "$", "keyOrObject", "===", "$", "obj", ")", "{", "if", "(", "$", "obj", "->", "isChanged", "(", ")", ")", "{", "return", "0", ";", "}", "else", "{", "unset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "key", "]", ")", ";", "return", "1", ";", "}", "}", "}", "// remove from static unpersisted", "if", "(", "false", "!==", "$", "_key", "=", "array_search", "(", "$", "keyOrObject", ",", "$", "this", "->", "instancesUnpersisted", ",", "true", ")", ")", "{", "unset", "(", "$", "this", "->", "instancesUnpersisted", "[", "$", "_key", "]", ")", ";", "}", "}", "elseif", "(", "is_scalar", "(", "$", "keyOrObject", ")", "&&", "isset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "keyOrObject", "]", ")", ")", "{", "if", "(", "$", "this", "->", "instancesPersisted", "[", "$", "keyOrObject", "]", "->", "isChanged", "(", ")", ")", "{", "return", "0", ";", "}", "else", "{", "unset", "(", "$", "this", "->", "instancesPersisted", "[", "$", "keyOrObject", "]", ")", ";", "return", "1", ";", "}", "}", "return", "0", ";", "}" ]
Removes a object from the multiton if 1. You pass its `key` (ie, the key that you would have used to instantiate it with get() 2. You pass it the object (includes objects in $this->instancesUnpersisted 3. You don't pass anything and there are > $this->instancesPersisted max_allowed persisted instances of this object in that have _not_ been changed This does not gaurentee that you will always have < $this->instancesPersisted records stored. @param mixed $keyOrObject @return int number of objects removed from the multiton
[ "Removes", "a", "object", "from", "the", "multiton", "if" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository/Multiton.php#L586-L652
train
ZendExperts/phpids
lib/IDS/Log/Email.php
IDS_Log_Email.isSpamAttempt
protected function isSpamAttempt() { /* * loop through all files in the tmp directory and * delete garbage files */ $dir = $this->tmp_path; $numPrefixChars = strlen($this->file_prefix); $files = scandir($dir); foreach ($files as $file) { if (is_file($dir . DIRECTORY_SEPARATOR . $file)) { if (substr($file, 0, $numPrefixChars) == $this->file_prefix) { $lastModified = filemtime($dir . DIRECTORY_SEPARATOR . $file); if ((time() - $lastModified) > 3600) { unlink($dir . DIRECTORY_SEPARATOR . $file); } } } } /* * end deleting garbage files */ $remoteAddr = $this->ip; $userAgent = $_SERVER['HTTP_USER_AGENT']; $filename = $this->file_prefix . md5($remoteAddr.$userAgent) . '.tmp'; $file = $dir . DIRECTORY_SEPARATOR . $filename; if (!file_exists($file)) { $handle = fopen($file, 'w'); fwrite($handle, time()); fclose($handle); return false; } $lastAttack = file_get_contents($file); $difference = time() - $lastAttack; if ($difference > $this->allowed_rate) { unlink($file); } else { return true; } return false; }
php
protected function isSpamAttempt() { /* * loop through all files in the tmp directory and * delete garbage files */ $dir = $this->tmp_path; $numPrefixChars = strlen($this->file_prefix); $files = scandir($dir); foreach ($files as $file) { if (is_file($dir . DIRECTORY_SEPARATOR . $file)) { if (substr($file, 0, $numPrefixChars) == $this->file_prefix) { $lastModified = filemtime($dir . DIRECTORY_SEPARATOR . $file); if ((time() - $lastModified) > 3600) { unlink($dir . DIRECTORY_SEPARATOR . $file); } } } } /* * end deleting garbage files */ $remoteAddr = $this->ip; $userAgent = $_SERVER['HTTP_USER_AGENT']; $filename = $this->file_prefix . md5($remoteAddr.$userAgent) . '.tmp'; $file = $dir . DIRECTORY_SEPARATOR . $filename; if (!file_exists($file)) { $handle = fopen($file, 'w'); fwrite($handle, time()); fclose($handle); return false; } $lastAttack = file_get_contents($file); $difference = time() - $lastAttack; if ($difference > $this->allowed_rate) { unlink($file); } else { return true; } return false; }
[ "protected", "function", "isSpamAttempt", "(", ")", "{", "/*\n * loop through all files in the tmp directory and\n * delete garbage files\n */", "$", "dir", "=", "$", "this", "->", "tmp_path", ";", "$", "numPrefixChars", "=", "strlen", "(", "$", "this", "->", "file_prefix", ")", ";", "$", "files", "=", "scandir", "(", "$", "dir", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "if", "(", "is_file", "(", "$", "dir", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ")", ")", "{", "if", "(", "substr", "(", "$", "file", ",", "0", ",", "$", "numPrefixChars", ")", "==", "$", "this", "->", "file_prefix", ")", "{", "$", "lastModified", "=", "filemtime", "(", "$", "dir", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ")", ";", "if", "(", "(", "time", "(", ")", "-", "$", "lastModified", ")", ">", "3600", ")", "{", "unlink", "(", "$", "dir", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ")", ";", "}", "}", "}", "}", "/*\n * end deleting garbage files\n */", "$", "remoteAddr", "=", "$", "this", "->", "ip", ";", "$", "userAgent", "=", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ";", "$", "filename", "=", "$", "this", "->", "file_prefix", ".", "md5", "(", "$", "remoteAddr", ".", "$", "userAgent", ")", ".", "'.tmp'", ";", "$", "file", "=", "$", "dir", ".", "DIRECTORY_SEPARATOR", ".", "$", "filename", ";", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "$", "handle", "=", "fopen", "(", "$", "file", ",", "'w'", ")", ";", "fwrite", "(", "$", "handle", ",", "time", "(", ")", ")", ";", "fclose", "(", "$", "handle", ")", ";", "return", "false", ";", "}", "$", "lastAttack", "=", "file_get_contents", "(", "$", "file", ")", ";", "$", "difference", "=", "time", "(", ")", "-", "$", "lastAttack", ";", "if", "(", "$", "difference", ">", "$", "this", "->", "allowed_rate", ")", "{", "unlink", "(", "$", "file", ")", ";", "}", "else", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Detects spam attempts To avoid mail spam through this logging class this function is used to detect such attempts based on the alert frequency. @return boolean
[ "Detects", "spam", "attempts" ]
f30df04eea47b94d056e2ae9ec8fea1c626f1c03
https://github.com/ZendExperts/phpids/blob/f30df04eea47b94d056e2ae9ec8fea1c626f1c03/lib/IDS/Log/Email.php#L211-L257
train
ZendExperts/phpids
lib/IDS/Log/Email.php
IDS_Log_Email.execute
public function execute(IDS_Report $data) { if ($this->safemode) { if ($this->isSpamAttempt()) { return false; } } /* * In case the data has been modified before it might * be necessary to convert it to string since it's pretty * senseless to send array or object via e-mail */ $data = $this->prepareData($data); if (is_string($data)) { $data = trim($data); // if headers are passed as array, we need to make a string of it if (is_array($this->headers)) { $headers = ""; foreach ($this->headers as $header) { $headers .= $header . "\r\n"; } } else { $headers = $this->headers; } if (!empty($this->recipients)) { if (is_array($this->recipients)) { foreach ($this->recipients as $address) { $this->send( $address, $data, $headers, $this->envelope ); } } else { $this->send( $this->recipients, $data, $headers, $this->envelope ); } } } else { throw new Exception( 'Please make sure that data returned by IDS_Log_Email::prepareData() is a string.' ); } return true; }
php
public function execute(IDS_Report $data) { if ($this->safemode) { if ($this->isSpamAttempt()) { return false; } } /* * In case the data has been modified before it might * be necessary to convert it to string since it's pretty * senseless to send array or object via e-mail */ $data = $this->prepareData($data); if (is_string($data)) { $data = trim($data); // if headers are passed as array, we need to make a string of it if (is_array($this->headers)) { $headers = ""; foreach ($this->headers as $header) { $headers .= $header . "\r\n"; } } else { $headers = $this->headers; } if (!empty($this->recipients)) { if (is_array($this->recipients)) { foreach ($this->recipients as $address) { $this->send( $address, $data, $headers, $this->envelope ); } } else { $this->send( $this->recipients, $data, $headers, $this->envelope ); } } } else { throw new Exception( 'Please make sure that data returned by IDS_Log_Email::prepareData() is a string.' ); } return true; }
[ "public", "function", "execute", "(", "IDS_Report", "$", "data", ")", "{", "if", "(", "$", "this", "->", "safemode", ")", "{", "if", "(", "$", "this", "->", "isSpamAttempt", "(", ")", ")", "{", "return", "false", ";", "}", "}", "/*\n * In case the data has been modified before it might\n * be necessary to convert it to string since it's pretty\n * senseless to send array or object via e-mail\n */", "$", "data", "=", "$", "this", "->", "prepareData", "(", "$", "data", ")", ";", "if", "(", "is_string", "(", "$", "data", ")", ")", "{", "$", "data", "=", "trim", "(", "$", "data", ")", ";", "// if headers are passed as array, we need to make a string of it", "if", "(", "is_array", "(", "$", "this", "->", "headers", ")", ")", "{", "$", "headers", "=", "\"\"", ";", "foreach", "(", "$", "this", "->", "headers", "as", "$", "header", ")", "{", "$", "headers", ".=", "$", "header", ".", "\"\\r\\n\"", ";", "}", "}", "else", "{", "$", "headers", "=", "$", "this", "->", "headers", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "recipients", ")", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "recipients", ")", ")", "{", "foreach", "(", "$", "this", "->", "recipients", "as", "$", "address", ")", "{", "$", "this", "->", "send", "(", "$", "address", ",", "$", "data", ",", "$", "headers", ",", "$", "this", "->", "envelope", ")", ";", "}", "}", "else", "{", "$", "this", "->", "send", "(", "$", "this", "->", "recipients", ",", "$", "data", ",", "$", "headers", ",", "$", "this", "->", "envelope", ")", ";", "}", "}", "}", "else", "{", "throw", "new", "Exception", "(", "'Please make sure that data returned by\n IDS_Log_Email::prepareData() is a string.'", ")", ";", "}", "return", "true", ";", "}" ]
Sends the report to registered recipients @param object $data IDS_Report instance @throws Exception if data is no string @return boolean
[ "Sends", "the", "report", "to", "registered", "recipients" ]
f30df04eea47b94d056e2ae9ec8fea1c626f1c03
https://github.com/ZendExperts/phpids/blob/f30df04eea47b94d056e2ae9ec8fea1c626f1c03/lib/IDS/Log/Email.php#L308-L365
train
horntell/php-sdk
src/Horntell/Card.php
Card.toProfile
public function toProfile($uid, $card) { $card['canvas'] = isset($card['canvas']) ? $card['canvas'] : self::DEFAULT_CANVAS; return $this->request->send('POST', "/profiles/$uid/cards", $card); }
php
public function toProfile($uid, $card) { $card['canvas'] = isset($card['canvas']) ? $card['canvas'] : self::DEFAULT_CANVAS; return $this->request->send('POST', "/profiles/$uid/cards", $card); }
[ "public", "function", "toProfile", "(", "$", "uid", ",", "$", "card", ")", "{", "$", "card", "[", "'canvas'", "]", "=", "isset", "(", "$", "card", "[", "'canvas'", "]", ")", "?", "$", "card", "[", "'canvas'", "]", ":", "self", "::", "DEFAULT_CANVAS", ";", "return", "$", "this", "->", "request", "->", "send", "(", "'POST'", ",", "\"/profiles/$uid/cards\"", ",", "$", "card", ")", ";", "}" ]
Sends a card to a profile @param string $uid @param array $card @return Horntell\Http\Response
[ "Sends", "a", "card", "to", "a", "profile" ]
e5205e9396a21b754d5651a8aa5898da5922a1b7
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/src/Horntell/Card.php#L29-L34
train
horntell/php-sdk
src/Horntell/Card.php
Card.toProfiles
public function toProfiles($profiles, $card) { $card = array_merge(['profile_uids' => $profiles], $card); $card['canvas'] = isset($card['canvas']) ? $card['canvas'] : self::DEFAULT_CANVAS; return $this->request->send('POST', "/profiles/cards", $card); }
php
public function toProfiles($profiles, $card) { $card = array_merge(['profile_uids' => $profiles], $card); $card['canvas'] = isset($card['canvas']) ? $card['canvas'] : self::DEFAULT_CANVAS; return $this->request->send('POST', "/profiles/cards", $card); }
[ "public", "function", "toProfiles", "(", "$", "profiles", ",", "$", "card", ")", "{", "$", "card", "=", "array_merge", "(", "[", "'profile_uids'", "=>", "$", "profiles", "]", ",", "$", "card", ")", ";", "$", "card", "[", "'canvas'", "]", "=", "isset", "(", "$", "card", "[", "'canvas'", "]", ")", "?", "$", "card", "[", "'canvas'", "]", ":", "self", "::", "DEFAULT_CANVAS", ";", "return", "$", "this", "->", "request", "->", "send", "(", "'POST'", ",", "\"/profiles/cards\"", ",", "$", "card", ")", ";", "}" ]
Sends a card to a multiple profiles @param array $card @return Horntell\Http\Response
[ "Sends", "a", "card", "to", "a", "multiple", "profiles" ]
e5205e9396a21b754d5651a8aa5898da5922a1b7
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/src/Horntell/Card.php#L42-L49
train
horntell/php-sdk
src/Horntell/Card.php
Card.toChannels
public function toChannels($channels, $card) { $card = array_merge(['channel_uids' => $channels], $card); $card['canvas'] = isset($card['canvas']) ? $card['canvas'] : self::DEFAULT_CANVAS; return $this->request->send('POST', "/channels/cards", $card); }
php
public function toChannels($channels, $card) { $card = array_merge(['channel_uids' => $channels], $card); $card['canvas'] = isset($card['canvas']) ? $card['canvas'] : self::DEFAULT_CANVAS; return $this->request->send('POST', "/channels/cards", $card); }
[ "public", "function", "toChannels", "(", "$", "channels", ",", "$", "card", ")", "{", "$", "card", "=", "array_merge", "(", "[", "'channel_uids'", "=>", "$", "channels", "]", ",", "$", "card", ")", ";", "$", "card", "[", "'canvas'", "]", "=", "isset", "(", "$", "card", "[", "'canvas'", "]", ")", "?", "$", "card", "[", "'canvas'", "]", ":", "self", "::", "DEFAULT_CANVAS", ";", "return", "$", "this", "->", "request", "->", "send", "(", "'POST'", ",", "\"/channels/cards\"", ",", "$", "card", ")", ";", "}" ]
Sends a card to a multiple channels @param array $card @return Horntell\Http\Response
[ "Sends", "a", "card", "to", "a", "multiple", "channels" ]
e5205e9396a21b754d5651a8aa5898da5922a1b7
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/src/Horntell/Card.php#L72-L79
train
swaros/golib
src/Types/ValueSet.php
ValueSet.applyData
public function applyData($applyEntrie = NULL, $full = true){ if (is_array($applyEntrie)){ if ($full) { $this->values = $applyEntrie; } else { $this->values = array_replace($this->values, $applyEntrie); } }elseif (is_string($applyEntrie)){ if ($full) { $this->values = explode($this->getDelimiter(), $applyEntrie); } else { $this->values = array_replace($this->values,explode($this->getDelimiter(), $applyEntrie)); } } else { throw new \InvalidArgumentException("Argument must be an array or Speparated string"); } }
php
public function applyData($applyEntrie = NULL, $full = true){ if (is_array($applyEntrie)){ if ($full) { $this->values = $applyEntrie; } else { $this->values = array_replace($this->values, $applyEntrie); } }elseif (is_string($applyEntrie)){ if ($full) { $this->values = explode($this->getDelimiter(), $applyEntrie); } else { $this->values = array_replace($this->values,explode($this->getDelimiter(), $applyEntrie)); } } else { throw new \InvalidArgumentException("Argument must be an array or Speparated string"); } }
[ "public", "function", "applyData", "(", "$", "applyEntrie", "=", "NULL", ",", "$", "full", "=", "true", ")", "{", "if", "(", "is_array", "(", "$", "applyEntrie", ")", ")", "{", "if", "(", "$", "full", ")", "{", "$", "this", "->", "values", "=", "$", "applyEntrie", ";", "}", "else", "{", "$", "this", "->", "values", "=", "array_replace", "(", "$", "this", "->", "values", ",", "$", "applyEntrie", ")", ";", "}", "}", "elseif", "(", "is_string", "(", "$", "applyEntrie", ")", ")", "{", "if", "(", "$", "full", ")", "{", "$", "this", "->", "values", "=", "explode", "(", "$", "this", "->", "getDelimiter", "(", ")", ",", "$", "applyEntrie", ")", ";", "}", "else", "{", "$", "this", "->", "values", "=", "array_replace", "(", "$", "this", "->", "values", ",", "explode", "(", "$", "this", "->", "getDelimiter", "(", ")", ",", "$", "applyEntrie", ")", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Argument must be an array or Speparated string\"", ")", ";", "}", "}" ]
apply content via string or array @param array/string $applyEntrie is an array or and seperated string @param boolean $full if true the whole set will be overwritten.on flase just the fisrt entries @throws \InvalidArgumentException
[ "apply", "content", "via", "string", "or", "array" ]
9e75c8fb36de7c09b01a6c1c0d27c45f02fed567
https://github.com/swaros/golib/blob/9e75c8fb36de7c09b01a6c1c0d27c45f02fed567/src/Types/ValueSet.php#L38-L56
train
swaros/golib
src/Types/ValueSet.php
ValueSet.checkCount
private function checkCount(){ $cnt = (int) $this->getMaxEntries(); if ($cnt !== NULL && count($this->values) !== $cnt){ trigger_error("Wrong count of Elements. Expected are $cnt. But right now there are ". count($this->values)); } }
php
private function checkCount(){ $cnt = (int) $this->getMaxEntries(); if ($cnt !== NULL && count($this->values) !== $cnt){ trigger_error("Wrong count of Elements. Expected are $cnt. But right now there are ". count($this->values)); } }
[ "private", "function", "checkCount", "(", ")", "{", "$", "cnt", "=", "(", "int", ")", "$", "this", "->", "getMaxEntries", "(", ")", ";", "if", "(", "$", "cnt", "!==", "NULL", "&&", "count", "(", "$", "this", "->", "values", ")", "!==", "$", "cnt", ")", "{", "trigger_error", "(", "\"Wrong count of Elements. Expected are $cnt. But right now there are \"", ".", "count", "(", "$", "this", "->", "values", ")", ")", ";", "}", "}" ]
checks if the expected count is given triggers an error if getMaxEntries Returns a number and this number is not equal to the count of elements.
[ "checks", "if", "the", "expected", "count", "is", "given", "triggers", "an", "error", "if", "getMaxEntries", "Returns", "a", "number", "and", "this", "number", "is", "not", "equal", "to", "the", "count", "of", "elements", "." ]
9e75c8fb36de7c09b01a6c1c0d27c45f02fed567
https://github.com/swaros/golib/blob/9e75c8fb36de7c09b01a6c1c0d27c45f02fed567/src/Types/ValueSet.php#L63-L69
train
taylornetwork/make-html
src/MakeHTML.php
MakeHTML.getHTMLGeneratorInstance
public function getHTMLGeneratorInstance() { if (!isset($this->HTMLGenerator) || !$this->HTMLGenerator instanceof HTMLGenerator) { $this->HTMLGenerator = new HTMLGenerator(); $this->HTMLConfig($this->HTMLGenerator); } return $this->HTMLGenerator; }
php
public function getHTMLGeneratorInstance() { if (!isset($this->HTMLGenerator) || !$this->HTMLGenerator instanceof HTMLGenerator) { $this->HTMLGenerator = new HTMLGenerator(); $this->HTMLConfig($this->HTMLGenerator); } return $this->HTMLGenerator; }
[ "public", "function", "getHTMLGeneratorInstance", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "HTMLGenerator", ")", "||", "!", "$", "this", "->", "HTMLGenerator", "instanceof", "HTMLGenerator", ")", "{", "$", "this", "->", "HTMLGenerator", "=", "new", "HTMLGenerator", "(", ")", ";", "$", "this", "->", "HTMLConfig", "(", "$", "this", "->", "HTMLGenerator", ")", ";", "}", "return", "$", "this", "->", "HTMLGenerator", ";", "}" ]
Get the generator instance, or create one. @return HTMLGenerator
[ "Get", "the", "generator", "instance", "or", "create", "one", "." ]
216308d5ba8c9d2412dc787fb6db1a837c20b820
https://github.com/taylornetwork/make-html/blob/216308d5ba8c9d2412dc787fb6db1a837c20b820/src/MakeHTML.php#L41-L49
train
rawphp/RawConsole
src/RawPHP/RawConsole/Option.php
Option.isLongCode
public static function isLongCode( $arg ) { $retVal = ( strlen( $arg ) > 2 ) && ( '-' === $arg[ 0 ] && '-' === $arg[ 1 ] ); if ( 2 === strlen( $arg ) ) { return $retVal; } if ( ( !is_bool( $arg ) && !Util::validIndex( 2, $arg ) ) || '-' === $arg[ 2 ] ) { throw new CommandException( 'Unknown option type [ ' . $arg . ' ]' ); } return $retVal; }
php
public static function isLongCode( $arg ) { $retVal = ( strlen( $arg ) > 2 ) && ( '-' === $arg[ 0 ] && '-' === $arg[ 1 ] ); if ( 2 === strlen( $arg ) ) { return $retVal; } if ( ( !is_bool( $arg ) && !Util::validIndex( 2, $arg ) ) || '-' === $arg[ 2 ] ) { throw new CommandException( 'Unknown option type [ ' . $arg . ' ]' ); } return $retVal; }
[ "public", "static", "function", "isLongCode", "(", "$", "arg", ")", "{", "$", "retVal", "=", "(", "strlen", "(", "$", "arg", ")", ">", "2", ")", "&&", "(", "'-'", "===", "$", "arg", "[", "0", "]", "&&", "'-'", "===", "$", "arg", "[", "1", "]", ")", ";", "if", "(", "2", "===", "strlen", "(", "$", "arg", ")", ")", "{", "return", "$", "retVal", ";", "}", "if", "(", "(", "!", "is_bool", "(", "$", "arg", ")", "&&", "!", "Util", "::", "validIndex", "(", "2", ",", "$", "arg", ")", ")", "||", "'-'", "===", "$", "arg", "[", "2", "]", ")", "{", "throw", "new", "CommandException", "(", "'Unknown option type [ '", ".", "$", "arg", ".", "' ]'", ")", ";", "}", "return", "$", "retVal", ";", "}" ]
Checks if the argument is a long code. @param string $arg the argument @return bool TRUE if long code, else FALSE @throws CommandException if the argument is malformed
[ "Checks", "if", "the", "argument", "is", "a", "long", "code", "." ]
602bedd10f24962305a7ac1979ed326852f4224a
https://github.com/rawphp/RawConsole/blob/602bedd10f24962305a7ac1979ed326852f4224a/src/RawPHP/RawConsole/Option.php#L107-L122
train
rawphp/RawConsole
src/RawPHP/RawConsole/Option.php
Option.setRequiredValue
public static function setRequiredValue( Option &$option, $arg ) { if ( self::isShortCode( $arg ) || self::isLongCode( $arg ) ) { throw new CommandException( 'Missing argument for option --' . $option->longCode ); } else { if ( is_string( $arg ) ) { $arg = trim( $arg ); } $option->value = $arg; } }
php
public static function setRequiredValue( Option &$option, $arg ) { if ( self::isShortCode( $arg ) || self::isLongCode( $arg ) ) { throw new CommandException( 'Missing argument for option --' . $option->longCode ); } else { if ( is_string( $arg ) ) { $arg = trim( $arg ); } $option->value = $arg; } }
[ "public", "static", "function", "setRequiredValue", "(", "Option", "&", "$", "option", ",", "$", "arg", ")", "{", "if", "(", "self", "::", "isShortCode", "(", "$", "arg", ")", "||", "self", "::", "isLongCode", "(", "$", "arg", ")", ")", "{", "throw", "new", "CommandException", "(", "'Missing argument for option --'", ".", "$", "option", "->", "longCode", ")", ";", "}", "else", "{", "if", "(", "is_string", "(", "$", "arg", ")", ")", "{", "$", "arg", "=", "trim", "(", "$", "arg", ")", ";", "}", "$", "option", "->", "value", "=", "$", "arg", ";", "}", "}" ]
Sets the required argument. @param Option $option the option to set to @param mixed $arg the argument @throws CommandException if argument is missing
[ "Sets", "the", "required", "argument", "." ]
602bedd10f24962305a7ac1979ed326852f4224a
https://github.com/rawphp/RawConsole/blob/602bedd10f24962305a7ac1979ed326852f4224a/src/RawPHP/RawConsole/Option.php#L132-L147
train
rawphp/RawConsole
src/RawPHP/RawConsole/Option.php
Option.setOptionalValue
public static function setOptionalValue( Option &$option, $arg ) { if ( !self::isShortCode( $arg ) && !self::isLongCode( $arg ) ) { if ( is_bool( $arg ) ) { $option->value = ( bool )$arg; } elseif ( is_string( $arg ) ) { $arg = trim( $arg ); $option->value = $arg; } } }
php
public static function setOptionalValue( Option &$option, $arg ) { if ( !self::isShortCode( $arg ) && !self::isLongCode( $arg ) ) { if ( is_bool( $arg ) ) { $option->value = ( bool )$arg; } elseif ( is_string( $arg ) ) { $arg = trim( $arg ); $option->value = $arg; } } }
[ "public", "static", "function", "setOptionalValue", "(", "Option", "&", "$", "option", ",", "$", "arg", ")", "{", "if", "(", "!", "self", "::", "isShortCode", "(", "$", "arg", ")", "&&", "!", "self", "::", "isLongCode", "(", "$", "arg", ")", ")", "{", "if", "(", "is_bool", "(", "$", "arg", ")", ")", "{", "$", "option", "->", "value", "=", "(", "bool", ")", "$", "arg", ";", "}", "elseif", "(", "is_string", "(", "$", "arg", ")", ")", "{", "$", "arg", "=", "trim", "(", "$", "arg", ")", ";", "$", "option", "->", "value", "=", "$", "arg", ";", "}", "}", "}" ]
Sets an optional argument if available. @param Option $option the option to set to @param mixed $arg the argument
[ "Sets", "an", "optional", "argument", "if", "available", "." ]
602bedd10f24962305a7ac1979ed326852f4224a
https://github.com/rawphp/RawConsole/blob/602bedd10f24962305a7ac1979ed326852f4224a/src/RawPHP/RawConsole/Option.php#L155-L170
train
battis/simplecache
src/SimpleCache.php
SimpleCache.setTableName
public function setTableName($table) { if ($this->sql) { if ($this->validateToken($table)) { $this->table = $table; return true; } else { throw new SimpleCache_Exception("`$table` is not a valid table name"); } } return false; }
php
public function setTableName($table) { if ($this->sql) { if ($this->validateToken($table)) { $this->table = $table; return true; } else { throw new SimpleCache_Exception("`$table` is not a valid table name"); } } return false; }
[ "public", "function", "setTableName", "(", "$", "table", ")", "{", "if", "(", "$", "this", "->", "sql", ")", "{", "if", "(", "$", "this", "->", "validateToken", "(", "$", "table", ")", ")", "{", "$", "this", "->", "table", "=", "$", "table", ";", "return", "true", ";", "}", "else", "{", "throw", "new", "SimpleCache_Exception", "(", "\"`$table` is not a valid table name\"", ")", ";", "}", "}", "return", "false", ";", "}" ]
Set cache table name @param string $table @return boolean Returns `TRUE` on success, `FALSE` on failure
[ "Set", "cache", "table", "name" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L135-L146
train
battis/simplecache
src/SimpleCache.php
SimpleCache.setKeyName
public function setKeyName($key) { if ($this->sql) { if ($this->validateToken($key)) { $this->key = $key; return true; } else { throw new SimpleCache_Exception("`$key` is not a valid field name"); } } return false; }
php
public function setKeyName($key) { if ($this->sql) { if ($this->validateToken($key)) { $this->key = $key; return true; } else { throw new SimpleCache_Exception("`$key` is not a valid field name"); } } return false; }
[ "public", "function", "setKeyName", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "sql", ")", "{", "if", "(", "$", "this", "->", "validateToken", "(", "$", "key", ")", ")", "{", "$", "this", "->", "key", "=", "$", "key", ";", "return", "true", ";", "}", "else", "{", "throw", "new", "SimpleCache_Exception", "(", "\"`$key` is not a valid field name\"", ")", ";", "}", "}", "return", "false", ";", "}" ]
Set cache key field name @param string $key @return boolean Returns `TRUE` on success, `FALSE` on failure
[ "Set", "cache", "key", "field", "name" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L165-L176
train
battis/simplecache
src/SimpleCache.php
SimpleCache.setCacheName
public function setCacheName($cache) { if ($this->sql) { if ($this->validateToken($cache)) { $this->cache = $cache; return true; } else { throw new SimpleCache_Exception("`$cache` is not a valid field name"); } } return false; }
php
public function setCacheName($cache) { if ($this->sql) { if ($this->validateToken($cache)) { $this->cache = $cache; return true; } else { throw new SimpleCache_Exception("`$cache` is not a valid field name"); } } return false; }
[ "public", "function", "setCacheName", "(", "$", "cache", ")", "{", "if", "(", "$", "this", "->", "sql", ")", "{", "if", "(", "$", "this", "->", "validateToken", "(", "$", "cache", ")", ")", "{", "$", "this", "->", "cache", "=", "$", "cache", ";", "return", "true", ";", "}", "else", "{", "throw", "new", "SimpleCache_Exception", "(", "\"`$cache` is not a valid field name\"", ")", ";", "}", "}", "return", "false", ";", "}" ]
Set cache storage field name @param string $cache @return boolean Returns `TRUE` on success, `FALSE` on failure
[ "Set", "cache", "storage", "field", "name" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L195-L206
train
battis/simplecache
src/SimpleCache.php
SimpleCache.buildCache
public function buildCache($table = null, $key = null, $cache = null) { if ($this->sql && ($table === null || $this->setTableName($table)) && ($key === null || $this->setKeyName($key)) && ($cache === null || $this->setCacheName($cache))) { if ($this->sql->query(" CREATE TABLE IF NOT EXISTS `{$this->table}` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `{$this->key}` text NOT NULL, `{$this->cache}` longtext NOT NULL, `expire` timestamp NULL DEFAULT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ); ")) { $this->initialized = true; /* Upgrade older cache tables for longer cache data */ $this->sql->query(" ALTER TABLE `{$this->table}` CHANGE `{$this->cache}` `{$this->cache}` longtext NOT NULL; "); /* Upgrade older cached tables to include an expire column for each row */ $this->sql->query(" ALTER TABLE `{$this->table}` ADD `expire` timestamp NULL DEFAULT NULL AFTER `{$this->cache}; "); } } return $this->initialized; }
php
public function buildCache($table = null, $key = null, $cache = null) { if ($this->sql && ($table === null || $this->setTableName($table)) && ($key === null || $this->setKeyName($key)) && ($cache === null || $this->setCacheName($cache))) { if ($this->sql->query(" CREATE TABLE IF NOT EXISTS `{$this->table}` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `{$this->key}` text NOT NULL, `{$this->cache}` longtext NOT NULL, `expire` timestamp NULL DEFAULT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ); ")) { $this->initialized = true; /* Upgrade older cache tables for longer cache data */ $this->sql->query(" ALTER TABLE `{$this->table}` CHANGE `{$this->cache}` `{$this->cache}` longtext NOT NULL; "); /* Upgrade older cached tables to include an expire column for each row */ $this->sql->query(" ALTER TABLE `{$this->table}` ADD `expire` timestamp NULL DEFAULT NULL AFTER `{$this->cache}; "); } } return $this->initialized; }
[ "public", "function", "buildCache", "(", "$", "table", "=", "null", ",", "$", "key", "=", "null", ",", "$", "cache", "=", "null", ")", "{", "if", "(", "$", "this", "->", "sql", "&&", "(", "$", "table", "===", "null", "||", "$", "this", "->", "setTableName", "(", "$", "table", ")", ")", "&&", "(", "$", "key", "===", "null", "||", "$", "this", "->", "setKeyName", "(", "$", "key", ")", ")", "&&", "(", "$", "cache", "===", "null", "||", "$", "this", "->", "setCacheName", "(", "$", "cache", ")", ")", ")", "{", "if", "(", "$", "this", "->", "sql", "->", "query", "(", "\"\n CREATE TABLE IF NOT EXISTS `{$this->table}` (\n `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n `{$this->key}` text NOT NULL,\n `{$this->cache}` longtext NOT NULL,\n `expire` timestamp NULL DEFAULT NULL,\n `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`)\n );\n \"", ")", ")", "{", "$", "this", "->", "initialized", "=", "true", ";", "/* Upgrade older cache tables for longer cache data */", "$", "this", "->", "sql", "->", "query", "(", "\"\n ALTER TABLE `{$this->table}` CHANGE `{$this->cache}` `{$this->cache}` longtext NOT NULL;\n \"", ")", ";", "/* Upgrade older cached tables to include an expire column for each row */", "$", "this", "->", "sql", "->", "query", "(", "\"\n ALTER TABLE `{$this->table}` ADD `expire` timestamp NULL DEFAULT NULL AFTER `{$this->cache};\n \"", ")", ";", "}", "}", "return", "$", "this", "->", "initialized", ";", "}" ]
Create cache table in database @param string $table (Optional) Cache table name @param string $key (Optional) Cache key field name @param string $cache (Optional) Cache storage field name @return boolean Returns `TRUE` on success, `FALSE` on failure
[ "Create", "cache", "table", "in", "database" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L269-L299
train
battis/simplecache
src/SimpleCache.php
SimpleCache.getCache
public function getCache($key) { if ($this->sqlInitialized()) { if ($this->sql) { $_key = $this->sql->real_escape_string($key); if ($this->lifetime == self::IMMORTAL_LIFETIME) { if ($response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' AND `expire` IS NULL ")) { if ($cache = $response->fetch_assoc()) { return unserialize($cache[$this->cache]); } } } else { $liveCache = date('Y-m-d H:i:s', time() - $this->lifetime); if ($response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' AND ( ( `timestamp` > '{$liveCache}' AND `expire` IS NULL ) OR ( `expire` > NOW() ) ) ")) { if ($cache = $response->fetch_assoc()) { return unserialize($cache[$this->cache]); } } } } return false; } }
php
public function getCache($key) { if ($this->sqlInitialized()) { if ($this->sql) { $_key = $this->sql->real_escape_string($key); if ($this->lifetime == self::IMMORTAL_LIFETIME) { if ($response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' AND `expire` IS NULL ")) { if ($cache = $response->fetch_assoc()) { return unserialize($cache[$this->cache]); } } } else { $liveCache = date('Y-m-d H:i:s', time() - $this->lifetime); if ($response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' AND ( ( `timestamp` > '{$liveCache}' AND `expire` IS NULL ) OR ( `expire` > NOW() ) ) ")) { if ($cache = $response->fetch_assoc()) { return unserialize($cache[$this->cache]); } } } } return false; } }
[ "public", "function", "getCache", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "sqlInitialized", "(", ")", ")", "{", "if", "(", "$", "this", "->", "sql", ")", "{", "$", "_key", "=", "$", "this", "->", "sql", "->", "real_escape_string", "(", "$", "key", ")", ";", "if", "(", "$", "this", "->", "lifetime", "==", "self", "::", "IMMORTAL_LIFETIME", ")", "{", "if", "(", "$", "response", "=", "$", "this", "->", "sql", "->", "query", "(", "\"\n SELECT *\n FROM `{$this->table}`\n WHERE\n `{$this->key}` = '$_key' AND\n `expire` IS NULL\n \"", ")", ")", "{", "if", "(", "$", "cache", "=", "$", "response", "->", "fetch_assoc", "(", ")", ")", "{", "return", "unserialize", "(", "$", "cache", "[", "$", "this", "->", "cache", "]", ")", ";", "}", "}", "}", "else", "{", "$", "liveCache", "=", "date", "(", "'Y-m-d H:i:s'", ",", "time", "(", ")", "-", "$", "this", "->", "lifetime", ")", ";", "if", "(", "$", "response", "=", "$", "this", "->", "sql", "->", "query", "(", "\"\n SELECT *\n FROM `{$this->table}`\n WHERE\n `{$this->key}` = '$_key' AND (\n (\n `timestamp` > '{$liveCache}' AND\n `expire` IS NULL\n ) OR (\n `expire` > NOW()\n )\n )\n \"", ")", ")", "{", "if", "(", "$", "cache", "=", "$", "response", "->", "fetch_assoc", "(", ")", ")", "{", "return", "unserialize", "(", "$", "cache", "[", "$", "this", "->", "cache", "]", ")", ";", "}", "}", "}", "}", "return", "false", ";", "}", "}" ]
Get available cached data @param string $key @return mixed|boolean Returns the cached data or `FALSE` if no data cached
[ "Get", "available", "cached", "data" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L308-L348
train
battis/simplecache
src/SimpleCache.php
SimpleCache.getExpirationTimestamp
protected function getExpirationTimestamp($lifetimeInSeconds = false) { if ($lifetimeInSeconds === false) { $lifetimeInSeconds = $this->lifetime; } if ($lifetimeInSeconds === self::IMMORTAL_LIFETIME) { return false; } else { return date(self::MYSQL_TIMESTAMP, time() + $lifetimeInSeconds); } }
php
protected function getExpirationTimestamp($lifetimeInSeconds = false) { if ($lifetimeInSeconds === false) { $lifetimeInSeconds = $this->lifetime; } if ($lifetimeInSeconds === self::IMMORTAL_LIFETIME) { return false; } else { return date(self::MYSQL_TIMESTAMP, time() + $lifetimeInSeconds); } }
[ "protected", "function", "getExpirationTimestamp", "(", "$", "lifetimeInSeconds", "=", "false", ")", "{", "if", "(", "$", "lifetimeInSeconds", "===", "false", ")", "{", "$", "lifetimeInSeconds", "=", "$", "this", "->", "lifetime", ";", "}", "if", "(", "$", "lifetimeInSeconds", "===", "self", "::", "IMMORTAL_LIFETIME", ")", "{", "return", "false", ";", "}", "else", "{", "return", "date", "(", "self", "::", "MYSQL_TIMESTAMP", ",", "time", "(", ")", "+", "$", "lifetimeInSeconds", ")", ";", "}", "}" ]
Calculate the expiration timestamp @param integer|false $lifetimeInSeconds (Optional, defaults to `FALSE`) @return string|false Either a MySQL timestamp for the expiration date or `FALSE` if the lifetime was set to `IMMORTAL_LIFETIME`
[ "Calculate", "the", "expiration", "timestamp" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L358-L368
train
battis/simplecache
src/SimpleCache.php
SimpleCache.purgeExpired
public function purgeExpired() { if ($this->sqlInitialized()) { if ($this->sql) { if ($this->sql->query(" DELETE FROM `{$this->table}` WHERE `expire` < NOW() ")) { return true; } } } return false; }
php
public function purgeExpired() { if ($this->sqlInitialized()) { if ($this->sql) { if ($this->sql->query(" DELETE FROM `{$this->table}` WHERE `expire` < NOW() ")) { return true; } } } return false; }
[ "public", "function", "purgeExpired", "(", ")", "{", "if", "(", "$", "this", "->", "sqlInitialized", "(", ")", ")", "{", "if", "(", "$", "this", "->", "sql", ")", "{", "if", "(", "$", "this", "->", "sql", "->", "query", "(", "\"\n DELETE\n FROM `{$this->table}`\n WHERE `expire` < NOW()\n \"", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Purge expired cache data @return boolean Returns `TRUE` on success, `FALSE` on failure @see setLifetime() setLifetime()
[ "Purge", "expired", "cache", "data" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L377-L392
train
battis/simplecache
src/SimpleCache.php
SimpleCache.setCache
public function setCache($key, $data, $lifetimeInSeconds = false) { if ($this->sqlInitialized()) { if ($this->sql) { /* escape query data */ $_key = $this->sql->real_escape_string($key); $_data = $this->sql->real_escape_string(serialize($data)); $_expire = $this->getExpirationTimestamp($lifetimeInSeconds); $response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' "); if ($response->fetch_assoc()) { if ($this->sql->query(" UPDATE `{$this->table}` SET `{$this->cache}` = '$_data', `expire` = " . ($_expire === false ? 'NULL' : "'$_expire'") . " WHERE `{$this->key}` = '$_key' ")) { return true; } else { throw new SimpleCache_Exception( 'Could not update existing cache data. ' . $this->sql->error, SimpleCache_Exception::CACHE_WRITE ); } } elseif ($this->sql->query(" INSERT INTO `{$this->table}` ( `{$this->key}`, `{$this->cache}` " . ($_expire === false ? '' : ", `expire`") . " ) VALUES ( '$_key', '$_data' " . ($_expire === false ? '' : ", '$_expire'") . " ) ")) { return true; } else { throw new SimpleCache_Exception( 'Could not insert new cache data. ' . $this->sql->error, SimpleCache_Exception::CACHE_WRITE ); } } return false; } }
php
public function setCache($key, $data, $lifetimeInSeconds = false) { if ($this->sqlInitialized()) { if ($this->sql) { /* escape query data */ $_key = $this->sql->real_escape_string($key); $_data = $this->sql->real_escape_string(serialize($data)); $_expire = $this->getExpirationTimestamp($lifetimeInSeconds); $response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' "); if ($response->fetch_assoc()) { if ($this->sql->query(" UPDATE `{$this->table}` SET `{$this->cache}` = '$_data', `expire` = " . ($_expire === false ? 'NULL' : "'$_expire'") . " WHERE `{$this->key}` = '$_key' ")) { return true; } else { throw new SimpleCache_Exception( 'Could not update existing cache data. ' . $this->sql->error, SimpleCache_Exception::CACHE_WRITE ); } } elseif ($this->sql->query(" INSERT INTO `{$this->table}` ( `{$this->key}`, `{$this->cache}` " . ($_expire === false ? '' : ", `expire`") . " ) VALUES ( '$_key', '$_data' " . ($_expire === false ? '' : ", '$_expire'") . " ) ")) { return true; } else { throw new SimpleCache_Exception( 'Could not insert new cache data. ' . $this->sql->error, SimpleCache_Exception::CACHE_WRITE ); } } return false; } }
[ "public", "function", "setCache", "(", "$", "key", ",", "$", "data", ",", "$", "lifetimeInSeconds", "=", "false", ")", "{", "if", "(", "$", "this", "->", "sqlInitialized", "(", ")", ")", "{", "if", "(", "$", "this", "->", "sql", ")", "{", "/* escape query data */", "$", "_key", "=", "$", "this", "->", "sql", "->", "real_escape_string", "(", "$", "key", ")", ";", "$", "_data", "=", "$", "this", "->", "sql", "->", "real_escape_string", "(", "serialize", "(", "$", "data", ")", ")", ";", "$", "_expire", "=", "$", "this", "->", "getExpirationTimestamp", "(", "$", "lifetimeInSeconds", ")", ";", "$", "response", "=", "$", "this", "->", "sql", "->", "query", "(", "\"\n SELECT *\n FROM `{$this->table}`\n WHERE\n `{$this->key}` = '$_key'\n \"", ")", ";", "if", "(", "$", "response", "->", "fetch_assoc", "(", ")", ")", "{", "if", "(", "$", "this", "->", "sql", "->", "query", "(", "\"\n UPDATE\n `{$this->table}`\n SET\n `{$this->cache}` = '$_data',\n `expire` = \"", ".", "(", "$", "_expire", "===", "false", "?", "'NULL'", ":", "\"'$_expire'\"", ")", ".", "\"\n WHERE\n `{$this->key}` = '$_key'\n \"", ")", ")", "{", "return", "true", ";", "}", "else", "{", "throw", "new", "SimpleCache_Exception", "(", "'Could not update existing cache data. '", ".", "$", "this", "->", "sql", "->", "error", ",", "SimpleCache_Exception", "::", "CACHE_WRITE", ")", ";", "}", "}", "elseif", "(", "$", "this", "->", "sql", "->", "query", "(", "\"\n INSERT\n INTO `{$this->table}`\n (\n `{$this->key}`,\n `{$this->cache}`\n \"", ".", "(", "$", "_expire", "===", "false", "?", "''", ":", "\", `expire`\"", ")", ".", "\"\n ) VALUES (\n '$_key',\n '$_data'\n \"", ".", "(", "$", "_expire", "===", "false", "?", "''", ":", "\", '$_expire'\"", ")", ".", "\"\n )\n \"", ")", ")", "{", "return", "true", ";", "}", "else", "{", "throw", "new", "SimpleCache_Exception", "(", "'Could not insert new cache data. '", ".", "$", "this", "->", "sql", "->", "error", ",", "SimpleCache_Exception", "::", "CACHE_WRITE", ")", ";", "}", "}", "return", "false", ";", "}", "}" ]
Store data in cache @param string $key @param mixed $data Must be serializable @param int|false $lifetimeInSeconds (Optional) @return boolean Returns `TRUE` on success, `FALSE` on failure @see setLifetime() setLifetime()
[ "Store", "data", "in", "cache" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L405-L460
train
battis/simplecache
src/SimpleCache.php
SimpleCache.getCacheTimestamp
public function getCacheTimestamp($key) { if ($this->sqlInitialized()) { $_key = $this->sql->real_escape_string($key); if ($response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' ")) { if ($response->num_rows > 0) { return new \DateTime($response->fetch_assoc()['timestamp']); } } } return false; }
php
public function getCacheTimestamp($key) { if ($this->sqlInitialized()) { $_key = $this->sql->real_escape_string($key); if ($response = $this->sql->query(" SELECT * FROM `{$this->table}` WHERE `{$this->key}` = '$_key' ")) { if ($response->num_rows > 0) { return new \DateTime($response->fetch_assoc()['timestamp']); } } } return false; }
[ "public", "function", "getCacheTimestamp", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "sqlInitialized", "(", ")", ")", "{", "$", "_key", "=", "$", "this", "->", "sql", "->", "real_escape_string", "(", "$", "key", ")", ";", "if", "(", "$", "response", "=", "$", "this", "->", "sql", "->", "query", "(", "\"\n SELECT *\n FROM `{$this->table}`\n WHERE\n `{$this->key}` = '$_key'\n \"", ")", ")", "{", "if", "(", "$", "response", "->", "num_rows", ">", "0", ")", "{", "return", "new", "\\", "DateTime", "(", "$", "response", "->", "fetch_assoc", "(", ")", "[", "'timestamp'", "]", ")", ";", "}", "}", "}", "return", "false", ";", "}" ]
Get the timestamp of the cached data @param string $key @return \DateTime|boolean Returns `FALSE` on invalid key
[ "Get", "the", "timestamp", "of", "the", "cached", "data" ]
edda1bee5994fcc2a7b4a10e868d161d8dcddf3b
https://github.com/battis/simplecache/blob/edda1bee5994fcc2a7b4a10e868d161d8dcddf3b/src/SimpleCache.php#L492-L508
train
miguelibero/meinhof
src/Meinhof/Assetic/FormulaLoaderManager.php
FormulaLoaderManager.setLoaders
protected function setLoaders(array $loaders) { $this->loaders = array(); foreach ($loaders as $type=>$loader) { if (!$loader instanceof FormulaLoaderInterface) { throw new \InvalidArgumentException("Not a valid formula loader with key '${type}'."); } $this->setLoader($type, $loader); } }
php
protected function setLoaders(array $loaders) { $this->loaders = array(); foreach ($loaders as $type=>$loader) { if (!$loader instanceof FormulaLoaderInterface) { throw new \InvalidArgumentException("Not a valid formula loader with key '${type}'."); } $this->setLoader($type, $loader); } }
[ "protected", "function", "setLoaders", "(", "array", "$", "loaders", ")", "{", "$", "this", "->", "loaders", "=", "array", "(", ")", ";", "foreach", "(", "$", "loaders", "as", "$", "type", "=>", "$", "loader", ")", "{", "if", "(", "!", "$", "loader", "instanceof", "FormulaLoaderInterface", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Not a valid formula loader with key '${type}'.\"", ")", ";", "}", "$", "this", "->", "setLoader", "(", "$", "type", ",", "$", "loader", ")", ";", "}", "}" ]
Adds a list of loaders @param array $loaders list of loaders, the type should be the array key
[ "Adds", "a", "list", "of", "loaders" ]
3a090f08485dc0da3e27463cf349dba374201072
https://github.com/miguelibero/meinhof/blob/3a090f08485dc0da3e27463cf349dba374201072/src/Meinhof/Assetic/FormulaLoaderManager.php#L30-L39
train
ciims/ciims-modules-api
controllers/DefaultController.php
DefaultController.actionJsonProxyPost
public function actionJsonProxyPost() { $url = Cii::get($_POST, 'url', false); if ($url === false) throw new CHttpException(400, Yii::t('Api.index', 'Missing $_POST[url] parameter')); $hash = md5($url); $response = Yii::app()->cache->get('CiiMS::API::Proxy::'.$hash); if ($response == false) { $curl = new \Curl\Curl; $response = serialize($curl->get($url)); if ($curl->error) throw new CHttpException(500, Yii::t('Api.index', 'Failed to retrieve remote resource.')); $curl->close(); Yii::app()->cache->set('API::Proxy::'.$hash, $response, 600); } return unserialize($response); }
php
public function actionJsonProxyPost() { $url = Cii::get($_POST, 'url', false); if ($url === false) throw new CHttpException(400, Yii::t('Api.index', 'Missing $_POST[url] parameter')); $hash = md5($url); $response = Yii::app()->cache->get('CiiMS::API::Proxy::'.$hash); if ($response == false) { $curl = new \Curl\Curl; $response = serialize($curl->get($url)); if ($curl->error) throw new CHttpException(500, Yii::t('Api.index', 'Failed to retrieve remote resource.')); $curl->close(); Yii::app()->cache->set('API::Proxy::'.$hash, $response, 600); } return unserialize($response); }
[ "public", "function", "actionJsonProxyPost", "(", ")", "{", "$", "url", "=", "Cii", "::", "get", "(", "$", "_POST", ",", "'url'", ",", "false", ")", ";", "if", "(", "$", "url", "===", "false", ")", "throw", "new", "CHttpException", "(", "400", ",", "Yii", "::", "t", "(", "'Api.index'", ",", "'Missing $_POST[url] parameter'", ")", ")", ";", "$", "hash", "=", "md5", "(", "$", "url", ")", ";", "$", "response", "=", "Yii", "::", "app", "(", ")", "->", "cache", "->", "get", "(", "'CiiMS::API::Proxy::'", ".", "$", "hash", ")", ";", "if", "(", "$", "response", "==", "false", ")", "{", "$", "curl", "=", "new", "\\", "Curl", "\\", "Curl", ";", "$", "response", "=", "serialize", "(", "$", "curl", "->", "get", "(", "$", "url", ")", ")", ";", "if", "(", "$", "curl", "->", "error", ")", "throw", "new", "CHttpException", "(", "500", ",", "Yii", "::", "t", "(", "'Api.index'", ",", "'Failed to retrieve remote resource.'", ")", ")", ";", "$", "curl", "->", "close", "(", ")", ";", "Yii", "::", "app", "(", ")", "->", "cache", "->", "set", "(", "'API::Proxy::'", ".", "$", "hash", ",", "$", "response", ",", "600", ")", ";", "}", "return", "unserialize", "(", "$", "response", ")", ";", "}" ]
Global proxy for CiiMS to support JavaScript endpoints that either don't have proper CORS headers or SSL This endpoint will only process JSON, and will cache data for 10 minutes. @return mixed
[ "Global", "proxy", "for", "CiiMS", "to", "support", "JavaScript", "endpoints", "that", "either", "don", "t", "have", "proper", "CORS", "headers", "or", "SSL", "This", "endpoint", "will", "only", "process", "JSON", "and", "will", "cache", "data", "for", "10", "minutes", "." ]
4351855328da0b112ac27bde7e7e07e212be8689
https://github.com/ciims/ciims-modules-api/blob/4351855328da0b112ac27bde7e7e07e212be8689/controllers/DefaultController.php#L39-L63
train
staticka/staticka
src/Website.php
Website.compile
public function compile($output) { file_exists($output) || mkdir($output); $this->clear((string) $output); $this->output = (string) $output; foreach ((array) $this->pages as $page) { $folder = $this->folder($output, $page->uris()); $html = (string) $this->html($page); $path = $this->realpath($output . '/' . $folder); file_put_contents($path . 'index.html', $html); } return $this; }
php
public function compile($output) { file_exists($output) || mkdir($output); $this->clear((string) $output); $this->output = (string) $output; foreach ((array) $this->pages as $page) { $folder = $this->folder($output, $page->uris()); $html = (string) $this->html($page); $path = $this->realpath($output . '/' . $folder); file_put_contents($path . 'index.html', $html); } return $this; }
[ "public", "function", "compile", "(", "$", "output", ")", "{", "file_exists", "(", "$", "output", ")", "||", "mkdir", "(", "$", "output", ")", ";", "$", "this", "->", "clear", "(", "(", "string", ")", "$", "output", ")", ";", "$", "this", "->", "output", "=", "(", "string", ")", "$", "output", ";", "foreach", "(", "(", "array", ")", "$", "this", "->", "pages", "as", "$", "page", ")", "{", "$", "folder", "=", "$", "this", "->", "folder", "(", "$", "output", ",", "$", "page", "->", "uris", "(", ")", ")", ";", "$", "html", "=", "(", "string", ")", "$", "this", "->", "html", "(", "$", "page", ")", ";", "$", "path", "=", "$", "this", "->", "realpath", "(", "$", "output", ".", "'/'", ".", "$", "folder", ")", ";", "file_put_contents", "(", "$", "path", ".", "'index.html'", ",", "$", "html", ")", ";", "}", "return", "$", "this", ";", "}" ]
Compiles the specified pages into HTML output. @param string $output @return self
[ "Compiles", "the", "specified", "pages", "into", "HTML", "output", "." ]
6e3b814c391ed03b0bd409803e11579bae677ce4
https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Website.php#L70-L89
train
staticka/staticka
src/Website.php
Website.transfer
public function transfer($source, $path = null) { $path = $path === null ? $this->output : $path; $path = $this->realpath($path); $source = (string) $this->realpath($source); $directory = new \RecursiveDirectoryIterator($source, 4096); $iterator = new \RecursiveIteratorIterator($directory, 1); foreach ($iterator as $file) { $to = str_replace($source, $path, $from = $file->getRealPath()); $file->isDir() ? $this->transfer($from, $to) : copy($from, $to); } }
php
public function transfer($source, $path = null) { $path = $path === null ? $this->output : $path; $path = $this->realpath($path); $source = (string) $this->realpath($source); $directory = new \RecursiveDirectoryIterator($source, 4096); $iterator = new \RecursiveIteratorIterator($directory, 1); foreach ($iterator as $file) { $to = str_replace($source, $path, $from = $file->getRealPath()); $file->isDir() ? $this->transfer($from, $to) : copy($from, $to); } }
[ "public", "function", "transfer", "(", "$", "source", ",", "$", "path", "=", "null", ")", "{", "$", "path", "=", "$", "path", "===", "null", "?", "$", "this", "->", "output", ":", "$", "path", ";", "$", "path", "=", "$", "this", "->", "realpath", "(", "$", "path", ")", ";", "$", "source", "=", "(", "string", ")", "$", "this", "->", "realpath", "(", "$", "source", ")", ";", "$", "directory", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "source", ",", "4096", ")", ";", "$", "iterator", "=", "new", "\\", "RecursiveIteratorIterator", "(", "$", "directory", ",", "1", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "file", ")", "{", "$", "to", "=", "str_replace", "(", "$", "source", ",", "$", "path", ",", "$", "from", "=", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "$", "file", "->", "isDir", "(", ")", "?", "$", "this", "->", "transfer", "(", "$", "from", ",", "$", "to", ")", ":", "copy", "(", "$", "from", ",", "$", "to", ")", ";", "}", "}" ]
Transfers files from a directory into another path. @param string $source @param string|null $path @return void
[ "Transfers", "files", "from", "a", "directory", "into", "another", "path", "." ]
6e3b814c391ed03b0bd409803e11579bae677ce4
https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Website.php#L168-L185
train
staticka/staticka
src/Website.php
Website.clear
protected function clear($path) { $directory = new \RecursiveDirectoryIterator($path, 4096); $iterator = new \RecursiveIteratorIterator($directory, 2); foreach ($iterator as $file) { $git = strpos($file->getRealPath(), '.git') !== false; $path = (string) $file->getRealPath(); $git || ($file->isDir() ? rmdir($path) : unlink($path)); } }
php
protected function clear($path) { $directory = new \RecursiveDirectoryIterator($path, 4096); $iterator = new \RecursiveIteratorIterator($directory, 2); foreach ($iterator as $file) { $git = strpos($file->getRealPath(), '.git') !== false; $path = (string) $file->getRealPath(); $git || ($file->isDir() ? rmdir($path) : unlink($path)); } }
[ "protected", "function", "clear", "(", "$", "path", ")", "{", "$", "directory", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "path", ",", "4096", ")", ";", "$", "iterator", "=", "new", "\\", "RecursiveIteratorIterator", "(", "$", "directory", ",", "2", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "file", ")", "{", "$", "git", "=", "strpos", "(", "$", "file", "->", "getRealPath", "(", ")", ",", "'.git'", ")", "!==", "false", ";", "$", "path", "=", "(", "string", ")", "$", "file", "->", "getRealPath", "(", ")", ";", "$", "git", "||", "(", "$", "file", "->", "isDir", "(", ")", "?", "rmdir", "(", "$", "path", ")", ":", "unlink", "(", "$", "path", ")", ")", ";", "}", "}" ]
Removes the files recursively from the specified directory. @param string $path @return void
[ "Removes", "the", "files", "recursively", "from", "the", "specified", "directory", "." ]
6e3b814c391ed03b0bd409803e11579bae677ce4
https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Website.php#L193-L206
train
staticka/staticka
src/Website.php
Website.folder
protected function folder($output, array $uris) { $folder = (string) ''; foreach ((array) $uris as $uri) { $directory = $output . '/' . (string) $folder; file_exists($directory) ?: mkdir($directory); $folder === $uri ?: $folder .= '/' . $uri; } return $folder; }
php
protected function folder($output, array $uris) { $folder = (string) ''; foreach ((array) $uris as $uri) { $directory = $output . '/' . (string) $folder; file_exists($directory) ?: mkdir($directory); $folder === $uri ?: $folder .= '/' . $uri; } return $folder; }
[ "protected", "function", "folder", "(", "$", "output", ",", "array", "$", "uris", ")", "{", "$", "folder", "=", "(", "string", ")", "''", ";", "foreach", "(", "(", "array", ")", "$", "uris", "as", "$", "uri", ")", "{", "$", "directory", "=", "$", "output", ".", "'/'", ".", "(", "string", ")", "$", "folder", ";", "file_exists", "(", "$", "directory", ")", "?", ":", "mkdir", "(", "$", "directory", ")", ";", "$", "folder", "===", "$", "uri", "?", ":", "$", "folder", ".=", "'/'", ".", "$", "uri", ";", "}", "return", "$", "folder", ";", "}" ]
Returns the whole folder path based from specified URIs. Also creates the specified folder if it doesn't exists. @param string $output @param array $uris @return string
[ "Returns", "the", "whole", "folder", "path", "based", "from", "specified", "URIs", ".", "Also", "creates", "the", "specified", "folder", "if", "it", "doesn", "t", "exists", "." ]
6e3b814c391ed03b0bd409803e11579bae677ce4
https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Website.php#L216-L229
train
staticka/staticka
src/Website.php
Website.html
protected function html(Page $page) { $html = $this->content->make($content = $page->content()); if (($name = $page->layout()) !== null) { $data = array_merge($this->helpers(), (array) $page->data()); $layout = new Layout($this->renderer, $this, $data); $html = (string) $layout->render($name, (string) $content); } foreach ($this->filters as $filter) { $html = $filter->filter($html); } return $html; }
php
protected function html(Page $page) { $html = $this->content->make($content = $page->content()); if (($name = $page->layout()) !== null) { $data = array_merge($this->helpers(), (array) $page->data()); $layout = new Layout($this->renderer, $this, $data); $html = (string) $layout->render($name, (string) $content); } foreach ($this->filters as $filter) { $html = $filter->filter($html); } return $html; }
[ "protected", "function", "html", "(", "Page", "$", "page", ")", "{", "$", "html", "=", "$", "this", "->", "content", "->", "make", "(", "$", "content", "=", "$", "page", "->", "content", "(", ")", ")", ";", "if", "(", "(", "$", "name", "=", "$", "page", "->", "layout", "(", ")", ")", "!==", "null", ")", "{", "$", "data", "=", "array_merge", "(", "$", "this", "->", "helpers", "(", ")", ",", "(", "array", ")", "$", "page", "->", "data", "(", ")", ")", ";", "$", "layout", "=", "new", "Layout", "(", "$", "this", "->", "renderer", ",", "$", "this", ",", "$", "data", ")", ";", "$", "html", "=", "(", "string", ")", "$", "layout", "->", "render", "(", "$", "name", ",", "(", "string", ")", "$", "content", ")", ";", "}", "foreach", "(", "$", "this", "->", "filters", "as", "$", "filter", ")", "{", "$", "html", "=", "$", "filter", "->", "filter", "(", "$", "html", ")", ";", "}", "return", "$", "html", ";", "}" ]
Converts the specified page into HTML. @param \Staticka\Page $page @return string
[ "Converts", "the", "specified", "page", "into", "HTML", "." ]
6e3b814c391ed03b0bd409803e11579bae677ce4
https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Website.php#L237-L254
train
staticka/staticka
src/Website.php
Website.realpath
protected function realpath($folder) { $separator = (string) DIRECTORY_SEPARATOR; $search = array('\\', '/', (string) '\\\\'); $path = str_replace($search, $separator, $folder); file_exists($path) || mkdir((string) $path); $exists = in_array(substr($path, -1), $search); return $exists ? $path : $path . $separator; }
php
protected function realpath($folder) { $separator = (string) DIRECTORY_SEPARATOR; $search = array('\\', '/', (string) '\\\\'); $path = str_replace($search, $separator, $folder); file_exists($path) || mkdir((string) $path); $exists = in_array(substr($path, -1), $search); return $exists ? $path : $path . $separator; }
[ "protected", "function", "realpath", "(", "$", "folder", ")", "{", "$", "separator", "=", "(", "string", ")", "DIRECTORY_SEPARATOR", ";", "$", "search", "=", "array", "(", "'\\\\'", ",", "'/'", ",", "(", "string", ")", "'\\\\\\\\'", ")", ";", "$", "path", "=", "str_replace", "(", "$", "search", ",", "$", "separator", ",", "$", "folder", ")", ";", "file_exists", "(", "$", "path", ")", "||", "mkdir", "(", "(", "string", ")", "$", "path", ")", ";", "$", "exists", "=", "in_array", "(", "substr", "(", "$", "path", ",", "-", "1", ")", ",", "$", "search", ")", ";", "return", "$", "exists", "?", "$", "path", ":", "$", "path", ".", "$", "separator", ";", "}" ]
Replaces the slashes with the DIRECTORY_SEPARATOR. Also creates the directory if it doesn't exists. @param string $folder @return string
[ "Replaces", "the", "slashes", "with", "the", "DIRECTORY_SEPARATOR", ".", "Also", "creates", "the", "directory", "if", "it", "doesn", "t", "exists", "." ]
6e3b814c391ed03b0bd409803e11579bae677ce4
https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Website.php#L263-L276
train
RhubarbPHP/Scaffold.BackgroundTasks
docs/examples/Basic/SlowTask.php
SlowTask.execute
public function execute(callable $statusCallback) { for($this->iterations = 0; $this->iterations < 100; $this->iterations++){ usleep(100000); $statusCallback(new TaskStatus($this->iterations, "Busy bee...")); } }
php
public function execute(callable $statusCallback) { for($this->iterations = 0; $this->iterations < 100; $this->iterations++){ usleep(100000); $statusCallback(new TaskStatus($this->iterations, "Busy bee...")); } }
[ "public", "function", "execute", "(", "callable", "$", "statusCallback", ")", "{", "for", "(", "$", "this", "->", "iterations", "=", "0", ";", "$", "this", "->", "iterations", "<", "100", ";", "$", "this", "->", "iterations", "++", ")", "{", "usleep", "(", "100000", ")", ";", "$", "statusCallback", "(", "new", "TaskStatus", "(", "$", "this", "->", "iterations", ",", "\"Busy bee...\"", ")", ")", ";", "}", "}" ]
Executes the long running code. @param callable $statusCallback A callback providing the task with a means to report progress. A TaskStatus object should be passed. @return void
[ "Executes", "the", "long", "running", "code", "." ]
92a5feab27599288e8bf39deb522588115838904
https://github.com/RhubarbPHP/Scaffold.BackgroundTasks/blob/92a5feab27599288e8bf39deb522588115838904/docs/examples/Basic/SlowTask.php#L17-L24
train
SergioMadness/pwf-helpers
src/StringHelpers.php
StringHelpers.str2url
public static function str2url($str) { $str = self::rus2translit($str); $str = strtolower($str); $str = preg_replace('~[^-a-z0-9_]+~u', '-', $str); $str = trim($str, "-"); return $str; }
php
public static function str2url($str) { $str = self::rus2translit($str); $str = strtolower($str); $str = preg_replace('~[^-a-z0-9_]+~u', '-', $str); $str = trim($str, "-"); return $str; }
[ "public", "static", "function", "str2url", "(", "$", "str", ")", "{", "$", "str", "=", "self", "::", "rus2translit", "(", "$", "str", ")", ";", "$", "str", "=", "strtolower", "(", "$", "str", ")", ";", "$", "str", "=", "preg_replace", "(", "'~[^-a-z0-9_]+~u'", ",", "'-'", ",", "$", "str", ")", ";", "$", "str", "=", "trim", "(", "$", "str", ",", "\"-\"", ")", ";", "return", "$", "str", ";", "}" ]
String to url @param string $str @return string
[ "String", "to", "url" ]
d6cd44807c120356d60618cb08f237841c35e293
https://github.com/SergioMadness/pwf-helpers/blob/d6cd44807c120356d60618cb08f237841c35e293/src/StringHelpers.php#L89-L96
train
fulgurio/LightCMSBundle
Form/Handler/AdminPageHandler.php
AdminPageHandler.addSuffixNumber
protected function addSuffixNumber($slug, Page $page, $number = 0) { $slugTmp = $number > 0 ? $slug . $this->slugSuffixSeparator . $number : $slug; $parentFullpath = $page->getParent()->getFullpath(); $foundedPage = $this->doctrine->getRepository('FulgurioLightCMSBundle:Page')->findOneBy(array( 'fullpath' => ($parentFullpath !== '' ? ($parentFullpath . '/') : '') . $slugTmp )); if ($foundedPage && $foundedPage != $page) { return $this->addSuffixNumber($slug, $page, $number + 1); } return $slugTmp; }
php
protected function addSuffixNumber($slug, Page $page, $number = 0) { $slugTmp = $number > 0 ? $slug . $this->slugSuffixSeparator . $number : $slug; $parentFullpath = $page->getParent()->getFullpath(); $foundedPage = $this->doctrine->getRepository('FulgurioLightCMSBundle:Page')->findOneBy(array( 'fullpath' => ($parentFullpath !== '' ? ($parentFullpath . '/') : '') . $slugTmp )); if ($foundedPage && $foundedPage != $page) { return $this->addSuffixNumber($slug, $page, $number + 1); } return $slugTmp; }
[ "protected", "function", "addSuffixNumber", "(", "$", "slug", ",", "Page", "$", "page", ",", "$", "number", "=", "0", ")", "{", "$", "slugTmp", "=", "$", "number", ">", "0", "?", "$", "slug", ".", "$", "this", "->", "slugSuffixSeparator", ".", "$", "number", ":", "$", "slug", ";", "$", "parentFullpath", "=", "$", "page", "->", "getParent", "(", ")", "->", "getFullpath", "(", ")", ";", "$", "foundedPage", "=", "$", "this", "->", "doctrine", "->", "getRepository", "(", "'FulgurioLightCMSBundle:Page'", ")", "->", "findOneBy", "(", "array", "(", "'fullpath'", "=>", "(", "$", "parentFullpath", "!==", "''", "?", "(", "$", "parentFullpath", ".", "'/'", ")", ":", "''", ")", ".", "$", "slugTmp", ")", ")", ";", "if", "(", "$", "foundedPage", "&&", "$", "foundedPage", "!=", "$", "page", ")", "{", "return", "$", "this", "->", "addSuffixNumber", "(", "$", "slug", ",", "$", "page", ",", "$", "number", "+", "1", ")", ";", "}", "return", "$", "slugTmp", ";", "}" ]
Add suffix number if page exists @param string $slug @param Page $page @param number $number @return string
[ "Add", "suffix", "number", "if", "page", "exists" ]
66319af52b97b6552b7c391ee370538263f42d10
https://github.com/fulgurio/LightCMSBundle/blob/66319af52b97b6552b7c391ee370538263f42d10/Form/Handler/AdminPageHandler.php#L87-L99
train
fulgurio/LightCMSBundle
Form/Handler/AdminPageHandler.php
AdminPageHandler.makeFullpath
public function makeFullpath(Page $page) { if ($page->getParent() === NULL) { $page->setFullpath(''); $page->setSlug(''); } else { $parentFullpath = $page->getParent()->getFullpath(); $slug = $this->addSuffixNumber($page->getSlug(), $page); $page->setFullpath(($parentFullpath != '' ? ($parentFullpath . '/') : '') . $slug); $page->setSlug($slug); if ($page->hasChildren()) { foreach ($page->getChildren() as $children) { $this->makeFullpath($children); $this->doctrine->getManager()->persist($children); } } } }
php
public function makeFullpath(Page $page) { if ($page->getParent() === NULL) { $page->setFullpath(''); $page->setSlug(''); } else { $parentFullpath = $page->getParent()->getFullpath(); $slug = $this->addSuffixNumber($page->getSlug(), $page); $page->setFullpath(($parentFullpath != '' ? ($parentFullpath . '/') : '') . $slug); $page->setSlug($slug); if ($page->hasChildren()) { foreach ($page->getChildren() as $children) { $this->makeFullpath($children); $this->doctrine->getManager()->persist($children); } } } }
[ "public", "function", "makeFullpath", "(", "Page", "$", "page", ")", "{", "if", "(", "$", "page", "->", "getParent", "(", ")", "===", "NULL", ")", "{", "$", "page", "->", "setFullpath", "(", "''", ")", ";", "$", "page", "->", "setSlug", "(", "''", ")", ";", "}", "else", "{", "$", "parentFullpath", "=", "$", "page", "->", "getParent", "(", ")", "->", "getFullpath", "(", ")", ";", "$", "slug", "=", "$", "this", "->", "addSuffixNumber", "(", "$", "page", "->", "getSlug", "(", ")", ",", "$", "page", ")", ";", "$", "page", "->", "setFullpath", "(", "(", "$", "parentFullpath", "!=", "''", "?", "(", "$", "parentFullpath", ".", "'/'", ")", ":", "''", ")", ".", "$", "slug", ")", ";", "$", "page", "->", "setSlug", "(", "$", "slug", ")", ";", "if", "(", "$", "page", "->", "hasChildren", "(", ")", ")", "{", "foreach", "(", "$", "page", "->", "getChildren", "(", ")", "as", "$", "children", ")", "{", "$", "this", "->", "makeFullpath", "(", "$", "children", ")", ";", "$", "this", "->", "doctrine", "->", "getManager", "(", ")", "->", "persist", "(", "$", "children", ")", ";", "}", "}", "}", "}" ]
Init page full path and check if it doesn't already exist @param Page $page
[ "Init", "page", "full", "path", "and", "check", "if", "it", "doesn", "t", "already", "exist" ]
66319af52b97b6552b7c391ee370538263f42d10
https://github.com/fulgurio/LightCMSBundle/blob/66319af52b97b6552b7c391ee370538263f42d10/Form/Handler/AdminPageHandler.php#L106-L128
train
fulgurio/LightCMSBundle
Form/Handler/AdminPageHandler.php
AdminPageHandler.updatePageMenuPosition
private function updatePageMenuPosition(Page $page) { $pageMenuRepository = $this->doctrine->getRepository('FulgurioLightCMSBundle:PageMenu'); $em = $this->doctrine->getManager(); $data = $this->request->get('page'); if (isset($data['availableMenu'])) { if (!is_null($page->getId())) { $menus = $page->getMenu(); $alreadyInMenu = array(); foreach ($menus as $menu) { if (!in_array($menu->getLabel(), $data['availableMenu'])) { $pageMenuRepository->upMenuPagesPosition($menu->getLabel(), $menu->getPosition() + 1); $em->remove($menu); } else { $alreadyInMenu[] = $menu->getLabel(); } } } foreach ($data['availableMenu'] as $menuLabel) { // If it s a new page, or if it a page which we had a new menu if (!isset($alreadyInMenu) || !in_array($menuLabel, $alreadyInMenu)) { $menu = new PageMenu(); $menu->setPosition($pageMenuRepository->getNextMenuPosition($menuLabel)); $menu->setLabel($menuLabel); $menu->setPage($page); $em->persist($menu); } } } else if (!is_null($page->getId())) { $menus = $page->getMenu(); foreach ($menus as $menu) { $pageMenuRepository->upMenuPagesPosition($menu->getLabel(), $menu->getPosition() + 1); $em->remove($menu); } } }
php
private function updatePageMenuPosition(Page $page) { $pageMenuRepository = $this->doctrine->getRepository('FulgurioLightCMSBundle:PageMenu'); $em = $this->doctrine->getManager(); $data = $this->request->get('page'); if (isset($data['availableMenu'])) { if (!is_null($page->getId())) { $menus = $page->getMenu(); $alreadyInMenu = array(); foreach ($menus as $menu) { if (!in_array($menu->getLabel(), $data['availableMenu'])) { $pageMenuRepository->upMenuPagesPosition($menu->getLabel(), $menu->getPosition() + 1); $em->remove($menu); } else { $alreadyInMenu[] = $menu->getLabel(); } } } foreach ($data['availableMenu'] as $menuLabel) { // If it s a new page, or if it a page which we had a new menu if (!isset($alreadyInMenu) || !in_array($menuLabel, $alreadyInMenu)) { $menu = new PageMenu(); $menu->setPosition($pageMenuRepository->getNextMenuPosition($menuLabel)); $menu->setLabel($menuLabel); $menu->setPage($page); $em->persist($menu); } } } else if (!is_null($page->getId())) { $menus = $page->getMenu(); foreach ($menus as $menu) { $pageMenuRepository->upMenuPagesPosition($menu->getLabel(), $menu->getPosition() + 1); $em->remove($menu); } } }
[ "private", "function", "updatePageMenuPosition", "(", "Page", "$", "page", ")", "{", "$", "pageMenuRepository", "=", "$", "this", "->", "doctrine", "->", "getRepository", "(", "'FulgurioLightCMSBundle:PageMenu'", ")", ";", "$", "em", "=", "$", "this", "->", "doctrine", "->", "getManager", "(", ")", ";", "$", "data", "=", "$", "this", "->", "request", "->", "get", "(", "'page'", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "'availableMenu'", "]", ")", ")", "{", "if", "(", "!", "is_null", "(", "$", "page", "->", "getId", "(", ")", ")", ")", "{", "$", "menus", "=", "$", "page", "->", "getMenu", "(", ")", ";", "$", "alreadyInMenu", "=", "array", "(", ")", ";", "foreach", "(", "$", "menus", "as", "$", "menu", ")", "{", "if", "(", "!", "in_array", "(", "$", "menu", "->", "getLabel", "(", ")", ",", "$", "data", "[", "'availableMenu'", "]", ")", ")", "{", "$", "pageMenuRepository", "->", "upMenuPagesPosition", "(", "$", "menu", "->", "getLabel", "(", ")", ",", "$", "menu", "->", "getPosition", "(", ")", "+", "1", ")", ";", "$", "em", "->", "remove", "(", "$", "menu", ")", ";", "}", "else", "{", "$", "alreadyInMenu", "[", "]", "=", "$", "menu", "->", "getLabel", "(", ")", ";", "}", "}", "}", "foreach", "(", "$", "data", "[", "'availableMenu'", "]", "as", "$", "menuLabel", ")", "{", "// If it s a new page, or if it a page which we had a new menu", "if", "(", "!", "isset", "(", "$", "alreadyInMenu", ")", "||", "!", "in_array", "(", "$", "menuLabel", ",", "$", "alreadyInMenu", ")", ")", "{", "$", "menu", "=", "new", "PageMenu", "(", ")", ";", "$", "menu", "->", "setPosition", "(", "$", "pageMenuRepository", "->", "getNextMenuPosition", "(", "$", "menuLabel", ")", ")", ";", "$", "menu", "->", "setLabel", "(", "$", "menuLabel", ")", ";", "$", "menu", "->", "setPage", "(", "$", "page", ")", ";", "$", "em", "->", "persist", "(", "$", "menu", ")", ";", "}", "}", "}", "else", "if", "(", "!", "is_null", "(", "$", "page", "->", "getId", "(", ")", ")", ")", "{", "$", "menus", "=", "$", "page", "->", "getMenu", "(", ")", ";", "foreach", "(", "$", "menus", "as", "$", "menu", ")", "{", "$", "pageMenuRepository", "->", "upMenuPagesPosition", "(", "$", "menu", "->", "getLabel", "(", ")", ",", "$", "menu", "->", "getPosition", "(", ")", "+", "1", ")", ";", "$", "em", "->", "remove", "(", "$", "menu", ")", ";", "}", "}", "}" ]
Update page menu position @param Page $page
[ "Update", "page", "menu", "position" ]
66319af52b97b6552b7c391ee370538263f42d10
https://github.com/fulgurio/LightCMSBundle/blob/66319af52b97b6552b7c391ee370538263f42d10/Form/Handler/AdminPageHandler.php#L154-L200
train
fulgurio/LightCMSBundle
Form/Handler/AdminPageHandler.php
AdminPageHandler.initMetaEntity
final public function initMetaEntity(Page $page, $metaName, $metaValue) { $this->initPageMetas($page); if (isset($this->pageMetas[$metaName])) { $entity = $this->pageMetas[$metaName]; } else { $entity = new PageMeta(); $entity->setPage($page); $entity->setMetaKey($metaName); } $entity->setMetaValue($metaValue); return $entity; }
php
final public function initMetaEntity(Page $page, $metaName, $metaValue) { $this->initPageMetas($page); if (isset($this->pageMetas[$metaName])) { $entity = $this->pageMetas[$metaName]; } else { $entity = new PageMeta(); $entity->setPage($page); $entity->setMetaKey($metaName); } $entity->setMetaValue($metaValue); return $entity; }
[ "final", "public", "function", "initMetaEntity", "(", "Page", "$", "page", ",", "$", "metaName", ",", "$", "metaValue", ")", "{", "$", "this", "->", "initPageMetas", "(", "$", "page", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "pageMetas", "[", "$", "metaName", "]", ")", ")", "{", "$", "entity", "=", "$", "this", "->", "pageMetas", "[", "$", "metaName", "]", ";", "}", "else", "{", "$", "entity", "=", "new", "PageMeta", "(", ")", ";", "$", "entity", "->", "setPage", "(", "$", "page", ")", ";", "$", "entity", "->", "setMetaKey", "(", "$", "metaName", ")", ";", "}", "$", "entity", "->", "setMetaValue", "(", "$", "metaValue", ")", ";", "return", "$", "entity", ";", "}" ]
Add or update a PageMeta entity, and return it for save @param Page $page @param string $metaName @param string $metaValue @return \Fulgurio\LightCMSBundle\Entity\PageMeta
[ "Add", "or", "update", "a", "PageMeta", "entity", "and", "return", "it", "for", "save" ]
66319af52b97b6552b7c391ee370538263f42d10
https://github.com/fulgurio/LightCMSBundle/blob/66319af52b97b6552b7c391ee370538263f42d10/Form/Handler/AdminPageHandler.php#L210-L225
train
fulgurio/LightCMSBundle
Form/Handler/AdminPageHandler.php
AdminPageHandler.initPageMetas
final protected function initPageMetas(Page $page) { if (!isset($this->pageMetas)) { $this->pageMetas = array(); if ($page->getId() > 0) { $metas = $this->doctrine->getRepository('FulgurioLightCMSBundle:PageMeta')->findByPage($page->getId()); foreach ($metas as $meta) { $this->pageMetas[$meta->getMetaKey()] = $meta; } } } }
php
final protected function initPageMetas(Page $page) { if (!isset($this->pageMetas)) { $this->pageMetas = array(); if ($page->getId() > 0) { $metas = $this->doctrine->getRepository('FulgurioLightCMSBundle:PageMeta')->findByPage($page->getId()); foreach ($metas as $meta) { $this->pageMetas[$meta->getMetaKey()] = $meta; } } } }
[ "final", "protected", "function", "initPageMetas", "(", "Page", "$", "page", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "pageMetas", ")", ")", "{", "$", "this", "->", "pageMetas", "=", "array", "(", ")", ";", "if", "(", "$", "page", "->", "getId", "(", ")", ">", "0", ")", "{", "$", "metas", "=", "$", "this", "->", "doctrine", "->", "getRepository", "(", "'FulgurioLightCMSBundle:PageMeta'", ")", "->", "findByPage", "(", "$", "page", "->", "getId", "(", ")", ")", ";", "foreach", "(", "$", "metas", "as", "$", "meta", ")", "{", "$", "this", "->", "pageMetas", "[", "$", "meta", "->", "getMetaKey", "(", ")", "]", "=", "$", "meta", ";", "}", "}", "}", "}" ]
Init page meta of page @param Page $page
[ "Init", "page", "meta", "of", "page" ]
66319af52b97b6552b7c391ee370538263f42d10
https://github.com/fulgurio/LightCMSBundle/blob/66319af52b97b6552b7c391ee370538263f42d10/Form/Handler/AdminPageHandler.php#L232-L246
train
prolic/HumusMvc
src/HumusMvc/Controller/Action/HelperPluginManager.php
HelperPluginManager.getClassName
public function getClassName($name) { if (!$this->has($name)) { return false; } $helper = $this->get($name); return get_class($helper); }
php
public function getClassName($name) { if (!$this->has($name)) { return false; } $helper = $this->get($name); return get_class($helper); }
[ "public", "function", "getClassName", "(", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "name", ")", ")", "{", "return", "false", ";", "}", "$", "helper", "=", "$", "this", "->", "get", "(", "$", "name", ")", ";", "return", "get_class", "(", "$", "helper", ")", ";", "}" ]
Return full class name for a named helper @param string $name @return string|false
[ "Return", "full", "class", "name", "for", "a", "named", "helper" ]
09e8c6422d84b57745cc643047e10761be2a21a7
https://github.com/prolic/HumusMvc/blob/09e8c6422d84b57745cc643047e10761be2a21a7/src/HumusMvc/Controller/Action/HelperPluginManager.php#L114-L121
train
itcreator/custom-cmf
Module/Component/src/Cmf/Component/Grid/Pager/Adapter/Traversable.php
Traversable.getItems
public function getItems($offset, $limit, $sort = null) { $items = []; $cnt = count($this->rawData); for ($i = $offset; $i < $offset + $limit && $i < $cnt; $i++) { $items[] = $this->rawData[$i]; } return $items; }
php
public function getItems($offset, $limit, $sort = null) { $items = []; $cnt = count($this->rawData); for ($i = $offset; $i < $offset + $limit && $i < $cnt; $i++) { $items[] = $this->rawData[$i]; } return $items; }
[ "public", "function", "getItems", "(", "$", "offset", ",", "$", "limit", ",", "$", "sort", "=", "null", ")", "{", "$", "items", "=", "[", "]", ";", "$", "cnt", "=", "count", "(", "$", "this", "->", "rawData", ")", ";", "for", "(", "$", "i", "=", "$", "offset", ";", "$", "i", "<", "$", "offset", "+", "$", "limit", "&&", "$", "i", "<", "$", "cnt", ";", "$", "i", "++", ")", "{", "$", "items", "[", "]", "=", "$", "this", "->", "rawData", "[", "$", "i", "]", ";", "}", "return", "$", "items", ";", "}" ]
This method return an collection of items for a page. @param integer $offset @param integer $limit @param \Cmf\System\Sort $sort @return array
[ "This", "method", "return", "an", "collection", "of", "items", "for", "a", "page", "." ]
42fc0535dfa0f641856f06673f6ab596b2020c40
https://github.com/itcreator/custom-cmf/blob/42fc0535dfa0f641856f06673f6ab596b2020c40/Module/Component/src/Cmf/Component/Grid/Pager/Adapter/Traversable.php#L35-L44
train
khelonium/refactoring-time
src/Refactoring/Time/Interval.php
Interval.overlaps
public function overlaps(IntervalInterface $interval) { $startDate = $interval->getStart(); $endDate = $interval->getEnd(); return $this->checkOverlaping($startDate, $endDate); }
php
public function overlaps(IntervalInterface $interval) { $startDate = $interval->getStart(); $endDate = $interval->getEnd(); return $this->checkOverlaping($startDate, $endDate); }
[ "public", "function", "overlaps", "(", "IntervalInterface", "$", "interval", ")", "{", "$", "startDate", "=", "$", "interval", "->", "getStart", "(", ")", ";", "$", "endDate", "=", "$", "interval", "->", "getEnd", "(", ")", ";", "return", "$", "this", "->", "checkOverlaping", "(", "$", "startDate", ",", "$", "endDate", ")", ";", "}" ]
Checks if the interval overlaps another interval @param IntervalInterface $interval @return bool true if overal occurs
[ "Checks", "if", "the", "interval", "overlaps", "another", "interval" ]
6fad6a2ea329167789b09898dcf8e0b11db33109
https://github.com/khelonium/refactoring-time/blob/6fad6a2ea329167789b09898dcf8e0b11db33109/src/Refactoring/Time/Interval.php#L47-L53
train
khelonium/refactoring-time
src/Refactoring/Time/Interval.php
Interval.toArray
public function toArray() { $start = $this->intervalStart; $end = $this->intervalEnd; $period = new \DatePeriod($start, new \DateInterval('P1D'), $end); $days = array(); foreach ($period as $current_day) { $days[] = $current_day; } $days[] = $end; return $days; }
php
public function toArray() { $start = $this->intervalStart; $end = $this->intervalEnd; $period = new \DatePeriod($start, new \DateInterval('P1D'), $end); $days = array(); foreach ($period as $current_day) { $days[] = $current_day; } $days[] = $end; return $days; }
[ "public", "function", "toArray", "(", ")", "{", "$", "start", "=", "$", "this", "->", "intervalStart", ";", "$", "end", "=", "$", "this", "->", "intervalEnd", ";", "$", "period", "=", "new", "\\", "DatePeriod", "(", "$", "start", ",", "new", "\\", "DateInterval", "(", "'P1D'", ")", ",", "$", "end", ")", ";", "$", "days", "=", "array", "(", ")", ";", "foreach", "(", "$", "period", "as", "$", "current_day", ")", "{", "$", "days", "[", "]", "=", "$", "current_day", ";", "}", "$", "days", "[", "]", "=", "$", "end", ";", "return", "$", "days", ";", "}" ]
Array of \DateTime objects
[ "Array", "of", "\\", "DateTime", "objects" ]
6fad6a2ea329167789b09898dcf8e0b11db33109
https://github.com/khelonium/refactoring-time/blob/6fad6a2ea329167789b09898dcf8e0b11db33109/src/Refactoring/Time/Interval.php#L141-L155
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.initializeAttributeOnData
protected function initializeAttributeOnData( $attribute ) { $explicitPath = $this->getLeadingExplicitAttributePath( $attribute ); $data = $this->extractDataFromPath( $explicitPath ); if ( !Str::contains( $attribute, '*' ) || Str::endsWith( $attribute, '*' ) ) { return $data; } return data_set( $data, $attribute, null, true ); }
php
protected function initializeAttributeOnData( $attribute ) { $explicitPath = $this->getLeadingExplicitAttributePath( $attribute ); $data = $this->extractDataFromPath( $explicitPath ); if ( !Str::contains( $attribute, '*' ) || Str::endsWith( $attribute, '*' ) ) { return $data; } return data_set( $data, $attribute, null, true ); }
[ "protected", "function", "initializeAttributeOnData", "(", "$", "attribute", ")", "{", "$", "explicitPath", "=", "$", "this", "->", "getLeadingExplicitAttributePath", "(", "$", "attribute", ")", ";", "$", "data", "=", "$", "this", "->", "extractDataFromPath", "(", "$", "explicitPath", ")", ";", "if", "(", "!", "Str", "::", "contains", "(", "$", "attribute", ",", "'*'", ")", "||", "Str", "::", "endsWith", "(", "$", "attribute", ",", "'*'", ")", ")", "{", "return", "$", "data", ";", "}", "return", "data_set", "(", "$", "data", ",", "$", "attribute", ",", "null", ",", "true", ")", ";", "}" ]
Gather a copy of the attribute data filled with any missing attributes. @param string $attribute @return array
[ "Gather", "a", "copy", "of", "the", "attribute", "data", "filled", "with", "any", "missing", "attributes", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L354-L366
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.shouldStopValidating
protected function shouldStopValidating( $attribute ) { if ( !$this->hasRule( $attribute, ['Bail'] ) ) { return false; } return $this->messages->has( $attribute ); }
php
protected function shouldStopValidating( $attribute ) { if ( !$this->hasRule( $attribute, ['Bail'] ) ) { return false; } return $this->messages->has( $attribute ); }
[ "protected", "function", "shouldStopValidating", "(", "$", "attribute", ")", "{", "if", "(", "!", "$", "this", "->", "hasRule", "(", "$", "attribute", ",", "[", "'Bail'", "]", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "messages", "->", "has", "(", "$", "attribute", ")", ";", "}" ]
Stop on error if "bail" rule is assigned and attribute has a message. @param string $attribute @return bool
[ "Stop", "on", "error", "if", "bail", "rule", "is", "assigned", "and", "attribute", "has", "a", "message", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L695-L703
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.validateArray
protected function validateArray( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || is_array( $value ); }
php
protected function validateArray( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || is_array( $value ); }
[ "protected", "function", "validateArray", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "hasAttribute", "(", "$", "attribute", ")", ")", "{", "return", "true", ";", "}", "return", "is_null", "(", "$", "value", ")", "||", "is_array", "(", "$", "value", ")", ";", "}" ]
Validate that an attribute is an array. @param string $attribute @param mixed $value @return bool
[ "Validate", "that", "an", "attribute", "is", "an", "array", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L1050-L1058
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.validateInteger
protected function validateInteger( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || filter_var( $value, FILTER_VALIDATE_INT ) !== false; }
php
protected function validateInteger( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || filter_var( $value, FILTER_VALIDATE_INT ) !== false; }
[ "protected", "function", "validateInteger", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "hasAttribute", "(", "$", "attribute", ")", ")", "{", "return", "true", ";", "}", "return", "is_null", "(", "$", "value", ")", "||", "filter_var", "(", "$", "value", ",", "FILTER_VALIDATE_INT", ")", "!==", "false", ";", "}" ]
Validate that an attribute is an integer. @param string $attribute @param mixed $value @return bool
[ "Validate", "that", "an", "attribute", "is", "an", "integer", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L1086-L1094
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.validateNumeric
protected function validateNumeric( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || is_numeric( $value ); }
php
protected function validateNumeric( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || is_numeric( $value ); }
[ "protected", "function", "validateNumeric", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "hasAttribute", "(", "$", "attribute", ")", ")", "{", "return", "true", ";", "}", "return", "is_null", "(", "$", "value", ")", "||", "is_numeric", "(", "$", "value", ")", ";", "}" ]
Validate that an attribute is numeric. @param string $attribute @param mixed $value @return bool
[ "Validate", "that", "an", "attribute", "is", "numeric", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L1103-L1111
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.validateString
protected function validateString( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || is_string( $value ); }
php
protected function validateString( $attribute, $value ) { if ( !$this->hasAttribute( $attribute ) ) { return true; } return is_null( $value ) || is_string( $value ); }
[ "protected", "function", "validateString", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "hasAttribute", "(", "$", "attribute", ")", ")", "{", "return", "true", ";", "}", "return", "is_null", "(", "$", "value", ")", "||", "is_string", "(", "$", "value", ")", ";", "}" ]
Validate that an attribute is a string. @param string $attribute @param mixed $value @return bool
[ "Validate", "that", "an", "attribute", "is", "a", "string", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L1120-L1128
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.validateActiveUrl
protected function validateActiveUrl( $attribute, $value ) { if ( !is_string( $value ) ) { return false; } if ( $url = parse_url( $value, PHP_URL_HOST ) ) { return count( dns_get_record( $url, DNS_A | DNS_AAAA ) ) > 0; } return false; }
php
protected function validateActiveUrl( $attribute, $value ) { if ( !is_string( $value ) ) { return false; } if ( $url = parse_url( $value, PHP_URL_HOST ) ) { return count( dns_get_record( $url, DNS_A | DNS_AAAA ) ) > 0; } return false; }
[ "protected", "function", "validateActiveUrl", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "url", "=", "parse_url", "(", "$", "value", ",", "PHP_URL_HOST", ")", ")", "{", "return", "count", "(", "dns_get_record", "(", "$", "url", ",", "DNS_A", "|", "DNS_AAAA", ")", ")", ">", "0", ";", "}", "return", "false", ";", "}" ]
Validate that an attribute is an active URL. @param string $attribute @param mixed $value @return bool
[ "Validate", "that", "an", "attribute", "is", "an", "active", "URL", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L1591-L1604
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.validateAlphaNum
protected function validateAlphaNum( $attribute, $value ) { if ( !is_string( $value ) && !is_numeric( $value ) ) { return false; } return preg_match( '/^[\pL\pM\pN]+$/u', $value ); }
php
protected function validateAlphaNum( $attribute, $value ) { if ( !is_string( $value ) && !is_numeric( $value ) ) { return false; } return preg_match( '/^[\pL\pM\pN]+$/u', $value ); }
[ "protected", "function", "validateAlphaNum", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", "&&", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "return", "preg_match", "(", "'/^[\\pL\\pM\\pN]+$/u'", ",", "$", "value", ")", ";", "}" ]
Validate that an attribute contains only alpha-numeric characters. @param string $attribute @param mixed $value @return bool
[ "Validate", "that", "an", "attribute", "contains", "only", "alpha", "-", "numeric", "characters", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L1737-L1745
train
PenoaksDev/Milky-Framework
src/Milky/Validation/Validator.php
Validator.validateAlphaDash
protected function validateAlphaDash( $attribute, $value ) { if ( !is_string( $value ) && !is_numeric( $value ) ) { return false; } return preg_match( '/^[\pL\pM\pN_-]+$/u', $value ); }
php
protected function validateAlphaDash( $attribute, $value ) { if ( !is_string( $value ) && !is_numeric( $value ) ) { return false; } return preg_match( '/^[\pL\pM\pN_-]+$/u', $value ); }
[ "protected", "function", "validateAlphaDash", "(", "$", "attribute", ",", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", "&&", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "return", "preg_match", "(", "'/^[\\pL\\pM\\pN_-]+$/u'", ",", "$", "value", ")", ";", "}" ]
Validate that an attribute contains only alpha-numeric characters, dashes, and underscores. @param string $attribute @param mixed $value @return bool
[ "Validate", "that", "an", "attribute", "contains", "only", "alpha", "-", "numeric", "characters", "dashes", "and", "underscores", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Validation/Validator.php#L1754-L1762
train
Codifico/phpspec-rest-view-extension
features/bootstrap/FeatureContext.php
FeatureContext.iRunPhpspec
public function iRunPhpspec($argumentsString = '') { $argumentsString = strtr($argumentsString, array('\'' => '"')); $this->process->setWorkingDirectory($this->workingDir); $this->process->setCommandLine( sprintf( '%s %s %s --no-interaction', $this->phpBin, escapeshellarg($this->getPhpspecBinPath()), $argumentsString ) ); $this->process->start(); $this->process->wait(); }
php
public function iRunPhpspec($argumentsString = '') { $argumentsString = strtr($argumentsString, array('\'' => '"')); $this->process->setWorkingDirectory($this->workingDir); $this->process->setCommandLine( sprintf( '%s %s %s --no-interaction', $this->phpBin, escapeshellarg($this->getPhpspecBinPath()), $argumentsString ) ); $this->process->start(); $this->process->wait(); }
[ "public", "function", "iRunPhpspec", "(", "$", "argumentsString", "=", "''", ")", "{", "$", "argumentsString", "=", "strtr", "(", "$", "argumentsString", ",", "array", "(", "'\\''", "=>", "'\"'", ")", ")", ";", "$", "this", "->", "process", "->", "setWorkingDirectory", "(", "$", "this", "->", "workingDir", ")", ";", "$", "this", "->", "process", "->", "setCommandLine", "(", "sprintf", "(", "'%s %s %s --no-interaction'", ",", "$", "this", "->", "phpBin", ",", "escapeshellarg", "(", "$", "this", "->", "getPhpspecBinPath", "(", ")", ")", ",", "$", "argumentsString", ")", ")", ";", "$", "this", "->", "process", "->", "start", "(", ")", ";", "$", "this", "->", "process", "->", "wait", "(", ")", ";", "}" ]
Runs phpspec command with provided parameters @When /^I run "phpspec(?: ((?:\"|[^"])*))?"$/ @param string $argumentsString
[ "Runs", "phpspec", "command", "with", "provided", "parameters" ]
2528f20e648f887a14ec94bafe486246d7deefb8
https://github.com/Codifico/phpspec-rest-view-extension/blob/2528f20e648f887a14ec94bafe486246d7deefb8/features/bootstrap/FeatureContext.php#L144-L159
train
Wedeto/Util
src/Validation/Validator.php
Validator.filter
public function filter($value) { $filtered = null; if (!$this->validate($value, $filtered)) { throw new \InvalidArgumentException( "Not a valid value for " . $this->__toString() . ": " . WF::str($value) ); } return $filtered; }
php
public function filter($value) { $filtered = null; if (!$this->validate($value, $filtered)) { throw new \InvalidArgumentException( "Not a valid value for " . $this->__toString() . ": " . WF::str($value) ); } return $filtered; }
[ "public", "function", "filter", "(", "$", "value", ")", "{", "$", "filtered", "=", "null", ";", "if", "(", "!", "$", "this", "->", "validate", "(", "$", "value", ",", "$", "filtered", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Not a valid value for \"", ".", "$", "this", "->", "__toString", "(", ")", ".", "\": \"", ".", "WF", "::", "str", "(", "$", "value", ")", ")", ";", "}", "return", "$", "filtered", ";", "}" ]
Return a properly typed value @param mixed $value The value to match and correct @return mixed The filtered value @throws InvalidArgumentException When the value is incompatible
[ "Return", "a", "properly", "typed", "value" ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Validation/Validator.php#L109-L120
train
Wedeto/Util
src/Validation/Validator.php
Validator.validate
public function validate($value, &$filtered = null) { $this->error = null; if ($value === null) return $this->options['nullable'] ?? false; $filtered = $value; if ($this->type === Validator::EXISTS) return true; $o = $this->options; if ($this->type !== Validator::VALIDATE_CUSTOM && !$this->matchType($value, $filtered)) return false; if (isset($o['custom']) && is_callable($o['custom'])) { try { $valid = $o['custom']($value); if (!is_bool($valid)) throw new \RuntimeException("Validator did not return boolean: " . WF::str($valid)); } catch (ValidationException $e) { $this->error = $e->getError(); $valid = false; } return $valid; } return true; }
php
public function validate($value, &$filtered = null) { $this->error = null; if ($value === null) return $this->options['nullable'] ?? false; $filtered = $value; if ($this->type === Validator::EXISTS) return true; $o = $this->options; if ($this->type !== Validator::VALIDATE_CUSTOM && !$this->matchType($value, $filtered)) return false; if (isset($o['custom']) && is_callable($o['custom'])) { try { $valid = $o['custom']($value); if (!is_bool($valid)) throw new \RuntimeException("Validator did not return boolean: " . WF::str($valid)); } catch (ValidationException $e) { $this->error = $e->getError(); $valid = false; } return $valid; } return true; }
[ "public", "function", "validate", "(", "$", "value", ",", "&", "$", "filtered", "=", "null", ")", "{", "$", "this", "->", "error", "=", "null", ";", "if", "(", "$", "value", "===", "null", ")", "return", "$", "this", "->", "options", "[", "'nullable'", "]", "??", "false", ";", "$", "filtered", "=", "$", "value", ";", "if", "(", "$", "this", "->", "type", "===", "Validator", "::", "EXISTS", ")", "return", "true", ";", "$", "o", "=", "$", "this", "->", "options", ";", "if", "(", "$", "this", "->", "type", "!==", "Validator", "::", "VALIDATE_CUSTOM", "&&", "!", "$", "this", "->", "matchType", "(", "$", "value", ",", "$", "filtered", ")", ")", "return", "false", ";", "if", "(", "isset", "(", "$", "o", "[", "'custom'", "]", ")", "&&", "is_callable", "(", "$", "o", "[", "'custom'", "]", ")", ")", "{", "try", "{", "$", "valid", "=", "$", "o", "[", "'custom'", "]", "(", "$", "value", ")", ";", "if", "(", "!", "is_bool", "(", "$", "valid", ")", ")", "throw", "new", "\\", "RuntimeException", "(", "\"Validator did not return boolean: \"", ".", "WF", "::", "str", "(", "$", "valid", ")", ")", ";", "}", "catch", "(", "ValidationException", "$", "e", ")", "{", "$", "this", "->", "error", "=", "$", "e", "->", "getError", "(", ")", ";", "$", "valid", "=", "false", ";", "}", "return", "$", "valid", ";", "}", "return", "true", ";", "}" ]
Check if the value matches the expected value @param mixed $value @return bool True if the value matches all constraints, false if it does not
[ "Check", "if", "the", "value", "matches", "the", "expected", "value" ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Validation/Validator.php#L127-L159
train
Wedeto/Util
src/Validation/Validator.php
Validator.numRangeCheck
protected function numRangeCheck($value, $min, $max) { if ($min !== null && $value < $min) return false; if ($max !== null && $value > $max) return false; return true; }
php
protected function numRangeCheck($value, $min, $max) { if ($min !== null && $value < $min) return false; if ($max !== null && $value > $max) return false; return true; }
[ "protected", "function", "numRangeCheck", "(", "$", "value", ",", "$", "min", ",", "$", "max", ")", "{", "if", "(", "$", "min", "!==", "null", "&&", "$", "value", "<", "$", "min", ")", "return", "false", ";", "if", "(", "$", "max", "!==", "null", "&&", "$", "value", ">", "$", "max", ")", "return", "false", ";", "return", "true", ";", "}" ]
Check if the numeric value is between the configured minimum and maximum @param numeric $value The value to compare @param numeric $min The minimum value @param numeric $max The maximum value @return bool True when the value is in range, false if it is out of range
[ "Check", "if", "the", "numeric", "value", "is", "between", "the", "configured", "minimum", "and", "maximum" ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Validation/Validator.php#L284-L291
train
ARCANESOFT/Backups
src/Http/Routes/StatusesRoutes.php
StatusesRoutes.map
public function map() { $this->prefix('statuses')->as('statuses.')->group(function () { $this->get('/', 'StatusesController@index') ->name('index'); // admin::backups.statuses.index $this->post('backup', 'StatusesController@backup') ->middleware('ajax') ->name('backup'); // admin::backups.statuses.backup $this->post('clear', 'StatusesController@clear') ->middleware('ajax') ->name('clear'); // admin::backups.statuses.clear $this->get('{index}', 'StatusesController@show') ->name('show'); // admin::backups.statuses.clear }); }
php
public function map() { $this->prefix('statuses')->as('statuses.')->group(function () { $this->get('/', 'StatusesController@index') ->name('index'); // admin::backups.statuses.index $this->post('backup', 'StatusesController@backup') ->middleware('ajax') ->name('backup'); // admin::backups.statuses.backup $this->post('clear', 'StatusesController@clear') ->middleware('ajax') ->name('clear'); // admin::backups.statuses.clear $this->get('{index}', 'StatusesController@show') ->name('show'); // admin::backups.statuses.clear }); }
[ "public", "function", "map", "(", ")", "{", "$", "this", "->", "prefix", "(", "'statuses'", ")", "->", "as", "(", "'statuses.'", ")", "->", "group", "(", "function", "(", ")", "{", "$", "this", "->", "get", "(", "'/'", ",", "'StatusesController@index'", ")", "->", "name", "(", "'index'", ")", ";", "// admin::backups.statuses.index", "$", "this", "->", "post", "(", "'backup'", ",", "'StatusesController@backup'", ")", "->", "middleware", "(", "'ajax'", ")", "->", "name", "(", "'backup'", ")", ";", "// admin::backups.statuses.backup", "$", "this", "->", "post", "(", "'clear'", ",", "'StatusesController@clear'", ")", "->", "middleware", "(", "'ajax'", ")", "->", "name", "(", "'clear'", ")", ";", "// admin::backups.statuses.clear", "$", "this", "->", "get", "(", "'{index}'", ",", "'StatusesController@show'", ")", "->", "name", "(", "'show'", ")", ";", "// admin::backups.statuses.clear", "}", ")", ";", "}" ]
Map the routes for the application.
[ "Map", "the", "routes", "for", "the", "application", "." ]
e191f0ccf55c7684173b82b7244fce9c0803bfe0
https://github.com/ARCANESOFT/Backups/blob/e191f0ccf55c7684173b82b7244fce9c0803bfe0/src/Http/Routes/StatusesRoutes.php#L21-L38
train
wb-crowdfusion/crowdfusion
system/core/classes/libraries/dates/DateFactory.php
DateFactory.newDate
protected function newDate($desiredTZ, $date = false) { if ($date === false) { $date = 'now'; } try { $newDate = new Date(is_numeric('' . $date) ? '@' . $date : $date, $desiredTZ); // if the string TZ was not the desired TZ, we must convert it //$temp = new DateTime(is_numeric(''.$date)?'@'.$date:$date); //if(intVal($temp->format('Z')) != $desiredTZ->getOffset(new DateTime())) $newDate->setTimezone($desiredTZ); } catch (Exception $e) { throw new DateException($e); } unset($date); unset($desiredTZ); return $newDate; }
php
protected function newDate($desiredTZ, $date = false) { if ($date === false) { $date = 'now'; } try { $newDate = new Date(is_numeric('' . $date) ? '@' . $date : $date, $desiredTZ); // if the string TZ was not the desired TZ, we must convert it //$temp = new DateTime(is_numeric(''.$date)?'@'.$date:$date); //if(intVal($temp->format('Z')) != $desiredTZ->getOffset(new DateTime())) $newDate->setTimezone($desiredTZ); } catch (Exception $e) { throw new DateException($e); } unset($date); unset($desiredTZ); return $newDate; }
[ "protected", "function", "newDate", "(", "$", "desiredTZ", ",", "$", "date", "=", "false", ")", "{", "if", "(", "$", "date", "===", "false", ")", "{", "$", "date", "=", "'now'", ";", "}", "try", "{", "$", "newDate", "=", "new", "Date", "(", "is_numeric", "(", "''", ".", "$", "date", ")", "?", "'@'", ".", "$", "date", ":", "$", "date", ",", "$", "desiredTZ", ")", ";", "// if the string TZ was not the desired TZ, we must convert it", "//$temp = new DateTime(is_numeric(''.$date)?'@'.$date:$date);", "//if(intVal($temp->format('Z')) != $desiredTZ->getOffset(new DateTime()))", "$", "newDate", "->", "setTimezone", "(", "$", "desiredTZ", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "DateException", "(", "$", "e", ")", ";", "}", "unset", "(", "$", "date", ")", ";", "unset", "(", "$", "desiredTZ", ")", ";", "return", "$", "newDate", ";", "}" ]
Creates a new date in the desired timezone @param string $desiredTZ The desired timezone in which to return the date @param mixed $date An initialization string used to define the date. @return Date @throws \DateException
[ "Creates", "a", "new", "date", "in", "the", "desired", "timezone" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/dates/DateFactory.php#L84-L105
train
modulusphp/request
Cookies.php
Cookies.make
public function make(string $name, int $expireTime = 604800, string $path = "/", string $domain = "", bool $secure = false, bool $httpOnly = true) { return new PHPCookie($name, $expireTime, $path, $domain, $secure, $httpOnly); }
php
public function make(string $name, int $expireTime = 604800, string $path = "/", string $domain = "", bool $secure = false, bool $httpOnly = true) { return new PHPCookie($name, $expireTime, $path, $domain, $secure, $httpOnly); }
[ "public", "function", "make", "(", "string", "$", "name", ",", "int", "$", "expireTime", "=", "604800", ",", "string", "$", "path", "=", "\"/\"", ",", "string", "$", "domain", "=", "\"\"", ",", "bool", "$", "secure", "=", "false", ",", "bool", "$", "httpOnly", "=", "true", ")", "{", "return", "new", "PHPCookie", "(", "$", "name", ",", "$", "expireTime", ",", "$", "path", ",", "$", "domain", ",", "$", "secure", ",", "$", "httpOnly", ")", ";", "}" ]
Create a new cookie @return void
[ "Create", "a", "new", "cookie" ]
9328d81e71994e2944636ad5aed70f7a32f3fb87
https://github.com/modulusphp/request/blob/9328d81e71994e2944636ad5aed70f7a32f3fb87/Cookies.php#L31-L34
train
vaniocz/stdlib
src/UniversalJsonDeserializer.php
UniversalJsonDeserializer.deserialize
public static function deserialize(string $json) { $deserialized = json_decode($json, true); $objects = []; return self::decode($deserialized, $objects); }
php
public static function deserialize(string $json) { $deserialized = json_decode($json, true); $objects = []; return self::decode($deserialized, $objects); }
[ "public", "static", "function", "deserialize", "(", "string", "$", "json", ")", "{", "$", "deserialized", "=", "json_decode", "(", "$", "json", ",", "true", ")", ";", "$", "objects", "=", "[", "]", ";", "return", "self", "::", "decode", "(", "$", "deserialized", ",", "$", "objects", ")", ";", "}" ]
Deserialize the given JSON string. @param string $json The JSON string to be deserialized. @return mixed The deserialized value/array/object.
[ "Deserialize", "the", "given", "JSON", "string", "." ]
06a8343c42829d8fdeecad2bb5c30946fbd73e74
https://github.com/vaniocz/stdlib/blob/06a8343c42829d8fdeecad2bb5c30946fbd73e74/src/UniversalJsonDeserializer.php#L18-L24
train
vaniocz/stdlib
src/UniversalJsonDeserializer.php
UniversalJsonDeserializer.setObjectProperties
private static function setObjectProperties($object, array &$properties, bool $isInternal, Closure $propertyDecoder) { Closure::bind(function () use ($object, &$properties, $propertyDecoder) { foreach ($properties as $key => &$value) { $object->$key = $propertyDecoder($value); } }, null, $isInternal ? null : $object)->__invoke(); }
php
private static function setObjectProperties($object, array &$properties, bool $isInternal, Closure $propertyDecoder) { Closure::bind(function () use ($object, &$properties, $propertyDecoder) { foreach ($properties as $key => &$value) { $object->$key = $propertyDecoder($value); } }, null, $isInternal ? null : $object)->__invoke(); }
[ "private", "static", "function", "setObjectProperties", "(", "$", "object", ",", "array", "&", "$", "properties", ",", "bool", "$", "isInternal", ",", "Closure", "$", "propertyDecoder", ")", "{", "Closure", "::", "bind", "(", "function", "(", ")", "use", "(", "$", "object", ",", "&", "$", "properties", ",", "$", "propertyDecoder", ")", "{", "foreach", "(", "$", "properties", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "$", "object", "->", "$", "key", "=", "$", "propertyDecoder", "(", "$", "value", ")", ";", "}", "}", ",", "null", ",", "$", "isInternal", "?", "null", ":", "$", "object", ")", "->", "__invoke", "(", ")", ";", "}" ]
Set the given object properties. @param mixed $object The object which properties should be set. @param mixed[] $properties The object properties. @param bool $isInternal Tells whether the object class is internal. @param Closure $propertyDecoder The object property decoder.
[ "Set", "the", "given", "object", "properties", "." ]
06a8343c42829d8fdeecad2bb5c30946fbd73e74
https://github.com/vaniocz/stdlib/blob/06a8343c42829d8fdeecad2bb5c30946fbd73e74/src/UniversalJsonDeserializer.php#L113-L120
train
aicouto/image
src/Image.php
Image.thumb
public function thumb(string $src, string $dst, integer $width, integer $height) { $anchor='center'; return $this ->image($src) ->thumbnail($width, $height, $anchor) ->toFile($dst); }
php
public function thumb(string $src, string $dst, integer $width, integer $height) { $anchor='center'; return $this ->image($src) ->thumbnail($width, $height, $anchor) ->toFile($dst); }
[ "public", "function", "thumb", "(", "string", "$", "src", ",", "string", "$", "dst", ",", "integer", "$", "width", ",", "integer", "$", "height", ")", "{", "$", "anchor", "=", "'center'", ";", "return", "$", "this", "->", "image", "(", "$", "src", ")", "->", "thumbnail", "(", "$", "width", ",", "$", "height", ",", "$", "anchor", ")", "->", "toFile", "(", "$", "dst", ")", ";", "}" ]
Miniatura da imagem @param string $src Imagem de origem @param string $dst Imagem de destino @param integer $width Largura da miniatura @param integer $height Altura da miniatura @return bool Retorna true ou false
[ "Miniatura", "da", "imagem" ]
ba94063b0554593a12c1e1f91d59ab33ff7c9520
https://github.com/aicouto/image/blob/ba94063b0554593a12c1e1f91d59ab33ff7c9520/src/Image.php#L97-L104
train
libreworks/caridea-validate
src/Rule/Compare.php
Compare.between
public static function between($min, $max): Compare { $value = $min > $max ? [$max, $min] : [$min, $max]; return new Compare('bt', $value); }
php
public static function between($min, $max): Compare { $value = $min > $max ? [$max, $min] : [$min, $max]; return new Compare('bt', $value); }
[ "public", "static", "function", "between", "(", "$", "min", ",", "$", "max", ")", ":", "Compare", "{", "$", "value", "=", "$", "min", ">", "$", "max", "?", "[", "$", "max", ",", "$", "min", "]", ":", "[", "$", "min", ",", "$", "max", "]", ";", "return", "new", "Compare", "(", "'bt'", ",", "$", "value", ")", ";", "}" ]
Gets a rule that requires numbers to be in a given range. @param int|float $min The minimum value, inclusive @param int|float $max The maximum value, inclusive @return \Caridea\Validate\Rule\Compare the created rule
[ "Gets", "a", "rule", "that", "requires", "numbers", "to", "be", "in", "a", "given", "range", "." ]
625835694d34591bfb1e3b2ce60c2cc28a28d006
https://github.com/libreworks/caridea-validate/blob/625835694d34591bfb1e3b2ce60c2cc28a28d006/src/Rule/Compare.php#L166-L170
train
dms-org/common.structure
src/FileSystem/FileSystemObject.php
FileSystemObject.getInfo
public function getInfo() { if ($this->info === null) { $this->info = new \SplFileInfo($this->fullPath); } return $this->info; }
php
public function getInfo() { if ($this->info === null) { $this->info = new \SplFileInfo($this->fullPath); } return $this->info; }
[ "public", "function", "getInfo", "(", ")", "{", "if", "(", "$", "this", "->", "info", "===", "null", ")", "{", "$", "this", "->", "info", "=", "new", "\\", "SplFileInfo", "(", "$", "this", "->", "fullPath", ")", ";", "}", "return", "$", "this", "->", "info", ";", "}" ]
Get the info @return \SplFileInfo
[ "Get", "the", "info" ]
23f122182f60df5ec847047a81a39c8aab019ff1
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/FileSystem/FileSystemObject.php#L72-L79
train
geoffadams/bedrest-core
library/BedRest/Content/Negotiation/EncodingList.php
EncodingList.parse
protected function parse(array $list) { $parsed = array(); foreach ($list as $item) { $item = explode(';', trim($item)); $entry = array( 'encoding' => array_shift($item), 'q' => 1 ); foreach ($item as $param) { $param = explode('=', $param); // ignore malformed params if (count($param) != 2) { continue; } $entry[$param[0]] = $param[1]; } $parsed[] = $entry; } return $parsed; }
php
protected function parse(array $list) { $parsed = array(); foreach ($list as $item) { $item = explode(';', trim($item)); $entry = array( 'encoding' => array_shift($item), 'q' => 1 ); foreach ($item as $param) { $param = explode('=', $param); // ignore malformed params if (count($param) != 2) { continue; } $entry[$param[0]] = $param[1]; } $parsed[] = $entry; } return $parsed; }
[ "protected", "function", "parse", "(", "array", "$", "list", ")", "{", "$", "parsed", "=", "array", "(", ")", ";", "foreach", "(", "$", "list", "as", "$", "item", ")", "{", "$", "item", "=", "explode", "(", "';'", ",", "trim", "(", "$", "item", ")", ")", ";", "$", "entry", "=", "array", "(", "'encoding'", "=>", "array_shift", "(", "$", "item", ")", ",", "'q'", "=>", "1", ")", ";", "foreach", "(", "$", "item", "as", "$", "param", ")", "{", "$", "param", "=", "explode", "(", "'='", ",", "$", "param", ")", ";", "// ignore malformed params", "if", "(", "count", "(", "$", "param", ")", "!=", "2", ")", "{", "continue", ";", "}", "$", "entry", "[", "$", "param", "[", "0", "]", "]", "=", "$", "param", "[", "1", "]", ";", "}", "$", "parsed", "[", "]", "=", "$", "entry", ";", "}", "return", "$", "parsed", ";", "}" ]
Parses a list of media types out into a normalised structure. @param array $list @return array
[ "Parses", "a", "list", "of", "media", "types", "out", "into", "a", "normalised", "structure", "." ]
a77bf8b7492dfbfb720b201f7ec91a4f03417b5c
https://github.com/geoffadams/bedrest-core/blob/a77bf8b7492dfbfb720b201f7ec91a4f03417b5c/library/BedRest/Content/Negotiation/EncodingList.php#L38-L65
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.authenticate
public function authenticate($username, $password, $type = self :: AUTH_ANY) { if(false === is_string($username)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($username)), E_USER_ERROR); } if(false === is_string($password)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($password)), E_USER_ERROR); } if(false === defined($type)) { return trigger_error(sprintf('Argument 3 passed to %s() is not a valid authentication type', __METHOD__), E_USER_ERROR); } $this -> options[CURLOPT_USERPWD] = sprintf('%s:%s', $username, $password); $this -> options[CURLOPT_HTTPAUTH] = constant($type); return $this; }
php
public function authenticate($username, $password, $type = self :: AUTH_ANY) { if(false === is_string($username)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($username)), E_USER_ERROR); } if(false === is_string($password)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($password)), E_USER_ERROR); } if(false === defined($type)) { return trigger_error(sprintf('Argument 3 passed to %s() is not a valid authentication type', __METHOD__), E_USER_ERROR); } $this -> options[CURLOPT_USERPWD] = sprintf('%s:%s', $username, $password); $this -> options[CURLOPT_HTTPAUTH] = constant($type); return $this; }
[ "public", "function", "authenticate", "(", "$", "username", ",", "$", "password", ",", "$", "type", "=", "self", "::", "AUTH_ANY", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "username", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "username", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "password", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "password", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "defined", "(", "$", "type", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 3 passed to %s() is not a valid authentication type'", ",", "__METHOD__", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "options", "[", "CURLOPT_USERPWD", "]", "=", "sprintf", "(", "'%s:%s'", ",", "$", "username", ",", "$", "password", ")", ";", "$", "this", "->", "options", "[", "CURLOPT_HTTPAUTH", "]", "=", "constant", "(", "$", "type", ")", ";", "return", "$", "this", ";", "}" ]
Adds a HTTP authentication method @param string $username @param string $password @param string $type @return sFire\HTTP\Client
[ "Adds", "a", "HTTP", "authentication", "method" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L265-L283
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.addParam
public function addParam($key, $value, $encode = false) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(false === is_string($value) && false === is_array($value)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string or array, "%s" given', __METHOD__, gettype($value)), E_USER_ERROR); } if(false === is_bool($encode)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type boolean, "%s" given', __METHOD__, gettype($encode)), E_USER_ERROR); } $this -> params[] = (object) ['key' => $key, 'value' => $value, 'encode' => $encode]; return $this; }
php
public function addParam($key, $value, $encode = false) { if(false === is_string($key)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($key)), E_USER_ERROR); } if(false === is_string($value) && false === is_array($value)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string or array, "%s" given', __METHOD__, gettype($value)), E_USER_ERROR); } if(false === is_bool($encode)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type boolean, "%s" given', __METHOD__, gettype($encode)), E_USER_ERROR); } $this -> params[] = (object) ['key' => $key, 'value' => $value, 'encode' => $encode]; return $this; }
[ "public", "function", "addParam", "(", "$", "key", ",", "$", "value", ",", "$", "encode", "=", "false", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "key", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "key", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "value", ")", "&&", "false", "===", "is_array", "(", "$", "value", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type string or array, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "value", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "is_bool", "(", "$", "encode", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 3 passed to %s() must be of the type boolean, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "encode", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "params", "[", "]", "=", "(", "object", ")", "[", "'key'", "=>", "$", "key", ",", "'value'", "=>", "$", "value", ",", "'encode'", "=>", "$", "encode", "]", ";", "return", "$", "this", ";", "}" ]
Add a new key value param to the url or query @param $key string @param $value string|array @param $encode boolean @return sFire\HTTP\Client
[ "Add", "a", "new", "key", "value", "param", "to", "the", "url", "or", "query" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L293-L310
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.addFile
public function addFile($file, $name = null, $mime = null) { if('post' !== $this -> method) { return trigger_error('File uploads are only supported with POST request method', E_USER_ERROR); } if(false === $file instanceof File && false === is_string($file)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string or instance of sFire\\System\\File, "%s" given', __METHOD__, gettype($file)), E_USER_ERROR); } if(null !== $name && false === is_string($name)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($name)), E_USER_ERROR); } if(null !== $mime && false === is_string($mime)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($mime)), E_USER_ERROR); } if(true === is_string($file)) { $file = new File($file); } if(false === $file -> isReadable()) { return trigger_error(sprintf('File %s passed to %s() is not readable', $file -> entity() -> getBasepath(), __METHOD__), E_USER_ERROR); } if(null === $name) { $name = $file -> entity() -> getBasename(); } if(null === $mime) { $mime = $file -> getMime(); } $this -> files[] = (object) ['file' => $file, 'name' => $name, 'mime' => $mime]; return $this; }
php
public function addFile($file, $name = null, $mime = null) { if('post' !== $this -> method) { return trigger_error('File uploads are only supported with POST request method', E_USER_ERROR); } if(false === $file instanceof File && false === is_string($file)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string or instance of sFire\\System\\File, "%s" given', __METHOD__, gettype($file)), E_USER_ERROR); } if(null !== $name && false === is_string($name)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($name)), E_USER_ERROR); } if(null !== $mime && false === is_string($mime)) { return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($mime)), E_USER_ERROR); } if(true === is_string($file)) { $file = new File($file); } if(false === $file -> isReadable()) { return trigger_error(sprintf('File %s passed to %s() is not readable', $file -> entity() -> getBasepath(), __METHOD__), E_USER_ERROR); } if(null === $name) { $name = $file -> entity() -> getBasename(); } if(null === $mime) { $mime = $file -> getMime(); } $this -> files[] = (object) ['file' => $file, 'name' => $name, 'mime' => $mime]; return $this; }
[ "public", "function", "addFile", "(", "$", "file", ",", "$", "name", "=", "null", ",", "$", "mime", "=", "null", ")", "{", "if", "(", "'post'", "!==", "$", "this", "->", "method", ")", "{", "return", "trigger_error", "(", "'File uploads are only supported with POST request method'", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "$", "file", "instanceof", "File", "&&", "false", "===", "is_string", "(", "$", "file", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string or instance of sFire\\\\System\\\\File, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "file", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "null", "!==", "$", "name", "&&", "false", "===", "is_string", "(", "$", "name", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "name", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "null", "!==", "$", "mime", "&&", "false", "===", "is_string", "(", "$", "mime", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 3 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "mime", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "true", "===", "is_string", "(", "$", "file", ")", ")", "{", "$", "file", "=", "new", "File", "(", "$", "file", ")", ";", "}", "if", "(", "false", "===", "$", "file", "->", "isReadable", "(", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'File %s passed to %s() is not readable'", ",", "$", "file", "->", "entity", "(", ")", "->", "getBasepath", "(", ")", ",", "__METHOD__", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "null", "===", "$", "name", ")", "{", "$", "name", "=", "$", "file", "->", "entity", "(", ")", "->", "getBasename", "(", ")", ";", "}", "if", "(", "null", "===", "$", "mime", ")", "{", "$", "mime", "=", "$", "file", "->", "getMime", "(", ")", ";", "}", "$", "this", "->", "files", "[", "]", "=", "(", "object", ")", "[", "'file'", "=>", "$", "file", ",", "'name'", "=>", "$", "name", ",", "'mime'", "=>", "$", "mime", "]", ";", "return", "$", "this", ";", "}" ]
Attach file to request @param $file string|sFire\System\File @param $name string @param $string mime @return sFire\HTTP\Client
[ "Attach", "file", "to", "request" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L320-L357
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.userAgent
public function userAgent($useragent) { if(false === is_string($useragent)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($useragent)), E_USER_ERROR); } $this -> options[CURLOPT_USERAGENT] = $useragent; return $this; }
php
public function userAgent($useragent) { if(false === is_string($useragent)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($useragent)), E_USER_ERROR); } $this -> options[CURLOPT_USERAGENT] = $useragent; return $this; }
[ "public", "function", "userAgent", "(", "$", "useragent", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "useragent", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "useragent", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "options", "[", "CURLOPT_USERAGENT", "]", "=", "$", "useragent", ";", "return", "$", "this", ";", "}" ]
Set a user agent to the request @param string $key @return sFire\HTTP\Client
[ "Set", "a", "user", "agent", "to", "the", "request" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L365-L374
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.timeout
public function timeout($connection = 30, $response = 30) { if(false === ('-' . intval($connection) == '-' . $connection)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($connection)), E_USER_ERROR); } if(false === ('-' . intval($response) == '-' . $response)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($response)), E_USER_ERROR); } $this -> options[CURLOPT_CONNECTTIMEOUT] = intval($connection); $this -> options[CURLOPT_TIMEOUT] = intval($response); return $this; }
php
public function timeout($connection = 30, $response = 30) { if(false === ('-' . intval($connection) == '-' . $connection)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($connection)), E_USER_ERROR); } if(false === ('-' . intval($response) == '-' . $response)) { return trigger_error(sprintf('Argument 2 passed to %s() must be of the type integer, "%s" given', __METHOD__, gettype($response)), E_USER_ERROR); } $this -> options[CURLOPT_CONNECTTIMEOUT] = intval($connection); $this -> options[CURLOPT_TIMEOUT] = intval($response); return $this; }
[ "public", "function", "timeout", "(", "$", "connection", "=", "30", ",", "$", "response", "=", "30", ")", "{", "if", "(", "false", "===", "(", "'-'", ".", "intval", "(", "$", "connection", ")", "==", "'-'", ".", "$", "connection", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "connection", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "if", "(", "false", "===", "(", "'-'", ".", "intval", "(", "$", "response", ")", "==", "'-'", ".", "$", "response", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 2 passed to %s() must be of the type integer, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "response", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "options", "[", "CURLOPT_CONNECTTIMEOUT", "]", "=", "intval", "(", "$", "connection", ")", ";", "$", "this", "->", "options", "[", "CURLOPT_TIMEOUT", "]", "=", "intval", "(", "$", "response", ")", ";", "return", "$", "this", ";", "}" ]
Set the connection and response timeout in seconds for the request @param int $connection @param int $response @return sFire\HTTP\Client
[ "Set", "the", "connection", "and", "response", "timeout", "in", "seconds", "for", "the", "request" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L383-L397
train
Kris-Kuiper/sFire-Framework
src/HTTP/Client.php
Client.referer
public function referer($referer) { if(false === is_string($referer)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($referer)), E_USER_ERROR); } $this -> options[CURLOPT_REFERER] = $referer; return $this; }
php
public function referer($referer) { if(false === is_string($referer)) { return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($referer)), E_USER_ERROR); } $this -> options[CURLOPT_REFERER] = $referer; return $this; }
[ "public", "function", "referer", "(", "$", "referer", ")", "{", "if", "(", "false", "===", "is_string", "(", "$", "referer", ")", ")", "{", "return", "trigger_error", "(", "sprintf", "(", "'Argument 1 passed to %s() must be of the type string, \"%s\" given'", ",", "__METHOD__", ",", "gettype", "(", "$", "referer", ")", ")", ",", "E_USER_ERROR", ")", ";", "}", "$", "this", "->", "options", "[", "CURLOPT_REFERER", "]", "=", "$", "referer", ";", "return", "$", "this", ";", "}" ]
Set the referer @param int $referer @return sFire\HTTP\Client
[ "Set", "the", "referer" ]
deefe1d9d2b40e7326381e8dcd4f01f9aa61885c
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/HTTP/Client.php#L426-L435
train