repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
oat-sa/qti-sdk | src/qtism/runtime/expressions/operators/RandomProcessor.php | RandomProcessor.process | public function process()
{
$operands = $this->getOperands();
if ($operands->containsNull() === true) {
return null;
}
if ($operands->exclusivelyMultipleOrOrdered() === false) {
$msg = "The Random operator only accepts values with multiple or ordered cardinality.";
throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_CARDINALITY);
}
$operand = $operands[0];
$maxIndex = count($operand) - 1;
return $operand[mt_rand(0, $maxIndex)];
} | php | public function process()
{
$operands = $this->getOperands();
if ($operands->containsNull() === true) {
return null;
}
if ($operands->exclusivelyMultipleOrOrdered() === false) {
$msg = "The Random operator only accepts values with multiple or ordered cardinality.";
throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_CARDINALITY);
}
$operand = $operands[0];
$maxIndex = count($operand) - 1;
return $operand[mt_rand(0, $maxIndex)];
} | [
"public",
"function",
"process",
"(",
")",
"{",
"$",
"operands",
"=",
"$",
"this",
"->",
"getOperands",
"(",
")",
";",
"if",
"(",
"$",
"operands",
"->",
"containsNull",
"(",
")",
"===",
"true",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"operands",
"->",
"exclusivelyMultipleOrOrdered",
"(",
")",
"===",
"false",
")",
"{",
"$",
"msg",
"=",
"\"The Random operator only accepts values with multiple or ordered cardinality.\"",
";",
"throw",
"new",
"OperatorProcessingException",
"(",
"$",
"msg",
",",
"$",
"this",
",",
"OperatorProcessingException",
"::",
"WRONG_CARDINALITY",
")",
";",
"}",
"$",
"operand",
"=",
"$",
"operands",
"[",
"0",
"]",
";",
"$",
"maxIndex",
"=",
"count",
"(",
"$",
"operand",
")",
"-",
"1",
";",
"return",
"$",
"operand",
"[",
"mt_rand",
"(",
"0",
",",
"$",
"maxIndex",
")",
"]",
";",
"}"
] | Process the Random operator.
@return mixed|null A single cardinality QTI runtime compliant value or NULL if the operand is considered to be NULL.
@throws \qtism\runtime\expressions\operators\OperatorProcessingException | [
"Process",
"the",
"Random",
"operator",
"."
] | train | https://github.com/oat-sa/qti-sdk/blob/fc3568d2a293ae6dbfe9f400dad2b94a0033ddb2/src/qtism/runtime/expressions/operators/RandomProcessor.php#L50-L67 |
oat-sa/extension-tao-itemhtml | model/export/OwiExporter.php | OwiExporter.export | public function export($options = array()) {
$itemService = \taoItems_models_classes_ItemsService::singleton();
// copy local files
$source = $itemService->getItemDirectory($this->getItem());
$files = $source->getFlyIterator(Directory::ITERATOR_FILE | Directory::ITERATOR_RECURSIVE);
foreach ($files as $file) {
$relPath = ltrim($source->getRelPath($file), '/');
$this->addFile($file->readStream(), $relPath);
}
} | php | public function export($options = array()) {
$itemService = \taoItems_models_classes_ItemsService::singleton();
// copy local files
$source = $itemService->getItemDirectory($this->getItem());
$files = $source->getFlyIterator(Directory::ITERATOR_FILE | Directory::ITERATOR_RECURSIVE);
foreach ($files as $file) {
$relPath = ltrim($source->getRelPath($file), '/');
$this->addFile($file->readStream(), $relPath);
}
} | [
"public",
"function",
"export",
"(",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"itemService",
"=",
"\\",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
";",
"// copy local files",
"$",
"source",
"=",
"$",
"itemService",
"->",
"getItemDirectory",
"(",
"$",
"this",
"->",
"getItem",
"(",
")",
")",
";",
"$",
"files",
"=",
"$",
"source",
"->",
"getFlyIterator",
"(",
"Directory",
"::",
"ITERATOR_FILE",
"|",
"Directory",
"::",
"ITERATOR_RECURSIVE",
")",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"file",
")",
"{",
"$",
"relPath",
"=",
"ltrim",
"(",
"$",
"source",
"->",
"getRelPath",
"(",
"$",
"file",
")",
",",
"'/'",
")",
";",
"$",
"this",
"->",
"addFile",
"(",
"$",
"file",
"->",
"readStream",
"(",
")",
",",
"$",
"relPath",
")",
";",
"}",
"}"
] | Overriden export for OWIs
@see taoItems_models_classes_ItemExporter::export() | [
"Overriden",
"export",
"for",
"OWIs"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/export/OwiExporter.php#L33-L43 |
oat-sa/extension-tao-itemhtml | model/import/ImportService.php | ImportService.importXhtmlFile | public function importXhtmlFile($xhtmlFile, core_kernel_classes_Class $itemClass, $validate = true)
{
//get the services instances we will need
$itemService = taoItems_models_classes_ItemsService::singleton();
$report = new common_report_Report(common_report_Report::TYPE_SUCCESS, '');
if (!$itemService->isItemClass($itemClass)) {
throw new common_exception_Error('provided non item class for '.__FUNCTION__);
}
//load and validate the package
$packageParser = new PackageParser($xhtmlFile);
$packageParser->validate();
if ($packageParser->isValid()) {
//extract the package
$folder = $packageParser->extract();
if (!is_dir($folder)) {
throw new taoItems_models_classes_Import_ExtractException();
}
//load and validate the manifest
$fileParser = new tao_models_classes_Parser($folder .'index.html', array('extension' => 'html'));
$taoItemsBasePath = common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems')->getDir();
$fileParser->validate($taoItemsBasePath.'/models/classes/data/xhtml/xhtml.xsd');
if(!$validate || $fileParser->isValid()) {
//create a new item in the model
$rdfItem = $itemService->createInstance($itemClass);
if(is_null($rdfItem)){
helpers_File::remove($folder);
throw new common_exception_Error('Unable to create instance of '.$itemClass->getUri());
}
//set the XHTML type
$rdfItem->setPropertyValue(new core_kernel_classes_Property(taoItems_models_classes_ItemsService::PROPERTY_ITEM_MODEL), OwiItemModel::ITEMMODEL_URI);
$itemContent = file_get_contents($folder .'index.html');
$dir = $itemService->getItemDirectory($rdfItem);
foreach (
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $item
) {
if (!$item->isDir()) {
common_Logger::i('Upload '.$item.' to '.$iterator->getSubPathName());
$file = $dir->getFile($iterator->getSubPathName());
$fh = fopen($item, 'r');
$file->write($fh);
fclose($fh);
}
}
$report->setMessage(__('The OWI Item was successfully imported.'));
$report->setData($rdfItem);
}
else {
helpers_File::remove($folder);
if ($fileParser->getReport()->hasChildren() === true) {
foreach ($fileParser->getReport() as $r) {
$report->add($r);
}
}
else {
$report->add($fileParser->getReport());
}
}
}
else {
if ($packageParser->getReport()->hasChildren() === true) {
foreach ($packageParser->getReport() as $r) {
$report->add($r);
}
}
else {
$report->add($packageParser->getReport());
}
}
// $folder has been moved, no need to delete it here
if ($report->containsError() === true) {
$report->setMessage("The OWI Item could not be imported.");
$report->setType(common_report_Report::TYPE_ERROR);
$report->setData(null);
}
return $report;
} | php | public function importXhtmlFile($xhtmlFile, core_kernel_classes_Class $itemClass, $validate = true)
{
//get the services instances we will need
$itemService = taoItems_models_classes_ItemsService::singleton();
$report = new common_report_Report(common_report_Report::TYPE_SUCCESS, '');
if (!$itemService->isItemClass($itemClass)) {
throw new common_exception_Error('provided non item class for '.__FUNCTION__);
}
//load and validate the package
$packageParser = new PackageParser($xhtmlFile);
$packageParser->validate();
if ($packageParser->isValid()) {
//extract the package
$folder = $packageParser->extract();
if (!is_dir($folder)) {
throw new taoItems_models_classes_Import_ExtractException();
}
//load and validate the manifest
$fileParser = new tao_models_classes_Parser($folder .'index.html', array('extension' => 'html'));
$taoItemsBasePath = common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems')->getDir();
$fileParser->validate($taoItemsBasePath.'/models/classes/data/xhtml/xhtml.xsd');
if(!$validate || $fileParser->isValid()) {
//create a new item in the model
$rdfItem = $itemService->createInstance($itemClass);
if(is_null($rdfItem)){
helpers_File::remove($folder);
throw new common_exception_Error('Unable to create instance of '.$itemClass->getUri());
}
//set the XHTML type
$rdfItem->setPropertyValue(new core_kernel_classes_Property(taoItems_models_classes_ItemsService::PROPERTY_ITEM_MODEL), OwiItemModel::ITEMMODEL_URI);
$itemContent = file_get_contents($folder .'index.html');
$dir = $itemService->getItemDirectory($rdfItem);
foreach (
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $item
) {
if (!$item->isDir()) {
common_Logger::i('Upload '.$item.' to '.$iterator->getSubPathName());
$file = $dir->getFile($iterator->getSubPathName());
$fh = fopen($item, 'r');
$file->write($fh);
fclose($fh);
}
}
$report->setMessage(__('The OWI Item was successfully imported.'));
$report->setData($rdfItem);
}
else {
helpers_File::remove($folder);
if ($fileParser->getReport()->hasChildren() === true) {
foreach ($fileParser->getReport() as $r) {
$report->add($r);
}
}
else {
$report->add($fileParser->getReport());
}
}
}
else {
if ($packageParser->getReport()->hasChildren() === true) {
foreach ($packageParser->getReport() as $r) {
$report->add($r);
}
}
else {
$report->add($packageParser->getReport());
}
}
// $folder has been moved, no need to delete it here
if ($report->containsError() === true) {
$report->setMessage("The OWI Item could not be imported.");
$report->setType(common_report_Report::TYPE_ERROR);
$report->setData(null);
}
return $report;
} | [
"public",
"function",
"importXhtmlFile",
"(",
"$",
"xhtmlFile",
",",
"core_kernel_classes_Class",
"$",
"itemClass",
",",
"$",
"validate",
"=",
"true",
")",
"{",
"//get the services instances we will need",
"$",
"itemService",
"=",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
";",
"$",
"report",
"=",
"new",
"common_report_Report",
"(",
"common_report_Report",
"::",
"TYPE_SUCCESS",
",",
"''",
")",
";",
"if",
"(",
"!",
"$",
"itemService",
"->",
"isItemClass",
"(",
"$",
"itemClass",
")",
")",
"{",
"throw",
"new",
"common_exception_Error",
"(",
"'provided non item class for '",
".",
"__FUNCTION__",
")",
";",
"}",
"//load and validate the package",
"$",
"packageParser",
"=",
"new",
"PackageParser",
"(",
"$",
"xhtmlFile",
")",
";",
"$",
"packageParser",
"->",
"validate",
"(",
")",
";",
"if",
"(",
"$",
"packageParser",
"->",
"isValid",
"(",
")",
")",
"{",
"//extract the package",
"$",
"folder",
"=",
"$",
"packageParser",
"->",
"extract",
"(",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"folder",
")",
")",
"{",
"throw",
"new",
"taoItems_models_classes_Import_ExtractException",
"(",
")",
";",
"}",
"//load and validate the manifest",
"$",
"fileParser",
"=",
"new",
"tao_models_classes_Parser",
"(",
"$",
"folder",
".",
"'index.html'",
",",
"array",
"(",
"'extension'",
"=>",
"'html'",
")",
")",
";",
"$",
"taoItemsBasePath",
"=",
"common_ext_ExtensionsManager",
"::",
"singleton",
"(",
")",
"->",
"getExtensionById",
"(",
"'taoItems'",
")",
"->",
"getDir",
"(",
")",
";",
"$",
"fileParser",
"->",
"validate",
"(",
"$",
"taoItemsBasePath",
".",
"'/models/classes/data/xhtml/xhtml.xsd'",
")",
";",
"if",
"(",
"!",
"$",
"validate",
"||",
"$",
"fileParser",
"->",
"isValid",
"(",
")",
")",
"{",
"//create a new item in the model",
"$",
"rdfItem",
"=",
"$",
"itemService",
"->",
"createInstance",
"(",
"$",
"itemClass",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"rdfItem",
")",
")",
"{",
"helpers_File",
"::",
"remove",
"(",
"$",
"folder",
")",
";",
"throw",
"new",
"common_exception_Error",
"(",
"'Unable to create instance of '",
".",
"$",
"itemClass",
"->",
"getUri",
"(",
")",
")",
";",
"}",
"//set the XHTML type",
"$",
"rdfItem",
"->",
"setPropertyValue",
"(",
"new",
"core_kernel_classes_Property",
"(",
"taoItems_models_classes_ItemsService",
"::",
"PROPERTY_ITEM_MODEL",
")",
",",
"OwiItemModel",
"::",
"ITEMMODEL_URI",
")",
";",
"$",
"itemContent",
"=",
"file_get_contents",
"(",
"$",
"folder",
".",
"'index.html'",
")",
";",
"$",
"dir",
"=",
"$",
"itemService",
"->",
"getItemDirectory",
"(",
"$",
"rdfItem",
")",
";",
"foreach",
"(",
"$",
"iterator",
"=",
"new",
"\\",
"RecursiveIteratorIterator",
"(",
"new",
"\\",
"RecursiveDirectoryIterator",
"(",
"$",
"folder",
",",
"\\",
"RecursiveDirectoryIterator",
"::",
"SKIP_DOTS",
")",
",",
"\\",
"RecursiveIteratorIterator",
"::",
"SELF_FIRST",
")",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"!",
"$",
"item",
"->",
"isDir",
"(",
")",
")",
"{",
"common_Logger",
"::",
"i",
"(",
"'Upload '",
".",
"$",
"item",
".",
"' to '",
".",
"$",
"iterator",
"->",
"getSubPathName",
"(",
")",
")",
";",
"$",
"file",
"=",
"$",
"dir",
"->",
"getFile",
"(",
"$",
"iterator",
"->",
"getSubPathName",
"(",
")",
")",
";",
"$",
"fh",
"=",
"fopen",
"(",
"$",
"item",
",",
"'r'",
")",
";",
"$",
"file",
"->",
"write",
"(",
"$",
"fh",
")",
";",
"fclose",
"(",
"$",
"fh",
")",
";",
"}",
"}",
"$",
"report",
"->",
"setMessage",
"(",
"__",
"(",
"'The OWI Item was successfully imported.'",
")",
")",
";",
"$",
"report",
"->",
"setData",
"(",
"$",
"rdfItem",
")",
";",
"}",
"else",
"{",
"helpers_File",
"::",
"remove",
"(",
"$",
"folder",
")",
";",
"if",
"(",
"$",
"fileParser",
"->",
"getReport",
"(",
")",
"->",
"hasChildren",
"(",
")",
"===",
"true",
")",
"{",
"foreach",
"(",
"$",
"fileParser",
"->",
"getReport",
"(",
")",
"as",
"$",
"r",
")",
"{",
"$",
"report",
"->",
"add",
"(",
"$",
"r",
")",
";",
"}",
"}",
"else",
"{",
"$",
"report",
"->",
"add",
"(",
"$",
"fileParser",
"->",
"getReport",
"(",
")",
")",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"packageParser",
"->",
"getReport",
"(",
")",
"->",
"hasChildren",
"(",
")",
"===",
"true",
")",
"{",
"foreach",
"(",
"$",
"packageParser",
"->",
"getReport",
"(",
")",
"as",
"$",
"r",
")",
"{",
"$",
"report",
"->",
"add",
"(",
"$",
"r",
")",
";",
"}",
"}",
"else",
"{",
"$",
"report",
"->",
"add",
"(",
"$",
"packageParser",
"->",
"getReport",
"(",
")",
")",
";",
"}",
"}",
"// $folder has been moved, no need to delete it here",
"if",
"(",
"$",
"report",
"->",
"containsError",
"(",
")",
"===",
"true",
")",
"{",
"$",
"report",
"->",
"setMessage",
"(",
"\"The OWI Item could not be imported.\"",
")",
";",
"$",
"report",
"->",
"setType",
"(",
"common_report_Report",
"::",
"TYPE_ERROR",
")",
";",
"$",
"report",
"->",
"setData",
"(",
"null",
")",
";",
"}",
"return",
"$",
"report",
";",
"}"
] | imports a zip file as a new instance of the specified item class
parameter repository is ignored for now
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@param string xhtmlFile
@param Class itemClass
@param boolean validate
@param Repository repository
@return common_report_Report | [
"imports",
"a",
"zip",
"file",
"as",
"a",
"new",
"instance",
"of",
"the",
"specified",
"item",
"class",
"parameter",
"repository",
"is",
"ignored",
"for",
"now"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/import/ImportService.php#L59-L150 |
oat-sa/extension-tao-itemhtml | model/import/ImportService.php | ImportService.importContent | public function importContent($package, $item, $language = '', $validate = true) {
//load and validate the package
$packageParser = new PackageParser($package);
$packageParser->validate();
if($packageParser->isValid()){
//extract the package
$folder = $packageParser->extract();
if(!is_dir($folder)){
throw new taoItems_models_classes_Import_ExtractException();
}
//load and validate the manifest
$fileParser = new tao_models_classes_Parser($folder .'index.html', array('extension' => 'html'));
$taoItemsBasePath = common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems')->getDir();
$fileParser->validate($taoItemsBasePath.'/models/classes/data/xhtml/xhtml.xsd');
if(!$validate || $fileParser->isValid()){
$dir = taoItems_models_classes_ItemsService::singleton()->getItemDirectory($item);
foreach (
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $content
) {
if (!$content->isDir()) {
common_Logger::i('Upload '.$content.' to '.$iterator->getSubPathName());
$file = $dir->getFile($iterator->getSubPathName());
$fh = fopen($content, 'r');
$file->write($fh);
fclose($fh);
}
}
$returnValue = common_report_Report::createSuccess(__('%s was successfully replaced', $item->getLabel()), $item);
} else {
helpers_File::remove($folder);
$returnValue = $fileParser->getReport();
$returnValue->setTitle(__('Validation of the imported file has failed'));
}
} else {
$returnValue = $packageParser->getReport();
$returnValue->setTitle(__('Validation of the imported package has failed'));
}
return $returnValue;
} | php | public function importContent($package, $item, $language = '', $validate = true) {
//load and validate the package
$packageParser = new PackageParser($package);
$packageParser->validate();
if($packageParser->isValid()){
//extract the package
$folder = $packageParser->extract();
if(!is_dir($folder)){
throw new taoItems_models_classes_Import_ExtractException();
}
//load and validate the manifest
$fileParser = new tao_models_classes_Parser($folder .'index.html', array('extension' => 'html'));
$taoItemsBasePath = common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems')->getDir();
$fileParser->validate($taoItemsBasePath.'/models/classes/data/xhtml/xhtml.xsd');
if(!$validate || $fileParser->isValid()){
$dir = taoItems_models_classes_ItemsService::singleton()->getItemDirectory($item);
foreach (
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $content
) {
if (!$content->isDir()) {
common_Logger::i('Upload '.$content.' to '.$iterator->getSubPathName());
$file = $dir->getFile($iterator->getSubPathName());
$fh = fopen($content, 'r');
$file->write($fh);
fclose($fh);
}
}
$returnValue = common_report_Report::createSuccess(__('%s was successfully replaced', $item->getLabel()), $item);
} else {
helpers_File::remove($folder);
$returnValue = $fileParser->getReport();
$returnValue->setTitle(__('Validation of the imported file has failed'));
}
} else {
$returnValue = $packageParser->getReport();
$returnValue->setTitle(__('Validation of the imported package has failed'));
}
return $returnValue;
} | [
"public",
"function",
"importContent",
"(",
"$",
"package",
",",
"$",
"item",
",",
"$",
"language",
"=",
"''",
",",
"$",
"validate",
"=",
"true",
")",
"{",
"//load and validate the package",
"$",
"packageParser",
"=",
"new",
"PackageParser",
"(",
"$",
"package",
")",
";",
"$",
"packageParser",
"->",
"validate",
"(",
")",
";",
"if",
"(",
"$",
"packageParser",
"->",
"isValid",
"(",
")",
")",
"{",
"//extract the package",
"$",
"folder",
"=",
"$",
"packageParser",
"->",
"extract",
"(",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"folder",
")",
")",
"{",
"throw",
"new",
"taoItems_models_classes_Import_ExtractException",
"(",
")",
";",
"}",
"//load and validate the manifest",
"$",
"fileParser",
"=",
"new",
"tao_models_classes_Parser",
"(",
"$",
"folder",
".",
"'index.html'",
",",
"array",
"(",
"'extension'",
"=>",
"'html'",
")",
")",
";",
"$",
"taoItemsBasePath",
"=",
"common_ext_ExtensionsManager",
"::",
"singleton",
"(",
")",
"->",
"getExtensionById",
"(",
"'taoItems'",
")",
"->",
"getDir",
"(",
")",
";",
"$",
"fileParser",
"->",
"validate",
"(",
"$",
"taoItemsBasePath",
".",
"'/models/classes/data/xhtml/xhtml.xsd'",
")",
";",
"if",
"(",
"!",
"$",
"validate",
"||",
"$",
"fileParser",
"->",
"isValid",
"(",
")",
")",
"{",
"$",
"dir",
"=",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
"->",
"getItemDirectory",
"(",
"$",
"item",
")",
";",
"foreach",
"(",
"$",
"iterator",
"=",
"new",
"\\",
"RecursiveIteratorIterator",
"(",
"new",
"\\",
"RecursiveDirectoryIterator",
"(",
"$",
"folder",
",",
"\\",
"RecursiveDirectoryIterator",
"::",
"SKIP_DOTS",
")",
",",
"\\",
"RecursiveIteratorIterator",
"::",
"SELF_FIRST",
")",
"as",
"$",
"content",
")",
"{",
"if",
"(",
"!",
"$",
"content",
"->",
"isDir",
"(",
")",
")",
"{",
"common_Logger",
"::",
"i",
"(",
"'Upload '",
".",
"$",
"content",
".",
"' to '",
".",
"$",
"iterator",
"->",
"getSubPathName",
"(",
")",
")",
";",
"$",
"file",
"=",
"$",
"dir",
"->",
"getFile",
"(",
"$",
"iterator",
"->",
"getSubPathName",
"(",
")",
")",
";",
"$",
"fh",
"=",
"fopen",
"(",
"$",
"content",
",",
"'r'",
")",
";",
"$",
"file",
"->",
"write",
"(",
"$",
"fh",
")",
";",
"fclose",
"(",
"$",
"fh",
")",
";",
"}",
"}",
"$",
"returnValue",
"=",
"common_report_Report",
"::",
"createSuccess",
"(",
"__",
"(",
"'%s was successfully replaced'",
",",
"$",
"item",
"->",
"getLabel",
"(",
")",
")",
",",
"$",
"item",
")",
";",
"}",
"else",
"{",
"helpers_File",
"::",
"remove",
"(",
"$",
"folder",
")",
";",
"$",
"returnValue",
"=",
"$",
"fileParser",
"->",
"getReport",
"(",
")",
";",
"$",
"returnValue",
"->",
"setTitle",
"(",
"__",
"(",
"'Validation of the imported file has failed'",
")",
")",
";",
"}",
"}",
"else",
"{",
"$",
"returnValue",
"=",
"$",
"packageParser",
"->",
"getReport",
"(",
")",
";",
"$",
"returnValue",
"->",
"setTitle",
"(",
"__",
"(",
"'Validation of the imported package has failed'",
")",
")",
";",
"}",
"return",
"$",
"returnValue",
";",
"}"
] | import the owi as content into an existing item
replacing the old content
@param string $package
@param \core_kernel_classes_Resource $item
@param string $language
@param string $validate
@throws taoItems_models_classes_Import_ExtractException
@throws taoItems_models_classes_Import_ImportException
@return common_report_Report | [
"import",
"the",
"owi",
"as",
"content",
"into",
"an",
"existing",
"item",
"replacing",
"the",
"old",
"content"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/import/ImportService.php#L164-L209 |
oat-sa/extension-tao-itemhtml | model/OwiItemModel.php | OwiItemModel.render | public function render( core_kernel_classes_Resource $item, $langCode)
{
$itemService = taoItems_models_classes_ItemsService::singleton();
$file = $itemService->getItemDirectory($item)->getFile('index.html');
$xhtml = $file->read();
// Check if all needed APIs are referenced.
$xhtml = $this->replaceDeprecatedApis($xhtml); // throws ItemModelException.
return $xhtml;
} | php | public function render( core_kernel_classes_Resource $item, $langCode)
{
$itemService = taoItems_models_classes_ItemsService::singleton();
$file = $itemService->getItemDirectory($item)->getFile('index.html');
$xhtml = $file->read();
// Check if all needed APIs are referenced.
$xhtml = $this->replaceDeprecatedApis($xhtml); // throws ItemModelException.
return $xhtml;
} | [
"public",
"function",
"render",
"(",
"core_kernel_classes_Resource",
"$",
"item",
",",
"$",
"langCode",
")",
"{",
"$",
"itemService",
"=",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
";",
"$",
"file",
"=",
"$",
"itemService",
"->",
"getItemDirectory",
"(",
"$",
"item",
")",
"->",
"getFile",
"(",
"'index.html'",
")",
";",
"$",
"xhtml",
"=",
"$",
"file",
"->",
"read",
"(",
")",
";",
"// Check if all needed APIs are referenced.",
"$",
"xhtml",
"=",
"$",
"this",
"->",
"replaceDeprecatedApis",
"(",
"$",
"xhtml",
")",
";",
"// throws ItemModelException.",
"return",
"$",
"xhtml",
";",
"}"
] | Render an XHTML item.
@access public
@author Joel Bout, <joel@taotesting.com>
@param Resource item The item to render.
@return string The rendered item.
@throws taoItems_models_classes_ItemModelException | [
"Render",
"an",
"XHTML",
"item",
"."
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/OwiItemModel.php#L72-L82 |
oat-sa/extension-tao-itemhtml | model/OwiItemModel.php | OwiItemModel.replaceDeprecatedApis | protected function replaceDeprecatedApis($xhtml) {
$dom = new DOMDocument('1.0', TAO_DEFAULT_ENCODING);
if (!$dom->loadHTML($xhtml)){
throw new taoItems_models_classes_ItemModelException("An error occured while loading the XML content of the rendered item.");
}
$found = 0;
$deprecatedApis = array('taoApi', 'wfApi');
foreach ($deprecatedApis as $pattern){
$found += taoItems_helpers_Xhtml::removeScriptElements($dom, '/' . $pattern . '/i');
}
if ($found > 0) {
common_Logger::i('found '.$found.' references to deprecated APIs, replacing with legacy API');
$taoItemsExt = common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems');
$legacyApiSrc = Template::js('legacyApi/taoLegacyApi.min.js', 'taoItems');
taoItems_helpers_Xhtml::addScriptElement($dom, $legacyApiSrc);
}
return $dom->saveHTML();
} | php | protected function replaceDeprecatedApis($xhtml) {
$dom = new DOMDocument('1.0', TAO_DEFAULT_ENCODING);
if (!$dom->loadHTML($xhtml)){
throw new taoItems_models_classes_ItemModelException("An error occured while loading the XML content of the rendered item.");
}
$found = 0;
$deprecatedApis = array('taoApi', 'wfApi');
foreach ($deprecatedApis as $pattern){
$found += taoItems_helpers_Xhtml::removeScriptElements($dom, '/' . $pattern . '/i');
}
if ($found > 0) {
common_Logger::i('found '.$found.' references to deprecated APIs, replacing with legacy API');
$taoItemsExt = common_ext_ExtensionsManager::singleton()->getExtensionById('taoItems');
$legacyApiSrc = Template::js('legacyApi/taoLegacyApi.min.js', 'taoItems');
taoItems_helpers_Xhtml::addScriptElement($dom, $legacyApiSrc);
}
return $dom->saveHTML();
} | [
"protected",
"function",
"replaceDeprecatedApis",
"(",
"$",
"xhtml",
")",
"{",
"$",
"dom",
"=",
"new",
"DOMDocument",
"(",
"'1.0'",
",",
"TAO_DEFAULT_ENCODING",
")",
";",
"if",
"(",
"!",
"$",
"dom",
"->",
"loadHTML",
"(",
"$",
"xhtml",
")",
")",
"{",
"throw",
"new",
"taoItems_models_classes_ItemModelException",
"(",
"\"An error occured while loading the XML content of the rendered item.\"",
")",
";",
"}",
"$",
"found",
"=",
"0",
";",
"$",
"deprecatedApis",
"=",
"array",
"(",
"'taoApi'",
",",
"'wfApi'",
")",
";",
"foreach",
"(",
"$",
"deprecatedApis",
"as",
"$",
"pattern",
")",
"{",
"$",
"found",
"+=",
"taoItems_helpers_Xhtml",
"::",
"removeScriptElements",
"(",
"$",
"dom",
",",
"'/'",
".",
"$",
"pattern",
".",
"'/i'",
")",
";",
"}",
"if",
"(",
"$",
"found",
">",
"0",
")",
"{",
"common_Logger",
"::",
"i",
"(",
"'found '",
".",
"$",
"found",
".",
"' references to deprecated APIs, replacing with legacy API'",
")",
";",
"$",
"taoItemsExt",
"=",
"common_ext_ExtensionsManager",
"::",
"singleton",
"(",
")",
"->",
"getExtensionById",
"(",
"'taoItems'",
")",
";",
"$",
"legacyApiSrc",
"=",
"Template",
"::",
"js",
"(",
"'legacyApi/taoLegacyApi.min.js'",
",",
"'taoItems'",
")",
";",
"taoItems_helpers_Xhtml",
"::",
"addScriptElement",
"(",
"$",
"dom",
",",
"$",
"legacyApiSrc",
")",
";",
"}",
"return",
"$",
"dom",
"->",
"saveHTML",
"(",
")",
";",
"}"
] | Removes unnescessary API references
@param Resource $item | [
"Removes",
"unnescessary",
"API",
"references"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/OwiItemModel.php#L104-L122 |
oat-sa/extension-tao-itemhtml | model/export/OwiExportHandler.php | OwiExportHandler.export | public function export($formValues, $destination)
{
if (!isset($formValues['filename'])) {
$msg = 'Missing filename for export using '.__CLASS__;
common_Logger::w($msg);
return Report::createFailure($msg);
}
$exportUri = isset($formValues['uri']) ? $formValues['uri'] : $formValues['classUri'];
$report = Report::createSuccess();
$itemService = taoItems_models_classes_ItemsService::singleton();
$fileName = $formValues['filename'].'_'.time().'.zip';
$path = tao_helpers_File::concat([$destination, $fileName]);
if (!tao_helpers_File::securityCheck($path, true)) {
throw new Exception('Unauthorized file name');
}
$zipArchive = new ZipArchive();
if ($zipArchive->open($path, ZipArchive::CREATE) !== true) {
throw new Exception('Unable to create archive at '.$path);
}
$item = new core_kernel_classes_Resource($exportUri);
if ($itemService->hasItemModel($item, [OwiItemModel::ITEMMODEL_URI])) {
$exporter = new OwiExporter($item, $zipArchive);
$exporter->export();
} else {
throw new common_Exception('Tried to export non OWI ('.$item->getUri().') as OWI ');
}
$zipArchive->close();
$report->setData($path);
$report->setMessage(__('Resource(s) successfully exported.'));
return $report;
} | php | public function export($formValues, $destination)
{
if (!isset($formValues['filename'])) {
$msg = 'Missing filename for export using '.__CLASS__;
common_Logger::w($msg);
return Report::createFailure($msg);
}
$exportUri = isset($formValues['uri']) ? $formValues['uri'] : $formValues['classUri'];
$report = Report::createSuccess();
$itemService = taoItems_models_classes_ItemsService::singleton();
$fileName = $formValues['filename'].'_'.time().'.zip';
$path = tao_helpers_File::concat([$destination, $fileName]);
if (!tao_helpers_File::securityCheck($path, true)) {
throw new Exception('Unauthorized file name');
}
$zipArchive = new ZipArchive();
if ($zipArchive->open($path, ZipArchive::CREATE) !== true) {
throw new Exception('Unable to create archive at '.$path);
}
$item = new core_kernel_classes_Resource($exportUri);
if ($itemService->hasItemModel($item, [OwiItemModel::ITEMMODEL_URI])) {
$exporter = new OwiExporter($item, $zipArchive);
$exporter->export();
} else {
throw new common_Exception('Tried to export non OWI ('.$item->getUri().') as OWI ');
}
$zipArchive->close();
$report->setData($path);
$report->setMessage(__('Resource(s) successfully exported.'));
return $report;
} | [
"public",
"function",
"export",
"(",
"$",
"formValues",
",",
"$",
"destination",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"formValues",
"[",
"'filename'",
"]",
")",
")",
"{",
"$",
"msg",
"=",
"'Missing filename for export using '",
".",
"__CLASS__",
";",
"common_Logger",
"::",
"w",
"(",
"$",
"msg",
")",
";",
"return",
"Report",
"::",
"createFailure",
"(",
"$",
"msg",
")",
";",
"}",
"$",
"exportUri",
"=",
"isset",
"(",
"$",
"formValues",
"[",
"'uri'",
"]",
")",
"?",
"$",
"formValues",
"[",
"'uri'",
"]",
":",
"$",
"formValues",
"[",
"'classUri'",
"]",
";",
"$",
"report",
"=",
"Report",
"::",
"createSuccess",
"(",
")",
";",
"$",
"itemService",
"=",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
";",
"$",
"fileName",
"=",
"$",
"formValues",
"[",
"'filename'",
"]",
".",
"'_'",
".",
"time",
"(",
")",
".",
"'.zip'",
";",
"$",
"path",
"=",
"tao_helpers_File",
"::",
"concat",
"(",
"[",
"$",
"destination",
",",
"$",
"fileName",
"]",
")",
";",
"if",
"(",
"!",
"tao_helpers_File",
"::",
"securityCheck",
"(",
"$",
"path",
",",
"true",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Unauthorized file name'",
")",
";",
"}",
"$",
"zipArchive",
"=",
"new",
"ZipArchive",
"(",
")",
";",
"if",
"(",
"$",
"zipArchive",
"->",
"open",
"(",
"$",
"path",
",",
"ZipArchive",
"::",
"CREATE",
")",
"!==",
"true",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Unable to create archive at '",
".",
"$",
"path",
")",
";",
"}",
"$",
"item",
"=",
"new",
"core_kernel_classes_Resource",
"(",
"$",
"exportUri",
")",
";",
"if",
"(",
"$",
"itemService",
"->",
"hasItemModel",
"(",
"$",
"item",
",",
"[",
"OwiItemModel",
"::",
"ITEMMODEL_URI",
"]",
")",
")",
"{",
"$",
"exporter",
"=",
"new",
"OwiExporter",
"(",
"$",
"item",
",",
"$",
"zipArchive",
")",
";",
"$",
"exporter",
"->",
"export",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"common_Exception",
"(",
"'Tried to export non OWI ('",
".",
"$",
"item",
"->",
"getUri",
"(",
")",
".",
"') as OWI '",
")",
";",
"}",
"$",
"zipArchive",
"->",
"close",
"(",
")",
";",
"$",
"report",
"->",
"setData",
"(",
"$",
"path",
")",
";",
"$",
"report",
"->",
"setMessage",
"(",
"__",
"(",
"'Resource(s) successfully exported.'",
")",
")",
";",
"return",
"$",
"report",
";",
"}"
] | @param array $formValues
@param string $destination
@return Report
@throws \common_exception_Error
@throws common_Exception | [
"@param",
"array",
"$formValues",
"@param",
"string",
"$destination",
"@return",
"Report"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/export/OwiExportHandler.php#L77-L116 |
oat-sa/extension-tao-itemhtml | model/export/ExportForm.php | ExportForm.initElements | public function initElements()
{
$itemService = taoItems_models_classes_ItemsService::singleton();
$fileName = '';
$options = array();
if(isset($this->data['instance'])){
$item = $this->data['instance'];
if($item instanceof core_kernel_classes_Resource)
{
if($itemService->hasItemModel($item, array(OwiItemModel::ITEMMODEL_URI))){
$fileName = strtolower(tao_helpers_Display::textCleaner($item->getLabel()));
$options[$item->getUri()] = $item->getLabel();
}
}
}
else {
if(isset($this->data['class'])){
$class = $this->data['class'];
}
else{
$class = $itemService->getRootClass();
}
if($class instanceof core_kernel_classes_Class){
$fileName = strtolower(tao_helpers_Display::textCleaner($class->getLabel(), '*'));
foreach($class->getInstances() as $instance){
if($itemService->hasItemModel($instance, array(OwiItemModel::ITEMMODEL_URI)) && $itemService->hasItemContent($instance)){
$options[$instance->getUri()] = $instance->getLabel();
}
}
}
}
$nameElt = tao_helpers_form_FormFactory::getElement('filename', 'Textbox');
$nameElt->setDescription(__('File name'));
$nameElt->setValue($fileName);
$nameElt->setUnit(".zip");
$nameElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($nameElt);
$instanceElt = tao_helpers_form_FormFactory::getElement('exportInstance', 'Radiobox');
$instanceElt->setDescription(__('Items'));
$instanceElt->setAttribute('checkAll', true);
$instanceElt->setOptions(tao_helpers_Uri::encodeArray($options, tao_helpers_Uri::ENCODE_ARRAY_KEYS));
$instanceElt->setValue(current(array_keys($options)));
$this->form->addElement($instanceElt);
$this->form->createGroup('options', __('Export an Open Web Item'), array('filename', 'exportInstance'));
} | php | public function initElements()
{
$itemService = taoItems_models_classes_ItemsService::singleton();
$fileName = '';
$options = array();
if(isset($this->data['instance'])){
$item = $this->data['instance'];
if($item instanceof core_kernel_classes_Resource)
{
if($itemService->hasItemModel($item, array(OwiItemModel::ITEMMODEL_URI))){
$fileName = strtolower(tao_helpers_Display::textCleaner($item->getLabel()));
$options[$item->getUri()] = $item->getLabel();
}
}
}
else {
if(isset($this->data['class'])){
$class = $this->data['class'];
}
else{
$class = $itemService->getRootClass();
}
if($class instanceof core_kernel_classes_Class){
$fileName = strtolower(tao_helpers_Display::textCleaner($class->getLabel(), '*'));
foreach($class->getInstances() as $instance){
if($itemService->hasItemModel($instance, array(OwiItemModel::ITEMMODEL_URI)) && $itemService->hasItemContent($instance)){
$options[$instance->getUri()] = $instance->getLabel();
}
}
}
}
$nameElt = tao_helpers_form_FormFactory::getElement('filename', 'Textbox');
$nameElt->setDescription(__('File name'));
$nameElt->setValue($fileName);
$nameElt->setUnit(".zip");
$nameElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty'));
$this->form->addElement($nameElt);
$instanceElt = tao_helpers_form_FormFactory::getElement('exportInstance', 'Radiobox');
$instanceElt->setDescription(__('Items'));
$instanceElt->setAttribute('checkAll', true);
$instanceElt->setOptions(tao_helpers_Uri::encodeArray($options, tao_helpers_Uri::ENCODE_ARRAY_KEYS));
$instanceElt->setValue(current(array_keys($options)));
$this->form->addElement($instanceElt);
$this->form->createGroup('options', __('Export an Open Web Item'), array('filename', 'exportInstance'));
} | [
"public",
"function",
"initElements",
"(",
")",
"{",
"$",
"itemService",
"=",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
";",
"$",
"fileName",
"=",
"''",
";",
"$",
"options",
"=",
"array",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"data",
"[",
"'instance'",
"]",
")",
")",
"{",
"$",
"item",
"=",
"$",
"this",
"->",
"data",
"[",
"'instance'",
"]",
";",
"if",
"(",
"$",
"item",
"instanceof",
"core_kernel_classes_Resource",
")",
"{",
"if",
"(",
"$",
"itemService",
"->",
"hasItemModel",
"(",
"$",
"item",
",",
"array",
"(",
"OwiItemModel",
"::",
"ITEMMODEL_URI",
")",
")",
")",
"{",
"$",
"fileName",
"=",
"strtolower",
"(",
"tao_helpers_Display",
"::",
"textCleaner",
"(",
"$",
"item",
"->",
"getLabel",
"(",
")",
")",
")",
";",
"$",
"options",
"[",
"$",
"item",
"->",
"getUri",
"(",
")",
"]",
"=",
"$",
"item",
"->",
"getLabel",
"(",
")",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"data",
"[",
"'class'",
"]",
")",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"data",
"[",
"'class'",
"]",
";",
"}",
"else",
"{",
"$",
"class",
"=",
"$",
"itemService",
"->",
"getRootClass",
"(",
")",
";",
"}",
"if",
"(",
"$",
"class",
"instanceof",
"core_kernel_classes_Class",
")",
"{",
"$",
"fileName",
"=",
"strtolower",
"(",
"tao_helpers_Display",
"::",
"textCleaner",
"(",
"$",
"class",
"->",
"getLabel",
"(",
")",
",",
"'*'",
")",
")",
";",
"foreach",
"(",
"$",
"class",
"->",
"getInstances",
"(",
")",
"as",
"$",
"instance",
")",
"{",
"if",
"(",
"$",
"itemService",
"->",
"hasItemModel",
"(",
"$",
"instance",
",",
"array",
"(",
"OwiItemModel",
"::",
"ITEMMODEL_URI",
")",
")",
"&&",
"$",
"itemService",
"->",
"hasItemContent",
"(",
"$",
"instance",
")",
")",
"{",
"$",
"options",
"[",
"$",
"instance",
"->",
"getUri",
"(",
")",
"]",
"=",
"$",
"instance",
"->",
"getLabel",
"(",
")",
";",
"}",
"}",
"}",
"}",
"$",
"nameElt",
"=",
"tao_helpers_form_FormFactory",
"::",
"getElement",
"(",
"'filename'",
",",
"'Textbox'",
")",
";",
"$",
"nameElt",
"->",
"setDescription",
"(",
"__",
"(",
"'File name'",
")",
")",
";",
"$",
"nameElt",
"->",
"setValue",
"(",
"$",
"fileName",
")",
";",
"$",
"nameElt",
"->",
"setUnit",
"(",
"\".zip\"",
")",
";",
"$",
"nameElt",
"->",
"addValidator",
"(",
"tao_helpers_form_FormFactory",
"::",
"getValidator",
"(",
"'NotEmpty'",
")",
")",
";",
"$",
"this",
"->",
"form",
"->",
"addElement",
"(",
"$",
"nameElt",
")",
";",
"$",
"instanceElt",
"=",
"tao_helpers_form_FormFactory",
"::",
"getElement",
"(",
"'exportInstance'",
",",
"'Radiobox'",
")",
";",
"$",
"instanceElt",
"->",
"setDescription",
"(",
"__",
"(",
"'Items'",
")",
")",
";",
"$",
"instanceElt",
"->",
"setAttribute",
"(",
"'checkAll'",
",",
"true",
")",
";",
"$",
"instanceElt",
"->",
"setOptions",
"(",
"tao_helpers_Uri",
"::",
"encodeArray",
"(",
"$",
"options",
",",
"tao_helpers_Uri",
"::",
"ENCODE_ARRAY_KEYS",
")",
")",
";",
"$",
"instanceElt",
"->",
"setValue",
"(",
"current",
"(",
"array_keys",
"(",
"$",
"options",
")",
")",
")",
";",
"$",
"this",
"->",
"form",
"->",
"addElement",
"(",
"$",
"instanceElt",
")",
";",
"$",
"this",
"->",
"form",
"->",
"createGroup",
"(",
"'options'",
",",
"__",
"(",
"'Export an Open Web Item'",
")",
",",
"array",
"(",
"'filename'",
",",
"'exportInstance'",
")",
")",
";",
"}"
] | overriden
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@return mixed | [
"overriden"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/export/ExportForm.php#L87-L138 |
oat-sa/extension-tao-itemhtml | model/import/OwiImportHandler.php | OwiImportHandler.import | public function import($class, $form, $userId = null)
{
$uploadedFile = $this->fetchUploadedFile($form);
if (isset($uploadedFile)) {
helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG);
// for backward compatibility
$disable_validation = $form instanceof \tao_helpers_form_Form
? (array)$form->getValue('disable_validation')
: (array)$form['disable_validation'];
$validate = count($disable_validation) == 0 ? true : false;
$importService = new ImportService();
try {
$report = $importService->importXhtmlFile($uploadedFile, $class, $validate);
} catch (Exception $e) {
$report = common_report_Report::createFailure(
__('An unexpected error occured during the OWI Item import.')
);
if ($e instanceof common_exception_UserReadableException) {
$report->add($e);
}
}
helpers_TimeOutHelper::reset();
$this->getUploadService()->remove($uploadedFile);
} else {
throw new common_exception_Error('No file provided as parameter \'source\' for OWI import');
}
return $report;
} | php | public function import($class, $form, $userId = null)
{
$uploadedFile = $this->fetchUploadedFile($form);
if (isset($uploadedFile)) {
helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::LONG);
// for backward compatibility
$disable_validation = $form instanceof \tao_helpers_form_Form
? (array)$form->getValue('disable_validation')
: (array)$form['disable_validation'];
$validate = count($disable_validation) == 0 ? true : false;
$importService = new ImportService();
try {
$report = $importService->importXhtmlFile($uploadedFile, $class, $validate);
} catch (Exception $e) {
$report = common_report_Report::createFailure(
__('An unexpected error occured during the OWI Item import.')
);
if ($e instanceof common_exception_UserReadableException) {
$report->add($e);
}
}
helpers_TimeOutHelper::reset();
$this->getUploadService()->remove($uploadedFile);
} else {
throw new common_exception_Error('No file provided as parameter \'source\' for OWI import');
}
return $report;
} | [
"public",
"function",
"import",
"(",
"$",
"class",
",",
"$",
"form",
",",
"$",
"userId",
"=",
"null",
")",
"{",
"$",
"uploadedFile",
"=",
"$",
"this",
"->",
"fetchUploadedFile",
"(",
"$",
"form",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"uploadedFile",
")",
")",
"{",
"helpers_TimeOutHelper",
"::",
"setTimeOutLimit",
"(",
"helpers_TimeOutHelper",
"::",
"LONG",
")",
";",
"// for backward compatibility",
"$",
"disable_validation",
"=",
"$",
"form",
"instanceof",
"\\",
"tao_helpers_form_Form",
"?",
"(",
"array",
")",
"$",
"form",
"->",
"getValue",
"(",
"'disable_validation'",
")",
":",
"(",
"array",
")",
"$",
"form",
"[",
"'disable_validation'",
"]",
";",
"$",
"validate",
"=",
"count",
"(",
"$",
"disable_validation",
")",
"==",
"0",
"?",
"true",
":",
"false",
";",
"$",
"importService",
"=",
"new",
"ImportService",
"(",
")",
";",
"try",
"{",
"$",
"report",
"=",
"$",
"importService",
"->",
"importXhtmlFile",
"(",
"$",
"uploadedFile",
",",
"$",
"class",
",",
"$",
"validate",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"report",
"=",
"common_report_Report",
"::",
"createFailure",
"(",
"__",
"(",
"'An unexpected error occured during the OWI Item import.'",
")",
")",
";",
"if",
"(",
"$",
"e",
"instanceof",
"common_exception_UserReadableException",
")",
"{",
"$",
"report",
"->",
"add",
"(",
"$",
"e",
")",
";",
"}",
"}",
"helpers_TimeOutHelper",
"::",
"reset",
"(",
")",
";",
"$",
"this",
"->",
"getUploadService",
"(",
")",
"->",
"remove",
"(",
"$",
"uploadedFile",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"common_exception_Error",
"(",
"'No file provided as parameter \\'source\\' for OWI import'",
")",
";",
"}",
"return",
"$",
"report",
";",
"}"
] | (non-PHPdoc)
@see tao_models_classes_import_ImportHandler::import()
@param \core_kernel_classes_Class $class
@param \tao_helpers_form_Form $form
@param string|null $userId owner of the resource
@return common_report_Report
@throws \oat\oatbox\service\ServiceNotFoundException
@throws \common_Exception
@throws common_exception_Error | [
"(",
"non",
"-",
"PHPdoc",
")"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/import/OwiImportHandler.php#L78-L113 |
oat-sa/extension-tao-itemhtml | model/import/PackageParser.php | PackageParser.validate | public function validate($schema = '')
{
$forced = $this->valid;
$this->valid = true;
try {
switch ($this->sourceType) {
case self::SOURCE_FILE:
if (!file_exists($this->source)) {
throw new Exception("File " . $this->source . " not found.");
}
if (!is_readable($this->source)) {
throw new Exception("Unable to read file " . $this->source);
}
if (!preg_match("/\.zip$/", basename($this->source))) {
throw new Exception("Wrong file extension in " . $this->source . ", zip extension is expected");
}
if (!tao_helpers_File::securityCheck($this->source)) {
throw new Exception($this->source . " seems to contain some security issues");
}
break;
case self::SOURCE_FLYFILE:
/** @var File $this->source */
if (! $this->source->exists()) {
throw new Exception('Source file does not exists ("' . $this->source->getBasename() . '").');
}
if (!preg_match("/\.zip$/", $this->source->getBasename())) {
throw new Exception('Wrong file extension in ' . $this->source->getBasename() . ', zip extension is expected.');
}
if (! $this->content = $this->source->read()) {
throw new Exception('Unable to read file ("' . $this->source->getBasename() . '").');
}
break;
default:
throw new Exception("File cannot be handled by package parser.");
break;
}
} catch (Exception $e) {
if ($forced) {
throw $e;
} else {
$this->addError($e);
}
}
if ($this->valid && !$forced) {
$this->valid = false;
$this->valid = $this->isValidArchive();
}
return $this->valid;
} | php | public function validate($schema = '')
{
$forced = $this->valid;
$this->valid = true;
try {
switch ($this->sourceType) {
case self::SOURCE_FILE:
if (!file_exists($this->source)) {
throw new Exception("File " . $this->source . " not found.");
}
if (!is_readable($this->source)) {
throw new Exception("Unable to read file " . $this->source);
}
if (!preg_match("/\.zip$/", basename($this->source))) {
throw new Exception("Wrong file extension in " . $this->source . ", zip extension is expected");
}
if (!tao_helpers_File::securityCheck($this->source)) {
throw new Exception($this->source . " seems to contain some security issues");
}
break;
case self::SOURCE_FLYFILE:
/** @var File $this->source */
if (! $this->source->exists()) {
throw new Exception('Source file does not exists ("' . $this->source->getBasename() . '").');
}
if (!preg_match("/\.zip$/", $this->source->getBasename())) {
throw new Exception('Wrong file extension in ' . $this->source->getBasename() . ', zip extension is expected.');
}
if (! $this->content = $this->source->read()) {
throw new Exception('Unable to read file ("' . $this->source->getBasename() . '").');
}
break;
default:
throw new Exception("File cannot be handled by package parser.");
break;
}
} catch (Exception $e) {
if ($forced) {
throw $e;
} else {
$this->addError($e);
}
}
if ($this->valid && !$forced) {
$this->valid = false;
$this->valid = $this->isValidArchive();
}
return $this->valid;
} | [
"public",
"function",
"validate",
"(",
"$",
"schema",
"=",
"''",
")",
"{",
"$",
"forced",
"=",
"$",
"this",
"->",
"valid",
";",
"$",
"this",
"->",
"valid",
"=",
"true",
";",
"try",
"{",
"switch",
"(",
"$",
"this",
"->",
"sourceType",
")",
"{",
"case",
"self",
"::",
"SOURCE_FILE",
":",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"source",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"File \"",
".",
"$",
"this",
"->",
"source",
".",
"\" not found.\"",
")",
";",
"}",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"this",
"->",
"source",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Unable to read file \"",
".",
"$",
"this",
"->",
"source",
")",
";",
"}",
"if",
"(",
"!",
"preg_match",
"(",
"\"/\\.zip$/\"",
",",
"basename",
"(",
"$",
"this",
"->",
"source",
")",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Wrong file extension in \"",
".",
"$",
"this",
"->",
"source",
".",
"\", zip extension is expected\"",
")",
";",
"}",
"if",
"(",
"!",
"tao_helpers_File",
"::",
"securityCheck",
"(",
"$",
"this",
"->",
"source",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"$",
"this",
"->",
"source",
".",
"\" seems to contain some security issues\"",
")",
";",
"}",
"break",
";",
"case",
"self",
"::",
"SOURCE_FLYFILE",
":",
"/** @var File $this->source */",
"if",
"(",
"!",
"$",
"this",
"->",
"source",
"->",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Source file does not exists (\"'",
".",
"$",
"this",
"->",
"source",
"->",
"getBasename",
"(",
")",
".",
"'\").'",
")",
";",
"}",
"if",
"(",
"!",
"preg_match",
"(",
"\"/\\.zip$/\"",
",",
"$",
"this",
"->",
"source",
"->",
"getBasename",
"(",
")",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Wrong file extension in '",
".",
"$",
"this",
"->",
"source",
"->",
"getBasename",
"(",
")",
".",
"', zip extension is expected.'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"content",
"=",
"$",
"this",
"->",
"source",
"->",
"read",
"(",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Unable to read file (\"'",
".",
"$",
"this",
"->",
"source",
"->",
"getBasename",
"(",
")",
".",
"'\").'",
")",
";",
"}",
"break",
";",
"default",
":",
"throw",
"new",
"Exception",
"(",
"\"File cannot be handled by package parser.\"",
")",
";",
"break",
";",
"}",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"forced",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"addError",
"(",
"$",
"e",
")",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"valid",
"&&",
"!",
"$",
"forced",
")",
"{",
"$",
"this",
"->",
"valid",
"=",
"false",
";",
"$",
"this",
"->",
"valid",
"=",
"$",
"this",
"->",
"isValidArchive",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"valid",
";",
"}"
] | Validate the zip archive. Local and remote file are allowed.
- Check if file is found
- Check content is not empty
- Check extension as zip
- In case of local, check path security
- Then validate archive
@param string $schema
@return bool
@throws Exception | [
"Validate",
"the",
"zip",
"archive",
".",
"Local",
"and",
"remote",
"file",
"are",
"allowed",
".",
"-",
"Check",
"if",
"file",
"is",
"found",
"-",
"Check",
"content",
"is",
"not",
"empty",
"-",
"Check",
"extension",
"as",
"zip",
"-",
"In",
"case",
"of",
"local",
"check",
"path",
"security",
"-",
"Then",
"validate",
"archive"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/import/PackageParser.php#L61-L114 |
oat-sa/extension-tao-itemhtml | model/import/PackageParser.php | PackageParser.extract | public function extract()
{
$content = '';
$folder = tao_helpers_File::createTempDir();
$zip = new ZipArchive();
$source = $this->getExtractedSource();
if ($zip->open($source) === true) {
if (tao_helpers_File::checkWhetherArchiveIsBomb($zip)) {
throw new \common_Exception(sprintf('Source "%s" seems to be a ZIP bomb', $source));
}
if ($zip->extractTo($folder)) {
$content = $folder;
}
$zip->close();
}
return $content;
} | php | public function extract()
{
$content = '';
$folder = tao_helpers_File::createTempDir();
$zip = new ZipArchive();
$source = $this->getExtractedSource();
if ($zip->open($source) === true) {
if (tao_helpers_File::checkWhetherArchiveIsBomb($zip)) {
throw new \common_Exception(sprintf('Source "%s" seems to be a ZIP bomb', $source));
}
if ($zip->extractTo($folder)) {
$content = $folder;
}
$zip->close();
}
return $content;
} | [
"public",
"function",
"extract",
"(",
")",
"{",
"$",
"content",
"=",
"''",
";",
"$",
"folder",
"=",
"tao_helpers_File",
"::",
"createTempDir",
"(",
")",
";",
"$",
"zip",
"=",
"new",
"ZipArchive",
"(",
")",
";",
"$",
"source",
"=",
"$",
"this",
"->",
"getExtractedSource",
"(",
")",
";",
"if",
"(",
"$",
"zip",
"->",
"open",
"(",
"$",
"source",
")",
"===",
"true",
")",
"{",
"if",
"(",
"tao_helpers_File",
"::",
"checkWhetherArchiveIsBomb",
"(",
"$",
"zip",
")",
")",
"{",
"throw",
"new",
"\\",
"common_Exception",
"(",
"sprintf",
"(",
"'Source \"%s\" seems to be a ZIP bomb'",
",",
"$",
"source",
")",
")",
";",
"}",
"if",
"(",
"$",
"zip",
"->",
"extractTo",
"(",
"$",
"folder",
")",
")",
"{",
"$",
"content",
"=",
"$",
"folder",
";",
"}",
"$",
"zip",
"->",
"close",
"(",
")",
";",
"}",
"return",
"$",
"content",
";",
"}"
] | Extract the zip archive and return the path to extracted package
@return string
@throws \common_exception | [
"Extract",
"the",
"zip",
"archive",
"and",
"return",
"the",
"path",
"to",
"extracted",
"package"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/import/PackageParser.php#L122-L139 |
oat-sa/extension-tao-itemhtml | model/import/PackageParser.php | PackageParser.isValidArchive | protected function isValidArchive()
{
$isValid = false;
$zip = new ZipArchive();
//check the archive opening and the consistency
if ($zip->open($this->getExtractedSource(), ZIPARCHIVE::CHECKCONS) !== false) {
//check if the manifest is there
if ($zip->locateName("index.html") !== false) {
$isValid = true;
} else {
$this->addError(__("An Open Web Item package must contain an index.html file at the root of the archive."));
}
} else {
$this->addError(__("The ZIP archive containing the Open Web Item could not be open."));
}
return $isValid;
} | php | protected function isValidArchive()
{
$isValid = false;
$zip = new ZipArchive();
//check the archive opening and the consistency
if ($zip->open($this->getExtractedSource(), ZIPARCHIVE::CHECKCONS) !== false) {
//check if the manifest is there
if ($zip->locateName("index.html") !== false) {
$isValid = true;
} else {
$this->addError(__("An Open Web Item package must contain an index.html file at the root of the archive."));
}
} else {
$this->addError(__("The ZIP archive containing the Open Web Item could not be open."));
}
return $isValid;
} | [
"protected",
"function",
"isValidArchive",
"(",
")",
"{",
"$",
"isValid",
"=",
"false",
";",
"$",
"zip",
"=",
"new",
"ZipArchive",
"(",
")",
";",
"//check the archive opening and the consistency\r",
"if",
"(",
"$",
"zip",
"->",
"open",
"(",
"$",
"this",
"->",
"getExtractedSource",
"(",
")",
",",
"ZIPARCHIVE",
"::",
"CHECKCONS",
")",
"!==",
"false",
")",
"{",
"//check if the manifest is there\r",
"if",
"(",
"$",
"zip",
"->",
"locateName",
"(",
"\"index.html\"",
")",
"!==",
"false",
")",
"{",
"$",
"isValid",
"=",
"true",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"addError",
"(",
"__",
"(",
"\"An Open Web Item package must contain an index.html file at the root of the archive.\"",
")",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"addError",
"(",
"__",
"(",
"\"The ZIP archive containing the Open Web Item could not be open.\"",
")",
")",
";",
"}",
"return",
"$",
"isValid",
";",
"}"
] | Check if the archive is valid by checking if an index.html exists at package root
@return bool | [
"Check",
"if",
"the",
"archive",
"is",
"valid",
"by",
"checking",
"if",
"an",
"index",
".",
"html",
"exists",
"at",
"package",
"root"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/import/PackageParser.php#L159-L176 |
oat-sa/extension-tao-itemhtml | model/import/PackageParser.php | PackageParser.getExtractedSource | protected function getExtractedSource()
{
if ($this->source instanceof File) {
$this->tmpDirectory = tao_helpers_File::createTempDir();
$this->tmpFile = $this->tmpDirectory . uniqid('owiArchive') . 'zip';
$sourceResource = $this->source->readStream();
$destinationResource = fopen($this->tmpFile, 'w');
stream_copy_to_stream($sourceResource, $destinationResource);
fclose($sourceResource);
fclose($destinationResource);
$this->source = $this->tmpFile;
}
if (!is_file($this->source)) {
throw new \common_exception_Error("Source " . $this->source . " is not a file");
}
return $this->source;
} | php | protected function getExtractedSource()
{
if ($this->source instanceof File) {
$this->tmpDirectory = tao_helpers_File::createTempDir();
$this->tmpFile = $this->tmpDirectory . uniqid('owiArchive') . 'zip';
$sourceResource = $this->source->readStream();
$destinationResource = fopen($this->tmpFile, 'w');
stream_copy_to_stream($sourceResource, $destinationResource);
fclose($sourceResource);
fclose($destinationResource);
$this->source = $this->tmpFile;
}
if (!is_file($this->source)) {
throw new \common_exception_Error("Source " . $this->source . " is not a file");
}
return $this->source;
} | [
"protected",
"function",
"getExtractedSource",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"source",
"instanceof",
"File",
")",
"{",
"$",
"this",
"->",
"tmpDirectory",
"=",
"tao_helpers_File",
"::",
"createTempDir",
"(",
")",
";",
"$",
"this",
"->",
"tmpFile",
"=",
"$",
"this",
"->",
"tmpDirectory",
".",
"uniqid",
"(",
"'owiArchive'",
")",
".",
"'zip'",
";",
"$",
"sourceResource",
"=",
"$",
"this",
"->",
"source",
"->",
"readStream",
"(",
")",
";",
"$",
"destinationResource",
"=",
"fopen",
"(",
"$",
"this",
"->",
"tmpFile",
",",
"'w'",
")",
";",
"stream_copy_to_stream",
"(",
"$",
"sourceResource",
",",
"$",
"destinationResource",
")",
";",
"fclose",
"(",
"$",
"sourceResource",
")",
";",
"fclose",
"(",
"$",
"destinationResource",
")",
";",
"$",
"this",
"->",
"source",
"=",
"$",
"this",
"->",
"tmpFile",
";",
"}",
"if",
"(",
"!",
"is_file",
"(",
"$",
"this",
"->",
"source",
")",
")",
"{",
"throw",
"new",
"\\",
"common_exception_Error",
"(",
"\"Source \"",
".",
"$",
"this",
"->",
"source",
".",
"\" is not a file\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"source",
";",
"}"
] | Get a real path of source. If the source is a remote file, download it and return the new path.
@return File|string
@throws \common_exception_Error | [
"Get",
"a",
"real",
"path",
"of",
"source",
".",
"If",
"the",
"source",
"is",
"a",
"remote",
"file",
"download",
"it",
"and",
"return",
"the",
"new",
"path",
"."
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/import/PackageParser.php#L184-L202 |
oat-sa/extension-tao-itemhtml | model/OwiItemCompiler.php | OwiItemCompiler.compile | public function compile()
{
$publicDirectory = $this->spawnPublicDirectory();
$item = $this->getResource();
$report = new common_report_Report(common_report_Report::TYPE_SUCCESS, __('Published %s', $item->getLabel()));
if (!taoItems_models_classes_ItemsService::singleton()->isItemModelDefined($item)) {
return $this->fail(__('Item \'%s\' has no model', $item->getLabel()));
}
$langs = $this->getContentUsedLanguages();
if (empty($langs)) {
$report->setType(common_report_Report::TYPE_ERROR);
$report->setMessage(__('Item "%s" is not available in any language', $item->getLabel()));
}
foreach ($langs as $compilationLanguage) {
$langReport = $this->deployItem($item, $compilationLanguage, $publicDirectory->getDirectory($compilationLanguage));
if ($langReport->getType() == common_report_Report::TYPE_ERROR) {
$report->setType(common_report_Report::TYPE_ERROR);
$report->setMessage(__('Failed to publish %1$s', $item->getLabel()));
$report->add($langReport);
break;
}
}
if ($report->getType() == common_report_Report::TYPE_SUCCESS) {
$report->setData($this->createService($item, $publicDirectory));
}
return $report;
} | php | public function compile()
{
$publicDirectory = $this->spawnPublicDirectory();
$item = $this->getResource();
$report = new common_report_Report(common_report_Report::TYPE_SUCCESS, __('Published %s', $item->getLabel()));
if (!taoItems_models_classes_ItemsService::singleton()->isItemModelDefined($item)) {
return $this->fail(__('Item \'%s\' has no model', $item->getLabel()));
}
$langs = $this->getContentUsedLanguages();
if (empty($langs)) {
$report->setType(common_report_Report::TYPE_ERROR);
$report->setMessage(__('Item "%s" is not available in any language', $item->getLabel()));
}
foreach ($langs as $compilationLanguage) {
$langReport = $this->deployItem($item, $compilationLanguage, $publicDirectory->getDirectory($compilationLanguage));
if ($langReport->getType() == common_report_Report::TYPE_ERROR) {
$report->setType(common_report_Report::TYPE_ERROR);
$report->setMessage(__('Failed to publish %1$s', $item->getLabel()));
$report->add($langReport);
break;
}
}
if ($report->getType() == common_report_Report::TYPE_SUCCESS) {
$report->setData($this->createService($item, $publicDirectory));
}
return $report;
} | [
"public",
"function",
"compile",
"(",
")",
"{",
"$",
"publicDirectory",
"=",
"$",
"this",
"->",
"spawnPublicDirectory",
"(",
")",
";",
"$",
"item",
"=",
"$",
"this",
"->",
"getResource",
"(",
")",
";",
"$",
"report",
"=",
"new",
"common_report_Report",
"(",
"common_report_Report",
"::",
"TYPE_SUCCESS",
",",
"__",
"(",
"'Published %s'",
",",
"$",
"item",
"->",
"getLabel",
"(",
")",
")",
")",
";",
"if",
"(",
"!",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
"->",
"isItemModelDefined",
"(",
"$",
"item",
")",
")",
"{",
"return",
"$",
"this",
"->",
"fail",
"(",
"__",
"(",
"'Item \\'%s\\' has no model'",
",",
"$",
"item",
"->",
"getLabel",
"(",
")",
")",
")",
";",
"}",
"$",
"langs",
"=",
"$",
"this",
"->",
"getContentUsedLanguages",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"langs",
")",
")",
"{",
"$",
"report",
"->",
"setType",
"(",
"common_report_Report",
"::",
"TYPE_ERROR",
")",
";",
"$",
"report",
"->",
"setMessage",
"(",
"__",
"(",
"'Item \"%s\" is not available in any language'",
",",
"$",
"item",
"->",
"getLabel",
"(",
")",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"langs",
"as",
"$",
"compilationLanguage",
")",
"{",
"$",
"langReport",
"=",
"$",
"this",
"->",
"deployItem",
"(",
"$",
"item",
",",
"$",
"compilationLanguage",
",",
"$",
"publicDirectory",
"->",
"getDirectory",
"(",
"$",
"compilationLanguage",
")",
")",
";",
"if",
"(",
"$",
"langReport",
"->",
"getType",
"(",
")",
"==",
"common_report_Report",
"::",
"TYPE_ERROR",
")",
"{",
"$",
"report",
"->",
"setType",
"(",
"common_report_Report",
"::",
"TYPE_ERROR",
")",
";",
"$",
"report",
"->",
"setMessage",
"(",
"__",
"(",
"'Failed to publish %1$s'",
",",
"$",
"item",
"->",
"getLabel",
"(",
")",
")",
")",
";",
"$",
"report",
"->",
"add",
"(",
"$",
"langReport",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"$",
"report",
"->",
"getType",
"(",
")",
"==",
"common_report_Report",
"::",
"TYPE_SUCCESS",
")",
"{",
"$",
"report",
"->",
"setData",
"(",
"$",
"this",
"->",
"createService",
"(",
"$",
"item",
",",
"$",
"publicDirectory",
")",
")",
";",
"}",
"return",
"$",
"report",
";",
"}"
] | Compile qti item
@throws taoItems_models_classes_CompilationFailedException
@return tao_models_classes_service_ServiceCall | [
"Compile",
"qti",
"item"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/model/OwiItemCompiler.php#L48-L77 |
oat-sa/extension-tao-itemhtml | controller/Authoring.php | Authoring.index | public function index() {
if (!$this->hasRequestParameter('instance') || strlen($this->getRequestParameter('instance')) == 0) {
throw new common_exception_MissingParameter('instance', __CLASS__);
}
$item = new core_kernel_classes_Resource(tao_helpers_Uri::decode($this->getRequestParameter('instance')));
$this->setData('hasContent', \taoItems_models_classes_ItemsService::singleton()->hasItemContent($item));
$formContainer = new OwiImportForm();
$myForm = $formContainer->getForm();
$element = tao_helpers_form_FormFactory::getElement('instance', 'hidden');
$element->setValue($item->getUri());
$myForm->addElement($element);
// for dataAcl on items
$element = tao_helpers_form_FormFactory::getElement('id', 'hidden');
$element->setValue($item->getUri());
$myForm->addElement($element);
if($myForm->isSubmited()){
if($myForm->isValid()){
$validate = count($myForm->getValue('disable_validation')) == 0 ? true : false;
$fileInfo = $myForm->getValue('source');
$uploadedFile = $fileInfo['uploaded_file'];
$importer = new ImportService();
$report = $importer->importContent($uploadedFile, $item, '', $validate);
return $this->returnReport($report);
}
}
$this->setData('formTitle', __('Import Content'));
$this->setData('myForm', $myForm->render());
$this->setView('form.tpl');
} | php | public function index() {
if (!$this->hasRequestParameter('instance') || strlen($this->getRequestParameter('instance')) == 0) {
throw new common_exception_MissingParameter('instance', __CLASS__);
}
$item = new core_kernel_classes_Resource(tao_helpers_Uri::decode($this->getRequestParameter('instance')));
$this->setData('hasContent', \taoItems_models_classes_ItemsService::singleton()->hasItemContent($item));
$formContainer = new OwiImportForm();
$myForm = $formContainer->getForm();
$element = tao_helpers_form_FormFactory::getElement('instance', 'hidden');
$element->setValue($item->getUri());
$myForm->addElement($element);
// for dataAcl on items
$element = tao_helpers_form_FormFactory::getElement('id', 'hidden');
$element->setValue($item->getUri());
$myForm->addElement($element);
if($myForm->isSubmited()){
if($myForm->isValid()){
$validate = count($myForm->getValue('disable_validation')) == 0 ? true : false;
$fileInfo = $myForm->getValue('source');
$uploadedFile = $fileInfo['uploaded_file'];
$importer = new ImportService();
$report = $importer->importContent($uploadedFile, $item, '', $validate);
return $this->returnReport($report);
}
}
$this->setData('formTitle', __('Import Content'));
$this->setData('myForm', $myForm->render());
$this->setView('form.tpl');
} | [
"public",
"function",
"index",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasRequestParameter",
"(",
"'instance'",
")",
"||",
"strlen",
"(",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'instance'",
")",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"common_exception_MissingParameter",
"(",
"'instance'",
",",
"__CLASS__",
")",
";",
"}",
"$",
"item",
"=",
"new",
"core_kernel_classes_Resource",
"(",
"tao_helpers_Uri",
"::",
"decode",
"(",
"$",
"this",
"->",
"getRequestParameter",
"(",
"'instance'",
")",
")",
")",
";",
"$",
"this",
"->",
"setData",
"(",
"'hasContent'",
",",
"\\",
"taoItems_models_classes_ItemsService",
"::",
"singleton",
"(",
")",
"->",
"hasItemContent",
"(",
"$",
"item",
")",
")",
";",
"$",
"formContainer",
"=",
"new",
"OwiImportForm",
"(",
")",
";",
"$",
"myForm",
"=",
"$",
"formContainer",
"->",
"getForm",
"(",
")",
";",
"$",
"element",
"=",
"tao_helpers_form_FormFactory",
"::",
"getElement",
"(",
"'instance'",
",",
"'hidden'",
")",
";",
"$",
"element",
"->",
"setValue",
"(",
"$",
"item",
"->",
"getUri",
"(",
")",
")",
";",
"$",
"myForm",
"->",
"addElement",
"(",
"$",
"element",
")",
";",
"// for dataAcl on items",
"$",
"element",
"=",
"tao_helpers_form_FormFactory",
"::",
"getElement",
"(",
"'id'",
",",
"'hidden'",
")",
";",
"$",
"element",
"->",
"setValue",
"(",
"$",
"item",
"->",
"getUri",
"(",
")",
")",
";",
"$",
"myForm",
"->",
"addElement",
"(",
"$",
"element",
")",
";",
"if",
"(",
"$",
"myForm",
"->",
"isSubmited",
"(",
")",
")",
"{",
"if",
"(",
"$",
"myForm",
"->",
"isValid",
"(",
")",
")",
"{",
"$",
"validate",
"=",
"count",
"(",
"$",
"myForm",
"->",
"getValue",
"(",
"'disable_validation'",
")",
")",
"==",
"0",
"?",
"true",
":",
"false",
";",
"$",
"fileInfo",
"=",
"$",
"myForm",
"->",
"getValue",
"(",
"'source'",
")",
";",
"$",
"uploadedFile",
"=",
"$",
"fileInfo",
"[",
"'uploaded_file'",
"]",
";",
"$",
"importer",
"=",
"new",
"ImportService",
"(",
")",
";",
"$",
"report",
"=",
"$",
"importer",
"->",
"importContent",
"(",
"$",
"uploadedFile",
",",
"$",
"item",
",",
"''",
",",
"$",
"validate",
")",
";",
"return",
"$",
"this",
"->",
"returnReport",
"(",
"$",
"report",
")",
";",
"}",
"}",
"$",
"this",
"->",
"setData",
"(",
"'formTitle'",
",",
"__",
"(",
"'Import Content'",
")",
")",
";",
"$",
"this",
"->",
"setData",
"(",
"'myForm'",
",",
"$",
"myForm",
"->",
"render",
"(",
")",
")",
";",
"$",
"this",
"->",
"setView",
"(",
"'form.tpl'",
")",
";",
"}"
] | (non-PHPdoc)
@see tao_actions_TaoModule::getRootClass() | [
"(",
"non",
"-",
"PHPdoc",
")"
] | train | https://github.com/oat-sa/extension-tao-itemhtml/blob/453d79fb4a3eaf5ff051ab68f538dda86e369050/controller/Authoring.php#L61-L96 |
helhum/typo3-config-handling | src/Typo3SiteConfiguration.php | Typo3SiteConfiguration.load | public function load(string $siteIdentifier): array
{
$fileName = $this->configPath . '/' . $siteIdentifier . '/' . $this->configFileName;
$factory = new ConfigurationReaderFactory(Environment::getConfigPath());
$reader = $factory->createRootReader($fileName);
return $reader->readConfig();
} | php | public function load(string $siteIdentifier): array
{
$fileName = $this->configPath . '/' . $siteIdentifier . '/' . $this->configFileName;
$factory = new ConfigurationReaderFactory(Environment::getConfigPath());
$reader = $factory->createRootReader($fileName);
return $reader->readConfig();
} | [
"public",
"function",
"load",
"(",
"string",
"$",
"siteIdentifier",
")",
":",
"array",
"{",
"$",
"fileName",
"=",
"$",
"this",
"->",
"configPath",
".",
"'/'",
".",
"$",
"siteIdentifier",
".",
"'/'",
".",
"$",
"this",
"->",
"configFileName",
";",
"$",
"factory",
"=",
"new",
"ConfigurationReaderFactory",
"(",
"Environment",
"::",
"getConfigPath",
"(",
")",
")",
";",
"$",
"reader",
"=",
"$",
"factory",
"->",
"createRootReader",
"(",
"$",
"fileName",
")",
";",
"return",
"$",
"reader",
"->",
"readConfig",
"(",
")",
";",
"}"
] | Load plain configuration
This method should only be used in case the original configuration as it exists in the file should be loaded,
for example for writing / editing configuration.
All read related actions should be performed on the site entity.
@param string $siteIdentifier
@return array | [
"Load",
"plain",
"configuration",
"This",
"method",
"should",
"only",
"be",
"used",
"in",
"case",
"the",
"original",
"configuration",
"as",
"it",
"exists",
"in",
"the",
"file",
"should",
"be",
"loaded",
"for",
"example",
"for",
"writing",
"/",
"editing",
"configuration",
"."
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Typo3SiteConfiguration.php#L25-L32 |
helhum/typo3-config-handling | src/Typo3SiteConfiguration.php | Typo3SiteConfiguration.write | public function write(string $siteIdentifier, array $configuration): void
{
$fileName = $this->configPath . '/' . $siteIdentifier . '/' . $this->configFileName;
if (!file_exists($fileName)) {
GeneralUtility::mkdir_deep($this->configPath . '/' . $siteIdentifier);
}
$yamlFileContents = Yaml::dump($configuration, 99);
GeneralUtility::writeFile($fileName, $yamlFileContents);
$this->getCache()->remove($this->cacheIdentifier);
$this->getCache()->remove('pseudo-sites');
} | php | public function write(string $siteIdentifier, array $configuration): void
{
$fileName = $this->configPath . '/' . $siteIdentifier . '/' . $this->configFileName;
if (!file_exists($fileName)) {
GeneralUtility::mkdir_deep($this->configPath . '/' . $siteIdentifier);
}
$yamlFileContents = Yaml::dump($configuration, 99);
GeneralUtility::writeFile($fileName, $yamlFileContents);
$this->getCache()->remove($this->cacheIdentifier);
$this->getCache()->remove('pseudo-sites');
} | [
"public",
"function",
"write",
"(",
"string",
"$",
"siteIdentifier",
",",
"array",
"$",
"configuration",
")",
":",
"void",
"{",
"$",
"fileName",
"=",
"$",
"this",
"->",
"configPath",
".",
"'/'",
".",
"$",
"siteIdentifier",
".",
"'/'",
".",
"$",
"this",
"->",
"configFileName",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"fileName",
")",
")",
"{",
"GeneralUtility",
"::",
"mkdir_deep",
"(",
"$",
"this",
"->",
"configPath",
".",
"'/'",
".",
"$",
"siteIdentifier",
")",
";",
"}",
"$",
"yamlFileContents",
"=",
"Yaml",
"::",
"dump",
"(",
"$",
"configuration",
",",
"99",
")",
";",
"GeneralUtility",
"::",
"writeFile",
"(",
"$",
"fileName",
",",
"$",
"yamlFileContents",
")",
";",
"$",
"this",
"->",
"getCache",
"(",
")",
"->",
"remove",
"(",
"$",
"this",
"->",
"cacheIdentifier",
")",
";",
"$",
"this",
"->",
"getCache",
"(",
")",
"->",
"remove",
"(",
"'pseudo-sites'",
")",
";",
"}"
] | Add or update a site configuration
@param string $siteIdentifier
@param array $configuration
@throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException | [
"Add",
"or",
"update",
"a",
"site",
"configuration"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Typo3SiteConfiguration.php#L41-L51 |
helhum/typo3-config-handling | src/ConfigDumper.php | ConfigDumper.getPhpCode | public function getPhpCode($value, array $referenceConfig = [], array $path = []): string
{
if (is_array($value)) {
$level = count($path);
if ($value === []) {
$code = '[]';
} else {
$code = '[' . PHP_EOL;
foreach ($value as $key => $arrayValue) {
// Indention
$code .= str_repeat(' ', $level + 1);
// Integer / string keys
$code .= is_int($key) ? $key . ' => ' : $this->getPhpCodeForPlaceholder($key, $referenceConfig, [], true) . ' => ';
if ($level === 2 && $path[0] === 'EXT' && $path[1] === 'extConf' && \is_array($arrayValue)) {
$code .= 'serialize(';
$code .= $this->getPhpCode($this->addDotsToTypoScript($arrayValue), $referenceConfig, array_merge($path, [$key]));
$code .= ')';
} else {
$code .= $this->getPhpCode($arrayValue, $referenceConfig, array_merge($path, [$key]));
}
$code .= ',' . PHP_EOL;
}
$code .= str_repeat(' ', $level) . ']';
}
} elseif (is_int($value) || is_float($value)) {
$code = (string)$value;
} elseif ($value === null) {
$code = 'null';
} elseif (is_bool($value)) {
$code = $value ? 'true' : 'false';
} elseif (is_string($value)) {
$code = $this->getPhpCodeForPlaceholder($value, $referenceConfig, $path);
} else {
throw new \RuntimeException('Objects, closures and resources are not supported', 1519779656);
}
return $code;
} | php | public function getPhpCode($value, array $referenceConfig = [], array $path = []): string
{
if (is_array($value)) {
$level = count($path);
if ($value === []) {
$code = '[]';
} else {
$code = '[' . PHP_EOL;
foreach ($value as $key => $arrayValue) {
// Indention
$code .= str_repeat(' ', $level + 1);
// Integer / string keys
$code .= is_int($key) ? $key . ' => ' : $this->getPhpCodeForPlaceholder($key, $referenceConfig, [], true) . ' => ';
if ($level === 2 && $path[0] === 'EXT' && $path[1] === 'extConf' && \is_array($arrayValue)) {
$code .= 'serialize(';
$code .= $this->getPhpCode($this->addDotsToTypoScript($arrayValue), $referenceConfig, array_merge($path, [$key]));
$code .= ')';
} else {
$code .= $this->getPhpCode($arrayValue, $referenceConfig, array_merge($path, [$key]));
}
$code .= ',' . PHP_EOL;
}
$code .= str_repeat(' ', $level) . ']';
}
} elseif (is_int($value) || is_float($value)) {
$code = (string)$value;
} elseif ($value === null) {
$code = 'null';
} elseif (is_bool($value)) {
$code = $value ? 'true' : 'false';
} elseif (is_string($value)) {
$code = $this->getPhpCodeForPlaceholder($value, $referenceConfig, $path);
} else {
throw new \RuntimeException('Objects, closures and resources are not supported', 1519779656);
}
return $code;
} | [
"public",
"function",
"getPhpCode",
"(",
"$",
"value",
",",
"array",
"$",
"referenceConfig",
"=",
"[",
"]",
",",
"array",
"$",
"path",
"=",
"[",
"]",
")",
":",
"string",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"level",
"=",
"count",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"value",
"===",
"[",
"]",
")",
"{",
"$",
"code",
"=",
"'[]'",
";",
"}",
"else",
"{",
"$",
"code",
"=",
"'['",
".",
"PHP_EOL",
";",
"foreach",
"(",
"$",
"value",
"as",
"$",
"key",
"=>",
"$",
"arrayValue",
")",
"{",
"// Indention",
"$",
"code",
".=",
"str_repeat",
"(",
"' '",
",",
"$",
"level",
"+",
"1",
")",
";",
"// Integer / string keys",
"$",
"code",
".=",
"is_int",
"(",
"$",
"key",
")",
"?",
"$",
"key",
".",
"' => '",
":",
"$",
"this",
"->",
"getPhpCodeForPlaceholder",
"(",
"$",
"key",
",",
"$",
"referenceConfig",
",",
"[",
"]",
",",
"true",
")",
".",
"' => '",
";",
"if",
"(",
"$",
"level",
"===",
"2",
"&&",
"$",
"path",
"[",
"0",
"]",
"===",
"'EXT'",
"&&",
"$",
"path",
"[",
"1",
"]",
"===",
"'extConf'",
"&&",
"\\",
"is_array",
"(",
"$",
"arrayValue",
")",
")",
"{",
"$",
"code",
".=",
"'serialize('",
";",
"$",
"code",
".=",
"$",
"this",
"->",
"getPhpCode",
"(",
"$",
"this",
"->",
"addDotsToTypoScript",
"(",
"$",
"arrayValue",
")",
",",
"$",
"referenceConfig",
",",
"array_merge",
"(",
"$",
"path",
",",
"[",
"$",
"key",
"]",
")",
")",
";",
"$",
"code",
".=",
"')'",
";",
"}",
"else",
"{",
"$",
"code",
".=",
"$",
"this",
"->",
"getPhpCode",
"(",
"$",
"arrayValue",
",",
"$",
"referenceConfig",
",",
"array_merge",
"(",
"$",
"path",
",",
"[",
"$",
"key",
"]",
")",
")",
";",
"}",
"$",
"code",
".=",
"','",
".",
"PHP_EOL",
";",
"}",
"$",
"code",
".=",
"str_repeat",
"(",
"' '",
",",
"$",
"level",
")",
".",
"']'",
";",
"}",
"}",
"elseif",
"(",
"is_int",
"(",
"$",
"value",
")",
"||",
"is_float",
"(",
"$",
"value",
")",
")",
"{",
"$",
"code",
"=",
"(",
"string",
")",
"$",
"value",
";",
"}",
"elseif",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"code",
"=",
"'null'",
";",
"}",
"elseif",
"(",
"is_bool",
"(",
"$",
"value",
")",
")",
"{",
"$",
"code",
"=",
"$",
"value",
"?",
"'true'",
":",
"'false'",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"code",
"=",
"$",
"this",
"->",
"getPhpCodeForPlaceholder",
"(",
"$",
"value",
",",
"$",
"referenceConfig",
",",
"$",
"path",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Objects, closures and resources are not supported'",
",",
"1519779656",
")",
";",
"}",
"return",
"$",
"code",
";",
"}"
] | Returns a PHP representation of a value, including value with placeholder
@param mixed $value
@param array $referenceConfig
@param array $path
@return string | [
"Returns",
"a",
"PHP",
"representation",
"of",
"a",
"value",
"including",
"value",
"with",
"placeholder"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/ConfigDumper.php#L83-L120 |
helhum/typo3-config-handling | src/ConfigCleaner.php | ConfigCleaner.cleanConfig | public function cleanConfig(array $baseConfig, array ...$referenceConfigs): array
{
$cleanedConfig = $baseConfig;
foreach ($referenceConfigs as $referenceConfig) {
$cleanedConfig = $this->removeIdenticalValues($cleanedConfig, $referenceConfig);
}
return $this->sortConfig($cleanedConfig);
} | php | public function cleanConfig(array $baseConfig, array ...$referenceConfigs): array
{
$cleanedConfig = $baseConfig;
foreach ($referenceConfigs as $referenceConfig) {
$cleanedConfig = $this->removeIdenticalValues($cleanedConfig, $referenceConfig);
}
return $this->sortConfig($cleanedConfig);
} | [
"public",
"function",
"cleanConfig",
"(",
"array",
"$",
"baseConfig",
",",
"array",
"...",
"$",
"referenceConfigs",
")",
":",
"array",
"{",
"$",
"cleanedConfig",
"=",
"$",
"baseConfig",
";",
"foreach",
"(",
"$",
"referenceConfigs",
"as",
"$",
"referenceConfig",
")",
"{",
"$",
"cleanedConfig",
"=",
"$",
"this",
"->",
"removeIdenticalValues",
"(",
"$",
"cleanedConfig",
",",
"$",
"referenceConfig",
")",
";",
"}",
"return",
"$",
"this",
"->",
"sortConfig",
"(",
"$",
"cleanedConfig",
")",
";",
"}"
] | Remove all conf settings that are identical to the ones in default config,
which makes the setting obsolete
@param array $baseConfig
@param array[] $referenceConfigs
@return array | [
"Remove",
"all",
"conf",
"settings",
"that",
"are",
"identical",
"to",
"the",
"ones",
"in",
"default",
"config",
"which",
"makes",
"the",
"setting",
"obsolete"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/ConfigCleaner.php#L37-L45 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.getMergedLocalConfiguration | public function getMergedLocalConfiguration(): array
{
if ($this->mainConfig === null) {
$this->mainConfig = $this->configLoader->load();
}
return $this->mainConfig;
} | php | public function getMergedLocalConfiguration(): array
{
if ($this->mainConfig === null) {
$this->mainConfig = $this->configLoader->load();
}
return $this->mainConfig;
} | [
"public",
"function",
"getMergedLocalConfiguration",
"(",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"mainConfig",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"mainConfig",
"=",
"$",
"this",
"->",
"configLoader",
"->",
"load",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"mainConfig",
";",
"}"
] | Returns local configuration array merged with default configuration
@return array | [
"Returns",
"local",
"configuration",
"array",
"merged",
"with",
"default",
"configuration"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L223-L230 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.updateLocalConfiguration | public function updateLocalConfiguration(array $configurationToMerge)
{
// We take care exposing the legacy extension config ourselves
unset($configurationToMerge['EXT']['extConf']);
$overrideSettingsFile = SettingsFiles::getOverrideSettingsFile();
if (!$this->canWriteConfiguration()) {
throw new \RuntimeException(
$overrideSettingsFile . ' is not writable.',
1346323822
);
}
if ($this->configExtractor->extractConfig($configurationToMerge, $this->getMergedLocalConfiguration(), $overrideSettingsFile)) {
$this->configLoader->flushCache();
}
} | php | public function updateLocalConfiguration(array $configurationToMerge)
{
// We take care exposing the legacy extension config ourselves
unset($configurationToMerge['EXT']['extConf']);
$overrideSettingsFile = SettingsFiles::getOverrideSettingsFile();
if (!$this->canWriteConfiguration()) {
throw new \RuntimeException(
$overrideSettingsFile . ' is not writable.',
1346323822
);
}
if ($this->configExtractor->extractConfig($configurationToMerge, $this->getMergedLocalConfiguration(), $overrideSettingsFile)) {
$this->configLoader->flushCache();
}
} | [
"public",
"function",
"updateLocalConfiguration",
"(",
"array",
"$",
"configurationToMerge",
")",
"{",
"// We take care exposing the legacy extension config ourselves",
"unset",
"(",
"$",
"configurationToMerge",
"[",
"'EXT'",
"]",
"[",
"'extConf'",
"]",
")",
";",
"$",
"overrideSettingsFile",
"=",
"SettingsFiles",
"::",
"getOverrideSettingsFile",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"canWriteConfiguration",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"$",
"overrideSettingsFile",
".",
"' is not writable.'",
",",
"1346323822",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"configExtractor",
"->",
"extractConfig",
"(",
"$",
"configurationToMerge",
",",
"$",
"this",
"->",
"getMergedLocalConfiguration",
"(",
")",
",",
"$",
"overrideSettingsFile",
")",
")",
"{",
"$",
"this",
"->",
"configLoader",
"->",
"flushCache",
"(",
")",
";",
"}",
"}"
] | Override local configuration with new values.
@param array $configurationToMerge Override configuration array | [
"Override",
"local",
"configuration",
"with",
"new",
"values",
"."
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L269-L283 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.setLocalConfigurationValuesByPathValuePairs | public function setLocalConfigurationValuesByPathValuePairs(array $pairs)
{
$localConfiguration = [];
foreach ($pairs as $path => $value) {
if ($this->isValidLocalConfigurationPath($path)) {
$localConfiguration = ArrayUtility::setValueByPath($localConfiguration, $path, $value);
}
}
$this->updateLocalConfiguration($localConfiguration);
return true;
} | php | public function setLocalConfigurationValuesByPathValuePairs(array $pairs)
{
$localConfiguration = [];
foreach ($pairs as $path => $value) {
if ($this->isValidLocalConfigurationPath($path)) {
$localConfiguration = ArrayUtility::setValueByPath($localConfiguration, $path, $value);
}
}
$this->updateLocalConfiguration($localConfiguration);
return true;
} | [
"public",
"function",
"setLocalConfigurationValuesByPathValuePairs",
"(",
"array",
"$",
"pairs",
")",
"{",
"$",
"localConfiguration",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"pairs",
"as",
"$",
"path",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isValidLocalConfigurationPath",
"(",
"$",
"path",
")",
")",
"{",
"$",
"localConfiguration",
"=",
"ArrayUtility",
"::",
"setValueByPath",
"(",
"$",
"localConfiguration",
",",
"$",
"path",
",",
"$",
"value",
")",
";",
"}",
"}",
"$",
"this",
"->",
"updateLocalConfiguration",
"(",
"$",
"localConfiguration",
")",
";",
"return",
"true",
";",
"}"
] | Update / set a list of path and value pairs in local configuration file
@param array $pairs Key is path, value is value to set
@return bool TRUE on success | [
"Update",
"/",
"set",
"a",
"list",
"of",
"path",
"and",
"value",
"pairs",
"in",
"local",
"configuration",
"file"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L337-L348 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.removeLocalConfigurationKeysByPath | public function removeLocalConfigurationKeysByPath(array $keys)
{
$result = false;
$localConfiguration = $this->getLocalConfiguration();
foreach ($keys as $path) {
// Remove key if path is within LocalConfiguration
if (ArrayUtility::isValidPath($localConfiguration, $path)) {
$result = true;
$localConfiguration = ArrayUtility::removeByPath($localConfiguration, $path);
}
}
if ($result) {
$this->writeLocalConfiguration($localConfiguration);
}
return $result;
} | php | public function removeLocalConfigurationKeysByPath(array $keys)
{
$result = false;
$localConfiguration = $this->getLocalConfiguration();
foreach ($keys as $path) {
// Remove key if path is within LocalConfiguration
if (ArrayUtility::isValidPath($localConfiguration, $path)) {
$result = true;
$localConfiguration = ArrayUtility::removeByPath($localConfiguration, $path);
}
}
if ($result) {
$this->writeLocalConfiguration($localConfiguration);
}
return $result;
} | [
"public",
"function",
"removeLocalConfigurationKeysByPath",
"(",
"array",
"$",
"keys",
")",
"{",
"$",
"result",
"=",
"false",
";",
"$",
"localConfiguration",
"=",
"$",
"this",
"->",
"getLocalConfiguration",
"(",
")",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"path",
")",
"{",
"// Remove key if path is within LocalConfiguration",
"if",
"(",
"ArrayUtility",
"::",
"isValidPath",
"(",
"$",
"localConfiguration",
",",
"$",
"path",
")",
")",
"{",
"$",
"result",
"=",
"true",
";",
"$",
"localConfiguration",
"=",
"ArrayUtility",
"::",
"removeByPath",
"(",
"$",
"localConfiguration",
",",
"$",
"path",
")",
";",
"}",
"}",
"if",
"(",
"$",
"result",
")",
"{",
"$",
"this",
"->",
"writeLocalConfiguration",
"(",
"$",
"localConfiguration",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Remove keys from LocalConfiguration
@param array $keys Array with key paths to remove from LocalConfiguration
@return bool TRUE if something was removed | [
"Remove",
"keys",
"from",
"LocalConfiguration"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L356-L372 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.canWriteConfiguration | public function canWriteConfiguration()
{
$fileLocation = SettingsFiles::getOverrideSettingsFile();
return @is_writable(file_exists($fileLocation) ? $fileLocation : Environment::getConfigPath() . '/');
} | php | public function canWriteConfiguration()
{
$fileLocation = SettingsFiles::getOverrideSettingsFile();
return @is_writable(file_exists($fileLocation) ? $fileLocation : Environment::getConfigPath() . '/');
} | [
"public",
"function",
"canWriteConfiguration",
"(",
")",
"{",
"$",
"fileLocation",
"=",
"SettingsFiles",
"::",
"getOverrideSettingsFile",
"(",
")",
";",
"return",
"@",
"is_writable",
"(",
"file_exists",
"(",
"$",
"fileLocation",
")",
"?",
"$",
"fileLocation",
":",
"Environment",
"::",
"getConfigPath",
"(",
")",
".",
"'/'",
")",
";",
"}"
] | Checks if the configuration can be written.
@return bool
@internal | [
"Checks",
"if",
"the",
"configuration",
"can",
"be",
"written",
"."
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L404-L409 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.writeLocalConfiguration | public function writeLocalConfiguration(array $configuration)
{
$configuration = $this->configCleaner->cleanConfig($configuration, $this->getMergedLocalConfiguration());
$this->updateLocalConfiguration($configuration);
// Too many places require this file to exist, so we make sure to create it
return $this->configDumper->dumpToFile([], Environment::getLegacyConfigPath() . '/LocalConfiguration.php', "Auto generated by helhum/typo3-config-handling\nDo not edit this file");
} | php | public function writeLocalConfiguration(array $configuration)
{
$configuration = $this->configCleaner->cleanConfig($configuration, $this->getMergedLocalConfiguration());
$this->updateLocalConfiguration($configuration);
// Too many places require this file to exist, so we make sure to create it
return $this->configDumper->dumpToFile([], Environment::getLegacyConfigPath() . '/LocalConfiguration.php', "Auto generated by helhum/typo3-config-handling\nDo not edit this file");
} | [
"public",
"function",
"writeLocalConfiguration",
"(",
"array",
"$",
"configuration",
")",
"{",
"$",
"configuration",
"=",
"$",
"this",
"->",
"configCleaner",
"->",
"cleanConfig",
"(",
"$",
"configuration",
",",
"$",
"this",
"->",
"getMergedLocalConfiguration",
"(",
")",
")",
";",
"$",
"this",
"->",
"updateLocalConfiguration",
"(",
"$",
"configuration",
")",
";",
"// Too many places require this file to exist, so we make sure to create it",
"return",
"$",
"this",
"->",
"configDumper",
"->",
"dumpToFile",
"(",
"[",
"]",
",",
"Environment",
"::",
"getLegacyConfigPath",
"(",
")",
".",
"'/LocalConfiguration.php'",
",",
"\"Auto generated by helhum/typo3-config-handling\\nDo not edit this file\"",
")",
";",
"}"
] | Write local configuration array to typo3conf/LocalConfiguration.php
@param array $configuration The local configuration to be written
@throws \RuntimeException
@return bool TRUE on success
@internal | [
"Write",
"local",
"configuration",
"array",
"to",
"typo3conf",
"/",
"LocalConfiguration",
".",
"php"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L431-L438 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.writeAdditionalConfiguration | public function writeAdditionalConfiguration(array $additionalConfigurationLines)
{
return GeneralUtility::writeFile(
Environment::getPublicPath() . '/' . $this->additionalConfigurationFile,
'<?php' . LF .
implode(LF, $additionalConfigurationLines) . LF
);
} | php | public function writeAdditionalConfiguration(array $additionalConfigurationLines)
{
return GeneralUtility::writeFile(
Environment::getPublicPath() . '/' . $this->additionalConfigurationFile,
'<?php' . LF .
implode(LF, $additionalConfigurationLines) . LF
);
} | [
"public",
"function",
"writeAdditionalConfiguration",
"(",
"array",
"$",
"additionalConfigurationLines",
")",
"{",
"return",
"GeneralUtility",
"::",
"writeFile",
"(",
"Environment",
"::",
"getPublicPath",
"(",
")",
".",
"'/'",
".",
"$",
"this",
"->",
"additionalConfigurationFile",
",",
"'<?php'",
".",
"LF",
".",
"implode",
"(",
"LF",
",",
"$",
"additionalConfigurationLines",
")",
".",
"LF",
")",
";",
"}"
] | Write additional configuration array to typo3conf/AdditionalConfiguration.php
@param array $additionalConfigurationLines The configuration lines to be written
@throws \RuntimeException
@return bool TRUE on success
@internal | [
"Write",
"additional",
"configuration",
"array",
"to",
"typo3conf",
"/",
"AdditionalConfiguration",
".",
"php"
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L448-L455 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.createLocalConfigurationFromFactoryConfiguration | public function createLocalConfigurationFromFactoryConfiguration()
{
if (file_exists($this->getLocalConfigurationFileLocation())) {
throw new \RuntimeException(
'LocalConfiguration.php exists already',
1364836026
);
}
$localConfigurationArray = require $this->getFactoryConfigurationFileLocation();
$additionalFactoryConfigurationFileLocation = $this->getAdditionalFactoryConfigurationFileLocation();
if (file_exists($additionalFactoryConfigurationFileLocation)) {
$additionalFactoryConfigurationArray = require $additionalFactoryConfigurationFileLocation;
ArrayUtility::mergeRecursiveWithOverrule(
$localConfigurationArray,
$additionalFactoryConfigurationArray
);
}
$randomKey = GeneralUtility::makeInstance(Random::class)->generateRandomHexString(96);
$localConfigurationArray['SYS']['encryptionKey'] = $randomKey;
$this->writeLocalConfiguration($localConfigurationArray);
} | php | public function createLocalConfigurationFromFactoryConfiguration()
{
if (file_exists($this->getLocalConfigurationFileLocation())) {
throw new \RuntimeException(
'LocalConfiguration.php exists already',
1364836026
);
}
$localConfigurationArray = require $this->getFactoryConfigurationFileLocation();
$additionalFactoryConfigurationFileLocation = $this->getAdditionalFactoryConfigurationFileLocation();
if (file_exists($additionalFactoryConfigurationFileLocation)) {
$additionalFactoryConfigurationArray = require $additionalFactoryConfigurationFileLocation;
ArrayUtility::mergeRecursiveWithOverrule(
$localConfigurationArray,
$additionalFactoryConfigurationArray
);
}
$randomKey = GeneralUtility::makeInstance(Random::class)->generateRandomHexString(96);
$localConfigurationArray['SYS']['encryptionKey'] = $randomKey;
$this->writeLocalConfiguration($localConfigurationArray);
} | [
"public",
"function",
"createLocalConfigurationFromFactoryConfiguration",
"(",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"getLocalConfigurationFileLocation",
"(",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'LocalConfiguration.php exists already'",
",",
"1364836026",
")",
";",
"}",
"$",
"localConfigurationArray",
"=",
"require",
"$",
"this",
"->",
"getFactoryConfigurationFileLocation",
"(",
")",
";",
"$",
"additionalFactoryConfigurationFileLocation",
"=",
"$",
"this",
"->",
"getAdditionalFactoryConfigurationFileLocation",
"(",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"additionalFactoryConfigurationFileLocation",
")",
")",
"{",
"$",
"additionalFactoryConfigurationArray",
"=",
"require",
"$",
"additionalFactoryConfigurationFileLocation",
";",
"ArrayUtility",
"::",
"mergeRecursiveWithOverrule",
"(",
"$",
"localConfigurationArray",
",",
"$",
"additionalFactoryConfigurationArray",
")",
";",
"}",
"$",
"randomKey",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"Random",
"::",
"class",
")",
"->",
"generateRandomHexString",
"(",
"96",
")",
";",
"$",
"localConfigurationArray",
"[",
"'SYS'",
"]",
"[",
"'encryptionKey'",
"]",
"=",
"$",
"randomKey",
";",
"$",
"this",
"->",
"writeLocalConfiguration",
"(",
"$",
"localConfigurationArray",
")",
";",
"}"
] | Uses FactoryConfiguration file and a possible AdditionalFactoryConfiguration
file in typo3conf to create a basic LocalConfiguration.php. This is used
by the install tool in an early step.
@throws \RuntimeException
@internal | [
"Uses",
"FactoryConfiguration",
"file",
"and",
"a",
"possible",
"AdditionalFactoryConfiguration",
"file",
"in",
"typo3conf",
"to",
"create",
"a",
"basic",
"LocalConfiguration",
".",
"php",
".",
"This",
"is",
"used",
"by",
"the",
"install",
"tool",
"in",
"an",
"early",
"step",
"."
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L465-L485 |
helhum/typo3-config-handling | src/Xclass/ConfigurationManager.php | ConfigurationManager.isValidLocalConfigurationPath | protected function isValidLocalConfigurationPath($path)
{
// Early return for white listed paths
foreach ($this->whiteListedLocalConfigurationPaths as $whiteListedPath) {
if (GeneralUtility::isFirstPartOfStr($path, $whiteListedPath)) {
return true;
}
}
return ArrayUtility::isValidPath($this->getDefaultConfiguration(), $path);
} | php | protected function isValidLocalConfigurationPath($path)
{
// Early return for white listed paths
foreach ($this->whiteListedLocalConfigurationPaths as $whiteListedPath) {
if (GeneralUtility::isFirstPartOfStr($path, $whiteListedPath)) {
return true;
}
}
return ArrayUtility::isValidPath($this->getDefaultConfiguration(), $path);
} | [
"protected",
"function",
"isValidLocalConfigurationPath",
"(",
"$",
"path",
")",
"{",
"// Early return for white listed paths",
"foreach",
"(",
"$",
"this",
"->",
"whiteListedLocalConfigurationPaths",
"as",
"$",
"whiteListedPath",
")",
"{",
"if",
"(",
"GeneralUtility",
"::",
"isFirstPartOfStr",
"(",
"$",
"path",
",",
"$",
"whiteListedPath",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"ArrayUtility",
"::",
"isValidPath",
"(",
"$",
"this",
"->",
"getDefaultConfiguration",
"(",
")",
",",
"$",
"path",
")",
";",
"}"
] | Check if access / write to given path in local configuration is allowed.
@param string $path Path to search for
@return bool TRUE if access is allowed | [
"Check",
"if",
"access",
"/",
"write",
"to",
"given",
"path",
"in",
"local",
"configuration",
"is",
"allowed",
"."
] | train | https://github.com/helhum/typo3-config-handling/blob/72a8be3a613c87e2f63e1ee432fbd3f8a0a6f5c3/src/Xclass/ConfigurationManager.php#L493-L503 |
victorjonsson/PHP-Markdown-Documentation-Generator | src/PHPDocsMD/Reflector.php | Reflector.getParamType | static function getParamType(\ReflectionParameter $refParam)
{
$export = \ReflectionParameter::export([
$refParam->getDeclaringClass()->name,
$refParam->getDeclaringFunction()->name
],
$refParam->name,
true
);
$export = str_replace(' or NULL', '', $export);
$type = preg_replace('/.*?([\w\\\]+)\s+\$'.current(explode('=', $refParam->name)).'.*/', '\\1', $export);
if( strpos($type, 'Parameter ') !== false ) {
return '';
}
if( $type != 'array' && strpos($type, '\\') !== 0 ) {
$type = '\\'.$type;
}
return $type;
} | php | static function getParamType(\ReflectionParameter $refParam)
{
$export = \ReflectionParameter::export([
$refParam->getDeclaringClass()->name,
$refParam->getDeclaringFunction()->name
],
$refParam->name,
true
);
$export = str_replace(' or NULL', '', $export);
$type = preg_replace('/.*?([\w\\\]+)\s+\$'.current(explode('=', $refParam->name)).'.*/', '\\1', $export);
if( strpos($type, 'Parameter ') !== false ) {
return '';
}
if( $type != 'array' && strpos($type, '\\') !== 0 ) {
$type = '\\'.$type;
}
return $type;
} | [
"static",
"function",
"getParamType",
"(",
"\\",
"ReflectionParameter",
"$",
"refParam",
")",
"{",
"$",
"export",
"=",
"\\",
"ReflectionParameter",
"::",
"export",
"(",
"[",
"$",
"refParam",
"->",
"getDeclaringClass",
"(",
")",
"->",
"name",
",",
"$",
"refParam",
"->",
"getDeclaringFunction",
"(",
")",
"->",
"name",
"]",
",",
"$",
"refParam",
"->",
"name",
",",
"true",
")",
";",
"$",
"export",
"=",
"str_replace",
"(",
"' or NULL'",
",",
"''",
",",
"$",
"export",
")",
";",
"$",
"type",
"=",
"preg_replace",
"(",
"'/.*?([\\w\\\\\\]+)\\s+\\$'",
".",
"current",
"(",
"explode",
"(",
"'='",
",",
"$",
"refParam",
"->",
"name",
")",
")",
".",
"'.*/'",
",",
"'\\\\1'",
",",
"$",
"export",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"type",
",",
"'Parameter '",
")",
"!==",
"false",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"$",
"type",
"!=",
"'array'",
"&&",
"strpos",
"(",
"$",
"type",
",",
"'\\\\'",
")",
"!==",
"0",
")",
"{",
"$",
"type",
"=",
"'\\\\'",
".",
"$",
"type",
";",
"}",
"return",
"$",
"type",
";",
"}"
] | Tries to find out if the type of the given parameter. Will
return empty string if not possible.
@example
<code>
<?php
$reflector = new \\ReflectionClass('MyClass');
foreach($reflector->getMethods() as $method ) {
foreach($method->getParameters() as $param) {
$name = $param->getName();
$type = Reflector::getParamType($param);
printf("%s = %s\n", $name, $type);
}
}
</code>
@param \ReflectionParameter $refParam
@return string | [
"Tries",
"to",
"find",
"out",
"if",
"the",
"type",
"of",
"the",
"given",
"parameter",
".",
"Will",
"return",
"empty",
"string",
"if",
"not",
"possible",
"."
] | train | https://github.com/victorjonsson/PHP-Markdown-Documentation-Generator/blob/f1f70b2bb9a59d1447796b271286eb409c4a3a60/src/PHPDocsMD/Reflector.php#L337-L359 |
victorjonsson/PHP-Markdown-Documentation-Generator | src/PHPDocsMD/MDTableGenerator.php | MDTableGenerator.openTable | function openTable()
{
$this->examples = [];
$this->markdown = ''; // Clear table
$this->declareAbstraction = true;
$this->add('| Visibility | Function |');
$this->add('|:-----------|:---------|');
} | php | function openTable()
{
$this->examples = [];
$this->markdown = ''; // Clear table
$this->declareAbstraction = true;
$this->add('| Visibility | Function |');
$this->add('|:-----------|:---------|');
} | [
"function",
"openTable",
"(",
")",
"{",
"$",
"this",
"->",
"examples",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"markdown",
"=",
"''",
";",
"// Clear table",
"$",
"this",
"->",
"declareAbstraction",
"=",
"true",
";",
"$",
"this",
"->",
"add",
"(",
"'| Visibility | Function |'",
")",
";",
"$",
"this",
"->",
"add",
"(",
"'|:-----------|:---------|'",
")",
";",
"}"
] | Begin generating a new markdown-formatted table | [
"Begin",
"generating",
"a",
"new",
"markdown",
"-",
"formatted",
"table"
] | train | https://github.com/victorjonsson/PHP-Markdown-Documentation-Generator/blob/f1f70b2bb9a59d1447796b271286eb409c4a3a60/src/PHPDocsMD/MDTableGenerator.php#L80-L87 |
victorjonsson/PHP-Markdown-Documentation-Generator | src/PHPDocsMD/MDTableGenerator.php | MDTableGenerator.addFunc | function addFunc(FunctionEntity $func, $includeSee=false)
{
$this->fullClassName = $func->getClass();
$str = '<strong>';
if( $this->declareAbstraction && $func->isAbstract() )
$str .= 'abstract ';
$str .= $func->getName().'(';
if( $func->hasParams() ) {
$params = [];
foreach($func->getParams() as $param) {
$paramStr = '<em>'.$param->getType().'</em> <strong>'.$param->getName();
if( $param->getDefault() ) {
$paramStr .= '='.$param->getDefault();
}
$paramStr .= '</strong>';
$params[] = $paramStr;
}
$str .= '</strong>'.implode(', ', $params) .')';
} else {
$str .= ')';
}
$str .= '</strong> : <em>'.$func->getReturnType().'</em>';
if( $func->isDeprecated() ) {
$str = '<strike>'.$str.'</strike>';
$str .= '<br /><em>DEPRECATED - '.$func->getDeprecationMessage().'</em>';
} elseif( $func->getDescription() ) {
$str .= '<br /><em>'.$func->getDescription().'</em>';
}
if ($func->getSee() && $includeSee) {
$str .= '<br /><em> See: ' .
implode(', ', $func->getSee()) . '</em>';
}
$str = str_replace(['</strong><strong>', '</strong></strong> '], ['','</strong>'], trim($str));
if( $func->getExample() )
$this->examples[$func->getName()] = $func->getExample();
$firstCol = $func->getVisibility() . ($func->isStatic() ? ' static':'');
$markDown = '| '.$firstCol.' | '.$str.' |';
$this->add($markDown);
return $markDown;
} | php | function addFunc(FunctionEntity $func, $includeSee=false)
{
$this->fullClassName = $func->getClass();
$str = '<strong>';
if( $this->declareAbstraction && $func->isAbstract() )
$str .= 'abstract ';
$str .= $func->getName().'(';
if( $func->hasParams() ) {
$params = [];
foreach($func->getParams() as $param) {
$paramStr = '<em>'.$param->getType().'</em> <strong>'.$param->getName();
if( $param->getDefault() ) {
$paramStr .= '='.$param->getDefault();
}
$paramStr .= '</strong>';
$params[] = $paramStr;
}
$str .= '</strong>'.implode(', ', $params) .')';
} else {
$str .= ')';
}
$str .= '</strong> : <em>'.$func->getReturnType().'</em>';
if( $func->isDeprecated() ) {
$str = '<strike>'.$str.'</strike>';
$str .= '<br /><em>DEPRECATED - '.$func->getDeprecationMessage().'</em>';
} elseif( $func->getDescription() ) {
$str .= '<br /><em>'.$func->getDescription().'</em>';
}
if ($func->getSee() && $includeSee) {
$str .= '<br /><em> See: ' .
implode(', ', $func->getSee()) . '</em>';
}
$str = str_replace(['</strong><strong>', '</strong></strong> '], ['','</strong>'], trim($str));
if( $func->getExample() )
$this->examples[$func->getName()] = $func->getExample();
$firstCol = $func->getVisibility() . ($func->isStatic() ? ' static':'');
$markDown = '| '.$firstCol.' | '.$str.' |';
$this->add($markDown);
return $markDown;
} | [
"function",
"addFunc",
"(",
"FunctionEntity",
"$",
"func",
",",
"$",
"includeSee",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"fullClassName",
"=",
"$",
"func",
"->",
"getClass",
"(",
")",
";",
"$",
"str",
"=",
"'<strong>'",
";",
"if",
"(",
"$",
"this",
"->",
"declareAbstraction",
"&&",
"$",
"func",
"->",
"isAbstract",
"(",
")",
")",
"$",
"str",
".=",
"'abstract '",
";",
"$",
"str",
".=",
"$",
"func",
"->",
"getName",
"(",
")",
".",
"'('",
";",
"if",
"(",
"$",
"func",
"->",
"hasParams",
"(",
")",
")",
"{",
"$",
"params",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"func",
"->",
"getParams",
"(",
")",
"as",
"$",
"param",
")",
"{",
"$",
"paramStr",
"=",
"'<em>'",
".",
"$",
"param",
"->",
"getType",
"(",
")",
".",
"'</em> <strong>'",
".",
"$",
"param",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"$",
"param",
"->",
"getDefault",
"(",
")",
")",
"{",
"$",
"paramStr",
".=",
"'='",
".",
"$",
"param",
"->",
"getDefault",
"(",
")",
";",
"}",
"$",
"paramStr",
".=",
"'</strong>'",
";",
"$",
"params",
"[",
"]",
"=",
"$",
"paramStr",
";",
"}",
"$",
"str",
".=",
"'</strong>'",
".",
"implode",
"(",
"', '",
",",
"$",
"params",
")",
".",
"')'",
";",
"}",
"else",
"{",
"$",
"str",
".=",
"')'",
";",
"}",
"$",
"str",
".=",
"'</strong> : <em>'",
".",
"$",
"func",
"->",
"getReturnType",
"(",
")",
".",
"'</em>'",
";",
"if",
"(",
"$",
"func",
"->",
"isDeprecated",
"(",
")",
")",
"{",
"$",
"str",
"=",
"'<strike>'",
".",
"$",
"str",
".",
"'</strike>'",
";",
"$",
"str",
".=",
"'<br /><em>DEPRECATED - '",
".",
"$",
"func",
"->",
"getDeprecationMessage",
"(",
")",
".",
"'</em>'",
";",
"}",
"elseif",
"(",
"$",
"func",
"->",
"getDescription",
"(",
")",
")",
"{",
"$",
"str",
".=",
"'<br /><em>'",
".",
"$",
"func",
"->",
"getDescription",
"(",
")",
".",
"'</em>'",
";",
"}",
"if",
"(",
"$",
"func",
"->",
"getSee",
"(",
")",
"&&",
"$",
"includeSee",
")",
"{",
"$",
"str",
".=",
"'<br /><em> See: '",
".",
"implode",
"(",
"', '",
",",
"$",
"func",
"->",
"getSee",
"(",
")",
")",
".",
"'</em>'",
";",
"}",
"$",
"str",
"=",
"str_replace",
"(",
"[",
"'</strong><strong>'",
",",
"'</strong></strong> '",
"]",
",",
"[",
"''",
",",
"'</strong>'",
"]",
",",
"trim",
"(",
"$",
"str",
")",
")",
";",
"if",
"(",
"$",
"func",
"->",
"getExample",
"(",
")",
")",
"$",
"this",
"->",
"examples",
"[",
"$",
"func",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"func",
"->",
"getExample",
"(",
")",
";",
"$",
"firstCol",
"=",
"$",
"func",
"->",
"getVisibility",
"(",
")",
".",
"(",
"$",
"func",
"->",
"isStatic",
"(",
")",
"?",
"' static'",
":",
"''",
")",
";",
"$",
"markDown",
"=",
"'| '",
".",
"$",
"firstCol",
".",
"' | '",
".",
"$",
"str",
".",
"' |'",
";",
"$",
"this",
"->",
"add",
"(",
"$",
"markDown",
")",
";",
"return",
"$",
"markDown",
";",
"}"
] | Generates a markdown formatted table row with information about given function. Then adds the
row to the table and returns the markdown formatted string.
@param FunctionEntity $func
@param bool $see
@return string | [
"Generates",
"a",
"markdown",
"formatted",
"table",
"row",
"with",
"information",
"about",
"given",
"function",
".",
"Then",
"adds",
"the",
"row",
"to",
"the",
"table",
"and",
"returns",
"the",
"markdown",
"formatted",
"string",
"."
] | train | https://github.com/victorjonsson/PHP-Markdown-Documentation-Generator/blob/f1f70b2bb9a59d1447796b271286eb409c4a3a60/src/PHPDocsMD/MDTableGenerator.php#L106-L155 |
victorjonsson/PHP-Markdown-Documentation-Generator | src/PHPDocsMD/MDTableGenerator.php | MDTableGenerator.formatExampleComment | public static function formatExampleComment($example)
{
// Remove possible code tag
$example = self::stripCodeTags($example);
if( preg_match('/(\n )/', $example) ) {
$example = preg_replace('/(\n )/', "\n", $example);
}
elseif( preg_match('/(\n )/', $example) ) {
$example = preg_replace('/(\n )/', "\n", $example);
} else {
$example = preg_replace('/(\n )/', "\n", $example);
}
$type = '';
// A very naive analysis of the programming language used in the comment
if( strpos($example, '<?php') !== false ) {
$type = 'php';
}
elseif( strpos($example, 'var ') !== false && strpos($example, '</') === false ) {
$type = 'js';
}
return sprintf("```%s\n%s\n```", $type, trim($example));
} | php | public static function formatExampleComment($example)
{
// Remove possible code tag
$example = self::stripCodeTags($example);
if( preg_match('/(\n )/', $example) ) {
$example = preg_replace('/(\n )/', "\n", $example);
}
elseif( preg_match('/(\n )/', $example) ) {
$example = preg_replace('/(\n )/', "\n", $example);
} else {
$example = preg_replace('/(\n )/', "\n", $example);
}
$type = '';
// A very naive analysis of the programming language used in the comment
if( strpos($example, '<?php') !== false ) {
$type = 'php';
}
elseif( strpos($example, 'var ') !== false && strpos($example, '</') === false ) {
$type = 'js';
}
return sprintf("```%s\n%s\n```", $type, trim($example));
} | [
"public",
"static",
"function",
"formatExampleComment",
"(",
"$",
"example",
")",
"{",
"// Remove possible code tag",
"$",
"example",
"=",
"self",
"::",
"stripCodeTags",
"(",
"$",
"example",
")",
";",
"if",
"(",
"preg_match",
"(",
"'/(\\n )/'",
",",
"$",
"example",
")",
")",
"{",
"$",
"example",
"=",
"preg_replace",
"(",
"'/(\\n )/'",
",",
"\"\\n\"",
",",
"$",
"example",
")",
";",
"}",
"elseif",
"(",
"preg_match",
"(",
"'/(\\n )/'",
",",
"$",
"example",
")",
")",
"{",
"$",
"example",
"=",
"preg_replace",
"(",
"'/(\\n )/'",
",",
"\"\\n\"",
",",
"$",
"example",
")",
";",
"}",
"else",
"{",
"$",
"example",
"=",
"preg_replace",
"(",
"'/(\\n )/'",
",",
"\"\\n\"",
",",
"$",
"example",
")",
";",
"}",
"$",
"type",
"=",
"''",
";",
"// A very naive analysis of the programming language used in the comment",
"if",
"(",
"strpos",
"(",
"$",
"example",
",",
"'<?php'",
")",
"!==",
"false",
")",
"{",
"$",
"type",
"=",
"'php'",
";",
"}",
"elseif",
"(",
"strpos",
"(",
"$",
"example",
",",
"'var '",
")",
"!==",
"false",
"&&",
"strpos",
"(",
"$",
"example",
",",
"'</'",
")",
"===",
"false",
")",
"{",
"$",
"type",
"=",
"'js'",
";",
"}",
"return",
"sprintf",
"(",
"\"```%s\\n%s\\n```\"",
",",
"$",
"type",
",",
"trim",
"(",
"$",
"example",
")",
")",
";",
"}"
] | Create a markdown-formatted code view out of an example comment
@param string $example
@return string | [
"Create",
"a",
"markdown",
"-",
"formatted",
"code",
"view",
"out",
"of",
"an",
"example",
"comment"
] | train | https://github.com/victorjonsson/PHP-Markdown-Documentation-Generator/blob/f1f70b2bb9a59d1447796b271286eb409c4a3a60/src/PHPDocsMD/MDTableGenerator.php#L177-L201 |
victorjonsson/PHP-Markdown-Documentation-Generator | src/PHPDocsMD/ClassEntity.php | ClassEntity.generateTitle | function generateTitle($format='%label%: %name% %extra%')
{
$translate = [
'%label%' => $this->isInterface() ? 'Interface' : 'Class',
'%name%' => substr_count($this->getName(), '\\') == 1 ? substr($this->getName(), 1) : $this->getName(),
'%extra%' => ''
];
if( strpos($format, '%label%') === false ) {
if( $this->isInterface() )
$translate['%extra%'] = '(interface)';
elseif( $this->isAbstract() )
$translate['%extra%'] = '(abstract)';
} else {
$translate['%extra%'] = $this->isAbstract() && !$this->isInterface() ? '(abstract)' : '';
}
return trim(strtr($format, $translate));
} | php | function generateTitle($format='%label%: %name% %extra%')
{
$translate = [
'%label%' => $this->isInterface() ? 'Interface' : 'Class',
'%name%' => substr_count($this->getName(), '\\') == 1 ? substr($this->getName(), 1) : $this->getName(),
'%extra%' => ''
];
if( strpos($format, '%label%') === false ) {
if( $this->isInterface() )
$translate['%extra%'] = '(interface)';
elseif( $this->isAbstract() )
$translate['%extra%'] = '(abstract)';
} else {
$translate['%extra%'] = $this->isAbstract() && !$this->isInterface() ? '(abstract)' : '';
}
return trim(strtr($format, $translate));
} | [
"function",
"generateTitle",
"(",
"$",
"format",
"=",
"'%label%: %name% %extra%'",
")",
"{",
"$",
"translate",
"=",
"[",
"'%label%'",
"=>",
"$",
"this",
"->",
"isInterface",
"(",
")",
"?",
"'Interface'",
":",
"'Class'",
",",
"'%name%'",
"=>",
"substr_count",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"'\\\\'",
")",
"==",
"1",
"?",
"substr",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"1",
")",
":",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"'%extra%'",
"=>",
"''",
"]",
";",
"if",
"(",
"strpos",
"(",
"$",
"format",
",",
"'%label%'",
")",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isInterface",
"(",
")",
")",
"$",
"translate",
"[",
"'%extra%'",
"]",
"=",
"'(interface)'",
";",
"elseif",
"(",
"$",
"this",
"->",
"isAbstract",
"(",
")",
")",
"$",
"translate",
"[",
"'%extra%'",
"]",
"=",
"'(abstract)'",
";",
"}",
"else",
"{",
"$",
"translate",
"[",
"'%extra%'",
"]",
"=",
"$",
"this",
"->",
"isAbstract",
"(",
")",
"&&",
"!",
"$",
"this",
"->",
"isInterface",
"(",
")",
"?",
"'(abstract)'",
":",
"''",
";",
"}",
"return",
"trim",
"(",
"strtr",
"(",
"$",
"format",
",",
"$",
"translate",
")",
")",
";",
"}"
] | Generate a title describing the class this object is referring to
@param string $format
@return string | [
"Generate",
"a",
"title",
"describing",
"the",
"class",
"this",
"object",
"is",
"referring",
"to"
] | train | https://github.com/victorjonsson/PHP-Markdown-Documentation-Generator/blob/f1f70b2bb9a59d1447796b271286eb409c4a3a60/src/PHPDocsMD/ClassEntity.php#L215-L233 |
markstory/asset_compress | src/AssetScanner.php | AssetScanner._expandPrefix | protected function _expandPrefix($path)
{
if (preg_match(self::PLUGIN_PATTERN, $path)) {
return $this->_expandPlugin($path);
}
if ($this->theme && preg_match(self::THEME_PATTERN, $path)) {
return $this->_expandTheme($path);
}
return $path;
} | php | protected function _expandPrefix($path)
{
if (preg_match(self::PLUGIN_PATTERN, $path)) {
return $this->_expandPlugin($path);
}
if ($this->theme && preg_match(self::THEME_PATTERN, $path)) {
return $this->_expandTheme($path);
}
return $path;
} | [
"protected",
"function",
"_expandPrefix",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"preg_match",
"(",
"self",
"::",
"PLUGIN_PATTERN",
",",
"$",
"path",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_expandPlugin",
"(",
"$",
"path",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"theme",
"&&",
"preg_match",
"(",
"self",
"::",
"THEME_PATTERN",
",",
"$",
"path",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_expandTheme",
"(",
"$",
"path",
")",
";",
"}",
"return",
"$",
"path",
";",
"}"
] | Resolve a plugin or theme path into the file path without the search paths.
@param string $path Path to resolve
@return string resolved path | [
"Resolve",
"a",
"plugin",
"or",
"theme",
"path",
"into",
"the",
"file",
"path",
"without",
"the",
"search",
"paths",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/AssetScanner.php#L49-L59 |
markstory/asset_compress | src/AssetScanner.php | AssetScanner._expandTheme | protected function _expandTheme($file)
{
$file = preg_replace(self::THEME_PATTERN, '', $file);
return CorePlugin::path($this->theme) . 'webroot' . DS . $file;
} | php | protected function _expandTheme($file)
{
$file = preg_replace(self::THEME_PATTERN, '', $file);
return CorePlugin::path($this->theme) . 'webroot' . DS . $file;
} | [
"protected",
"function",
"_expandTheme",
"(",
"$",
"file",
")",
"{",
"$",
"file",
"=",
"preg_replace",
"(",
"self",
"::",
"THEME_PATTERN",
",",
"''",
",",
"$",
"file",
")",
";",
"return",
"CorePlugin",
"::",
"path",
"(",
"$",
"this",
"->",
"theme",
")",
".",
"'webroot'",
".",
"DS",
".",
"$",
"file",
";",
"}"
] | Resolve a themed file to its full path. The file will be found on the
current theme's path.
@param string $file The theme file to find.
@return string The expanded path | [
"Resolve",
"a",
"themed",
"file",
"to",
"its",
"full",
"path",
".",
"The",
"file",
"will",
"be",
"found",
"on",
"the",
"current",
"theme",
"s",
"path",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/AssetScanner.php#L68-L73 |
markstory/asset_compress | src/AssetScanner.php | AssetScanner._expandPlugin | protected function _expandPlugin($file)
{
preg_match(self::PLUGIN_PATTERN, $file, $matches);
if (empty($matches[1]) || empty($matches[2])) {
throw new RuntimeException('Missing required parameters');
}
if (!CorePlugin::isLoaded($matches[1])) {
throw new RuntimeException($matches[1] . ' is not a loaded plugin.');
}
$path = CorePlugin::path($matches[1]);
return $path . 'webroot' . DS . $matches[2];
} | php | protected function _expandPlugin($file)
{
preg_match(self::PLUGIN_PATTERN, $file, $matches);
if (empty($matches[1]) || empty($matches[2])) {
throw new RuntimeException('Missing required parameters');
}
if (!CorePlugin::isLoaded($matches[1])) {
throw new RuntimeException($matches[1] . ' is not a loaded plugin.');
}
$path = CorePlugin::path($matches[1]);
return $path . 'webroot' . DS . $matches[2];
} | [
"protected",
"function",
"_expandPlugin",
"(",
"$",
"file",
")",
"{",
"preg_match",
"(",
"self",
"::",
"PLUGIN_PATTERN",
",",
"$",
"file",
",",
"$",
"matches",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
"||",
"empty",
"(",
"$",
"matches",
"[",
"2",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Missing required parameters'",
")",
";",
"}",
"if",
"(",
"!",
"CorePlugin",
"::",
"isLoaded",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"$",
"matches",
"[",
"1",
"]",
".",
"' is not a loaded plugin.'",
")",
";",
"}",
"$",
"path",
"=",
"CorePlugin",
"::",
"path",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
";",
"return",
"$",
"path",
".",
"'webroot'",
".",
"DS",
".",
"$",
"matches",
"[",
"2",
"]",
";",
"}"
] | Resolve a plugin file to its full path.
@param string $file The theme file to find.
@throws RuntimeException when plugins are missing.
@return string The expanded path | [
"Resolve",
"a",
"plugin",
"file",
"to",
"its",
"full",
"path",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/AssetScanner.php#L82-L94 |
markstory/asset_compress | src/Routing/Filter/AssetCompressorFilter.php | AssetCompressorFilter.beforeDispatch | public function beforeDispatch(Event $event)
{
deprecationWarning(
'AssetCompressorFilter is deprecated. ' .
'You should update to use AssetCompress\Middleware\AssetCompressMiddleware instead.'
);
$request = $event->data['request'];
$response = $event->data['response'];
$config = $this->_getConfig();
$production = !Configure::read('debug');
if ($production && !$config->general('alwaysEnableController')) {
return null;
}
// Make sure the request looks like an asset.
$targetName = $this->getName($config, $request->url);
if (!$targetName) {
return null;
}
if (isset($request->query['theme'])) {
$config->theme($request->query['theme']);
}
$factory = new Factory($config);
$assets = $factory->assetCollection();
if (!$assets->contains($targetName)) {
return null;
}
$build = $assets->get($targetName);
try {
$compiler = $factory->cachedCompiler();
$contents = $compiler->generate($build);
} catch (Exception $e) {
throw new NotFoundException($e->getMessage());
}
$response->type($build->ext());
$response->body($contents);
$event->stopPropagation();
return $response;
} | php | public function beforeDispatch(Event $event)
{
deprecationWarning(
'AssetCompressorFilter is deprecated. ' .
'You should update to use AssetCompress\Middleware\AssetCompressMiddleware instead.'
);
$request = $event->data['request'];
$response = $event->data['response'];
$config = $this->_getConfig();
$production = !Configure::read('debug');
if ($production && !$config->general('alwaysEnableController')) {
return null;
}
// Make sure the request looks like an asset.
$targetName = $this->getName($config, $request->url);
if (!$targetName) {
return null;
}
if (isset($request->query['theme'])) {
$config->theme($request->query['theme']);
}
$factory = new Factory($config);
$assets = $factory->assetCollection();
if (!$assets->contains($targetName)) {
return null;
}
$build = $assets->get($targetName);
try {
$compiler = $factory->cachedCompiler();
$contents = $compiler->generate($build);
} catch (Exception $e) {
throw new NotFoundException($e->getMessage());
}
$response->type($build->ext());
$response->body($contents);
$event->stopPropagation();
return $response;
} | [
"public",
"function",
"beforeDispatch",
"(",
"Event",
"$",
"event",
")",
"{",
"deprecationWarning",
"(",
"'AssetCompressorFilter is deprecated. '",
".",
"'You should update to use AssetCompress\\Middleware\\AssetCompressMiddleware instead.'",
")",
";",
"$",
"request",
"=",
"$",
"event",
"->",
"data",
"[",
"'request'",
"]",
";",
"$",
"response",
"=",
"$",
"event",
"->",
"data",
"[",
"'response'",
"]",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"_getConfig",
"(",
")",
";",
"$",
"production",
"=",
"!",
"Configure",
"::",
"read",
"(",
"'debug'",
")",
";",
"if",
"(",
"$",
"production",
"&&",
"!",
"$",
"config",
"->",
"general",
"(",
"'alwaysEnableController'",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Make sure the request looks like an asset.",
"$",
"targetName",
"=",
"$",
"this",
"->",
"getName",
"(",
"$",
"config",
",",
"$",
"request",
"->",
"url",
")",
";",
"if",
"(",
"!",
"$",
"targetName",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"request",
"->",
"query",
"[",
"'theme'",
"]",
")",
")",
"{",
"$",
"config",
"->",
"theme",
"(",
"$",
"request",
"->",
"query",
"[",
"'theme'",
"]",
")",
";",
"}",
"$",
"factory",
"=",
"new",
"Factory",
"(",
"$",
"config",
")",
";",
"$",
"assets",
"=",
"$",
"factory",
"->",
"assetCollection",
"(",
")",
";",
"if",
"(",
"!",
"$",
"assets",
"->",
"contains",
"(",
"$",
"targetName",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"build",
"=",
"$",
"assets",
"->",
"get",
"(",
"$",
"targetName",
")",
";",
"try",
"{",
"$",
"compiler",
"=",
"$",
"factory",
"->",
"cachedCompiler",
"(",
")",
";",
"$",
"contents",
"=",
"$",
"compiler",
"->",
"generate",
"(",
"$",
"build",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"NotFoundException",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"$",
"response",
"->",
"type",
"(",
"$",
"build",
"->",
"ext",
"(",
")",
")",
";",
"$",
"response",
"->",
"body",
"(",
"$",
"contents",
")",
";",
"$",
"event",
"->",
"stopPropagation",
"(",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Checks if request is for a compiled asset, otherwise skip any operation
@param Event $event containing the request and response object
@throws \Cake\Network\Exception\NotFoundException
@return \Cake\Network\Response|null Response if the client is requesting a recognized asset, null otherwise | [
"Checks",
"if",
"request",
"is",
"for",
"a",
"compiled",
"asset",
"otherwise",
"skip",
"any",
"operation"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Routing/Filter/AssetCompressorFilter.php#L37-L79 |
markstory/asset_compress | src/Routing/Filter/AssetCompressorFilter.php | AssetCompressorFilter.getName | protected function getName($config, $url)
{
$parts = explode('.', $url);
if (count($parts) < 2) {
return false;
}
$path = $config->cachePath($parts[(count($parts) - 1)]);
if (empty($path)) {
return false;
}
$root = str_replace('\\', '/', WWW_ROOT);
$path = str_replace('\\', '/', $path);
$path = str_replace($root, '', $path);
if (strpos($url, $path) !== 0) {
return false;
}
return str_replace($path, '', $url);
} | php | protected function getName($config, $url)
{
$parts = explode('.', $url);
if (count($parts) < 2) {
return false;
}
$path = $config->cachePath($parts[(count($parts) - 1)]);
if (empty($path)) {
return false;
}
$root = str_replace('\\', '/', WWW_ROOT);
$path = str_replace('\\', '/', $path);
$path = str_replace($root, '', $path);
if (strpos($url, $path) !== 0) {
return false;
}
return str_replace($path, '', $url);
} | [
"protected",
"function",
"getName",
"(",
"$",
"config",
",",
"$",
"url",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"url",
")",
";",
"if",
"(",
"count",
"(",
"$",
"parts",
")",
"<",
"2",
")",
"{",
"return",
"false",
";",
"}",
"$",
"path",
"=",
"$",
"config",
"->",
"cachePath",
"(",
"$",
"parts",
"[",
"(",
"count",
"(",
"$",
"parts",
")",
"-",
"1",
")",
"]",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"root",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"WWW_ROOT",
")",
";",
"$",
"path",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"path",
")",
";",
"$",
"path",
"=",
"str_replace",
"(",
"$",
"root",
",",
"''",
",",
"$",
"path",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"url",
",",
"$",
"path",
")",
"!==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"return",
"str_replace",
"(",
"$",
"path",
",",
"''",
",",
"$",
"url",
")",
";",
"}"
] | Returns the build name for a requested asset
@param \MiniAsset\AssetConfig $config The config object to use.
@param string $url The url to get an asset name from.
@return bool|string false if no build can be parsed from URL
with url path otherwise | [
"Returns",
"the",
"build",
"name",
"for",
"a",
"requested",
"asset"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Routing/Filter/AssetCompressorFilter.php#L89-L109 |
markstory/asset_compress | src/Routing/Filter/AssetCompressorFilter.php | AssetCompressorFilter._getConfig | protected function _getConfig()
{
if ($this->config === null) {
$configFinder = new ConfigFinder();
$this->config = $configFinder->loadAll();
}
return $this->config;
} | php | protected function _getConfig()
{
if ($this->config === null) {
$configFinder = new ConfigFinder();
$this->config = $configFinder->loadAll();
}
return $this->config;
} | [
"protected",
"function",
"_getConfig",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"===",
"null",
")",
"{",
"$",
"configFinder",
"=",
"new",
"ConfigFinder",
"(",
")",
";",
"$",
"this",
"->",
"config",
"=",
"$",
"configFinder",
"->",
"loadAll",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"config",
";",
"}"
] | Config setter, used for testing the filter.
@return \MiniAsset\AssetConfig The completed config instance. | [
"Config",
"setter",
"used",
"for",
"testing",
"the",
"filter",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Routing/Filter/AssetCompressorFilter.php#L116-L124 |
markstory/asset_compress | src/Factory.php | Factory.cachedCompiler | public function cachedCompiler($outputDir = '', $debug = false)
{
$outputDir = $outputDir ?: CACHE . 'asset_compress' . DS;
$debug = $debug ?: Configure::read('debug');
return parent::cachedCompiler($outputDir, $debug);
} | php | public function cachedCompiler($outputDir = '', $debug = false)
{
$outputDir = $outputDir ?: CACHE . 'asset_compress' . DS;
$debug = $debug ?: Configure::read('debug');
return parent::cachedCompiler($outputDir, $debug);
} | [
"public",
"function",
"cachedCompiler",
"(",
"$",
"outputDir",
"=",
"''",
",",
"$",
"debug",
"=",
"false",
")",
"{",
"$",
"outputDir",
"=",
"$",
"outputDir",
"?",
":",
"CACHE",
".",
"'asset_compress'",
".",
"DS",
";",
"$",
"debug",
"=",
"$",
"debug",
"?",
":",
"Configure",
"::",
"read",
"(",
"'debug'",
")",
";",
"return",
"parent",
"::",
"cachedCompiler",
"(",
"$",
"outputDir",
",",
"$",
"debug",
")",
";",
"}"
] | Create a Caching Compiler
@param string $outputDir The directory to output cached files to.
@param bool $debug Whether or not to enable debugging mode for the compiler.
@return \MiniAsset\Output\CachedCompiler | [
"Create",
"a",
"Caching",
"Compiler"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Factory.php#L45-L51 |
markstory/asset_compress | src/Factory.php | Factory.buildFilter | protected function buildFilter($name, $config)
{
$className = App::className($name, 'Filter');
if (!class_exists($className)) {
$className = App::className('AssetCompress.' . $name, 'Filter');
}
$className = $className ?: $name;
return parent::buildFilter($className, $config);
} | php | protected function buildFilter($name, $config)
{
$className = App::className($name, 'Filter');
if (!class_exists($className)) {
$className = App::className('AssetCompress.' . $name, 'Filter');
}
$className = $className ?: $name;
return parent::buildFilter($className, $config);
} | [
"protected",
"function",
"buildFilter",
"(",
"$",
"name",
",",
"$",
"config",
")",
"{",
"$",
"className",
"=",
"App",
"::",
"className",
"(",
"$",
"name",
",",
"'Filter'",
")",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"className",
")",
")",
"{",
"$",
"className",
"=",
"App",
"::",
"className",
"(",
"'AssetCompress.'",
".",
"$",
"name",
",",
"'Filter'",
")",
";",
"}",
"$",
"className",
"=",
"$",
"className",
"?",
":",
"$",
"name",
";",
"return",
"parent",
"::",
"buildFilter",
"(",
"$",
"className",
",",
"$",
"config",
")",
";",
"}"
] | Create a single filter
@param string $name The name of the filter to build.
@param array $config The configuration for the filter.
@return \MiniAsset\Filter\FilterInterface | [
"Create",
"a",
"single",
"filter"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Factory.php#L86-L95 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper.assetConfig | public function assetConfig($config = null)
{
if ($config === null) {
return $this->config;
}
$this->config = $config;
} | php | public function assetConfig($config = null)
{
if ($config === null) {
return $this->config;
}
$this->config = $config;
} | [
"public",
"function",
"assetConfig",
"(",
"$",
"config",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"config",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"config",
";",
"}",
"$",
"this",
"->",
"config",
"=",
"$",
"config",
";",
"}"
] | Modify the runtime configuration of the helper.
Used as a get/set for the ini file values.
@param \MiniAsset\AssetConfig $config The config instance to set.
@return \MiniAsset\AssetConfig|null Either the current config object or null. | [
"Modify",
"the",
"runtime",
"configuration",
"of",
"the",
"helper",
".",
"Used",
"as",
"a",
"get",
"/",
"set",
"for",
"the",
"ini",
"file",
"values",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L83-L89 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper.factory | protected function factory()
{
if (empty($this->factory)) {
$this->config->theme($this->getView()->getTheme());
$this->factory = new Factory($this->config);
}
return $this->factory;
} | php | protected function factory()
{
if (empty($this->factory)) {
$this->config->theme($this->getView()->getTheme());
$this->factory = new Factory($this->config);
}
return $this->factory;
} | [
"protected",
"function",
"factory",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"factory",
")",
")",
"{",
"$",
"this",
"->",
"config",
"->",
"theme",
"(",
"$",
"this",
"->",
"getView",
"(",
")",
"->",
"getTheme",
"(",
")",
")",
";",
"$",
"this",
"->",
"factory",
"=",
"new",
"Factory",
"(",
"$",
"this",
"->",
"config",
")",
";",
"}",
"return",
"$",
"this",
"->",
"factory",
";",
"}"
] | Get the AssetCompress factory based on the config object.
@return \AssetCompress\Factory | [
"Get",
"the",
"AssetCompress",
"factory",
"based",
"on",
"the",
"config",
"object",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L96-L104 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper.collection | protected function collection()
{
if (empty($this->collection)) {
$this->collection = $this->factory()->assetCollection();
}
return $this->collection;
} | php | protected function collection()
{
if (empty($this->collection)) {
$this->collection = $this->factory()->assetCollection();
}
return $this->collection;
} | [
"protected",
"function",
"collection",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"collection",
")",
")",
"{",
"$",
"this",
"->",
"collection",
"=",
"$",
"this",
"->",
"factory",
"(",
")",
"->",
"assetCollection",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"collection",
";",
"}"
] | Get the AssetCollection
@return \MiniAsset\AssetCollection | [
"Get",
"the",
"AssetCollection"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L111-L118 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper.writer | protected function writer()
{
if (empty($this->writer)) {
$this->writer = $this->factory()->writer();
}
return $this->writer;
} | php | protected function writer()
{
if (empty($this->writer)) {
$this->writer = $this->factory()->writer();
}
return $this->writer;
} | [
"protected",
"function",
"writer",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"writer",
")",
")",
"{",
"$",
"this",
"->",
"writer",
"=",
"$",
"this",
"->",
"factory",
"(",
")",
"->",
"writer",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"writer",
";",
"}"
] | Get the AssetWriter
@return \MiniAsset\Output\AssetWriter | [
"Get",
"the",
"AssetWriter"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L125-L132 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper._addExt | protected function _addExt($file, $ext)
{
if (substr($file, strlen($ext) * -1) !== $ext) {
$file .= $ext;
}
return $file;
} | php | protected function _addExt($file, $ext)
{
if (substr($file, strlen($ext) * -1) !== $ext) {
$file .= $ext;
}
return $file;
} | [
"protected",
"function",
"_addExt",
"(",
"$",
"file",
",",
"$",
"ext",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"file",
",",
"strlen",
"(",
"$",
"ext",
")",
"*",
"-",
"1",
")",
"!==",
"$",
"ext",
")",
"{",
"$",
"file",
".=",
"$",
"ext",
";",
"}",
"return",
"$",
"file",
";",
"}"
] | Adds an extension if the file doesn't already end with it.
@param string $file Filename
@param string $ext Extension with .
@return string | [
"Adds",
"an",
"extension",
"if",
"the",
"file",
"doesn",
"t",
"already",
"end",
"with",
"it",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L141-L148 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper.css | public function css($file, $options = [])
{
$file = $this->_addExt($file, '.css');
if (!$this->collection()->contains($file)) {
throw new RuntimeException(
"Cannot create a stylesheet tag for a '$file'. That build is not defined."
);
}
$output = '';
if (!empty($options['raw'])) {
unset($options['raw']);
$target = $this->collection()->get($file);
foreach ($target->files() as $part) {
$path = $this->_relativizePath($part->path());
if (DS === '\\') {
$path = str_replace(DS, '/', $path);
}
$output .= $this->Html->css($path, $options);
}
return $output;
}
$url = $this->url($file, $options);
unset($options['full']);
return $this->Html->css($url, $options);
} | php | public function css($file, $options = [])
{
$file = $this->_addExt($file, '.css');
if (!$this->collection()->contains($file)) {
throw new RuntimeException(
"Cannot create a stylesheet tag for a '$file'. That build is not defined."
);
}
$output = '';
if (!empty($options['raw'])) {
unset($options['raw']);
$target = $this->collection()->get($file);
foreach ($target->files() as $part) {
$path = $this->_relativizePath($part->path());
if (DS === '\\') {
$path = str_replace(DS, '/', $path);
}
$output .= $this->Html->css($path, $options);
}
return $output;
}
$url = $this->url($file, $options);
unset($options['full']);
return $this->Html->css($url, $options);
} | [
"public",
"function",
"css",
"(",
"$",
"file",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"_addExt",
"(",
"$",
"file",
",",
"'.css'",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"collection",
"(",
")",
"->",
"contains",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot create a stylesheet tag for a '$file'. That build is not defined.\"",
")",
";",
"}",
"$",
"output",
"=",
"''",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"options",
"[",
"'raw'",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"options",
"[",
"'raw'",
"]",
")",
";",
"$",
"target",
"=",
"$",
"this",
"->",
"collection",
"(",
")",
"->",
"get",
"(",
"$",
"file",
")",
";",
"foreach",
"(",
"$",
"target",
"->",
"files",
"(",
")",
"as",
"$",
"part",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"_relativizePath",
"(",
"$",
"part",
"->",
"path",
"(",
")",
")",
";",
"if",
"(",
"DS",
"===",
"'\\\\'",
")",
"{",
"$",
"path",
"=",
"str_replace",
"(",
"DS",
",",
"'/'",
",",
"$",
"path",
")",
";",
"}",
"$",
"output",
".=",
"$",
"this",
"->",
"Html",
"->",
"css",
"(",
"$",
"path",
",",
"$",
"options",
")",
";",
"}",
"return",
"$",
"output",
";",
"}",
"$",
"url",
"=",
"$",
"this",
"->",
"url",
"(",
"$",
"file",
",",
"$",
"options",
")",
";",
"unset",
"(",
"$",
"options",
"[",
"'full'",
"]",
")",
";",
"return",
"$",
"this",
"->",
"Html",
"->",
"css",
"(",
"$",
"url",
",",
"$",
"options",
")",
";",
"}"
] | Create a CSS file. Will generate link tags
for either the dynamic build controller, or the generated file if it exists.
To create build files without configuration use addCss()
Options:
- All options supported by HtmlHelper::css() are supported.
- `raw` - Set to true to get one link element for each file in the build.
@param string $file A build target to include.
@param array $options An array of options for the stylesheet tag.
@throws RuntimeException
@return string A stylesheet tag | [
"Create",
"a",
"CSS",
"file",
".",
"Will",
"generate",
"link",
"tags",
"for",
"either",
"the",
"dynamic",
"build",
"controller",
"or",
"the",
"generated",
"file",
"if",
"it",
"exists",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L166-L193 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper._relativizePath | protected function _relativizePath($path)
{
$plugins = Plugin::loaded();
$index = array_search('AssetCompress', $plugins);
unset($plugins[$index]);
foreach ($plugins as $plugin) {
$pluginPath = Plugin::path($plugin) . 'webroot';
if (strpos($path, $pluginPath) === 0) {
return str_replace($pluginPath, '/' . Inflector::underscore($plugin), $path);
}
}
$path = str_replace(WWW_ROOT, '/', $path);
return str_replace(DS, '/', $path);
} | php | protected function _relativizePath($path)
{
$plugins = Plugin::loaded();
$index = array_search('AssetCompress', $plugins);
unset($plugins[$index]);
foreach ($plugins as $plugin) {
$pluginPath = Plugin::path($plugin) . 'webroot';
if (strpos($path, $pluginPath) === 0) {
return str_replace($pluginPath, '/' . Inflector::underscore($plugin), $path);
}
}
$path = str_replace(WWW_ROOT, '/', $path);
return str_replace(DS, '/', $path);
} | [
"protected",
"function",
"_relativizePath",
"(",
"$",
"path",
")",
"{",
"$",
"plugins",
"=",
"Plugin",
"::",
"loaded",
"(",
")",
";",
"$",
"index",
"=",
"array_search",
"(",
"'AssetCompress'",
",",
"$",
"plugins",
")",
";",
"unset",
"(",
"$",
"plugins",
"[",
"$",
"index",
"]",
")",
";",
"foreach",
"(",
"$",
"plugins",
"as",
"$",
"plugin",
")",
"{",
"$",
"pluginPath",
"=",
"Plugin",
"::",
"path",
"(",
"$",
"plugin",
")",
".",
"'webroot'",
";",
"if",
"(",
"strpos",
"(",
"$",
"path",
",",
"$",
"pluginPath",
")",
"===",
"0",
")",
"{",
"return",
"str_replace",
"(",
"$",
"pluginPath",
",",
"'/'",
".",
"Inflector",
"::",
"underscore",
"(",
"$",
"plugin",
")",
",",
"$",
"path",
")",
";",
"}",
"}",
"$",
"path",
"=",
"str_replace",
"(",
"WWW_ROOT",
",",
"'/'",
",",
"$",
"path",
")",
";",
"return",
"str_replace",
"(",
"DS",
",",
"'/'",
",",
"$",
"path",
")",
";",
"}"
] | Converts an absolute path into a web relative one.
@param string $path The path to convert
@return string A webroot relative string. | [
"Converts",
"an",
"absolute",
"path",
"into",
"a",
"web",
"relative",
"one",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L246-L261 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper.url | public function url($file = null, $full = false)
{
$collection = $this->collection();
if (!$collection->contains($file)) {
throw new RuntimeException('Cannot get URL for build file that does not exist.');
}
$options = $full;
if (!is_array($full)) {
$options = ['full' => $full];
}
$options += ['full' => false];
$target = $collection->get($file);
$type = $target->ext();
$config = $this->assetConfig();
$baseUrl = $config->get($type . '.baseUrl');
$devMode = Configure::read('debug');
// CDN routes.
if ($baseUrl && !$devMode) {
return $baseUrl . $this->_getBuildName($target);
}
$root = str_replace('\\', '/', WWW_ROOT);
$path = str_replace('\\', '/', $target->outputDir());
$path = str_replace($root, '/', $path);
$route = null;
if (!$devMode) {
$path = rtrim($path, '/') . '/';
$route = $path . $this->_getBuildName($target);
}
if ($devMode || $config->general('alwaysEnableController')) {
$route = $this->_getRoute($target, $path);
}
if (DS === '\\') {
$route = str_replace(DS, '/', $route);
}
if ($options['full']) {
$base = Router::fullBaseUrl();
return $base . $route;
}
return $route;
} | php | public function url($file = null, $full = false)
{
$collection = $this->collection();
if (!$collection->contains($file)) {
throw new RuntimeException('Cannot get URL for build file that does not exist.');
}
$options = $full;
if (!is_array($full)) {
$options = ['full' => $full];
}
$options += ['full' => false];
$target = $collection->get($file);
$type = $target->ext();
$config = $this->assetConfig();
$baseUrl = $config->get($type . '.baseUrl');
$devMode = Configure::read('debug');
// CDN routes.
if ($baseUrl && !$devMode) {
return $baseUrl . $this->_getBuildName($target);
}
$root = str_replace('\\', '/', WWW_ROOT);
$path = str_replace('\\', '/', $target->outputDir());
$path = str_replace($root, '/', $path);
$route = null;
if (!$devMode) {
$path = rtrim($path, '/') . '/';
$route = $path . $this->_getBuildName($target);
}
if ($devMode || $config->general('alwaysEnableController')) {
$route = $this->_getRoute($target, $path);
}
if (DS === '\\') {
$route = str_replace(DS, '/', $route);
}
if ($options['full']) {
$base = Router::fullBaseUrl();
return $base . $route;
}
return $route;
} | [
"public",
"function",
"url",
"(",
"$",
"file",
"=",
"null",
",",
"$",
"full",
"=",
"false",
")",
"{",
"$",
"collection",
"=",
"$",
"this",
"->",
"collection",
"(",
")",
";",
"if",
"(",
"!",
"$",
"collection",
"->",
"contains",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot get URL for build file that does not exist.'",
")",
";",
"}",
"$",
"options",
"=",
"$",
"full",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"full",
")",
")",
"{",
"$",
"options",
"=",
"[",
"'full'",
"=>",
"$",
"full",
"]",
";",
"}",
"$",
"options",
"+=",
"[",
"'full'",
"=>",
"false",
"]",
";",
"$",
"target",
"=",
"$",
"collection",
"->",
"get",
"(",
"$",
"file",
")",
";",
"$",
"type",
"=",
"$",
"target",
"->",
"ext",
"(",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"assetConfig",
"(",
")",
";",
"$",
"baseUrl",
"=",
"$",
"config",
"->",
"get",
"(",
"$",
"type",
".",
"'.baseUrl'",
")",
";",
"$",
"devMode",
"=",
"Configure",
"::",
"read",
"(",
"'debug'",
")",
";",
"// CDN routes.",
"if",
"(",
"$",
"baseUrl",
"&&",
"!",
"$",
"devMode",
")",
"{",
"return",
"$",
"baseUrl",
".",
"$",
"this",
"->",
"_getBuildName",
"(",
"$",
"target",
")",
";",
"}",
"$",
"root",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"WWW_ROOT",
")",
";",
"$",
"path",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"target",
"->",
"outputDir",
"(",
")",
")",
";",
"$",
"path",
"=",
"str_replace",
"(",
"$",
"root",
",",
"'/'",
",",
"$",
"path",
")",
";",
"$",
"route",
"=",
"null",
";",
"if",
"(",
"!",
"$",
"devMode",
")",
"{",
"$",
"path",
"=",
"rtrim",
"(",
"$",
"path",
",",
"'/'",
")",
".",
"'/'",
";",
"$",
"route",
"=",
"$",
"path",
".",
"$",
"this",
"->",
"_getBuildName",
"(",
"$",
"target",
")",
";",
"}",
"if",
"(",
"$",
"devMode",
"||",
"$",
"config",
"->",
"general",
"(",
"'alwaysEnableController'",
")",
")",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"_getRoute",
"(",
"$",
"target",
",",
"$",
"path",
")",
";",
"}",
"if",
"(",
"DS",
"===",
"'\\\\'",
")",
"{",
"$",
"route",
"=",
"str_replace",
"(",
"DS",
",",
"'/'",
",",
"$",
"route",
")",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'full'",
"]",
")",
"{",
"$",
"base",
"=",
"Router",
"::",
"fullBaseUrl",
"(",
")",
";",
"return",
"$",
"base",
".",
"$",
"route",
";",
"}",
"return",
"$",
"route",
";",
"}"
] | Get the URL for a given asset name.
Takes an build filename, and returns the URL
to that build file.
@param string $file The build file that you want a URL for.
@param bool|array $full Whether or not the URL should have the full base path.
@return string The generated URL.
@throws RuntimeException when the build file does not exist. | [
"Get",
"the",
"URL",
"for",
"a",
"given",
"asset",
"name",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L274-L323 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper._getRoute | protected function _getRoute(AssetTarget $file, $base)
{
$query = [];
if ($file->isThemed()) {
$query['theme'] = $this->theme;
}
$base = rtrim($base, '/') . '/';
$query = empty($query) ? '' : '?' . http_build_query($query);
return $base . $file->name() . $query;
} | php | protected function _getRoute(AssetTarget $file, $base)
{
$query = [];
if ($file->isThemed()) {
$query['theme'] = $this->theme;
}
$base = rtrim($base, '/') . '/';
$query = empty($query) ? '' : '?' . http_build_query($query);
return $base . $file->name() . $query;
} | [
"protected",
"function",
"_getRoute",
"(",
"AssetTarget",
"$",
"file",
",",
"$",
"base",
")",
"{",
"$",
"query",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"file",
"->",
"isThemed",
"(",
")",
")",
"{",
"$",
"query",
"[",
"'theme'",
"]",
"=",
"$",
"this",
"->",
"theme",
";",
"}",
"$",
"base",
"=",
"rtrim",
"(",
"$",
"base",
",",
"'/'",
")",
".",
"'/'",
";",
"$",
"query",
"=",
"empty",
"(",
"$",
"query",
")",
"?",
"''",
":",
"'?'",
".",
"http_build_query",
"(",
"$",
"query",
")",
";",
"return",
"$",
"base",
".",
"$",
"file",
"->",
"name",
"(",
")",
".",
"$",
"query",
";",
"}"
] | Get the dynamic build path for an asset.
This generates URLs that work with the development dispatcher filter.
@param \MiniAsset\AssetTarget $file The build file you want to make a url for.
@param string $base The base path to fetch a url with.
@return string Generated URL. | [
"Get",
"the",
"dynamic",
"build",
"path",
"for",
"an",
"asset",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L348-L360 |
markstory/asset_compress | src/View/Helper/AssetCompressHelper.php | AssetCompressHelper.inlineCss | public function inlineCss($file)
{
$collection = $this->collection();
if (!$collection->contains($file)) {
throw new RuntimeException('Cannot create a stylesheet for a build that does not exist.');
}
$compiler = $this->factory()->compiler();
$results = $compiler->generate($collection->get($file));
return $this->Html->tag('style', $results, ['type' => 'text/css']);
} | php | public function inlineCss($file)
{
$collection = $this->collection();
if (!$collection->contains($file)) {
throw new RuntimeException('Cannot create a stylesheet for a build that does not exist.');
}
$compiler = $this->factory()->compiler();
$results = $compiler->generate($collection->get($file));
return $this->Html->tag('style', $results, ['type' => 'text/css']);
} | [
"public",
"function",
"inlineCss",
"(",
"$",
"file",
")",
"{",
"$",
"collection",
"=",
"$",
"this",
"->",
"collection",
"(",
")",
";",
"if",
"(",
"!",
"$",
"collection",
"->",
"contains",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot create a stylesheet for a build that does not exist.'",
")",
";",
"}",
"$",
"compiler",
"=",
"$",
"this",
"->",
"factory",
"(",
")",
"->",
"compiler",
"(",
")",
";",
"$",
"results",
"=",
"$",
"compiler",
"->",
"generate",
"(",
"$",
"collection",
"->",
"get",
"(",
"$",
"file",
")",
")",
";",
"return",
"$",
"this",
"->",
"Html",
"->",
"tag",
"(",
"'style'",
",",
"$",
"results",
",",
"[",
"'type'",
"=>",
"'text/css'",
"]",
")",
";",
"}"
] | Create a CSS file. Will generate inline style tags
in production, or reference the dynamic build file in development
To create build files without configuration use addCss()
Options:
- All options supported by HtmlHelper::css() are supported.
@param string $file A build target to include.
@throws RuntimeException
@return string style tag | [
"Create",
"a",
"CSS",
"file",
".",
"Will",
"generate",
"inline",
"style",
"tags",
"in",
"production",
"or",
"reference",
"the",
"dynamic",
"build",
"file",
"in",
"development"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/View/Helper/AssetCompressHelper.php#L387-L397 |
markstory/asset_compress | src/Middleware/AssetCompressMiddleware.php | AssetCompressMiddleware.respond | protected function respond($response, $contents, $build)
{
// Deliver built asset.
$body = $response->getBody();
$body->write($contents);
$body->rewind();
return $response->withHeader('Content-Type', $this->mapType($build));
} | php | protected function respond($response, $contents, $build)
{
// Deliver built asset.
$body = $response->getBody();
$body->write($contents);
$body->rewind();
return $response->withHeader('Content-Type', $this->mapType($build));
} | [
"protected",
"function",
"respond",
"(",
"$",
"response",
",",
"$",
"contents",
",",
"$",
"build",
")",
"{",
"// Deliver built asset.",
"$",
"body",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"$",
"body",
"->",
"write",
"(",
"$",
"contents",
")",
";",
"$",
"body",
"->",
"rewind",
"(",
")",
";",
"return",
"$",
"response",
"->",
"withHeader",
"(",
"'Content-Type'",
",",
"$",
"this",
"->",
"mapType",
"(",
"$",
"build",
")",
")",
";",
"}"
] | Respond with the asset.
@param \Psr\Http\Message\ResponseInterface $response The response to augment
@param string $contents The asset contents.
@param \MiniAsset\AssetTarget $build The build target.
@return \Psr\Http\Message\ResponseInterface | [
"Respond",
"with",
"the",
"asset",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Middleware/AssetCompressMiddleware.php#L89-L97 |
markstory/asset_compress | src/Middleware/AssetCompressMiddleware.php | AssetCompressMiddleware.mapType | protected function mapType($build)
{
$ext = $build->ext();
$types = [
'css' => 'text/css',
'js' => 'application/javascript'
];
return isset($types[$ext]) ? $types[$ext] : 'application/octet-stream';
} | php | protected function mapType($build)
{
$ext = $build->ext();
$types = [
'css' => 'text/css',
'js' => 'application/javascript'
];
return isset($types[$ext]) ? $types[$ext] : 'application/octet-stream';
} | [
"protected",
"function",
"mapType",
"(",
"$",
"build",
")",
"{",
"$",
"ext",
"=",
"$",
"build",
"->",
"ext",
"(",
")",
";",
"$",
"types",
"=",
"[",
"'css'",
"=>",
"'text/css'",
",",
"'js'",
"=>",
"'application/javascript'",
"]",
";",
"return",
"isset",
"(",
"$",
"types",
"[",
"$",
"ext",
"]",
")",
"?",
"$",
"types",
"[",
"$",
"ext",
"]",
":",
"'application/octet-stream'",
";",
"}"
] | Map an extension to a content type
@param \MiniAsset\AssetTarget $build The build target.
@return string The mapped content type. | [
"Map",
"an",
"extension",
"to",
"a",
"content",
"type"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Middleware/AssetCompressMiddleware.php#L105-L114 |
markstory/asset_compress | src/Filter/Sprockets.php | Sprockets._scanner | protected function _scanner()
{
if (isset($this->_scanner)) {
return $this->_scanner;
}
$this->_scanner = new AssetScanner(
$this->_settings['paths'],
isset($this->_settings['theme']) ? $this->_settings['theme'] : null
);
return $this->_scanner;
} | php | protected function _scanner()
{
if (isset($this->_scanner)) {
return $this->_scanner;
}
$this->_scanner = new AssetScanner(
$this->_settings['paths'],
isset($this->_settings['theme']) ? $this->_settings['theme'] : null
);
return $this->_scanner;
} | [
"protected",
"function",
"_scanner",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_scanner",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_scanner",
";",
"}",
"$",
"this",
"->",
"_scanner",
"=",
"new",
"AssetScanner",
"(",
"$",
"this",
"->",
"_settings",
"[",
"'paths'",
"]",
",",
"isset",
"(",
"$",
"this",
"->",
"_settings",
"[",
"'theme'",
"]",
")",
"?",
"$",
"this",
"->",
"_settings",
"[",
"'theme'",
"]",
":",
"null",
")",
";",
"return",
"$",
"this",
"->",
"_scanner",
";",
"}"
] | Use the CakePHP flavoured AssetScanner instead of the default one.
This allows Sprockets to support theme & plugin prefixes.
@return \AssetCompress\AssetScanner | [
"Use",
"the",
"CakePHP",
"flavoured",
"AssetScanner",
"instead",
"of",
"the",
"default",
"one",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Filter/Sprockets.php#L19-L30 |
markstory/asset_compress | src/Shell/AssetCompressShell.php | AssetCompressShell.startup | public function startup()
{
parent::startup();
$configFinder = new ConfigFinder();
$this->setConfig($configFinder->loadAll());
$this->out();
} | php | public function startup()
{
parent::startup();
$configFinder = new ConfigFinder();
$this->setConfig($configFinder->loadAll());
$this->out();
} | [
"public",
"function",
"startup",
"(",
")",
"{",
"parent",
"::",
"startup",
"(",
")",
";",
"$",
"configFinder",
"=",
"new",
"ConfigFinder",
"(",
")",
";",
"$",
"this",
"->",
"setConfig",
"(",
"$",
"configFinder",
"->",
"loadAll",
"(",
")",
")",
";",
"$",
"this",
"->",
"out",
"(",
")",
";",
"}"
] | Create the configuration object used in other classes.
@return void | [
"Create",
"the",
"configuration",
"object",
"used",
"in",
"other",
"classes",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/AssetCompressShell.php#L45-L51 |
markstory/asset_compress | src/Shell/AssetCompressShell.php | AssetCompressShell.setConfig | public function setConfig($config)
{
$this->config = $config;
$this->factory = new Factory($config);
$this->AssetBuild->setConfig($config);
} | php | public function setConfig($config)
{
$this->config = $config;
$this->factory = new Factory($config);
$this->AssetBuild->setConfig($config);
} | [
"public",
"function",
"setConfig",
"(",
"$",
"config",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"$",
"config",
";",
"$",
"this",
"->",
"factory",
"=",
"new",
"Factory",
"(",
"$",
"config",
")",
";",
"$",
"this",
"->",
"AssetBuild",
"->",
"setConfig",
"(",
"$",
"config",
")",
";",
"}"
] | Set the config object.
@param \MiniAsset\AssetConfig $config The config instance.
@return void | [
"Set",
"the",
"config",
"object",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/AssetCompressShell.php#L59-L64 |
markstory/asset_compress | src/Shell/AssetCompressShell.php | AssetCompressShell.clear | public function clear()
{
$this->clearBuildTs();
$this->_io->verbose('Clearing build files:');
$this->_clearBuilds();
$this->_io->verbose('');
$this->out('<success>Complete</success>');
} | php | public function clear()
{
$this->clearBuildTs();
$this->_io->verbose('Clearing build files:');
$this->_clearBuilds();
$this->_io->verbose('');
$this->out('<success>Complete</success>');
} | [
"public",
"function",
"clear",
"(",
")",
"{",
"$",
"this",
"->",
"clearBuildTs",
"(",
")",
";",
"$",
"this",
"->",
"_io",
"->",
"verbose",
"(",
"'Clearing build files:'",
")",
";",
"$",
"this",
"->",
"_clearBuilds",
"(",
")",
";",
"$",
"this",
"->",
"_io",
"->",
"verbose",
"(",
"''",
")",
";",
"$",
"this",
"->",
"out",
"(",
"'<success>Complete</success>'",
")",
";",
"}"
] | Clears the build directories for both CSS and JS
@return void | [
"Clears",
"the",
"build",
"directories",
"for",
"both",
"CSS",
"and",
"JS"
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/AssetCompressShell.php#L82-L91 |
markstory/asset_compress | src/Shell/AssetCompressShell.php | AssetCompressShell.clearBuildTs | public function clearBuildTs()
{
$this->_io->verbose('Clearing build timestamp.');
$writer = $this->factory->writer();
$writer->clearTimestamps();
} | php | public function clearBuildTs()
{
$this->_io->verbose('Clearing build timestamp.');
$writer = $this->factory->writer();
$writer->clearTimestamps();
} | [
"public",
"function",
"clearBuildTs",
"(",
")",
"{",
"$",
"this",
"->",
"_io",
"->",
"verbose",
"(",
"'Clearing build timestamp.'",
")",
";",
"$",
"writer",
"=",
"$",
"this",
"->",
"factory",
"->",
"writer",
"(",
")",
";",
"$",
"writer",
"->",
"clearTimestamps",
"(",
")",
";",
"}"
] | Clears the build timestamp. Try to clear it out even if they do not have ts file enabled in
the INI.
Build timestamp file is only created when build() is run from this shell
@return void | [
"Clears",
"the",
"build",
"timestamp",
".",
"Try",
"to",
"clear",
"it",
"out",
"even",
"if",
"they",
"do",
"not",
"have",
"ts",
"file",
"enabled",
"in",
"the",
"INI",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/AssetCompressShell.php#L101-L106 |
markstory/asset_compress | src/Shell/AssetCompressShell.php | AssetCompressShell._clearBuilds | protected function _clearBuilds()
{
$themes = (array)$this->config->general('themes');
if ($themes) {
$this->config->theme($themes[0]);
}
$assets = $this->factory->assetCollection();
if (count($assets) === 0) {
$this->err('No build targets defined, skipping');
return;
}
$targets = array_map(function ($target) {
return $target->name();
}, iterator_to_array($assets));
$this->_clearPath(CACHE . 'asset_compress' . DS, $themes, $targets);
$this->_clearPath($this->config->cachePath('js'), $themes, $targets);
$this->_clearPath($this->config->cachePath('css'), $themes, $targets);
} | php | protected function _clearBuilds()
{
$themes = (array)$this->config->general('themes');
if ($themes) {
$this->config->theme($themes[0]);
}
$assets = $this->factory->assetCollection();
if (count($assets) === 0) {
$this->err('No build targets defined, skipping');
return;
}
$targets = array_map(function ($target) {
return $target->name();
}, iterator_to_array($assets));
$this->_clearPath(CACHE . 'asset_compress' . DS, $themes, $targets);
$this->_clearPath($this->config->cachePath('js'), $themes, $targets);
$this->_clearPath($this->config->cachePath('css'), $themes, $targets);
} | [
"protected",
"function",
"_clearBuilds",
"(",
")",
"{",
"$",
"themes",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"config",
"->",
"general",
"(",
"'themes'",
")",
";",
"if",
"(",
"$",
"themes",
")",
"{",
"$",
"this",
"->",
"config",
"->",
"theme",
"(",
"$",
"themes",
"[",
"0",
"]",
")",
";",
"}",
"$",
"assets",
"=",
"$",
"this",
"->",
"factory",
"->",
"assetCollection",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"assets",
")",
"===",
"0",
")",
"{",
"$",
"this",
"->",
"err",
"(",
"'No build targets defined, skipping'",
")",
";",
"return",
";",
"}",
"$",
"targets",
"=",
"array_map",
"(",
"function",
"(",
"$",
"target",
")",
"{",
"return",
"$",
"target",
"->",
"name",
"(",
")",
";",
"}",
",",
"iterator_to_array",
"(",
"$",
"assets",
")",
")",
";",
"$",
"this",
"->",
"_clearPath",
"(",
"CACHE",
".",
"'asset_compress'",
".",
"DS",
",",
"$",
"themes",
",",
"$",
"targets",
")",
";",
"$",
"this",
"->",
"_clearPath",
"(",
"$",
"this",
"->",
"config",
"->",
"cachePath",
"(",
"'js'",
")",
",",
"$",
"themes",
",",
"$",
"targets",
")",
";",
"$",
"this",
"->",
"_clearPath",
"(",
"$",
"this",
"->",
"config",
"->",
"cachePath",
"(",
"'css'",
")",
",",
"$",
"themes",
",",
"$",
"targets",
")",
";",
"}"
] | clear the builds for a specific extension.
@return void | [
"clear",
"the",
"builds",
"for",
"a",
"specific",
"extension",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/AssetCompressShell.php#L113-L132 |
markstory/asset_compress | src/Shell/AssetCompressShell.php | AssetCompressShell._clearPath | protected function _clearPath($path, $themes, $targets)
{
if (!file_exists($path)) {
return;
}
$dir = new DirectoryIterator($path);
foreach ($dir as $file) {
$name = $base = $file->getFilename();
if (in_array($name, ['.', '..'])) {
continue;
}
// timestamped files.
if (preg_match('/^(.*)\.v\d+(\.[a-z]+)$/', $name, $matches)) {
$base = $matches[1] . $matches[2];
}
// themed files
foreach ($themes as $theme) {
if (strpos($base, $theme) === 0 && strpos($base, '-') !== false) {
list($themePrefix, $base) = explode('-', $base);
}
}
if (in_array($base, $targets)) {
$this->_io->verbose(' - Deleting ' . $path . $name);
unlink($path . $name);
continue;
}
}
} | php | protected function _clearPath($path, $themes, $targets)
{
if (!file_exists($path)) {
return;
}
$dir = new DirectoryIterator($path);
foreach ($dir as $file) {
$name = $base = $file->getFilename();
if (in_array($name, ['.', '..'])) {
continue;
}
// timestamped files.
if (preg_match('/^(.*)\.v\d+(\.[a-z]+)$/', $name, $matches)) {
$base = $matches[1] . $matches[2];
}
// themed files
foreach ($themes as $theme) {
if (strpos($base, $theme) === 0 && strpos($base, '-') !== false) {
list($themePrefix, $base) = explode('-', $base);
}
}
if (in_array($base, $targets)) {
$this->_io->verbose(' - Deleting ' . $path . $name);
unlink($path . $name);
continue;
}
}
} | [
"protected",
"function",
"_clearPath",
"(",
"$",
"path",
",",
"$",
"themes",
",",
"$",
"targets",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"return",
";",
"}",
"$",
"dir",
"=",
"new",
"DirectoryIterator",
"(",
"$",
"path",
")",
";",
"foreach",
"(",
"$",
"dir",
"as",
"$",
"file",
")",
"{",
"$",
"name",
"=",
"$",
"base",
"=",
"$",
"file",
"->",
"getFilename",
"(",
")",
";",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"[",
"'.'",
",",
"'..'",
"]",
")",
")",
"{",
"continue",
";",
"}",
"// timestamped files.",
"if",
"(",
"preg_match",
"(",
"'/^(.*)\\.v\\d+(\\.[a-z]+)$/'",
",",
"$",
"name",
",",
"$",
"matches",
")",
")",
"{",
"$",
"base",
"=",
"$",
"matches",
"[",
"1",
"]",
".",
"$",
"matches",
"[",
"2",
"]",
";",
"}",
"// themed files",
"foreach",
"(",
"$",
"themes",
"as",
"$",
"theme",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"base",
",",
"$",
"theme",
")",
"===",
"0",
"&&",
"strpos",
"(",
"$",
"base",
",",
"'-'",
")",
"!==",
"false",
")",
"{",
"list",
"(",
"$",
"themePrefix",
",",
"$",
"base",
")",
"=",
"explode",
"(",
"'-'",
",",
"$",
"base",
")",
";",
"}",
"}",
"if",
"(",
"in_array",
"(",
"$",
"base",
",",
"$",
"targets",
")",
")",
"{",
"$",
"this",
"->",
"_io",
"->",
"verbose",
"(",
"' - Deleting '",
".",
"$",
"path",
".",
"$",
"name",
")",
";",
"unlink",
"(",
"$",
"path",
".",
"$",
"name",
")",
";",
"continue",
";",
"}",
"}",
"}"
] | Clear a path of build targets.
@param string $path The root path to clear.
@param array $themes The themes to clear.
@param array $targets The build targets to clear.
@return void | [
"Clear",
"a",
"path",
"of",
"build",
"targets",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/AssetCompressShell.php#L142-L170 |
markstory/asset_compress | src/Shell/AssetCompressShell.php | AssetCompressShell.getOptionParser | public function getOptionParser()
{
$parser = parent::getOptionParser();
return $parser->setDescription([
'Asset Compress Shell',
'',
'Builds and clears assets defined in your asset_compress.ini',
'file and in your view files.'
])->addSubcommand('clear', [
'help' => 'Clears all builds defined in the ini file.'
])->addSubcommand('build', [
'help' => 'Generate all builds defined in the ini files.'
])->addOption('force', [
'help' => 'Force assets to rebuild. Ignores timestamp rules.',
'short' => 'f',
'boolean' => true
]);
} | php | public function getOptionParser()
{
$parser = parent::getOptionParser();
return $parser->setDescription([
'Asset Compress Shell',
'',
'Builds and clears assets defined in your asset_compress.ini',
'file and in your view files.'
])->addSubcommand('clear', [
'help' => 'Clears all builds defined in the ini file.'
])->addSubcommand('build', [
'help' => 'Generate all builds defined in the ini files.'
])->addOption('force', [
'help' => 'Force assets to rebuild. Ignores timestamp rules.',
'short' => 'f',
'boolean' => true
]);
} | [
"public",
"function",
"getOptionParser",
"(",
")",
"{",
"$",
"parser",
"=",
"parent",
"::",
"getOptionParser",
"(",
")",
";",
"return",
"$",
"parser",
"->",
"setDescription",
"(",
"[",
"'Asset Compress Shell'",
",",
"''",
",",
"'Builds and clears assets defined in your asset_compress.ini'",
",",
"'file and in your view files.'",
"]",
")",
"->",
"addSubcommand",
"(",
"'clear'",
",",
"[",
"'help'",
"=>",
"'Clears all builds defined in the ini file.'",
"]",
")",
"->",
"addSubcommand",
"(",
"'build'",
",",
"[",
"'help'",
"=>",
"'Generate all builds defined in the ini files.'",
"]",
")",
"->",
"addOption",
"(",
"'force'",
",",
"[",
"'help'",
"=>",
"'Force assets to rebuild. Ignores timestamp rules.'",
",",
"'short'",
"=>",
"'f'",
",",
"'boolean'",
"=>",
"true",
"]",
")",
";",
"}"
] | get the option parser.
@return \Cake\Console\ConsoleOptionParser | [
"get",
"the",
"option",
"parser",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/AssetCompressShell.php#L177-L195 |
markstory/asset_compress | src/Config/ConfigFinder.php | ConfigFinder.loadAll | public function loadAll($path = null)
{
if (!$path) {
$path = CONFIG . 'asset_compress.ini';
}
$config = new AssetConfig([], [
'WEBROOT' => WWW_ROOT,
]);
$this->_load($config, $path);
$plugins = Plugin::loaded();
foreach ($plugins as $plugin) {
$pluginConfig = Plugin::path($plugin) . 'config' . DS . 'asset_compress.ini';
$this->_load($config, $pluginConfig, $plugin . '.');
}
return $config;
} | php | public function loadAll($path = null)
{
if (!$path) {
$path = CONFIG . 'asset_compress.ini';
}
$config = new AssetConfig([], [
'WEBROOT' => WWW_ROOT,
]);
$this->_load($config, $path);
$plugins = Plugin::loaded();
foreach ($plugins as $plugin) {
$pluginConfig = Plugin::path($plugin) . 'config' . DS . 'asset_compress.ini';
$this->_load($config, $pluginConfig, $plugin . '.');
}
return $config;
} | [
"public",
"function",
"loadAll",
"(",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"CONFIG",
".",
"'asset_compress.ini'",
";",
"}",
"$",
"config",
"=",
"new",
"AssetConfig",
"(",
"[",
"]",
",",
"[",
"'WEBROOT'",
"=>",
"WWW_ROOT",
",",
"]",
")",
";",
"$",
"this",
"->",
"_load",
"(",
"$",
"config",
",",
"$",
"path",
")",
";",
"$",
"plugins",
"=",
"Plugin",
"::",
"loaded",
"(",
")",
";",
"foreach",
"(",
"$",
"plugins",
"as",
"$",
"plugin",
")",
"{",
"$",
"pluginConfig",
"=",
"Plugin",
"::",
"path",
"(",
"$",
"plugin",
")",
".",
"'config'",
".",
"DS",
".",
"'asset_compress.ini'",
";",
"$",
"this",
"->",
"_load",
"(",
"$",
"config",
",",
"$",
"pluginConfig",
",",
"$",
"plugin",
".",
"'.'",
")",
";",
"}",
"return",
"$",
"config",
";",
"}"
] | Load all configuration files in the application.
Loads:
- The app config (asset_compress.ini)
- The asset_compress.ini file in each plugin.
In addition for each file found the `asset_compress.local.ini`
will be loaded if it is present.
@param string $path The configuration file path to start loading from.
@return \MiniAsset\AssetConfig The completed configuration object. | [
"Load",
"all",
"configuration",
"files",
"in",
"the",
"application",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Config/ConfigFinder.php#L33-L50 |
markstory/asset_compress | src/Config/ConfigFinder.php | ConfigFinder._load | protected function _load($config, $path, $prefix = '')
{
if (file_exists($path)) {
$config->load($path, $prefix);
}
$localConfig = preg_replace('/(.*)\.ini$/', '$1.local.ini', $path);
if (file_exists($localConfig)) {
$config->load($localConfig, $prefix);
}
} | php | protected function _load($config, $path, $prefix = '')
{
if (file_exists($path)) {
$config->load($path, $prefix);
}
$localConfig = preg_replace('/(.*)\.ini$/', '$1.local.ini', $path);
if (file_exists($localConfig)) {
$config->load($localConfig, $prefix);
}
} | [
"protected",
"function",
"_load",
"(",
"$",
"config",
",",
"$",
"path",
",",
"$",
"prefix",
"=",
"''",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"$",
"config",
"->",
"load",
"(",
"$",
"path",
",",
"$",
"prefix",
")",
";",
"}",
"$",
"localConfig",
"=",
"preg_replace",
"(",
"'/(.*)\\.ini$/'",
",",
"'$1.local.ini'",
",",
"$",
"path",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"localConfig",
")",
")",
"{",
"$",
"config",
"->",
"load",
"(",
"$",
"localConfig",
",",
"$",
"prefix",
")",
";",
"}",
"}"
] | Load a config file and its `.local` file if it exists.
@param \MiniAsset\AssetConfig $config The config object to update.
@param string $path The config file to load.
@param string $prefix The prefix to use.
@return void | [
"Load",
"a",
"config",
"file",
"and",
"its",
".",
"local",
"file",
"if",
"it",
"exists",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Config/ConfigFinder.php#L60-L70 |
markstory/asset_compress | src/Filter/ImportInline.php | ImportInline.scanner | protected function scanner()
{
if (isset($this->scanner)) {
return $this->scanner;
}
$this->scanner = new AssetScanner(
$this->_settings['paths'],
isset($this->_settings['theme']) ? $this->_settings['theme'] : null
);
return $this->scanner;
} | php | protected function scanner()
{
if (isset($this->scanner)) {
return $this->scanner;
}
$this->scanner = new AssetScanner(
$this->_settings['paths'],
isset($this->_settings['theme']) ? $this->_settings['theme'] : null
);
return $this->scanner;
} | [
"protected",
"function",
"scanner",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"scanner",
")",
")",
"{",
"return",
"$",
"this",
"->",
"scanner",
";",
"}",
"$",
"this",
"->",
"scanner",
"=",
"new",
"AssetScanner",
"(",
"$",
"this",
"->",
"_settings",
"[",
"'paths'",
"]",
",",
"isset",
"(",
"$",
"this",
"->",
"_settings",
"[",
"'theme'",
"]",
")",
"?",
"$",
"this",
"->",
"_settings",
"[",
"'theme'",
"]",
":",
"null",
")",
";",
"return",
"$",
"this",
"->",
"scanner",
";",
"}"
] | Use the CakePHP flavoured AssetScanner instead of the default one.
This allows ImportInline to support theme & plugin prefixes.
@return \AssetCompress\AssetScanner | [
"Use",
"the",
"CakePHP",
"flavoured",
"AssetScanner",
"instead",
"of",
"the",
"default",
"one",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Filter/ImportInline.php#L19-L30 |
markstory/asset_compress | src/Shell/Task/AssetBuildTask.php | AssetBuildTask.setConfig | public function setConfig(AssetConfig $config)
{
$this->config = $config;
$this->factory = new Factory($config);
} | php | public function setConfig(AssetConfig $config)
{
$this->config = $config;
$this->factory = new Factory($config);
} | [
"public",
"function",
"setConfig",
"(",
"AssetConfig",
"$",
"config",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"$",
"config",
";",
"$",
"this",
"->",
"factory",
"=",
"new",
"Factory",
"(",
"$",
"config",
")",
";",
"}"
] | Set the Configuration object that will be used.
@param \AssetCompress\AssetConfig $config The config object.
@return void | [
"Set",
"the",
"Configuration",
"object",
"that",
"will",
"be",
"used",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/Task/AssetBuildTask.php#L23-L27 |
markstory/asset_compress | src/Shell/Task/AssetBuildTask.php | AssetBuildTask.build | public function build()
{
$themes = (array)$this->config->general('themes');
foreach ($themes as $theme) {
$this->_io->verbose('Building with theme = ' . $theme);
$this->config->theme($theme);
foreach ($this->factory->assetCollection() as $target) {
if ($target->isThemed()) {
$this->_buildTarget($target);
}
}
}
$this->_io->verbose('Building un-themed targets.');
foreach ($this->factory->assetCollection() as $target) {
$this->_buildTarget($target);
}
} | php | public function build()
{
$themes = (array)$this->config->general('themes');
foreach ($themes as $theme) {
$this->_io->verbose('Building with theme = ' . $theme);
$this->config->theme($theme);
foreach ($this->factory->assetCollection() as $target) {
if ($target->isThemed()) {
$this->_buildTarget($target);
}
}
}
$this->_io->verbose('Building un-themed targets.');
foreach ($this->factory->assetCollection() as $target) {
$this->_buildTarget($target);
}
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"themes",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"config",
"->",
"general",
"(",
"'themes'",
")",
";",
"foreach",
"(",
"$",
"themes",
"as",
"$",
"theme",
")",
"{",
"$",
"this",
"->",
"_io",
"->",
"verbose",
"(",
"'Building with theme = '",
".",
"$",
"theme",
")",
";",
"$",
"this",
"->",
"config",
"->",
"theme",
"(",
"$",
"theme",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"factory",
"->",
"assetCollection",
"(",
")",
"as",
"$",
"target",
")",
"{",
"if",
"(",
"$",
"target",
"->",
"isThemed",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_buildTarget",
"(",
"$",
"target",
")",
";",
"}",
"}",
"}",
"$",
"this",
"->",
"_io",
"->",
"verbose",
"(",
"'Building un-themed targets.'",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"factory",
"->",
"assetCollection",
"(",
")",
"as",
"$",
"target",
")",
"{",
"$",
"this",
"->",
"_buildTarget",
"(",
"$",
"target",
")",
";",
"}",
"}"
] | Build all the files declared in the Configuration object.
@return void | [
"Build",
"all",
"the",
"files",
"declared",
"in",
"the",
"Configuration",
"object",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/Task/AssetBuildTask.php#L34-L50 |
markstory/asset_compress | src/Shell/Task/AssetBuildTask.php | AssetBuildTask._buildTarget | protected function _buildTarget(AssetTarget $build)
{
$writer = $this->factory->writer();
$compiler = $this->factory->compiler();
$name = $writer->buildFileName($build);
if ($writer->isFresh($build) && empty($this->params['force'])) {
$this->out('<info>Skip building</info> ' . $name . ' existing file is still fresh.');
return;
}
$writer->invalidate($build);
$name = $writer->buildFileName($build);
try {
$this->out('<success>Saving file</success> for ' . $name);
$contents = $compiler->generate($build);
$writer->write($build, $contents);
} catch (Exception $e) {
$this->err('Error: ' . $e->getMessage());
}
} | php | protected function _buildTarget(AssetTarget $build)
{
$writer = $this->factory->writer();
$compiler = $this->factory->compiler();
$name = $writer->buildFileName($build);
if ($writer->isFresh($build) && empty($this->params['force'])) {
$this->out('<info>Skip building</info> ' . $name . ' existing file is still fresh.');
return;
}
$writer->invalidate($build);
$name = $writer->buildFileName($build);
try {
$this->out('<success>Saving file</success> for ' . $name);
$contents = $compiler->generate($build);
$writer->write($build, $contents);
} catch (Exception $e) {
$this->err('Error: ' . $e->getMessage());
}
} | [
"protected",
"function",
"_buildTarget",
"(",
"AssetTarget",
"$",
"build",
")",
"{",
"$",
"writer",
"=",
"$",
"this",
"->",
"factory",
"->",
"writer",
"(",
")",
";",
"$",
"compiler",
"=",
"$",
"this",
"->",
"factory",
"->",
"compiler",
"(",
")",
";",
"$",
"name",
"=",
"$",
"writer",
"->",
"buildFileName",
"(",
"$",
"build",
")",
";",
"if",
"(",
"$",
"writer",
"->",
"isFresh",
"(",
"$",
"build",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"params",
"[",
"'force'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"out",
"(",
"'<info>Skip building</info> '",
".",
"$",
"name",
".",
"' existing file is still fresh.'",
")",
";",
"return",
";",
"}",
"$",
"writer",
"->",
"invalidate",
"(",
"$",
"build",
")",
";",
"$",
"name",
"=",
"$",
"writer",
"->",
"buildFileName",
"(",
"$",
"build",
")",
";",
"try",
"{",
"$",
"this",
"->",
"out",
"(",
"'<success>Saving file</success> for '",
".",
"$",
"name",
")",
";",
"$",
"contents",
"=",
"$",
"compiler",
"->",
"generate",
"(",
"$",
"build",
")",
";",
"$",
"writer",
"->",
"write",
"(",
"$",
"build",
",",
"$",
"contents",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"err",
"(",
"'Error: '",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Generate and save the cached file for a build target.
@param AssetTarget $build The build to generate.
@return void | [
"Generate",
"and",
"save",
"the",
"cached",
"file",
"for",
"a",
"build",
"target",
"."
] | train | https://github.com/markstory/asset_compress/blob/81851833233ad05a283d36c5564d1cc13d297af6/src/Shell/Task/AssetBuildTask.php#L58-L79 |
umpirsky/Symfony-Upgrade-Fixer | src/Symfony/Upgrade/Fixer/FormGetnameToGetblockprefixFixer.php | FormGetnameToGetblockprefixFixer.fix | public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if ($this->isFormType($tokens)) {
$this->fixGetNameMethod($tokens);
}
return $tokens->generateCode();
} | php | public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if ($this->isFormType($tokens)) {
$this->fixGetNameMethod($tokens);
}
return $tokens->generateCode();
} | [
"public",
"function",
"fix",
"(",
"\\",
"SplFileInfo",
"$",
"file",
",",
"$",
"content",
")",
"{",
"$",
"tokens",
"=",
"Tokens",
"::",
"fromCode",
"(",
"$",
"content",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isFormType",
"(",
"$",
"tokens",
")",
")",
"{",
"$",
"this",
"->",
"fixGetNameMethod",
"(",
"$",
"tokens",
")",
";",
"}",
"return",
"$",
"tokens",
"->",
"generateCode",
"(",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/umpirsky/Symfony-Upgrade-Fixer/blob/df97834d8ed0687d97a56c3e753db87a581ab2ce/src/Symfony/Upgrade/Fixer/FormGetnameToGetblockprefixFixer.php#L12-L21 |
umpirsky/Symfony-Upgrade-Fixer | src/Symfony/Upgrade/Fixer/FormExtensionGetExtendedTypeFixer.php | FormExtensionGetExtendedTypeFixer.fix | public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if ($this->isFormType($tokens)) {
foreach ($this->types as $type) {
if (null === $this->matchGetExtendedType($tokens, $type)) {
continue;
}
$this->addTypeUse($tokens, $type);
$this->fixGetExtendedTypeMethod($tokens, $type);
}
}
return $tokens->generateCode();
} | php | public function fix(\SplFileInfo $file, $content)
{
$tokens = Tokens::fromCode($content);
if ($this->isFormType($tokens)) {
foreach ($this->types as $type) {
if (null === $this->matchGetExtendedType($tokens, $type)) {
continue;
}
$this->addTypeUse($tokens, $type);
$this->fixGetExtendedTypeMethod($tokens, $type);
}
}
return $tokens->generateCode();
} | [
"public",
"function",
"fix",
"(",
"\\",
"SplFileInfo",
"$",
"file",
",",
"$",
"content",
")",
"{",
"$",
"tokens",
"=",
"Tokens",
"::",
"fromCode",
"(",
"$",
"content",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isFormType",
"(",
"$",
"tokens",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"types",
"as",
"$",
"type",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"matchGetExtendedType",
"(",
"$",
"tokens",
",",
"$",
"type",
")",
")",
"{",
"continue",
";",
"}",
"$",
"this",
"->",
"addTypeUse",
"(",
"$",
"tokens",
",",
"$",
"type",
")",
";",
"$",
"this",
"->",
"fixGetExtendedTypeMethod",
"(",
"$",
"tokens",
",",
"$",
"type",
")",
";",
"}",
"}",
"return",
"$",
"tokens",
"->",
"generateCode",
"(",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/umpirsky/Symfony-Upgrade-Fixer/blob/df97834d8ed0687d97a56c3e753db87a581ab2ce/src/Symfony/Upgrade/Fixer/FormExtensionGetExtendedTypeFixer.php#L13-L29 |
propelorm/Propel | generator/lib/behavior/sortable/SortableBehaviorPeerBuilderModifier.php | SortableBehaviorPeerBuilderModifier.staticMethods | public function staticMethods($builder)
{
$this->setBuilder($builder);
$script = '';
$this->addGetMaxRank($script);
$this->addRetrieveByRank($script);
$this->addReorder($script);
$this->addDoSelectOrderByRank($script);
if ($this->behavior->useScope()) {
$this->addRetrieveList($script);
$this->addCountList($script);
$this->addDeleteList($script);
$this->addSortableApplyScopeCriteria($script);
}
$this->addShiftRank($script);
return $script;
} | php | public function staticMethods($builder)
{
$this->setBuilder($builder);
$script = '';
$this->addGetMaxRank($script);
$this->addRetrieveByRank($script);
$this->addReorder($script);
$this->addDoSelectOrderByRank($script);
if ($this->behavior->useScope()) {
$this->addRetrieveList($script);
$this->addCountList($script);
$this->addDeleteList($script);
$this->addSortableApplyScopeCriteria($script);
}
$this->addShiftRank($script);
return $script;
} | [
"public",
"function",
"staticMethods",
"(",
"$",
"builder",
")",
"{",
"$",
"this",
"->",
"setBuilder",
"(",
"$",
"builder",
")",
";",
"$",
"script",
"=",
"''",
";",
"$",
"this",
"->",
"addGetMaxRank",
"(",
"$",
"script",
")",
";",
"$",
"this",
"->",
"addRetrieveByRank",
"(",
"$",
"script",
")",
";",
"$",
"this",
"->",
"addReorder",
"(",
"$",
"script",
")",
";",
"$",
"this",
"->",
"addDoSelectOrderByRank",
"(",
"$",
"script",
")",
";",
"if",
"(",
"$",
"this",
"->",
"behavior",
"->",
"useScope",
"(",
")",
")",
"{",
"$",
"this",
"->",
"addRetrieveList",
"(",
"$",
"script",
")",
";",
"$",
"this",
"->",
"addCountList",
"(",
"$",
"script",
")",
";",
"$",
"this",
"->",
"addDeleteList",
"(",
"$",
"script",
")",
";",
"$",
"this",
"->",
"addSortableApplyScopeCriteria",
"(",
"$",
"script",
")",
";",
"}",
"$",
"this",
"->",
"addShiftRank",
"(",
"$",
"script",
")",
";",
"return",
"$",
"script",
";",
"}"
] | Static methods
@return string | [
"Static",
"methods"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/behavior/sortable/SortableBehaviorPeerBuilderModifier.php#L133-L151 |
propelorm/Propel | generator/lib/model/AppData.php | AppData.getDatabase | public function getDatabase($name = null, $doFinalInit = true)
{
// this is temporary until we'll have a clean solution
// for packaging datamodels/requiring schemas
if ($doFinalInit) {
$this->doFinalInitialization();
}
if ($name === null) {
return $this->dbList[0];
}
for ($i = 0, $size = count($this->dbList); $i < $size; $i++) {
$db = $this->dbList[$i];
if ($db->getName() === $name) {
return $db;
}
}
return null;
} | php | public function getDatabase($name = null, $doFinalInit = true)
{
// this is temporary until we'll have a clean solution
// for packaging datamodels/requiring schemas
if ($doFinalInit) {
$this->doFinalInitialization();
}
if ($name === null) {
return $this->dbList[0];
}
for ($i = 0, $size = count($this->dbList); $i < $size; $i++) {
$db = $this->dbList[$i];
if ($db->getName() === $name) {
return $db;
}
}
return null;
} | [
"public",
"function",
"getDatabase",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"doFinalInit",
"=",
"true",
")",
"{",
"// this is temporary until we'll have a clean solution",
"// for packaging datamodels/requiring schemas",
"if",
"(",
"$",
"doFinalInit",
")",
"{",
"$",
"this",
"->",
"doFinalInitialization",
"(",
")",
";",
"}",
"if",
"(",
"$",
"name",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"dbList",
"[",
"0",
"]",
";",
"}",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"size",
"=",
"count",
"(",
"$",
"this",
"->",
"dbList",
")",
";",
"$",
"i",
"<",
"$",
"size",
";",
"$",
"i",
"++",
")",
"{",
"$",
"db",
"=",
"$",
"this",
"->",
"dbList",
"[",
"$",
"i",
"]",
";",
"if",
"(",
"$",
"db",
"->",
"getName",
"(",
")",
"===",
"$",
"name",
")",
"{",
"return",
"$",
"db",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Return the database with the specified name.
@param string $name database name
@param bool $doFinalInit
@return Database|null | [
"Return",
"the",
"database",
"with",
"the",
"specified",
"name",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/model/AppData.php#L177-L197 |
propelorm/Propel | generator/lib/model/AppData.php | AppData.hasDatabase | public function hasDatabase($name)
{
foreach ($this->dbList as $db) {
if ($db->getName() === $name) {
return true;
}
}
return false;
} | php | public function hasDatabase($name)
{
foreach ($this->dbList as $db) {
if ($db->getName() === $name) {
return true;
}
}
return false;
} | [
"public",
"function",
"hasDatabase",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"dbList",
"as",
"$",
"db",
")",
"{",
"if",
"(",
"$",
"db",
"->",
"getName",
"(",
")",
"===",
"$",
"name",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks whether a database with the specified nam exists in this AppData
@param string $name database name
@return boolean | [
"Checks",
"whether",
"a",
"database",
"with",
"the",
"specified",
"nam",
"exists",
"in",
"this",
"AppData"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/model/AppData.php#L206-L215 |
propelorm/Propel | generator/lib/model/AppData.php | AppData.addDatabase | public function addDatabase($db)
{
if ($db instanceof Database) {
$db->setAppData($this);
if ($db->getPlatform() === null) {
if ($config = $this->getGeneratorConfig()) {
$pf = $config->getConfiguredPlatform(null, $db->getName());
$db->setPlatform($pf ? $pf : $this->platform);
} else {
$db->setPlatform($this->platform);
}
}
$this->dbList[] = $db;
return $db;
} else {
// XML attributes array / hash
$d = new Database();
$d->setAppData($this);
$d->loadFromXML($db);
return $this->addDatabase($d); // calls self w/ different param type
}
} | php | public function addDatabase($db)
{
if ($db instanceof Database) {
$db->setAppData($this);
if ($db->getPlatform() === null) {
if ($config = $this->getGeneratorConfig()) {
$pf = $config->getConfiguredPlatform(null, $db->getName());
$db->setPlatform($pf ? $pf : $this->platform);
} else {
$db->setPlatform($this->platform);
}
}
$this->dbList[] = $db;
return $db;
} else {
// XML attributes array / hash
$d = new Database();
$d->setAppData($this);
$d->loadFromXML($db);
return $this->addDatabase($d); // calls self w/ different param type
}
} | [
"public",
"function",
"addDatabase",
"(",
"$",
"db",
")",
"{",
"if",
"(",
"$",
"db",
"instanceof",
"Database",
")",
"{",
"$",
"db",
"->",
"setAppData",
"(",
"$",
"this",
")",
";",
"if",
"(",
"$",
"db",
"->",
"getPlatform",
"(",
")",
"===",
"null",
")",
"{",
"if",
"(",
"$",
"config",
"=",
"$",
"this",
"->",
"getGeneratorConfig",
"(",
")",
")",
"{",
"$",
"pf",
"=",
"$",
"config",
"->",
"getConfiguredPlatform",
"(",
"null",
",",
"$",
"db",
"->",
"getName",
"(",
")",
")",
";",
"$",
"db",
"->",
"setPlatform",
"(",
"$",
"pf",
"?",
"$",
"pf",
":",
"$",
"this",
"->",
"platform",
")",
";",
"}",
"else",
"{",
"$",
"db",
"->",
"setPlatform",
"(",
"$",
"this",
"->",
"platform",
")",
";",
"}",
"}",
"$",
"this",
"->",
"dbList",
"[",
"]",
"=",
"$",
"db",
";",
"return",
"$",
"db",
";",
"}",
"else",
"{",
"// XML attributes array / hash",
"$",
"d",
"=",
"new",
"Database",
"(",
")",
";",
"$",
"d",
"->",
"setAppData",
"(",
"$",
"this",
")",
";",
"$",
"d",
"->",
"loadFromXML",
"(",
"$",
"db",
")",
";",
"return",
"$",
"this",
"->",
"addDatabase",
"(",
"$",
"d",
")",
";",
"// calls self w/ different param type",
"}",
"}"
] | Add a database to the list and sets the AppData property to this
AppData
@param Database|string $db the database to add
@return Database | [
"Add",
"a",
"database",
"to",
"the",
"list",
"and",
"sets",
"the",
"AppData",
"property",
"to",
"this",
"AppData"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/model/AppData.php#L225-L248 |
propelorm/Propel | generator/lib/model/AppData.php | AppData.joinAppDatas | public function joinAppDatas($ads)
{
foreach ($ads as $appData) {
foreach ($appData->getDatabases(false) as $addDb) {
$addDbName = $addDb->getName();
if ($this->hasDatabase($addDbName)) {
$db = $this->getDatabase($addDbName, false);
// temporarily reset database namespace to avoid double namespace decoration (see ticket #1355)
$namespace = $db->getNamespace();
$db->setNamespace(null);
// join tables
foreach ($addDb->getTables() as $addTable) {
if ($db->getTable($addTable->getName())) {
throw new Exception(sprintf('Duplicate table found: %s.', $addTable->getName()));
}
$db->addTable($addTable);
}
// join database behaviors
foreach ($addDb->getBehaviors() as $addBehavior) {
if (!$db->hasBehavior($addBehavior->getName())) {
$db->addBehavior($addBehavior);
}
}
// restore the database namespace
$db->setNamespace($namespace);
} else {
$this->addDatabase($addDb);
}
}
}
} | php | public function joinAppDatas($ads)
{
foreach ($ads as $appData) {
foreach ($appData->getDatabases(false) as $addDb) {
$addDbName = $addDb->getName();
if ($this->hasDatabase($addDbName)) {
$db = $this->getDatabase($addDbName, false);
// temporarily reset database namespace to avoid double namespace decoration (see ticket #1355)
$namespace = $db->getNamespace();
$db->setNamespace(null);
// join tables
foreach ($addDb->getTables() as $addTable) {
if ($db->getTable($addTable->getName())) {
throw new Exception(sprintf('Duplicate table found: %s.', $addTable->getName()));
}
$db->addTable($addTable);
}
// join database behaviors
foreach ($addDb->getBehaviors() as $addBehavior) {
if (!$db->hasBehavior($addBehavior->getName())) {
$db->addBehavior($addBehavior);
}
}
// restore the database namespace
$db->setNamespace($namespace);
} else {
$this->addDatabase($addDb);
}
}
}
} | [
"public",
"function",
"joinAppDatas",
"(",
"$",
"ads",
")",
"{",
"foreach",
"(",
"$",
"ads",
"as",
"$",
"appData",
")",
"{",
"foreach",
"(",
"$",
"appData",
"->",
"getDatabases",
"(",
"false",
")",
"as",
"$",
"addDb",
")",
"{",
"$",
"addDbName",
"=",
"$",
"addDb",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"hasDatabase",
"(",
"$",
"addDbName",
")",
")",
"{",
"$",
"db",
"=",
"$",
"this",
"->",
"getDatabase",
"(",
"$",
"addDbName",
",",
"false",
")",
";",
"// temporarily reset database namespace to avoid double namespace decoration (see ticket #1355)",
"$",
"namespace",
"=",
"$",
"db",
"->",
"getNamespace",
"(",
")",
";",
"$",
"db",
"->",
"setNamespace",
"(",
"null",
")",
";",
"// join tables",
"foreach",
"(",
"$",
"addDb",
"->",
"getTables",
"(",
")",
"as",
"$",
"addTable",
")",
"{",
"if",
"(",
"$",
"db",
"->",
"getTable",
"(",
"$",
"addTable",
"->",
"getName",
"(",
")",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"sprintf",
"(",
"'Duplicate table found: %s.'",
",",
"$",
"addTable",
"->",
"getName",
"(",
")",
")",
")",
";",
"}",
"$",
"db",
"->",
"addTable",
"(",
"$",
"addTable",
")",
";",
"}",
"// join database behaviors",
"foreach",
"(",
"$",
"addDb",
"->",
"getBehaviors",
"(",
")",
"as",
"$",
"addBehavior",
")",
"{",
"if",
"(",
"!",
"$",
"db",
"->",
"hasBehavior",
"(",
"$",
"addBehavior",
"->",
"getName",
"(",
")",
")",
")",
"{",
"$",
"db",
"->",
"addBehavior",
"(",
"$",
"addBehavior",
")",
";",
"}",
"}",
"// restore the database namespace",
"$",
"db",
"->",
"setNamespace",
"(",
"$",
"namespace",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"addDatabase",
"(",
"$",
"addDb",
")",
";",
"}",
"}",
"}",
"}"
] | Merge other appData objects into this object
@param AppData[] $ads
@throws Exception | [
"Merge",
"other",
"appData",
"objects",
"into",
"this",
"object"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/model/AppData.php#L267-L297 |
propelorm/Propel | generator/lib/model/AppData.php | AppData.toString | public function toString()
{
$result = "<app-data>\n";
foreach ($this->dbList as $dbList) {
$result .= $dbList->toString();
}
if ($this->dbList) {
$result .= "\n";
}
$result .= "</app-data>";
return $result;
} | php | public function toString()
{
$result = "<app-data>\n";
foreach ($this->dbList as $dbList) {
$result .= $dbList->toString();
}
if ($this->dbList) {
$result .= "\n";
}
$result .= "</app-data>";
return $result;
} | [
"public",
"function",
"toString",
"(",
")",
"{",
"$",
"result",
"=",
"\"<app-data>\\n\"",
";",
"foreach",
"(",
"$",
"this",
"->",
"dbList",
"as",
"$",
"dbList",
")",
"{",
"$",
"result",
".=",
"$",
"dbList",
"->",
"toString",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"dbList",
")",
"{",
"$",
"result",
".=",
"\"\\n\"",
";",
"}",
"$",
"result",
".=",
"\"</app-data>\"",
";",
"return",
"$",
"result",
";",
"}"
] | Creates a string representation of this AppData.
The representation is given in xml format.
@return string Representation in xml format | [
"Creates",
"a",
"string",
"representation",
"of",
"this",
"AppData",
".",
"The",
"representation",
"is",
"given",
"in",
"xml",
"format",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/model/AppData.php#L320-L332 |
propelorm/Propel | generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php | PgsqlDataSQLBuilder.buildRowSql | public function buildRowSql(DataRow $row)
{
$sql = parent::buildRowSql($row);
$table = $this->getTable();
if ($table->hasAutoIncrementPrimaryKey() && $table->getIdMethod() == IDMethod::NATIVE) {
foreach ($row->getColumnValues() as $colValue) {
if ($colValue->getColumn()->isAutoIncrement()) {
if ($colValue->getValue() > $this->maxSeqVal) {
$this->maxSeqVal = $colValue->getValue();
}
}
}
}
return $sql;
} | php | public function buildRowSql(DataRow $row)
{
$sql = parent::buildRowSql($row);
$table = $this->getTable();
if ($table->hasAutoIncrementPrimaryKey() && $table->getIdMethod() == IDMethod::NATIVE) {
foreach ($row->getColumnValues() as $colValue) {
if ($colValue->getColumn()->isAutoIncrement()) {
if ($colValue->getValue() > $this->maxSeqVal) {
$this->maxSeqVal = $colValue->getValue();
}
}
}
}
return $sql;
} | [
"public",
"function",
"buildRowSql",
"(",
"DataRow",
"$",
"row",
")",
"{",
"$",
"sql",
"=",
"parent",
"::",
"buildRowSql",
"(",
"$",
"row",
")",
";",
"$",
"table",
"=",
"$",
"this",
"->",
"getTable",
"(",
")",
";",
"if",
"(",
"$",
"table",
"->",
"hasAutoIncrementPrimaryKey",
"(",
")",
"&&",
"$",
"table",
"->",
"getIdMethod",
"(",
")",
"==",
"IDMethod",
"::",
"NATIVE",
")",
"{",
"foreach",
"(",
"$",
"row",
"->",
"getColumnValues",
"(",
")",
"as",
"$",
"colValue",
")",
"{",
"if",
"(",
"$",
"colValue",
"->",
"getColumn",
"(",
")",
"->",
"isAutoIncrement",
"(",
")",
")",
"{",
"if",
"(",
"$",
"colValue",
"->",
"getValue",
"(",
")",
">",
"$",
"this",
"->",
"maxSeqVal",
")",
"{",
"$",
"this",
"->",
"maxSeqVal",
"=",
"$",
"colValue",
"->",
"getValue",
"(",
")",
";",
"}",
"}",
"}",
"}",
"return",
"$",
"sql",
";",
"}"
] | The main method in this class, returns the SQL for INSERTing data into a row.
@param DataRow $row The row to process.
@return string | [
"The",
"main",
"method",
"in",
"this",
"class",
"returns",
"the",
"SQL",
"for",
"INSERTing",
"data",
"into",
"a",
"row",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/builder/sql/pgsql/PgsqlDataSQLBuilder.php#L46-L63 |
propelorm/Propel | runtime/lib/query/PropelQuery.php | PropelQuery.from | public static function from($queryClassAndAlias)
{
list($class, $alias) = ModelCriteria::getClassAndAlias($queryClassAndAlias);
$queryClass = $class . 'Query';
if (!class_exists($queryClass)) {
throw new PropelException('Cannot find a query class for ' . $class);
}
$query = new $queryClass();
if ($alias !== null) {
$query->setModelAlias($alias);
}
return $query;
} | php | public static function from($queryClassAndAlias)
{
list($class, $alias) = ModelCriteria::getClassAndAlias($queryClassAndAlias);
$queryClass = $class . 'Query';
if (!class_exists($queryClass)) {
throw new PropelException('Cannot find a query class for ' . $class);
}
$query = new $queryClass();
if ($alias !== null) {
$query->setModelAlias($alias);
}
return $query;
} | [
"public",
"static",
"function",
"from",
"(",
"$",
"queryClassAndAlias",
")",
"{",
"list",
"(",
"$",
"class",
",",
"$",
"alias",
")",
"=",
"ModelCriteria",
"::",
"getClassAndAlias",
"(",
"$",
"queryClassAndAlias",
")",
";",
"$",
"queryClass",
"=",
"$",
"class",
".",
"'Query'",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"queryClass",
")",
")",
"{",
"throw",
"new",
"PropelException",
"(",
"'Cannot find a query class for '",
".",
"$",
"class",
")",
";",
"}",
"$",
"query",
"=",
"new",
"$",
"queryClass",
"(",
")",
";",
"if",
"(",
"$",
"alias",
"!==",
"null",
")",
"{",
"$",
"query",
"->",
"setModelAlias",
"(",
"$",
"alias",
")",
";",
"}",
"return",
"$",
"query",
";",
"}"
] | @param string $queryClassAndAlias
@return ModelCriteria
@throws PropelException | [
"@param",
"string",
"$queryClassAndAlias"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/PropelQuery.php#L26-L39 |
propelorm/Propel | runtime/lib/query/ModelJoin.php | ModelJoin.equals | public function equals($join)
{
return parent::equals($join)
&& $this->relationMap == $join->getRelationMap()
&& $this->previousJoin == $join->getPreviousJoin()
&& $this->rightTableAlias == $join->getRightTableAlias();
} | php | public function equals($join)
{
return parent::equals($join)
&& $this->relationMap == $join->getRelationMap()
&& $this->previousJoin == $join->getPreviousJoin()
&& $this->rightTableAlias == $join->getRightTableAlias();
} | [
"public",
"function",
"equals",
"(",
"$",
"join",
")",
"{",
"return",
"parent",
"::",
"equals",
"(",
"$",
"join",
")",
"&&",
"$",
"this",
"->",
"relationMap",
"==",
"$",
"join",
"->",
"getRelationMap",
"(",
")",
"&&",
"$",
"this",
"->",
"previousJoin",
"==",
"$",
"join",
"->",
"getPreviousJoin",
"(",
")",
"&&",
"$",
"this",
"->",
"rightTableAlias",
"==",
"$",
"join",
"->",
"getRightTableAlias",
"(",
")",
";",
"}"
] | @param ModelJoin $join
@return bool | [
"@param",
"ModelJoin",
"$join"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/ModelJoin.php#L156-L162 |
propelorm/Propel | generator/lib/task/AbstractPropelDataModelTask.php | AbstractPropelDataModelTask.setOutputDirectory | public function setOutputDirectory(PhingFile $outputDirectory)
{
try {
if (!$outputDirectory->exists()) {
$this->log("Output directory does not exist, creating: " . $outputDirectory->getPath(), Project::MSG_VERBOSE);
if (!$outputDirectory->mkdirs()) {
throw new IOException("Unable to create Output directory: " . $outputDirectory->getAbsolutePath());
}
}
$this->outputDirectory = $outputDirectory->getCanonicalPath();
} catch (IOException $ioe) {
throw new BuildException($ioe);
}
} | php | public function setOutputDirectory(PhingFile $outputDirectory)
{
try {
if (!$outputDirectory->exists()) {
$this->log("Output directory does not exist, creating: " . $outputDirectory->getPath(), Project::MSG_VERBOSE);
if (!$outputDirectory->mkdirs()) {
throw new IOException("Unable to create Output directory: " . $outputDirectory->getAbsolutePath());
}
}
$this->outputDirectory = $outputDirectory->getCanonicalPath();
} catch (IOException $ioe) {
throw new BuildException($ioe);
}
} | [
"public",
"function",
"setOutputDirectory",
"(",
"PhingFile",
"$",
"outputDirectory",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"$",
"outputDirectory",
"->",
"exists",
"(",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Output directory does not exist, creating: \"",
".",
"$",
"outputDirectory",
"->",
"getPath",
"(",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"if",
"(",
"!",
"$",
"outputDirectory",
"->",
"mkdirs",
"(",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Unable to create Output directory: \"",
".",
"$",
"outputDirectory",
"->",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"}",
"$",
"this",
"->",
"outputDirectory",
"=",
"$",
"outputDirectory",
"->",
"getCanonicalPath",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"$",
"ioe",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"$",
"ioe",
")",
";",
"}",
"}"
] | [REQUIRED] Set the output directory. It will be
created if it doesn't exist.
@param PhingFile $outputDirectory
@return void
@throws BuildException | [
"[",
"REQUIRED",
"]",
"Set",
"the",
"output",
"directory",
".",
"It",
"will",
"be",
"created",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/AbstractPropelDataModelTask.php#L281-L294 |
propelorm/Propel | generator/lib/task/AbstractPropelDataModelTask.php | AbstractPropelDataModelTask.getMappedFile | protected function getMappedFile($from)
{
if (!$this->mapperElement) {
throw new BuildException("This task requires you to use a <mapper/> element to describe how filename changes should be handled.");
}
$mapper = $this->mapperElement->getImplementation();
$mapped = $mapper->main($from);
if (!$mapped) {
throw new BuildException("Cannot create new filename based on: " . $from);
}
// Mappers always return arrays since it's possible for some mappers to map to multiple names.
$outFilename = array_shift($mapped);
$outFile = new PhingFile($this->getOutputDirectory(), $outFilename);
return $outFile;
} | php | protected function getMappedFile($from)
{
if (!$this->mapperElement) {
throw new BuildException("This task requires you to use a <mapper/> element to describe how filename changes should be handled.");
}
$mapper = $this->mapperElement->getImplementation();
$mapped = $mapper->main($from);
if (!$mapped) {
throw new BuildException("Cannot create new filename based on: " . $from);
}
// Mappers always return arrays since it's possible for some mappers to map to multiple names.
$outFilename = array_shift($mapped);
$outFile = new PhingFile($this->getOutputDirectory(), $outFilename);
return $outFile;
} | [
"protected",
"function",
"getMappedFile",
"(",
"$",
"from",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"mapperElement",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"\"This task requires you to use a <mapper/> element to describe how filename changes should be handled.\"",
")",
";",
"}",
"$",
"mapper",
"=",
"$",
"this",
"->",
"mapperElement",
"->",
"getImplementation",
"(",
")",
";",
"$",
"mapped",
"=",
"$",
"mapper",
"->",
"main",
"(",
"$",
"from",
")",
";",
"if",
"(",
"!",
"$",
"mapped",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"\"Cannot create new filename based on: \"",
".",
"$",
"from",
")",
";",
"}",
"// Mappers always return arrays since it's possible for some mappers to map to multiple names.",
"$",
"outFilename",
"=",
"array_shift",
"(",
"$",
"mapped",
")",
";",
"$",
"outFile",
"=",
"new",
"PhingFile",
"(",
"$",
"this",
"->",
"getOutputDirectory",
"(",
")",
",",
"$",
"outFilename",
")",
";",
"return",
"$",
"outFile",
";",
"}"
] | Maps the passed in name to a new filename & returns resolved File object.
@param string $from
@return PhingFile Resolved File object.
@throws BuildException - if no Mapper element se
- if unable to map new filename. | [
"Maps",
"the",
"passed",
"in",
"name",
"to",
"a",
"new",
"filename",
"&",
"returns",
"resolved",
"File",
"object",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/AbstractPropelDataModelTask.php#L371-L387 |
propelorm/Propel | generator/lib/task/AbstractPropelDataModelTask.php | AbstractPropelDataModelTask.getConnection | public function getConnection()
{
if ($this->conn === false) {
$this->conn = null;
if ($this->url) {
$buf = "Using database settings:\n"
. " URL: " . $this->url . "\n"
. ($this->userId ? " user: " . $this->userId . "\n" : "")
. ($this->password ? " password: " . $this->password . "\n" : "");
$this->log($buf, Project::MSG_VERBOSE);
// Set user + password to null if they are empty strings
if (!$this->userId) {
$this->userId = null;
}
if (!$this->password) {
$this->password = null;
}
try {
$this->conn = new PDO($this->url, $this->userId, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $x) {
$this->log("Unable to create a PDO connection: " . $x->getMessage(), Project::MSG_WARN);
}
}
}
return $this->conn;
} | php | public function getConnection()
{
if ($this->conn === false) {
$this->conn = null;
if ($this->url) {
$buf = "Using database settings:\n"
. " URL: " . $this->url . "\n"
. ($this->userId ? " user: " . $this->userId . "\n" : "")
. ($this->password ? " password: " . $this->password . "\n" : "");
$this->log($buf, Project::MSG_VERBOSE);
// Set user + password to null if they are empty strings
if (!$this->userId) {
$this->userId = null;
}
if (!$this->password) {
$this->password = null;
}
try {
$this->conn = new PDO($this->url, $this->userId, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $x) {
$this->log("Unable to create a PDO connection: " . $x->getMessage(), Project::MSG_WARN);
}
}
}
return $this->conn;
} | [
"public",
"function",
"getConnection",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"conn",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"conn",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"url",
")",
"{",
"$",
"buf",
"=",
"\"Using database settings:\\n\"",
".",
"\" URL: \"",
".",
"$",
"this",
"->",
"url",
".",
"\"\\n\"",
".",
"(",
"$",
"this",
"->",
"userId",
"?",
"\" user: \"",
".",
"$",
"this",
"->",
"userId",
".",
"\"\\n\"",
":",
"\"\"",
")",
".",
"(",
"$",
"this",
"->",
"password",
"?",
"\" password: \"",
".",
"$",
"this",
"->",
"password",
".",
"\"\\n\"",
":",
"\"\"",
")",
";",
"$",
"this",
"->",
"log",
"(",
"$",
"buf",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"// Set user + password to null if they are empty strings",
"if",
"(",
"!",
"$",
"this",
"->",
"userId",
")",
"{",
"$",
"this",
"->",
"userId",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"password",
")",
"{",
"$",
"this",
"->",
"password",
"=",
"null",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"conn",
"=",
"new",
"PDO",
"(",
"$",
"this",
"->",
"url",
",",
"$",
"this",
"->",
"userId",
",",
"$",
"this",
"->",
"password",
")",
";",
"$",
"this",
"->",
"conn",
"->",
"setAttribute",
"(",
"PDO",
"::",
"ATTR_ERRMODE",
",",
"PDO",
"::",
"ERRMODE_EXCEPTION",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"x",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Unable to create a PDO connection: \"",
".",
"$",
"x",
"->",
"getMessage",
"(",
")",
",",
"Project",
"::",
"MSG_WARN",
")",
";",
"}",
"}",
"}",
"return",
"$",
"this",
"->",
"conn",
";",
"}"
] | Gets the PDO connection, if URL specified.
@return PDO Connection to use (for quoting, Platform class, etc.) or NULL if no connection params were specified. | [
"Gets",
"the",
"PDO",
"connection",
"if",
"URL",
"specified",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/AbstractPropelDataModelTask.php#L394-L423 |
propelorm/Propel | generator/lib/task/AbstractPropelDataModelTask.php | AbstractPropelDataModelTask.loadDataModels | protected function loadDataModels()
{
$ads = array();
$totalNbTables = 0;
$this->log('Loading XML schema files...');
// Get all matched files from schemaFilesets
foreach ($this->schemaFilesets as $fs) {
$ds = $fs->getDirectoryScanner($this->project);
$srcDir = $fs->getDir($this->project);
$dataModelFiles = $ds->getIncludedFiles();
sort($dataModelFiles);
$defaultPlatform = $this->getGeneratorConfig()->getConfiguredPlatform();
// Make a transaction for each file
foreach ($dataModelFiles as $dmFilename) {
$this->log("Processing: " . $dmFilename, Project::MSG_VERBOSE);
$xmlFile = new PhingFile($srcDir, $dmFilename);
$dom = new DomDocument('1.0', 'UTF-8');
$dom->load($xmlFile->getAbsolutePath());
// modify schema to include any external schemas (and remove the external-schema nodes)
$this->includeExternalSchemas($dom, $srcDir);
// normalize (or transform) the XML document using XSLT
if ($this->getGeneratorConfig()->getBuildProperty('schemaTransform') && $this->xslFile) {
$this->log("Transforming " . $dmFilename . " using stylesheet " . $this->xslFile->getPath(), Project::MSG_VERBOSE);
if (!class_exists('XSLTProcessor')) {
$this->log("Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.", Project::MSG_ERR);
} else {
// normalize the document using normalizer stylesheet
$xslDom = new DomDocument('1.0', 'UTF-8');
$xslDom->load($this->xslFile->getAbsolutePath());
$xsl = new XsltProcessor();
$xsl->importStyleSheet($xslDom);
$dom = $xsl->transformToDoc($dom);
}
}
// validate the XML document using XSD schema
if ($this->validate && $this->xsdFile) {
$this->log(" Validating XML using schema " . $this->xsdFile->getPath(), Project::MSG_VERBOSE);
if (!$dom->schemaValidate($this->xsdFile->getAbsolutePath())) {
throw new EngineException("XML schema file (" . $xmlFile->getPath() . ") does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).", $this->getLocation());
}
}
$xmlParser = new XmlToAppData($defaultPlatform, $this->getTargetPackage(), $this->dbEncoding);
$xmlParser->setGeneratorConfig($this->getGeneratorConfig());
$ad = $xmlParser->parseString($dom->saveXML(), $xmlFile->getAbsolutePath());
$nbTables = $ad->getDatabase(null, false)->countTables();
$totalNbTables += $nbTables;
$this->log(sprintf(' %d tables processed successfully', $nbTables), Project::MSG_VERBOSE);
$ad->setName($dmFilename);
$ads[] = $ad;
}
$this->log(sprintf('%d tables found in %d schema files.', $totalNbTables, count($dataModelFiles)));
}
if (empty($ads)) {
throw new BuildException("No schema files were found (matching your schema fileset definition).");
}
foreach ($ads as $ad) {
// map schema filename with database name
$this->dataModelDbMap[$ad->getName()] = $ad->getDatabase(null, false)->getName();
}
if (count($ads) > 1 && $this->packageObjectModel) {
$ad = $this->joinDataModels($ads);
$this->dataModels = array($ad);
} else {
$this->dataModels = $ads;
}
foreach ($this->dataModels as &$ad) {
$ad->doFinalInitialization();
}
if ($this->validate) {
foreach ($this->dataModels as $dataModel) {
$validator = new PropelSchemaValidator($dataModel);
if (!$validator->validate()) {
throw new EngineException(sprintf("The database schema contains errors:\n - %s", join("\n - ", $validator->getErrors())));
}
}
}
$this->dataModelsLoaded = true;
} | php | protected function loadDataModels()
{
$ads = array();
$totalNbTables = 0;
$this->log('Loading XML schema files...');
// Get all matched files from schemaFilesets
foreach ($this->schemaFilesets as $fs) {
$ds = $fs->getDirectoryScanner($this->project);
$srcDir = $fs->getDir($this->project);
$dataModelFiles = $ds->getIncludedFiles();
sort($dataModelFiles);
$defaultPlatform = $this->getGeneratorConfig()->getConfiguredPlatform();
// Make a transaction for each file
foreach ($dataModelFiles as $dmFilename) {
$this->log("Processing: " . $dmFilename, Project::MSG_VERBOSE);
$xmlFile = new PhingFile($srcDir, $dmFilename);
$dom = new DomDocument('1.0', 'UTF-8');
$dom->load($xmlFile->getAbsolutePath());
// modify schema to include any external schemas (and remove the external-schema nodes)
$this->includeExternalSchemas($dom, $srcDir);
// normalize (or transform) the XML document using XSLT
if ($this->getGeneratorConfig()->getBuildProperty('schemaTransform') && $this->xslFile) {
$this->log("Transforming " . $dmFilename . " using stylesheet " . $this->xslFile->getPath(), Project::MSG_VERBOSE);
if (!class_exists('XSLTProcessor')) {
$this->log("Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.", Project::MSG_ERR);
} else {
// normalize the document using normalizer stylesheet
$xslDom = new DomDocument('1.0', 'UTF-8');
$xslDom->load($this->xslFile->getAbsolutePath());
$xsl = new XsltProcessor();
$xsl->importStyleSheet($xslDom);
$dom = $xsl->transformToDoc($dom);
}
}
// validate the XML document using XSD schema
if ($this->validate && $this->xsdFile) {
$this->log(" Validating XML using schema " . $this->xsdFile->getPath(), Project::MSG_VERBOSE);
if (!$dom->schemaValidate($this->xsdFile->getAbsolutePath())) {
throw new EngineException("XML schema file (" . $xmlFile->getPath() . ") does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).", $this->getLocation());
}
}
$xmlParser = new XmlToAppData($defaultPlatform, $this->getTargetPackage(), $this->dbEncoding);
$xmlParser->setGeneratorConfig($this->getGeneratorConfig());
$ad = $xmlParser->parseString($dom->saveXML(), $xmlFile->getAbsolutePath());
$nbTables = $ad->getDatabase(null, false)->countTables();
$totalNbTables += $nbTables;
$this->log(sprintf(' %d tables processed successfully', $nbTables), Project::MSG_VERBOSE);
$ad->setName($dmFilename);
$ads[] = $ad;
}
$this->log(sprintf('%d tables found in %d schema files.', $totalNbTables, count($dataModelFiles)));
}
if (empty($ads)) {
throw new BuildException("No schema files were found (matching your schema fileset definition).");
}
foreach ($ads as $ad) {
// map schema filename with database name
$this->dataModelDbMap[$ad->getName()] = $ad->getDatabase(null, false)->getName();
}
if (count($ads) > 1 && $this->packageObjectModel) {
$ad = $this->joinDataModels($ads);
$this->dataModels = array($ad);
} else {
$this->dataModels = $ads;
}
foreach ($this->dataModels as &$ad) {
$ad->doFinalInitialization();
}
if ($this->validate) {
foreach ($this->dataModels as $dataModel) {
$validator = new PropelSchemaValidator($dataModel);
if (!$validator->validate()) {
throw new EngineException(sprintf("The database schema contains errors:\n - %s", join("\n - ", $validator->getErrors())));
}
}
}
$this->dataModelsLoaded = true;
} | [
"protected",
"function",
"loadDataModels",
"(",
")",
"{",
"$",
"ads",
"=",
"array",
"(",
")",
";",
"$",
"totalNbTables",
"=",
"0",
";",
"$",
"this",
"->",
"log",
"(",
"'Loading XML schema files...'",
")",
";",
"// Get all matched files from schemaFilesets",
"foreach",
"(",
"$",
"this",
"->",
"schemaFilesets",
"as",
"$",
"fs",
")",
"{",
"$",
"ds",
"=",
"$",
"fs",
"->",
"getDirectoryScanner",
"(",
"$",
"this",
"->",
"project",
")",
";",
"$",
"srcDir",
"=",
"$",
"fs",
"->",
"getDir",
"(",
"$",
"this",
"->",
"project",
")",
";",
"$",
"dataModelFiles",
"=",
"$",
"ds",
"->",
"getIncludedFiles",
"(",
")",
";",
"sort",
"(",
"$",
"dataModelFiles",
")",
";",
"$",
"defaultPlatform",
"=",
"$",
"this",
"->",
"getGeneratorConfig",
"(",
")",
"->",
"getConfiguredPlatform",
"(",
")",
";",
"// Make a transaction for each file",
"foreach",
"(",
"$",
"dataModelFiles",
"as",
"$",
"dmFilename",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Processing: \"",
".",
"$",
"dmFilename",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"$",
"xmlFile",
"=",
"new",
"PhingFile",
"(",
"$",
"srcDir",
",",
"$",
"dmFilename",
")",
";",
"$",
"dom",
"=",
"new",
"DomDocument",
"(",
"'1.0'",
",",
"'UTF-8'",
")",
";",
"$",
"dom",
"->",
"load",
"(",
"$",
"xmlFile",
"->",
"getAbsolutePath",
"(",
")",
")",
";",
"// modify schema to include any external schemas (and remove the external-schema nodes)",
"$",
"this",
"->",
"includeExternalSchemas",
"(",
"$",
"dom",
",",
"$",
"srcDir",
")",
";",
"// normalize (or transform) the XML document using XSLT",
"if",
"(",
"$",
"this",
"->",
"getGeneratorConfig",
"(",
")",
"->",
"getBuildProperty",
"(",
"'schemaTransform'",
")",
"&&",
"$",
"this",
"->",
"xslFile",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Transforming \"",
".",
"$",
"dmFilename",
".",
"\" using stylesheet \"",
".",
"$",
"this",
"->",
"xslFile",
"->",
"getPath",
"(",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"if",
"(",
"!",
"class_exists",
"(",
"'XSLTProcessor'",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.\"",
",",
"Project",
"::",
"MSG_ERR",
")",
";",
"}",
"else",
"{",
"// normalize the document using normalizer stylesheet",
"$",
"xslDom",
"=",
"new",
"DomDocument",
"(",
"'1.0'",
",",
"'UTF-8'",
")",
";",
"$",
"xslDom",
"->",
"load",
"(",
"$",
"this",
"->",
"xslFile",
"->",
"getAbsolutePath",
"(",
")",
")",
";",
"$",
"xsl",
"=",
"new",
"XsltProcessor",
"(",
")",
";",
"$",
"xsl",
"->",
"importStyleSheet",
"(",
"$",
"xslDom",
")",
";",
"$",
"dom",
"=",
"$",
"xsl",
"->",
"transformToDoc",
"(",
"$",
"dom",
")",
";",
"}",
"}",
"// validate the XML document using XSD schema",
"if",
"(",
"$",
"this",
"->",
"validate",
"&&",
"$",
"this",
"->",
"xsdFile",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\" Validating XML using schema \"",
".",
"$",
"this",
"->",
"xsdFile",
"->",
"getPath",
"(",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"if",
"(",
"!",
"$",
"dom",
"->",
"schemaValidate",
"(",
"$",
"this",
"->",
"xsdFile",
"->",
"getAbsolutePath",
"(",
")",
")",
")",
"{",
"throw",
"new",
"EngineException",
"(",
"\"XML schema file (\"",
".",
"$",
"xmlFile",
"->",
"getPath",
"(",
")",
".",
"\") does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).\"",
",",
"$",
"this",
"->",
"getLocation",
"(",
")",
")",
";",
"}",
"}",
"$",
"xmlParser",
"=",
"new",
"XmlToAppData",
"(",
"$",
"defaultPlatform",
",",
"$",
"this",
"->",
"getTargetPackage",
"(",
")",
",",
"$",
"this",
"->",
"dbEncoding",
")",
";",
"$",
"xmlParser",
"->",
"setGeneratorConfig",
"(",
"$",
"this",
"->",
"getGeneratorConfig",
"(",
")",
")",
";",
"$",
"ad",
"=",
"$",
"xmlParser",
"->",
"parseString",
"(",
"$",
"dom",
"->",
"saveXML",
"(",
")",
",",
"$",
"xmlFile",
"->",
"getAbsolutePath",
"(",
")",
")",
";",
"$",
"nbTables",
"=",
"$",
"ad",
"->",
"getDatabase",
"(",
"null",
",",
"false",
")",
"->",
"countTables",
"(",
")",
";",
"$",
"totalNbTables",
"+=",
"$",
"nbTables",
";",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"' %d tables processed successfully'",
",",
"$",
"nbTables",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"$",
"ad",
"->",
"setName",
"(",
"$",
"dmFilename",
")",
";",
"$",
"ads",
"[",
"]",
"=",
"$",
"ad",
";",
"}",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'%d tables found in %d schema files.'",
",",
"$",
"totalNbTables",
",",
"count",
"(",
"$",
"dataModelFiles",
")",
")",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"ads",
")",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"\"No schema files were found (matching your schema fileset definition).\"",
")",
";",
"}",
"foreach",
"(",
"$",
"ads",
"as",
"$",
"ad",
")",
"{",
"// map schema filename with database name",
"$",
"this",
"->",
"dataModelDbMap",
"[",
"$",
"ad",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"ad",
"->",
"getDatabase",
"(",
"null",
",",
"false",
")",
"->",
"getName",
"(",
")",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"ads",
")",
">",
"1",
"&&",
"$",
"this",
"->",
"packageObjectModel",
")",
"{",
"$",
"ad",
"=",
"$",
"this",
"->",
"joinDataModels",
"(",
"$",
"ads",
")",
";",
"$",
"this",
"->",
"dataModels",
"=",
"array",
"(",
"$",
"ad",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"dataModels",
"=",
"$",
"ads",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"dataModels",
"as",
"&",
"$",
"ad",
")",
"{",
"$",
"ad",
"->",
"doFinalInitialization",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"validate",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"dataModels",
"as",
"$",
"dataModel",
")",
"{",
"$",
"validator",
"=",
"new",
"PropelSchemaValidator",
"(",
"$",
"dataModel",
")",
";",
"if",
"(",
"!",
"$",
"validator",
"->",
"validate",
"(",
")",
")",
"{",
"throw",
"new",
"EngineException",
"(",
"sprintf",
"(",
"\"The database schema contains errors:\\n - %s\"",
",",
"join",
"(",
"\"\\n - \"",
",",
"$",
"validator",
"->",
"getErrors",
"(",
")",
")",
")",
")",
";",
"}",
"}",
"}",
"$",
"this",
"->",
"dataModelsLoaded",
"=",
"true",
";",
"}"
] | Gets all matching XML schema files and loads them into data models for class.
@return void
@throws EngineException
@throws BuildException | [
"Gets",
"all",
"matching",
"XML",
"schema",
"files",
"and",
"loads",
"them",
"into",
"data",
"models",
"for",
"class",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/AbstractPropelDataModelTask.php#L432-L525 |
propelorm/Propel | generator/lib/task/AbstractPropelDataModelTask.php | AbstractPropelDataModelTask.includeExternalSchemas | protected function includeExternalSchemas(DomDocument $dom, $srcDir)
{
$databaseNode = $dom->getElementsByTagName("database")->item(0);
$externalSchemaNodes = $dom->getElementsByTagName("external-schema");
$fs = FileSystem::getFileSystem();
$nbIncludedSchemas = 0;
while ($externalSchema = $externalSchemaNodes->item(0)) {
$include = $externalSchema->getAttribute("filename");
$this->log('Processing external schema: ' . $include, Project::MSG_VERBOSE);
$externalSchema->parentNode->removeChild($externalSchema);
if ($fs->prefixLength($include) != 0) {
$externalSchemaFile = new PhingFile($include);
} else {
$externalSchemaFile = new PhingFile($srcDir, $include);
}
$externalSchemaDom = new DomDocument('1.0', 'UTF-8');
$externalSchemaDom->load($externalSchemaFile->getAbsolutePath());
// The external schema may have external schemas of its own ; recurse
$this->includeExternalSchemas($externalSchemaDom, $srcDir);
foreach ($externalSchemaDom->getElementsByTagName("table") as $tableNode) { // see xsd, database may only have table or external-schema, the latter was just deleted so this should cover everything
$databaseNode->appendChild($dom->importNode($tableNode, true));
}
$nbIncludedSchemas++;
}
return $nbIncludedSchemas;
} | php | protected function includeExternalSchemas(DomDocument $dom, $srcDir)
{
$databaseNode = $dom->getElementsByTagName("database")->item(0);
$externalSchemaNodes = $dom->getElementsByTagName("external-schema");
$fs = FileSystem::getFileSystem();
$nbIncludedSchemas = 0;
while ($externalSchema = $externalSchemaNodes->item(0)) {
$include = $externalSchema->getAttribute("filename");
$this->log('Processing external schema: ' . $include, Project::MSG_VERBOSE);
$externalSchema->parentNode->removeChild($externalSchema);
if ($fs->prefixLength($include) != 0) {
$externalSchemaFile = new PhingFile($include);
} else {
$externalSchemaFile = new PhingFile($srcDir, $include);
}
$externalSchemaDom = new DomDocument('1.0', 'UTF-8');
$externalSchemaDom->load($externalSchemaFile->getAbsolutePath());
// The external schema may have external schemas of its own ; recurse
$this->includeExternalSchemas($externalSchemaDom, $srcDir);
foreach ($externalSchemaDom->getElementsByTagName("table") as $tableNode) { // see xsd, database may only have table or external-schema, the latter was just deleted so this should cover everything
$databaseNode->appendChild($dom->importNode($tableNode, true));
}
$nbIncludedSchemas++;
}
return $nbIncludedSchemas;
} | [
"protected",
"function",
"includeExternalSchemas",
"(",
"DomDocument",
"$",
"dom",
",",
"$",
"srcDir",
")",
"{",
"$",
"databaseNode",
"=",
"$",
"dom",
"->",
"getElementsByTagName",
"(",
"\"database\"",
")",
"->",
"item",
"(",
"0",
")",
";",
"$",
"externalSchemaNodes",
"=",
"$",
"dom",
"->",
"getElementsByTagName",
"(",
"\"external-schema\"",
")",
";",
"$",
"fs",
"=",
"FileSystem",
"::",
"getFileSystem",
"(",
")",
";",
"$",
"nbIncludedSchemas",
"=",
"0",
";",
"while",
"(",
"$",
"externalSchema",
"=",
"$",
"externalSchemaNodes",
"->",
"item",
"(",
"0",
")",
")",
"{",
"$",
"include",
"=",
"$",
"externalSchema",
"->",
"getAttribute",
"(",
"\"filename\"",
")",
";",
"$",
"this",
"->",
"log",
"(",
"'Processing external schema: '",
".",
"$",
"include",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"$",
"externalSchema",
"->",
"parentNode",
"->",
"removeChild",
"(",
"$",
"externalSchema",
")",
";",
"if",
"(",
"$",
"fs",
"->",
"prefixLength",
"(",
"$",
"include",
")",
"!=",
"0",
")",
"{",
"$",
"externalSchemaFile",
"=",
"new",
"PhingFile",
"(",
"$",
"include",
")",
";",
"}",
"else",
"{",
"$",
"externalSchemaFile",
"=",
"new",
"PhingFile",
"(",
"$",
"srcDir",
",",
"$",
"include",
")",
";",
"}",
"$",
"externalSchemaDom",
"=",
"new",
"DomDocument",
"(",
"'1.0'",
",",
"'UTF-8'",
")",
";",
"$",
"externalSchemaDom",
"->",
"load",
"(",
"$",
"externalSchemaFile",
"->",
"getAbsolutePath",
"(",
")",
")",
";",
"// The external schema may have external schemas of its own ; recurse",
"$",
"this",
"->",
"includeExternalSchemas",
"(",
"$",
"externalSchemaDom",
",",
"$",
"srcDir",
")",
";",
"foreach",
"(",
"$",
"externalSchemaDom",
"->",
"getElementsByTagName",
"(",
"\"table\"",
")",
"as",
"$",
"tableNode",
")",
"{",
"// see xsd, database may only have table or external-schema, the latter was just deleted so this should cover everything",
"$",
"databaseNode",
"->",
"appendChild",
"(",
"$",
"dom",
"->",
"importNode",
"(",
"$",
"tableNode",
",",
"true",
")",
")",
";",
"}",
"$",
"nbIncludedSchemas",
"++",
";",
"}",
"return",
"$",
"nbIncludedSchemas",
";",
"}"
] | Replaces all external-schema nodes with the content of xml schema that node refers to
Recurses to include any external schema referenced from in an included xml (and deeper)
Note: this function very much assumes at least a reasonable XML schema, maybe it'll proof
users don't have those and adding some more informative exceptions would be better
@param DomDocument $dom
@param string $srcDir
@return void (objects, DomDocument, are references by default in PHP 5, so returning it is useless) | [
"Replaces",
"all",
"external",
"-",
"schema",
"nodes",
"with",
"the",
"content",
"of",
"xml",
"schema",
"that",
"node",
"refers",
"to"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/AbstractPropelDataModelTask.php#L539-L565 |
propelorm/Propel | generator/lib/task/AbstractPropelDataModelTask.php | AbstractPropelDataModelTask.getGeneratorConfig | protected function getGeneratorConfig()
{
if ($this->generatorConfig === null) {
$this->generatorConfig = new GeneratorConfig();
$this->generatorConfig->setBuildProperties($this->getProject()->getProperties());
}
return $this->generatorConfig;
} | php | protected function getGeneratorConfig()
{
if ($this->generatorConfig === null) {
$this->generatorConfig = new GeneratorConfig();
$this->generatorConfig->setBuildProperties($this->getProject()->getProperties());
}
return $this->generatorConfig;
} | [
"protected",
"function",
"getGeneratorConfig",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"generatorConfig",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"generatorConfig",
"=",
"new",
"GeneratorConfig",
"(",
")",
";",
"$",
"this",
"->",
"generatorConfig",
"->",
"setBuildProperties",
"(",
"$",
"this",
"->",
"getProject",
"(",
")",
"->",
"getProperties",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"generatorConfig",
";",
"}"
] | Gets the GeneratorConfig object for this task or creates it on-demand.
@return GeneratorConfig | [
"Gets",
"the",
"GeneratorConfig",
"object",
"for",
"this",
"task",
"or",
"creates",
"it",
"on",
"-",
"demand",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/AbstractPropelDataModelTask.php#L589-L597 |
propelorm/Propel | generator/lib/task/AbstractPropelDataModelTask.php | AbstractPropelDataModelTask.validate | protected function validate()
{
if (empty($this->schemaFilesets)) {
throw new BuildException("You must specify a fileset of XML schemas.", $this->getLocation());
}
// Make sure the output directory is set.
if ($this->outputDirectory === null) {
throw new BuildException("The output directory needs to be defined!", $this->getLocation());
}
if ($this->validate) {
if (!$this->xsdFile) {
throw new BuildException("'validate' set to TRUE, but no XSD specified (use 'xsd' attribute).", $this->getLocation());
}
}
} | php | protected function validate()
{
if (empty($this->schemaFilesets)) {
throw new BuildException("You must specify a fileset of XML schemas.", $this->getLocation());
}
// Make sure the output directory is set.
if ($this->outputDirectory === null) {
throw new BuildException("The output directory needs to be defined!", $this->getLocation());
}
if ($this->validate) {
if (!$this->xsdFile) {
throw new BuildException("'validate' set to TRUE, but no XSD specified (use 'xsd' attribute).", $this->getLocation());
}
}
} | [
"protected",
"function",
"validate",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"schemaFilesets",
")",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"\"You must specify a fileset of XML schemas.\"",
",",
"$",
"this",
"->",
"getLocation",
"(",
")",
")",
";",
"}",
"// Make sure the output directory is set.",
"if",
"(",
"$",
"this",
"->",
"outputDirectory",
"===",
"null",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"\"The output directory needs to be defined!\"",
",",
"$",
"this",
"->",
"getLocation",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"validate",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"xsdFile",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"\"'validate' set to TRUE, but no XSD specified (use 'xsd' attribute).\"",
",",
"$",
"this",
"->",
"getLocation",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Checks this class against Basic requirements of any propel datamodel task.
@throws BuildException - if schema fileset was not defined
- if no output directory was specified | [
"Checks",
"this",
"class",
"against",
"Basic",
"requirements",
"of",
"any",
"propel",
"datamodel",
"task",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/AbstractPropelDataModelTask.php#L605-L621 |
propelorm/Propel | generator/lib/task/PropelSQLDiffTask.php | PropelSQLDiffTask.main | public function main()
{
// check to make sure task received all correct params
$this->validate();
$generatorConfig = $this->getGeneratorConfig();
// loading model from database
$this->log('Reading databases structure...');
$connections = $generatorConfig->getBuildConnections();
if (!$connections) {
throw new Exception('You must define database connection settings in a buildtime-conf.xml file to use diff');
}
$manager = new PropelMigrationManager();
$manager->setConnections($connections);
$manager->setMigrationDir($this->getOutputDirectory());
$manager->setMigrationTable($this->getGeneratorConfig()->getBuildProperty('migrationTable'));
if ($manager->hasPendingMigrations()) {
throw new Exception('Uncommitted migrations have been found ; you should either execute or delete them before rerunning the \'diff\' task');
}
$totalNbTables = 0;
$ad = new AppData();
foreach ($connections as $name => $params) {
$this->log(sprintf('Connecting to database "%s" using DSN "%s"', $name, $params['dsn']), Project::MSG_VERBOSE);
$pdo = $generatorConfig->getBuildPDO($name);
$database = new Database($name);
$platform = $generatorConfig->getConfiguredPlatform($pdo);
if (!$platform->supportsMigrations()) {
$this->log(sprintf('Skipping database "%s" since vendor "%s" does not support migrations', $name, $platform->getDatabaseType()));
continue;
}
$database->setPlatform($platform);
$database->setDefaultIdMethod(IDMethod::NATIVE);
$parser = $generatorConfig->getConfiguredSchemaParser($pdo);
$nbTables = $parser->parse($database, $this);
$ad->addDatabase($database);
$totalNbTables += $nbTables;
$this->log(sprintf('%d tables found in database "%s"', $nbTables, $name), Project::MSG_VERBOSE);
}
if ($totalNbTables) {
$this->log(sprintf('%d tables found in all databases.', $totalNbTables));
} else {
$this->log('No table found in all databases');
}
// loading model from XML
$this->packageObjectModel = true;
$appDatasFromXml = $this->getDataModels();
$appDataFromXml = array_pop($appDatasFromXml);
// comparing models
$this->log('Comparing models...');
$migrationsUp = array();
$migrationsDown = array();
foreach ($ad->getDatabases() as $database) {
$name = $database->getName();
$this->log(sprintf('Comparing database "%s"', $name), Project::MSG_VERBOSE);
if (!$appDataFromXml->hasDatabase($name)) {
// FIXME: tables present in database but not in XML
continue;
}
$databaseDiff = PropelDatabaseComparator::computeDiff($database, $appDataFromXml->getDatabase($name), $this->isCaseInsensitive());
if (!$databaseDiff) {
$this->log(sprintf('Same XML and database structures for datasource "%s" - no diff to generate', $name), Project::MSG_VERBOSE);
continue;
}
$this->log(sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription()));
$platform = $generatorConfig->getConfiguredPlatform(null, $name);
$migrationsUp[$name] = $platform->getModifyDatabaseDDL($databaseDiff);
$migrationsDown[$name] = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff());
}
if (!$migrationsUp) {
$this->log('Same XML and database structures for all datasource - no diff to generate');
return;
}
$timestamp = time();
$migrationFileName = $manager->getMigrationFileName($timestamp);
$migrationClassBody = $manager->getMigrationClassBody($migrationsUp, $migrationsDown, $timestamp);
$_f = new PhingFile($this->getOutputDirectory(), $migrationFileName);
file_put_contents($_f->getAbsolutePath(), $migrationClassBody);
$this->log(sprintf('"%s" file successfully created in %s', $_f->getName(), $_f->getParent()));
if ($editorCmd = $this->getEditorCmd()) {
$this->log(sprintf('Using "%s" as text editor', $editorCmd));
shell_exec($editorCmd . ' ' . escapeshellarg($_f->getAbsolutePath()));
} else {
$this->log(' Please review the generated SQL statements, and add data migration code if necessary.');
$this->log(' Once the migration class is valid, call the "migrate" task to execute it.');
}
} | php | public function main()
{
// check to make sure task received all correct params
$this->validate();
$generatorConfig = $this->getGeneratorConfig();
// loading model from database
$this->log('Reading databases structure...');
$connections = $generatorConfig->getBuildConnections();
if (!$connections) {
throw new Exception('You must define database connection settings in a buildtime-conf.xml file to use diff');
}
$manager = new PropelMigrationManager();
$manager->setConnections($connections);
$manager->setMigrationDir($this->getOutputDirectory());
$manager->setMigrationTable($this->getGeneratorConfig()->getBuildProperty('migrationTable'));
if ($manager->hasPendingMigrations()) {
throw new Exception('Uncommitted migrations have been found ; you should either execute or delete them before rerunning the \'diff\' task');
}
$totalNbTables = 0;
$ad = new AppData();
foreach ($connections as $name => $params) {
$this->log(sprintf('Connecting to database "%s" using DSN "%s"', $name, $params['dsn']), Project::MSG_VERBOSE);
$pdo = $generatorConfig->getBuildPDO($name);
$database = new Database($name);
$platform = $generatorConfig->getConfiguredPlatform($pdo);
if (!$platform->supportsMigrations()) {
$this->log(sprintf('Skipping database "%s" since vendor "%s" does not support migrations', $name, $platform->getDatabaseType()));
continue;
}
$database->setPlatform($platform);
$database->setDefaultIdMethod(IDMethod::NATIVE);
$parser = $generatorConfig->getConfiguredSchemaParser($pdo);
$nbTables = $parser->parse($database, $this);
$ad->addDatabase($database);
$totalNbTables += $nbTables;
$this->log(sprintf('%d tables found in database "%s"', $nbTables, $name), Project::MSG_VERBOSE);
}
if ($totalNbTables) {
$this->log(sprintf('%d tables found in all databases.', $totalNbTables));
} else {
$this->log('No table found in all databases');
}
// loading model from XML
$this->packageObjectModel = true;
$appDatasFromXml = $this->getDataModels();
$appDataFromXml = array_pop($appDatasFromXml);
// comparing models
$this->log('Comparing models...');
$migrationsUp = array();
$migrationsDown = array();
foreach ($ad->getDatabases() as $database) {
$name = $database->getName();
$this->log(sprintf('Comparing database "%s"', $name), Project::MSG_VERBOSE);
if (!$appDataFromXml->hasDatabase($name)) {
// FIXME: tables present in database but not in XML
continue;
}
$databaseDiff = PropelDatabaseComparator::computeDiff($database, $appDataFromXml->getDatabase($name), $this->isCaseInsensitive());
if (!$databaseDiff) {
$this->log(sprintf('Same XML and database structures for datasource "%s" - no diff to generate', $name), Project::MSG_VERBOSE);
continue;
}
$this->log(sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription()));
$platform = $generatorConfig->getConfiguredPlatform(null, $name);
$migrationsUp[$name] = $platform->getModifyDatabaseDDL($databaseDiff);
$migrationsDown[$name] = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff());
}
if (!$migrationsUp) {
$this->log('Same XML and database structures for all datasource - no diff to generate');
return;
}
$timestamp = time();
$migrationFileName = $manager->getMigrationFileName($timestamp);
$migrationClassBody = $manager->getMigrationClassBody($migrationsUp, $migrationsDown, $timestamp);
$_f = new PhingFile($this->getOutputDirectory(), $migrationFileName);
file_put_contents($_f->getAbsolutePath(), $migrationClassBody);
$this->log(sprintf('"%s" file successfully created in %s', $_f->getName(), $_f->getParent()));
if ($editorCmd = $this->getEditorCmd()) {
$this->log(sprintf('Using "%s" as text editor', $editorCmd));
shell_exec($editorCmd . ' ' . escapeshellarg($_f->getAbsolutePath()));
} else {
$this->log(' Please review the generated SQL statements, and add data migration code if necessary.');
$this->log(' Once the migration class is valid, call the "migrate" task to execute it.');
}
} | [
"public",
"function",
"main",
"(",
")",
"{",
"// check to make sure task received all correct params",
"$",
"this",
"->",
"validate",
"(",
")",
";",
"$",
"generatorConfig",
"=",
"$",
"this",
"->",
"getGeneratorConfig",
"(",
")",
";",
"// loading model from database",
"$",
"this",
"->",
"log",
"(",
"'Reading databases structure...'",
")",
";",
"$",
"connections",
"=",
"$",
"generatorConfig",
"->",
"getBuildConnections",
"(",
")",
";",
"if",
"(",
"!",
"$",
"connections",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'You must define database connection settings in a buildtime-conf.xml file to use diff'",
")",
";",
"}",
"$",
"manager",
"=",
"new",
"PropelMigrationManager",
"(",
")",
";",
"$",
"manager",
"->",
"setConnections",
"(",
"$",
"connections",
")",
";",
"$",
"manager",
"->",
"setMigrationDir",
"(",
"$",
"this",
"->",
"getOutputDirectory",
"(",
")",
")",
";",
"$",
"manager",
"->",
"setMigrationTable",
"(",
"$",
"this",
"->",
"getGeneratorConfig",
"(",
")",
"->",
"getBuildProperty",
"(",
"'migrationTable'",
")",
")",
";",
"if",
"(",
"$",
"manager",
"->",
"hasPendingMigrations",
"(",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Uncommitted migrations have been found ; you should either execute or delete them before rerunning the \\'diff\\' task'",
")",
";",
"}",
"$",
"totalNbTables",
"=",
"0",
";",
"$",
"ad",
"=",
"new",
"AppData",
"(",
")",
";",
"foreach",
"(",
"$",
"connections",
"as",
"$",
"name",
"=>",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Connecting to database \"%s\" using DSN \"%s\"'",
",",
"$",
"name",
",",
"$",
"params",
"[",
"'dsn'",
"]",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"$",
"pdo",
"=",
"$",
"generatorConfig",
"->",
"getBuildPDO",
"(",
"$",
"name",
")",
";",
"$",
"database",
"=",
"new",
"Database",
"(",
"$",
"name",
")",
";",
"$",
"platform",
"=",
"$",
"generatorConfig",
"->",
"getConfiguredPlatform",
"(",
"$",
"pdo",
")",
";",
"if",
"(",
"!",
"$",
"platform",
"->",
"supportsMigrations",
"(",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Skipping database \"%s\" since vendor \"%s\" does not support migrations'",
",",
"$",
"name",
",",
"$",
"platform",
"->",
"getDatabaseType",
"(",
")",
")",
")",
";",
"continue",
";",
"}",
"$",
"database",
"->",
"setPlatform",
"(",
"$",
"platform",
")",
";",
"$",
"database",
"->",
"setDefaultIdMethod",
"(",
"IDMethod",
"::",
"NATIVE",
")",
";",
"$",
"parser",
"=",
"$",
"generatorConfig",
"->",
"getConfiguredSchemaParser",
"(",
"$",
"pdo",
")",
";",
"$",
"nbTables",
"=",
"$",
"parser",
"->",
"parse",
"(",
"$",
"database",
",",
"$",
"this",
")",
";",
"$",
"ad",
"->",
"addDatabase",
"(",
"$",
"database",
")",
";",
"$",
"totalNbTables",
"+=",
"$",
"nbTables",
";",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'%d tables found in database \"%s\"'",
",",
"$",
"nbTables",
",",
"$",
"name",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"}",
"if",
"(",
"$",
"totalNbTables",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'%d tables found in all databases.'",
",",
"$",
"totalNbTables",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"log",
"(",
"'No table found in all databases'",
")",
";",
"}",
"// loading model from XML",
"$",
"this",
"->",
"packageObjectModel",
"=",
"true",
";",
"$",
"appDatasFromXml",
"=",
"$",
"this",
"->",
"getDataModels",
"(",
")",
";",
"$",
"appDataFromXml",
"=",
"array_pop",
"(",
"$",
"appDatasFromXml",
")",
";",
"// comparing models",
"$",
"this",
"->",
"log",
"(",
"'Comparing models...'",
")",
";",
"$",
"migrationsUp",
"=",
"array",
"(",
")",
";",
"$",
"migrationsDown",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"ad",
"->",
"getDatabases",
"(",
")",
"as",
"$",
"database",
")",
"{",
"$",
"name",
"=",
"$",
"database",
"->",
"getName",
"(",
")",
";",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Comparing database \"%s\"'",
",",
"$",
"name",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"if",
"(",
"!",
"$",
"appDataFromXml",
"->",
"hasDatabase",
"(",
"$",
"name",
")",
")",
"{",
"// FIXME: tables present in database but not in XML",
"continue",
";",
"}",
"$",
"databaseDiff",
"=",
"PropelDatabaseComparator",
"::",
"computeDiff",
"(",
"$",
"database",
",",
"$",
"appDataFromXml",
"->",
"getDatabase",
"(",
"$",
"name",
")",
",",
"$",
"this",
"->",
"isCaseInsensitive",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"databaseDiff",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Same XML and database structures for datasource \"%s\" - no diff to generate'",
",",
"$",
"name",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"continue",
";",
"}",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Structure of database was modified in datasource \"%s\": %s'",
",",
"$",
"name",
",",
"$",
"databaseDiff",
"->",
"getDescription",
"(",
")",
")",
")",
";",
"$",
"platform",
"=",
"$",
"generatorConfig",
"->",
"getConfiguredPlatform",
"(",
"null",
",",
"$",
"name",
")",
";",
"$",
"migrationsUp",
"[",
"$",
"name",
"]",
"=",
"$",
"platform",
"->",
"getModifyDatabaseDDL",
"(",
"$",
"databaseDiff",
")",
";",
"$",
"migrationsDown",
"[",
"$",
"name",
"]",
"=",
"$",
"platform",
"->",
"getModifyDatabaseDDL",
"(",
"$",
"databaseDiff",
"->",
"getReverseDiff",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"$",
"migrationsUp",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'Same XML and database structures for all datasource - no diff to generate'",
")",
";",
"return",
";",
"}",
"$",
"timestamp",
"=",
"time",
"(",
")",
";",
"$",
"migrationFileName",
"=",
"$",
"manager",
"->",
"getMigrationFileName",
"(",
"$",
"timestamp",
")",
";",
"$",
"migrationClassBody",
"=",
"$",
"manager",
"->",
"getMigrationClassBody",
"(",
"$",
"migrationsUp",
",",
"$",
"migrationsDown",
",",
"$",
"timestamp",
")",
";",
"$",
"_f",
"=",
"new",
"PhingFile",
"(",
"$",
"this",
"->",
"getOutputDirectory",
"(",
")",
",",
"$",
"migrationFileName",
")",
";",
"file_put_contents",
"(",
"$",
"_f",
"->",
"getAbsolutePath",
"(",
")",
",",
"$",
"migrationClassBody",
")",
";",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'\"%s\" file successfully created in %s'",
",",
"$",
"_f",
"->",
"getName",
"(",
")",
",",
"$",
"_f",
"->",
"getParent",
"(",
")",
")",
")",
";",
"if",
"(",
"$",
"editorCmd",
"=",
"$",
"this",
"->",
"getEditorCmd",
"(",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Using \"%s\" as text editor'",
",",
"$",
"editorCmd",
")",
")",
";",
"shell_exec",
"(",
"$",
"editorCmd",
".",
"' '",
".",
"escapeshellarg",
"(",
"$",
"_f",
"->",
"getAbsolutePath",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"log",
"(",
"' Please review the generated SQL statements, and add data migration code if necessary.'",
")",
";",
"$",
"this",
"->",
"log",
"(",
"' Once the migration class is valid, call the \"migrate\" task to execute it.'",
")",
";",
"}",
"}"
] | Main method builds all the targets for a typical propel project. | [
"Main",
"method",
"builds",
"all",
"the",
"targets",
"for",
"a",
"typical",
"propel",
"project",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/PropelSQLDiffTask.php#L94-L190 |
propelorm/Propel | runtime/lib/query/Join.php | Join.addCondition | public function addCondition($left, $right, $operator = self::EQUAL)
{
if ($pos = strrpos($left, '.')) {
list($this->leftTableName, $this->left[]) = explode('.', $left);
} else {
$this->left[] = $left;
}
if ($pos = strrpos($right, '.')) {
list($this->rightTableName, $this->right[]) = explode('.', $right);
} else {
$this->right[] = $right;
}
$this->operator[] = $operator;
$this->count++;
} | php | public function addCondition($left, $right, $operator = self::EQUAL)
{
if ($pos = strrpos($left, '.')) {
list($this->leftTableName, $this->left[]) = explode('.', $left);
} else {
$this->left[] = $left;
}
if ($pos = strrpos($right, '.')) {
list($this->rightTableName, $this->right[]) = explode('.', $right);
} else {
$this->right[] = $right;
}
$this->operator[] = $operator;
$this->count++;
} | [
"public",
"function",
"addCondition",
"(",
"$",
"left",
",",
"$",
"right",
",",
"$",
"operator",
"=",
"self",
"::",
"EQUAL",
")",
"{",
"if",
"(",
"$",
"pos",
"=",
"strrpos",
"(",
"$",
"left",
",",
"'.'",
")",
")",
"{",
"list",
"(",
"$",
"this",
"->",
"leftTableName",
",",
"$",
"this",
"->",
"left",
"[",
"]",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"left",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"left",
"[",
"]",
"=",
"$",
"left",
";",
"}",
"if",
"(",
"$",
"pos",
"=",
"strrpos",
"(",
"$",
"right",
",",
"'.'",
")",
")",
"{",
"list",
"(",
"$",
"this",
"->",
"rightTableName",
",",
"$",
"this",
"->",
"right",
"[",
"]",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"right",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"right",
"[",
"]",
"=",
"$",
"right",
";",
"}",
"$",
"this",
"->",
"operator",
"[",
"]",
"=",
"$",
"operator",
";",
"$",
"this",
"->",
"count",
"++",
";",
"}"
] | Join condition definition.
Warning: doesn't support table aliases. Use the explicit methods to use aliases.
@param string $left The left column of the join condition
(may contain an alias name)
@param string $right The right column of the join condition
(may contain an alias name)
@param string $operator The comparison operator of the join condition, default Join::EQUAL | [
"Join",
"condition",
"definition",
".",
"Warning",
":",
"doesn",
"t",
"support",
"table",
"aliases",
".",
"Use",
"the",
"explicit",
"methods",
"to",
"use",
"aliases",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/Join.php#L97-L111 |
propelorm/Propel | runtime/lib/query/Join.php | Join.addConditions | public function addConditions($lefts, $rights, $operators = array())
{
if (count($lefts) != count($rights)) {
throw new PropelException("Unable to create join because the left column count isn't equal to the right column count");
}
foreach ($lefts as $key => $left) {
$this->addCondition($left, $rights[$key], isset($operators[$key]) ? $operators[$key] : self::EQUAL);
}
} | php | public function addConditions($lefts, $rights, $operators = array())
{
if (count($lefts) != count($rights)) {
throw new PropelException("Unable to create join because the left column count isn't equal to the right column count");
}
foreach ($lefts as $key => $left) {
$this->addCondition($left, $rights[$key], isset($operators[$key]) ? $operators[$key] : self::EQUAL);
}
} | [
"public",
"function",
"addConditions",
"(",
"$",
"lefts",
",",
"$",
"rights",
",",
"$",
"operators",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"lefts",
")",
"!=",
"count",
"(",
"$",
"rights",
")",
")",
"{",
"throw",
"new",
"PropelException",
"(",
"\"Unable to create join because the left column count isn't equal to the right column count\"",
")",
";",
"}",
"foreach",
"(",
"$",
"lefts",
"as",
"$",
"key",
"=>",
"$",
"left",
")",
"{",
"$",
"this",
"->",
"addCondition",
"(",
"$",
"left",
",",
"$",
"rights",
"[",
"$",
"key",
"]",
",",
"isset",
"(",
"$",
"operators",
"[",
"$",
"key",
"]",
")",
"?",
"$",
"operators",
"[",
"$",
"key",
"]",
":",
"self",
"::",
"EQUAL",
")",
";",
"}",
"}"
] | Join condition definition, for several conditions
@param array $lefts The left columns of the join condition
@param array $rights The right columns of the join condition
@param array $operators The comparison operators of the join condition, default Join::EQUAL
@throws PropelException | [
"Join",
"condition",
"definition",
"for",
"several",
"conditions"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/Join.php#L122-L130 |
propelorm/Propel | runtime/lib/query/Join.php | Join.getConditions | public function getConditions()
{
$conditions = array();
for ($i = 0; $i < $this->count; $i++) {
$conditions[] = array(
'left' => $this->getLeftColumn($i),
'operator' => $this->getOperator($i),
'right' => $this->getRightColumn($i)
);
}
return $conditions;
} | php | public function getConditions()
{
$conditions = array();
for ($i = 0; $i < $this->count; $i++) {
$conditions[] = array(
'left' => $this->getLeftColumn($i),
'operator' => $this->getOperator($i),
'right' => $this->getRightColumn($i)
);
}
return $conditions;
} | [
"public",
"function",
"getConditions",
"(",
")",
"{",
"$",
"conditions",
"=",
"array",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"count",
";",
"$",
"i",
"++",
")",
"{",
"$",
"conditions",
"[",
"]",
"=",
"array",
"(",
"'left'",
"=>",
"$",
"this",
"->",
"getLeftColumn",
"(",
"$",
"i",
")",
",",
"'operator'",
"=>",
"$",
"this",
"->",
"getOperator",
"(",
"$",
"i",
")",
",",
"'right'",
"=>",
"$",
"this",
"->",
"getRightColumn",
"(",
"$",
"i",
")",
")",
";",
"}",
"return",
"$",
"conditions",
";",
"}"
] | Return an array of the join conditions
@return array An array of arrays representing (left, comparison, right) for each condition | [
"Return",
"an",
"array",
"of",
"the",
"join",
"conditions"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/Join.php#L179-L191 |
propelorm/Propel | runtime/lib/query/Join.php | Join.getLeftColumns | public function getLeftColumns()
{
$columns = array();
foreach ($this->left as $index => $column) {
$columns[] = $this->getLeftColumn($index);
}
return $columns;
} | php | public function getLeftColumns()
{
$columns = array();
foreach ($this->left as $index => $column) {
$columns[] = $this->getLeftColumn($index);
}
return $columns;
} | [
"public",
"function",
"getLeftColumns",
"(",
")",
"{",
"$",
"columns",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"left",
"as",
"$",
"index",
"=>",
"$",
"column",
")",
"{",
"$",
"columns",
"[",
"]",
"=",
"$",
"this",
"->",
"getLeftColumn",
"(",
"$",
"index",
")",
";",
"}",
"return",
"$",
"columns",
";",
"}"
] | Get the list of all the names of left columns of the join condition
@return array | [
"Get",
"the",
"list",
"of",
"all",
"the",
"names",
"of",
"left",
"columns",
"of",
"the",
"join",
"condition"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/Join.php#L297-L305 |
propelorm/Propel | runtime/lib/query/Join.php | Join.buildJoinCondition | public function buildJoinCondition(Criteria $c)
{
$joinCondition = null;
for ($i = 0; $i < $this->count; $i++) {
$criterion = $c->getNewCriterion($this->getLeftColumn($i), $this->getLeftColumn($i) . $this->getOperator($i) . $this->getRightColumn($i), Criteria::CUSTOM);
if (null === $joinCondition) {
$joinCondition = $criterion;
} else {
$joinCondition = $joinCondition->addAnd($criterion);
}
}
$this->joinCondition = $joinCondition;
} | php | public function buildJoinCondition(Criteria $c)
{
$joinCondition = null;
for ($i = 0; $i < $this->count; $i++) {
$criterion = $c->getNewCriterion($this->getLeftColumn($i), $this->getLeftColumn($i) . $this->getOperator($i) . $this->getRightColumn($i), Criteria::CUSTOM);
if (null === $joinCondition) {
$joinCondition = $criterion;
} else {
$joinCondition = $joinCondition->addAnd($criterion);
}
}
$this->joinCondition = $joinCondition;
} | [
"public",
"function",
"buildJoinCondition",
"(",
"Criteria",
"$",
"c",
")",
"{",
"$",
"joinCondition",
"=",
"null",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"count",
";",
"$",
"i",
"++",
")",
"{",
"$",
"criterion",
"=",
"$",
"c",
"->",
"getNewCriterion",
"(",
"$",
"this",
"->",
"getLeftColumn",
"(",
"$",
"i",
")",
",",
"$",
"this",
"->",
"getLeftColumn",
"(",
"$",
"i",
")",
".",
"$",
"this",
"->",
"getOperator",
"(",
"$",
"i",
")",
".",
"$",
"this",
"->",
"getRightColumn",
"(",
"$",
"i",
")",
",",
"Criteria",
"::",
"CUSTOM",
")",
";",
"if",
"(",
"null",
"===",
"$",
"joinCondition",
")",
"{",
"$",
"joinCondition",
"=",
"$",
"criterion",
";",
"}",
"else",
"{",
"$",
"joinCondition",
"=",
"$",
"joinCondition",
"->",
"addAnd",
"(",
"$",
"criterion",
")",
";",
"}",
"}",
"$",
"this",
"->",
"joinCondition",
"=",
"$",
"joinCondition",
";",
"}"
] | Set the custom join condition Criterion based on the conditions of this join
@param Criteria $c A Criteria object to get Criterions from | [
"Set",
"the",
"custom",
"join",
"condition",
"Criterion",
"based",
"on",
"the",
"conditions",
"of",
"this",
"join"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/Join.php#L502-L514 |
propelorm/Propel | runtime/lib/query/Join.php | Join.getClause | public function getClause(&$params)
{
if (null === $this->joinCondition) {
$conditions = array();
for ($i = 0; $i < $this->count; $i++) {
$conditions [] = $this->getLeftColumn($i) . $this->getOperator($i) . $this->getRightColumn($i);
}
$joinCondition = sprintf('(%s)', implode($conditions, ' AND '));
} else {
$joinCondition = '';
$this->getJoinCondition()->appendPsTo($joinCondition, $params);
}
$rightTableName = $this->getRightTableWithAlias();
if (null !== $this->db && $this->db->useQuoteIdentifier()) {
$rightTableName = $this->db->quoteIdentifierTable($rightTableName);
}
return sprintf('%s %s ON %s',
$this->getJoinType(),
$rightTableName,
$joinCondition
);
} | php | public function getClause(&$params)
{
if (null === $this->joinCondition) {
$conditions = array();
for ($i = 0; $i < $this->count; $i++) {
$conditions [] = $this->getLeftColumn($i) . $this->getOperator($i) . $this->getRightColumn($i);
}
$joinCondition = sprintf('(%s)', implode($conditions, ' AND '));
} else {
$joinCondition = '';
$this->getJoinCondition()->appendPsTo($joinCondition, $params);
}
$rightTableName = $this->getRightTableWithAlias();
if (null !== $this->db && $this->db->useQuoteIdentifier()) {
$rightTableName = $this->db->quoteIdentifierTable($rightTableName);
}
return sprintf('%s %s ON %s',
$this->getJoinType(),
$rightTableName,
$joinCondition
);
} | [
"public",
"function",
"getClause",
"(",
"&",
"$",
"params",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"joinCondition",
")",
"{",
"$",
"conditions",
"=",
"array",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"count",
";",
"$",
"i",
"++",
")",
"{",
"$",
"conditions",
"[",
"]",
"=",
"$",
"this",
"->",
"getLeftColumn",
"(",
"$",
"i",
")",
".",
"$",
"this",
"->",
"getOperator",
"(",
"$",
"i",
")",
".",
"$",
"this",
"->",
"getRightColumn",
"(",
"$",
"i",
")",
";",
"}",
"$",
"joinCondition",
"=",
"sprintf",
"(",
"'(%s)'",
",",
"implode",
"(",
"$",
"conditions",
",",
"' AND '",
")",
")",
";",
"}",
"else",
"{",
"$",
"joinCondition",
"=",
"''",
";",
"$",
"this",
"->",
"getJoinCondition",
"(",
")",
"->",
"appendPsTo",
"(",
"$",
"joinCondition",
",",
"$",
"params",
")",
";",
"}",
"$",
"rightTableName",
"=",
"$",
"this",
"->",
"getRightTableWithAlias",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"db",
"&&",
"$",
"this",
"->",
"db",
"->",
"useQuoteIdentifier",
"(",
")",
")",
"{",
"$",
"rightTableName",
"=",
"$",
"this",
"->",
"db",
"->",
"quoteIdentifierTable",
"(",
"$",
"rightTableName",
")",
";",
"}",
"return",
"sprintf",
"(",
"'%s %s ON %s'",
",",
"$",
"this",
"->",
"getJoinType",
"(",
")",
",",
"$",
"rightTableName",
",",
"$",
"joinCondition",
")",
";",
"}"
] | Get the join clause for this Join.
If the join condition needs binding, uses the passed params array.
@example
<code>
$join = new Join();
$join->addExplicitCondition('book', 'AUTHOR_ID', null, 'author', 'ID');
$params = array();
echo $j->getClause($params);
// 'LEFT JOIN author ON (book.AUTHOR_ID=author.ID)'
</code>
@param array &$params
@return string SQL join clause with join condition | [
"Get",
"the",
"join",
"clause",
"for",
"this",
"Join",
".",
"If",
"the",
"join",
"condition",
"needs",
"binding",
"uses",
"the",
"passed",
"params",
"array",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/query/Join.php#L533-L557 |
propelorm/Propel | runtime/lib/parser/yaml/sfYaml.php | sfYaml.setSpecVersion | public static function setSpecVersion($version)
{
if (!in_array($version, array('1.1', '1.2'))) {
throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version));
}
self::$spec = $version;
} | php | public static function setSpecVersion($version)
{
if (!in_array($version, array('1.1', '1.2'))) {
throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version));
}
self::$spec = $version;
} | [
"public",
"static",
"function",
"setSpecVersion",
"(",
"$",
"version",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"version",
",",
"array",
"(",
"'1.1'",
",",
"'1.2'",
")",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Version %s of the YAML specifications is not supported'",
",",
"$",
"version",
")",
")",
";",
"}",
"self",
"::",
"$",
"spec",
"=",
"$",
"version",
";",
"}"
] | Sets the YAML specification version to use.
@param string $version The YAML specification version | [
"Sets",
"the",
"YAML",
"specification",
"version",
"to",
"use",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/parser/yaml/sfYaml.php#L29-L36 |
propelorm/Propel | runtime/lib/parser/yaml/sfYaml.php | sfYaml.load | public static function load($input)
{
$file = '';
// if input is a file, process it
if (strpos($input, "\n") === false && is_file($input)) {
$file = $input;
ob_start();
$retval = include($input);
$content = ob_get_clean();
// if an array is returned by the config file assume it's in plain php form else in YAML
$input = is_array($retval) ? $retval : $content;
}
// if an array is returned by the config file assume it's in plain php form else in YAML
if (is_array($input)) {
return $input;
}
require_once dirname(__FILE__).'/sfYamlParser.php';
$yaml = new sfYamlParser();
try {
$ret = $yaml->parse($input);
} catch (Exception $e) {
throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage()));
}
return $ret;
} | php | public static function load($input)
{
$file = '';
// if input is a file, process it
if (strpos($input, "\n") === false && is_file($input)) {
$file = $input;
ob_start();
$retval = include($input);
$content = ob_get_clean();
// if an array is returned by the config file assume it's in plain php form else in YAML
$input = is_array($retval) ? $retval : $content;
}
// if an array is returned by the config file assume it's in plain php form else in YAML
if (is_array($input)) {
return $input;
}
require_once dirname(__FILE__).'/sfYamlParser.php';
$yaml = new sfYamlParser();
try {
$ret = $yaml->parse($input);
} catch (Exception $e) {
throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage()));
}
return $ret;
} | [
"public",
"static",
"function",
"load",
"(",
"$",
"input",
")",
"{",
"$",
"file",
"=",
"''",
";",
"// if input is a file, process it",
"if",
"(",
"strpos",
"(",
"$",
"input",
",",
"\"\\n\"",
")",
"===",
"false",
"&&",
"is_file",
"(",
"$",
"input",
")",
")",
"{",
"$",
"file",
"=",
"$",
"input",
";",
"ob_start",
"(",
")",
";",
"$",
"retval",
"=",
"include",
"(",
"$",
"input",
")",
";",
"$",
"content",
"=",
"ob_get_clean",
"(",
")",
";",
"// if an array is returned by the config file assume it's in plain php form else in YAML",
"$",
"input",
"=",
"is_array",
"(",
"$",
"retval",
")",
"?",
"$",
"retval",
":",
"$",
"content",
";",
"}",
"// if an array is returned by the config file assume it's in plain php form else in YAML",
"if",
"(",
"is_array",
"(",
"$",
"input",
")",
")",
"{",
"return",
"$",
"input",
";",
"}",
"require_once",
"dirname",
"(",
"__FILE__",
")",
".",
"'/sfYamlParser.php'",
";",
"$",
"yaml",
"=",
"new",
"sfYamlParser",
"(",
")",
";",
"try",
"{",
"$",
"ret",
"=",
"$",
"yaml",
"->",
"parse",
"(",
"$",
"input",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unable to parse %s: %s'",
",",
"$",
"file",
"?",
"sprintf",
"(",
"'file \"%s\"'",
",",
"$",
"file",
")",
":",
"'string'",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Loads YAML into a PHP array.
The load method, when supplied with a YAML stream (string or file),
will do its best to convert YAML in a file into a PHP array.
Usage:
<code>
$array = sfYaml::load('config.yml');
print_r($array);
</code>
@param string $input Path of YAML file or string containing YAML
@return array The YAML converted to a PHP array
@throws InvalidArgumentException If the YAML is not valid | [
"Loads",
"YAML",
"into",
"a",
"PHP",
"array",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/parser/yaml/sfYaml.php#L66-L98 |
propelorm/Propel | generator/lib/task/PropelMigrationTask.php | PropelMigrationTask.main | public function main()
{
$manager = new PropelMigrationManager();
$manager->setConnections($this->getGeneratorConfig()->getBuildConnections());
$manager->setMigrationTable($this->getMigrationTable());
$manager->setMigrationDir($this->getOutputDirectory());
if (!$nextMigrationTimestamp = $manager->getFirstUpMigrationTimestamp()) {
$this->log('All migrations were already executed - nothing to migrate.');
return false;
}
$timestamps = $manager->getValidMigrationTimestamps();
if (count($timestamps) > 1) {
$this->log(sprintf('%d migrations to execute', count($timestamps)));
}
foreach ($timestamps as $timestamp) {
$this->log(sprintf(
'Executing migration %s up',
$manager->getMigrationClassName($timestamp)
));
$migration = $manager->getMigrationObject($timestamp);
if (false === $migration->preUp($manager)) {
$this->log('preUp() returned false. Aborting migration.', Project::MSG_ERR);
return false;
}
foreach ($migration->getUpSQL() as $datasource => $sql) {
$connection = $manager->getConnection($datasource);
$this->log(sprintf(
'Connecting to database "%s" using DSN "%s"',
$datasource,
$connection['dsn']
), Project::MSG_VERBOSE);
$pdo = $manager->getPdoConnection($datasource);
$res = 0;
$statements = PropelSQLParser::parseString($sql);
foreach ($statements as $statement) {
try {
$this->log(sprintf('Executing statement "%s"', $statement), Project::MSG_VERBOSE);
$stmt = $pdo->prepare($statement);
$stmt->execute();
$res++;
} catch (PDOException $e) {
$this->log(sprintf('Failed to execute SQL "%s"', $statement), Project::MSG_ERR);
// continue
}
}
if (!$res) {
$this->log('No statement was executed. The version was not updated.');
$this->log(sprintf(
'Please review the code in "%s"',
$manager->getMigrationDir() . DIRECTORY_SEPARATOR . $manager->getMigrationClassName($timestamp)
));
$this->log('Migration aborted', Project::MSG_ERR);
return false;
}
$this->log(sprintf(
'%d of %d SQL statements executed successfully on datasource "%s"',
$res,
count($statements),
$datasource
));
}
// migrations for datasources have passed - update the timestamp
// for all datasources
foreach ($manager->getConnections() as $datasource => $connection) {
$manager->updateLatestMigrationTimestamp($datasource, $timestamp);
$this->log(sprintf(
'Updated latest migration date to %d for datasource "%s"',
$timestamp,
$datasource
), Project::MSG_VERBOSE);
}
$migration->postUp($manager);
}
$this->log('Migration complete. No further migration to execute.');
} | php | public function main()
{
$manager = new PropelMigrationManager();
$manager->setConnections($this->getGeneratorConfig()->getBuildConnections());
$manager->setMigrationTable($this->getMigrationTable());
$manager->setMigrationDir($this->getOutputDirectory());
if (!$nextMigrationTimestamp = $manager->getFirstUpMigrationTimestamp()) {
$this->log('All migrations were already executed - nothing to migrate.');
return false;
}
$timestamps = $manager->getValidMigrationTimestamps();
if (count($timestamps) > 1) {
$this->log(sprintf('%d migrations to execute', count($timestamps)));
}
foreach ($timestamps as $timestamp) {
$this->log(sprintf(
'Executing migration %s up',
$manager->getMigrationClassName($timestamp)
));
$migration = $manager->getMigrationObject($timestamp);
if (false === $migration->preUp($manager)) {
$this->log('preUp() returned false. Aborting migration.', Project::MSG_ERR);
return false;
}
foreach ($migration->getUpSQL() as $datasource => $sql) {
$connection = $manager->getConnection($datasource);
$this->log(sprintf(
'Connecting to database "%s" using DSN "%s"',
$datasource,
$connection['dsn']
), Project::MSG_VERBOSE);
$pdo = $manager->getPdoConnection($datasource);
$res = 0;
$statements = PropelSQLParser::parseString($sql);
foreach ($statements as $statement) {
try {
$this->log(sprintf('Executing statement "%s"', $statement), Project::MSG_VERBOSE);
$stmt = $pdo->prepare($statement);
$stmt->execute();
$res++;
} catch (PDOException $e) {
$this->log(sprintf('Failed to execute SQL "%s"', $statement), Project::MSG_ERR);
// continue
}
}
if (!$res) {
$this->log('No statement was executed. The version was not updated.');
$this->log(sprintf(
'Please review the code in "%s"',
$manager->getMigrationDir() . DIRECTORY_SEPARATOR . $manager->getMigrationClassName($timestamp)
));
$this->log('Migration aborted', Project::MSG_ERR);
return false;
}
$this->log(sprintf(
'%d of %d SQL statements executed successfully on datasource "%s"',
$res,
count($statements),
$datasource
));
}
// migrations for datasources have passed - update the timestamp
// for all datasources
foreach ($manager->getConnections() as $datasource => $connection) {
$manager->updateLatestMigrationTimestamp($datasource, $timestamp);
$this->log(sprintf(
'Updated latest migration date to %d for datasource "%s"',
$timestamp,
$datasource
), Project::MSG_VERBOSE);
}
$migration->postUp($manager);
}
$this->log('Migration complete. No further migration to execute.');
} | [
"public",
"function",
"main",
"(",
")",
"{",
"$",
"manager",
"=",
"new",
"PropelMigrationManager",
"(",
")",
";",
"$",
"manager",
"->",
"setConnections",
"(",
"$",
"this",
"->",
"getGeneratorConfig",
"(",
")",
"->",
"getBuildConnections",
"(",
")",
")",
";",
"$",
"manager",
"->",
"setMigrationTable",
"(",
"$",
"this",
"->",
"getMigrationTable",
"(",
")",
")",
";",
"$",
"manager",
"->",
"setMigrationDir",
"(",
"$",
"this",
"->",
"getOutputDirectory",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"nextMigrationTimestamp",
"=",
"$",
"manager",
"->",
"getFirstUpMigrationTimestamp",
"(",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'All migrations were already executed - nothing to migrate.'",
")",
";",
"return",
"false",
";",
"}",
"$",
"timestamps",
"=",
"$",
"manager",
"->",
"getValidMigrationTimestamps",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"timestamps",
")",
">",
"1",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'%d migrations to execute'",
",",
"count",
"(",
"$",
"timestamps",
")",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"timestamps",
"as",
"$",
"timestamp",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Executing migration %s up'",
",",
"$",
"manager",
"->",
"getMigrationClassName",
"(",
"$",
"timestamp",
")",
")",
")",
";",
"$",
"migration",
"=",
"$",
"manager",
"->",
"getMigrationObject",
"(",
"$",
"timestamp",
")",
";",
"if",
"(",
"false",
"===",
"$",
"migration",
"->",
"preUp",
"(",
"$",
"manager",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'preUp() returned false. Aborting migration.'",
",",
"Project",
"::",
"MSG_ERR",
")",
";",
"return",
"false",
";",
"}",
"foreach",
"(",
"$",
"migration",
"->",
"getUpSQL",
"(",
")",
"as",
"$",
"datasource",
"=>",
"$",
"sql",
")",
"{",
"$",
"connection",
"=",
"$",
"manager",
"->",
"getConnection",
"(",
"$",
"datasource",
")",
";",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Connecting to database \"%s\" using DSN \"%s\"'",
",",
"$",
"datasource",
",",
"$",
"connection",
"[",
"'dsn'",
"]",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"$",
"pdo",
"=",
"$",
"manager",
"->",
"getPdoConnection",
"(",
"$",
"datasource",
")",
";",
"$",
"res",
"=",
"0",
";",
"$",
"statements",
"=",
"PropelSQLParser",
"::",
"parseString",
"(",
"$",
"sql",
")",
";",
"foreach",
"(",
"$",
"statements",
"as",
"$",
"statement",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Executing statement \"%s\"'",
",",
"$",
"statement",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"$",
"stmt",
"=",
"$",
"pdo",
"->",
"prepare",
"(",
"$",
"statement",
")",
";",
"$",
"stmt",
"->",
"execute",
"(",
")",
";",
"$",
"res",
"++",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Failed to execute SQL \"%s\"'",
",",
"$",
"statement",
")",
",",
"Project",
"::",
"MSG_ERR",
")",
";",
"// continue",
"}",
"}",
"if",
"(",
"!",
"$",
"res",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'No statement was executed. The version was not updated.'",
")",
";",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Please review the code in \"%s\"'",
",",
"$",
"manager",
"->",
"getMigrationDir",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"manager",
"->",
"getMigrationClassName",
"(",
"$",
"timestamp",
")",
")",
")",
";",
"$",
"this",
"->",
"log",
"(",
"'Migration aborted'",
",",
"Project",
"::",
"MSG_ERR",
")",
";",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'%d of %d SQL statements executed successfully on datasource \"%s\"'",
",",
"$",
"res",
",",
"count",
"(",
"$",
"statements",
")",
",",
"$",
"datasource",
")",
")",
";",
"}",
"// migrations for datasources have passed - update the timestamp",
"// for all datasources",
"foreach",
"(",
"$",
"manager",
"->",
"getConnections",
"(",
")",
"as",
"$",
"datasource",
"=>",
"$",
"connection",
")",
"{",
"$",
"manager",
"->",
"updateLatestMigrationTimestamp",
"(",
"$",
"datasource",
",",
"$",
"timestamp",
")",
";",
"$",
"this",
"->",
"log",
"(",
"sprintf",
"(",
"'Updated latest migration date to %d for datasource \"%s\"'",
",",
"$",
"timestamp",
",",
"$",
"datasource",
")",
",",
"Project",
"::",
"MSG_VERBOSE",
")",
";",
"}",
"$",
"migration",
"->",
"postUp",
"(",
"$",
"manager",
")",
";",
"}",
"$",
"this",
"->",
"log",
"(",
"'Migration complete. No further migration to execute.'",
")",
";",
"}"
] | Main method builds all the targets for a typical propel project. | [
"Main",
"method",
"builds",
"all",
"the",
"targets",
"for",
"a",
"typical",
"propel",
"project",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/generator/lib/task/PropelMigrationTask.php#L25-L106 |
propelorm/Propel | runtime/lib/collection/PropelObjectCollection.php | PropelObjectCollection.save | public function save($con = null)
{
if (!method_exists($this->getModel(), 'save')) {
throw new PropelException('Cannot save objects on a read-only model');
}
if (null === $con) {
$con = $this->getConnection(Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
try {
/** @var $element BaseObject */
foreach ($this as $element) {
$element->save($con);
}
$con->commit();
} catch (Exception $e) {
$con->rollback();
throw $e;
}
} | php | public function save($con = null)
{
if (!method_exists($this->getModel(), 'save')) {
throw new PropelException('Cannot save objects on a read-only model');
}
if (null === $con) {
$con = $this->getConnection(Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
try {
/** @var $element BaseObject */
foreach ($this as $element) {
$element->save($con);
}
$con->commit();
} catch (Exception $e) {
$con->rollback();
throw $e;
}
} | [
"public",
"function",
"save",
"(",
"$",
"con",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"this",
"->",
"getModel",
"(",
")",
",",
"'save'",
")",
")",
"{",
"throw",
"new",
"PropelException",
"(",
"'Cannot save objects on a read-only model'",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"con",
")",
"{",
"$",
"con",
"=",
"$",
"this",
"->",
"getConnection",
"(",
"Propel",
"::",
"CONNECTION_WRITE",
")",
";",
"}",
"$",
"con",
"->",
"beginTransaction",
"(",
")",
";",
"try",
"{",
"/** @var $element BaseObject */",
"foreach",
"(",
"$",
"this",
"as",
"$",
"element",
")",
"{",
"$",
"element",
"->",
"save",
"(",
"$",
"con",
")",
";",
"}",
"$",
"con",
"->",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"con",
"->",
"rollback",
"(",
")",
";",
"throw",
"$",
"e",
";",
"}",
"}"
] | Save all the elements in the collection
@param PropelPDO $con
@throws PropelException | [
"Save",
"all",
"the",
"elements",
"in",
"the",
"collection"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/collection/PropelObjectCollection.php#L26-L45 |
propelorm/Propel | runtime/lib/collection/PropelObjectCollection.php | PropelObjectCollection.fromArray | public function fromArray($arr)
{
$class = $this->getModel();
foreach ($arr as $element) {
/** @var $obj BaseObject */
$obj = new $class();
$obj->fromArray($element);
$this->append($obj);
}
} | php | public function fromArray($arr)
{
$class = $this->getModel();
foreach ($arr as $element) {
/** @var $obj BaseObject */
$obj = new $class();
$obj->fromArray($element);
$this->append($obj);
}
} | [
"public",
"function",
"fromArray",
"(",
"$",
"arr",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"foreach",
"(",
"$",
"arr",
"as",
"$",
"element",
")",
"{",
"/** @var $obj BaseObject */",
"$",
"obj",
"=",
"new",
"$",
"class",
"(",
")",
";",
"$",
"obj",
"->",
"fromArray",
"(",
"$",
"element",
")",
";",
"$",
"this",
"->",
"append",
"(",
"$",
"obj",
")",
";",
"}",
"}"
] | Populates the collection from an array
Each object is populated from an array and the result is stored
Does not empty the collection before adding the data from the array
@param array $arr | [
"Populates",
"the",
"collection",
"from",
"an",
"array",
"Each",
"object",
"is",
"populated",
"from",
"an",
"array",
"and",
"the",
"result",
"is",
"stored",
"Does",
"not",
"empty",
"the",
"collection",
"before",
"adding",
"the",
"data",
"from",
"the",
"array"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/collection/PropelObjectCollection.php#L102-L111 |
propelorm/Propel | runtime/lib/collection/PropelObjectCollection.php | PropelObjectCollection.getArrayCopy | public function getArrayCopy($keyColumn = null, $usePrefix = false)
{
if (null === $keyColumn && false === $usePrefix) {
return parent::getArrayCopy();
}
$ret = array();
$keyGetterMethod = 'get' . $keyColumn;
foreach ($this as $key => $obj) {
$key = null === $keyColumn ? $key : $obj->$keyGetterMethod();
$key = $usePrefix ? ($this->getModel() . '_' . $key) : $key;
$ret[$key] = $obj;
}
return $ret;
} | php | public function getArrayCopy($keyColumn = null, $usePrefix = false)
{
if (null === $keyColumn && false === $usePrefix) {
return parent::getArrayCopy();
}
$ret = array();
$keyGetterMethod = 'get' . $keyColumn;
foreach ($this as $key => $obj) {
$key = null === $keyColumn ? $key : $obj->$keyGetterMethod();
$key = $usePrefix ? ($this->getModel() . '_' . $key) : $key;
$ret[$key] = $obj;
}
return $ret;
} | [
"public",
"function",
"getArrayCopy",
"(",
"$",
"keyColumn",
"=",
"null",
",",
"$",
"usePrefix",
"=",
"false",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"keyColumn",
"&&",
"false",
"===",
"$",
"usePrefix",
")",
"{",
"return",
"parent",
"::",
"getArrayCopy",
"(",
")",
";",
"}",
"$",
"ret",
"=",
"array",
"(",
")",
";",
"$",
"keyGetterMethod",
"=",
"'get'",
".",
"$",
"keyColumn",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"key",
"=>",
"$",
"obj",
")",
"{",
"$",
"key",
"=",
"null",
"===",
"$",
"keyColumn",
"?",
"$",
"key",
":",
"$",
"obj",
"->",
"$",
"keyGetterMethod",
"(",
")",
";",
"$",
"key",
"=",
"$",
"usePrefix",
"?",
"(",
"$",
"this",
"->",
"getModel",
"(",
")",
".",
"'_'",
".",
"$",
"key",
")",
":",
"$",
"key",
";",
"$",
"ret",
"[",
"$",
"key",
"]",
"=",
"$",
"obj",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Get an array representation of the collection
@param string $keyColumn If null, the returned array uses an incremental index.
Otherwise, the array is indexed using the specified column
@param boolean $usePrefix If true, the returned array prefixes keys
with the model class name ('Article_0', 'Article_1', etc).
<code>
$bookCollection->getArrayCopy();
array(
0 => $book0,
1 => $book1,
)
$bookCollection->getArrayCopy('Id');
array(
123 => $book0,
456 => $book1,
)
$bookCollection->getArrayCopy(null, true);
array(
'Book_0' => $book0,
'Book_1' => $book1,
)
</code>
@return array | [
"Get",
"an",
"array",
"representation",
"of",
"the",
"collection"
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/collection/PropelObjectCollection.php#L141-L155 |
propelorm/Propel | runtime/lib/collection/PropelObjectCollection.php | PropelObjectCollection.toKeyValue | public function toKeyValue($keyColumn = 'PrimaryKey', $valueColumn = null)
{
$ret = array();
$valueGetterMethod = (null === $valueColumn) ? '__toString' : ('get' . $valueColumn);
if (!is_array($keyColumn)) {
$keyColumn = array($keyColumn);
}
foreach ($this as $obj) {
$ret[$this->getValueForColumns($obj, $keyColumn)] = $obj->$valueGetterMethod();
}
return $ret;
} | php | public function toKeyValue($keyColumn = 'PrimaryKey', $valueColumn = null)
{
$ret = array();
$valueGetterMethod = (null === $valueColumn) ? '__toString' : ('get' . $valueColumn);
if (!is_array($keyColumn)) {
$keyColumn = array($keyColumn);
}
foreach ($this as $obj) {
$ret[$this->getValueForColumns($obj, $keyColumn)] = $obj->$valueGetterMethod();
}
return $ret;
} | [
"public",
"function",
"toKeyValue",
"(",
"$",
"keyColumn",
"=",
"'PrimaryKey'",
",",
"$",
"valueColumn",
"=",
"null",
")",
"{",
"$",
"ret",
"=",
"array",
"(",
")",
";",
"$",
"valueGetterMethod",
"=",
"(",
"null",
"===",
"$",
"valueColumn",
")",
"?",
"'__toString'",
":",
"(",
"'get'",
".",
"$",
"valueColumn",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"keyColumn",
")",
")",
"{",
"$",
"keyColumn",
"=",
"array",
"(",
"$",
"keyColumn",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"as",
"$",
"obj",
")",
"{",
"$",
"ret",
"[",
"$",
"this",
"->",
"getValueForColumns",
"(",
"$",
"obj",
",",
"$",
"keyColumn",
")",
"]",
"=",
"$",
"obj",
"->",
"$",
"valueGetterMethod",
"(",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Get an associative array representation of the collection
The first parameter specifies the column to be used for the key,
And the seconf for the value.
<code>
$res = $coll->toKeyValue('Id', 'Name');
</code>
<code>
$res = $coll->toKeyValue(array('RelatedModel', 'Name'), 'Name');
</code>
@param string|array $keyColumn The name of the column, or a list of columns to call.
@param string $valueColumn
@return array | [
"Get",
"an",
"associative",
"array",
"representation",
"of",
"the",
"collection",
"The",
"first",
"parameter",
"specifies",
"the",
"column",
"to",
"be",
"used",
"for",
"the",
"key",
"And",
"the",
"seconf",
"for",
"the",
"value",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/collection/PropelObjectCollection.php#L174-L188 |
propelorm/Propel | runtime/lib/collection/PropelObjectCollection.php | PropelObjectCollection.getValueForColumns | protected function getValueForColumns($object, array $columns)
{
$value = $object;
foreach ($columns as $eachKeyColumn) {
$keyGetterMethod = 'get' . $eachKeyColumn;
$value = $value->$keyGetterMethod();
}
return $value;
} | php | protected function getValueForColumns($object, array $columns)
{
$value = $object;
foreach ($columns as $eachKeyColumn) {
$keyGetterMethod = 'get' . $eachKeyColumn;
$value = $value->$keyGetterMethod();
}
return $value;
} | [
"protected",
"function",
"getValueForColumns",
"(",
"$",
"object",
",",
"array",
"$",
"columns",
")",
"{",
"$",
"value",
"=",
"$",
"object",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"eachKeyColumn",
")",
"{",
"$",
"keyGetterMethod",
"=",
"'get'",
".",
"$",
"eachKeyColumn",
";",
"$",
"value",
"=",
"$",
"value",
"->",
"$",
"keyGetterMethod",
"(",
")",
";",
"}",
"return",
"$",
"value",
";",
"}"
] | Return the value for a given set of key columns.
Each column will be resolved on the value returned by the previous one.
@param object $object The object to start with.
@param array $columns The sequence of key columns.
@return mixed | [
"Return",
"the",
"value",
"for",
"a",
"given",
"set",
"of",
"key",
"columns",
"."
] | train | https://github.com/propelorm/Propel/blob/3f7a284906ce3e402bcb101938270842fdad71fa/runtime/lib/collection/PropelObjectCollection.php#L200-L210 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.