sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function tableHead($options = []) { $_options = [ 'beforeActionHead' => '<td class="actions">', 'afterActionHead' => '</td>', 'actionsLabel' => __d('CakeAdmin', 'Actions'), ]; $options = array_merge($_options, $options); $html = ''; $html .= '<tr>'; foreach ($this->type()['tableColumns'] as $column => $opt) : $html .= '<th>'; $html .= $this->Paginator->sort($column); $html .= '</th>'; endforeach; $html .= $options['beforeActionHead'] . $options['actionsLabel'] . $options['afterActionHead']; $html .= '</tr>'; return $html; }
tableHead Generates the head of the table (all columns). ### Options - `beforeActionHead` - Html before the action-column. - `afterActionHead` - Html after the action-column. - `actionsLabel` - Label of `Actions`. @param array $options Options. @return string
entailment
public function tableBody($options = []) { $_options = [ 'beforeActionBody' => '<td class="actions">', 'afterActionBody' => '</td>', 'viewLabel' => __d('CakeAdmin', 'View'), 'editLabel' => __d('CakeAdmin', 'Edit'), 'deleteLabel' => __d('CakeAdmin', 'Delete'), ]; $options = array_merge($_options, $options); $html = ''; foreach ($this->_data as $item) : $html .= '<tr>'; foreach ($this->_type['tableColumns'] as $column => $opt) : $html .= '<td>'; $html .= $opt['before']; $html .= Hash::get($item->toArray(), $opt['get']); $html .= $opt['after']; $html .= '</td>'; endforeach; $html .= $options['beforeActionBody']; $html .= $this->Html->link($options['viewLabel'], [ 'action' => 'view', 'type' => $this->type()['slug'], $item->get('id') ]) . ' '; $html .= $this->Html->link($options['editLabel'], [ 'action' => 'edit', 'type' => $this->type()['slug'], $item->get('id') ]) . ' '; $html .= $this->Form->postLink($options['deleteLabel'], [ 'action' => 'delete', 'type' => $this->type()['slug'], $item->get('id') ], [ 'confirm' => __d('CakeAdmin', 'Are you sure you want to delete # {0}?', $item->get('id')) ]); $html .= $options['afterActionBody']; $html .= '</tr>'; endforeach; return $html; }
tableBody Generates the head of the table (all columns). ### Options - `beforeActionBody` - Html before the actions-cell. - `afterActionBody` - Html after the actions-cell. - `viewLabel` - Label for the view-button. - `editLabel` - Label for the edit-button. - `deleteLabel` - Label for the delete-button. @param array $options Options. @return string
entailment
public function createForm($entity, $options = []) { $options = array_merge($this->type()['formFields']['_create'], $options); return $this->Form->create($entity, $options); }
createForm Initializer for a form. @param \Cake\ORM\Entity $entity Entity. @param array $options Options. @return mixed
entailment
public function fieldset($options = []) { $_options = [ 'beforeLegend' => '<legend>', 'afterLegend' => '</legend>', 'label' => __d('CakeAdmin', 'Add '), 'on' => ['both'] ]; $options = array_merge($_options, $options); $html = ''; $html .= $options['beforeLegend'] . $options['label'] . $this->type()['alias'] . $options['afterLegend']; foreach ($this->type()['formFields'] as $field => $opt) : if (substr($field, 0, 1) !== '_') { if (in_array($opt['on'], $options['on'])) { echo $this->Form->input($field, $opt); } } endforeach; return $html; }
fieldset Generates a fieldset, ### Options - `beforeLegend` - Html before the legend. - `afterLegend` - Html after the legend. - `label` - Label at top of the fieldset. - `on` - Array with the validations (`both`, `add` or `edit`). @param array $options Options. @return string
entailment
public function submitForm($options = []) { $_options = [ 'submitLabel' => __d('CakeAdmin', 'Submit'), 'options' => [], ]; $options = array_merge($_options, $options); return $this->Form->button($options['submitLabel'], $options['options']); }
submitForm Submitbutton for the form. ### Options - `submitLabel` - Label to use. - `options` - Options for the button. @param array $options Options. @return mixed
entailment
public static function getTypeFromPath($file_name){ $ext = strtolower(preg_replace('/^.*\.([^.]+)$/', '$1', $file_name)); switch( $ext ){ case 'jpeg': case 'jpg': return self::JPEG; break; case 'otf': return self::OpenType; break; case 'opf': return self::OPF2; break; case 'smil': return self::MediaOverlays301; break; case 'js': return self::JS; break; default: $const_name = strtoupper($ext); $refl = new \ReflectionClass(get_called_class()); return $refl->getConstant($const_name); break; } }
Get extension from file path @param string $file_name @return string
entailment
public static function getDestinationFolder($path){ $path = (string) $path; if( preg_match('/\.(jpe?g|gif|png|svg)$/i', $path) ) { return 'Image'; }elseif( preg_match('/\.(otf|woff|ttf)$/i', $path) ) { return 'Font'; }elseif( preg_match('/\.(css)$/i', $path) ) { return 'CSS'; }elseif( preg_match('/\.(mp4|mp3)$/i', $path) ){ return 'Media'; }elseif( preg_match('/\.(smil|pls)$/i', $path) ){ return 'Speech'; }elseif( preg_match('/\.(js|json)$/i', $path) ){ return 'JS'; }elseif( preg_match('/\.x?html$/i', $path) ){ return 'Text'; }else{ return 'Misc'; } }
Return folder name @param string $path @return string
entailment
public function addRootFile($path){ $rootFile = $this->dom->rootfiles->addChild('rootfile'); $rootFile['full-path'] = $path; $rootFile['media-type'] = 'application/oebps-package+xml'; }
Set root file element @param string $path
entailment
function key() { if ($this->current() instanceof File_MARC_Field) { return $this->current()->getTag(); } elseif ($this->current() instanceof File_MARC_Subfield) { return $this->current()->getCode(); } return false; }
Returns the tag for a {@link File_MARC_Field} object, or the code for a {@link File_MARC_Subfield} object. This method enables you to use a foreach iterator to retrieve the tag or code as the key for the iterator. @return string returns the tag or code
entailment
public function insertNode($new_node, $existing_node, $before = false) { $pos = 0; $exist_pos = $existing_node->getPosition(); $this->rewind(); // Now add the node according to the requested mode switch ($before) { case true: $this->add($exist_pos, $new_node); break; // after case false: if ($this->offsetExists($exist_pos + 1)) { $this->add($exist_pos + 1, $new_node); } else { $this->appendNode($new_node); return true; } break; } // Fix positions $this->rewind(); while ($n = $this->current()) { $n->setPosition($pos); $this->next(); $pos++; } return true; }
Inserts a node into the linked list, based on a reference node that already exists in the list. @param mixed $new_node New node to add to the list @param mixed $existing_node Reference position node @param bool $before Insert new node before or after the existing node @return bool Success or failure
entailment
public function appendNode($new_node) { $pos = $this->count(); $new_node->setPosition($pos); $this->push($new_node); }
Adds a node onto the linked list. @param mixed $new_node New node to add to the list @return void
entailment
public function deleteNode($node) { $target_pos = $node->getPosition(); $this->rewind(); $pos = 0; // Omit target node and adjust pos of remainder $done = false; try { while ($n = $this->current()) { if ($pos == $target_pos && !$done) { $done = true; $this->next(); $this->offsetUnset($pos); } elseif ($pos >= $target_pos) { $n->setPosition($pos); $pos++; $this->next(); } else { $pos++; $this->next(); } } } catch (Exception $e) { // no-op - shift() throws an exception, sigh } }
Deletes a node from the linked list. @param mixed $node Node to delete from the list @return void
entailment
public function setIdentifier($urn){ $identifier = $this->dom->metadata->children('dc', true)->identifier[0]; $identifier[0] = $urn; return $identifier->attributes()->id; }
Set identifier @param string $urn @return string ID of identifier
entailment
public function setLang($lang_code){ $lang = $this->dom->metadata->children('dc', true)->language[0]; $lang[0] = $this->h($lang_code); return $lang; }
Set language @param string $lang_code @return \SimpleXMLElement
entailment
public function setTitle($string, $id, $type = 'main', $sequence = 1){ $sequence = max(1, $sequence); // Add title $title = $this->dom->metadata->addChild('title', $this->h($string), Schemas::DC); $title['id'] = $id; // Add title meta $meta = $this->dom->metadata->addChild('meta', $type); $meta['refines'] = '#'.$id; $meta['property'] = 'title-type'; // Add sequence $meta = $this->dom->metadata->addChild('meta', $sequence); $meta['refines'] = '#'.$id; $meta['property'] = 'display-seq'; }
Set title meta @param string $string @param string $id @param string $type 1 of 'main', 'subtitle', 'short', 'collection', 'edition' and 'expanded' @param int $sequence
entailment
public function addMeta($tag, $value, array $attributes = []){ $value = $this->h($value); if( false !== strpos($tag, ':') ){ $tags = explode(':', $tag); $node = $this->dom->metadata->addChild($tags[1], $value, Schemas::getUri($tags[0])); }else{ $node = $this->dom->metadata->addChild($tag, $value); } foreach( $attributes as $key => $val ){ $node[$key] = $this->h($val); } }
Add meta item @param string $tag @param string $value @param array $attributes
entailment
public function addItem($relative_path, $id = '', array $properties = []){ $id = $id ?: $this->pathToId($relative_path); // Avoid duplication foreach( $this->dom->manifest->item as $item ){ /** @var \SimpleXMLElement $item */ $attr = $item->attributes(); if( isset($attr['id']) && $id == $attr['id'] ){ return $id; } } // This is unique. $item = $this->dom->manifest->addChild('item'); $item['id'] = $id; $item['href'] = $relative_path; $item['media-type'] = Mime::getTypeFromPath($relative_path); if( $properties ){ $item['properties'] = implode(' ', $properties); } return $id; }
Add item to @param string $relative_path @param string $id If empty, path will convert to id @param array $properties Default empty. If set, properties will be set. @return string
entailment
public function addIdref($id, $liner = 'yes', array $properties = [] ){ $itemref = $this->dom->spine->addChild('itemref'); $itemref['idref'] = $id; if( 'no' === $liner ){ $itemref['linear'] = 'no'; } if( !empty($properties) ){ $itemref['properties'] = implode(' ', $properties); } return $itemref; }
Add item ref to spine @param string $id @param string $liner @param array $properties List of property. 'page-spread-left' or 'page-spread-right' is allowed. @return mixed
entailment
public function addGuide($type, $href){ if( !$this->dom->guide->count() ){ $guide = $this->dom->addChild('guide'); }else{ $guide = $this->dom->guide; } $ref = $guide->addChild('reference'); $ref['type'] = $type; $ref['href'] = $href; return $ref; }
Add guide element This `guide` element is not nescesary for ePub 3.0, but KF8(Kindle) still requires it. @see http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.6 @param string $type @param string $href @return mixed
entailment
public function pathToId($path){ $path = ltrim(ltrim($path, '.'), DIRECTORY_SEPARATOR); return strtolower(preg_replace('/[_\.\/\\\\]/', '-', $path)); }
Convert id to path @param string $path @return string
entailment
public function initialize(array $config) { parent::initialize($config); $this->Controller = $this->_registry->getController(); $this->_setRecipientList(); }
Initialize component. @param array $config Configurations. @return void
entailment
public function administrators($field = null) { $model = TableRegistry::get('CakeAdmin.Administrators'); $query = $model->find('all'); if ($field) { $model->displayField($field); $query->find('list'); } $result = $query->toArray(); return $result; }
Returns a list of administrators. @param null $field Non-required field, if empty all data will be returned. @return array|string
entailment
public function isLoggedIn() { $session = $this->Controller->request->session(); if ($session->check('Auth.CakeAdmin')) { return (bool)$session->read('Auth.CakeAdmin'); } return false; }
Checks if an administrator is logged in. @return bool
entailment
public function authUser() { $session = $this->Controller->request->session(); if ($session->check('Auth.CakeAdmin')) { return $session->read('Auth.CakeAdmin'); } return false; }
Returns the logged in administrator. Will return `false` when there'se no session. @return bool
entailment
public function addChild($label, $link, $index = -1){ $this->children[$link] = new Toc($label, $link); return $this->children[$link]; }
Add child @param string $label @param string $link @param int $index @return Toc
entailment
public function getHTML($header = '', $footer = ''){ $title = htmlspecialchars($this->label, ENT_QUOTES, 'UTF-8'); $html = <<<HTML <html xmlns:epub="http://www.idpf.org/2007/ops"> <head> <meta charset="UTF-8"> <title>{$title}</title> {$header} </head> <body> HTML; $html .= $this->getNavHTML(); $html .= <<<HTML {$footer} </body> </html> HTML; return $html; }
Get simple navigation @param string $header @param string $footer @return string
entailment
public function getNavHTML($content_label){ if( !$this->root ){ return ''; } $landmarks = ''; $toc = ''; foreach( $this->children as $child ){ $toc .= $this->makeList($child, false); $landmarks .= $this->makeList($child, true, $content_label); } $html = <<<HTML <nav epub:type="toc" id="toc"> <ol> {$toc} </ol> </nav> <nav id="landmarks" epub:type="landmarks" hidden="hidden" class="hidden"> <ol epub:type="list"> {$landmarks} </ol> </nav> HTML; return trim($html); }
Get navigation html @param string $content_label @return string
entailment
private function makeList( Toc $toc, $require_type = false, $content_label = ''){ static $did_body_matter = false; if( !$require_type ){ // For toc $html = sprintf('<li><a href="%s">%s</a>', $toc->link, htmlspecialchars($toc->label, ENT_QUOTES, 'UTF-8')); if( !empty($toc->children) ){ $html .= "\n<ol". ($require_type ? ' epub:type="list"' : '') .">\n"; foreach( $toc->children as $child ){ $html .= $this->makeList($child, $require_type); } $html .= "</ol>\n"; } }else{ // For landmark $type = strtolower(str_replace('.xhtml', '', $toc->link)); switch( $type ){ case 'cover': case 'toc': case 'landmarks': case 'preface': case 'prologue': case 'epigraph': case 'epilogue': case 'afterword': case 'colophon': case 'bibliography': case 'titlepage': case 'contributors': case 'dedication': $epub_type = $type; break; default: if( false !== strpos($type, '#') ){ $epub_type = 'bridgehead'; }else{ $epub_type = 'bodymatter'; } break; } if( !$epub_type || 'bridgehead' == $epub_type ){ return ''; } $label = $toc->label; if( 'bodymatter' === $epub_type ){ if( $did_body_matter ){ return ''; }else{ $did_body_matter = true; } if( $content_label ){ $label = $content_label; } } $html = sprintf('<li><a href="%s" epub:type="%s">%s</a>', $toc->link, $epub_type, htmlspecialchars($label, ENT_QUOTES, 'UTF-8')); } $html .= "</li>\n"; return $html; }
Make list @param Toc $toc @param bool $require_type Default false. If true, landmarks will be created. @param string $content_label @return string
entailment
public static function get($id){ if( isset(self::$instances[$id]) ){ return self::$instances[$id]; } return null; }
Get toc instance @param string $id @return static
entailment
public static function init($id, $label = 'Index'){ if( !isset(self::$instances[$id]) ){ self::$instances[$id] = new Toc($label, '', true); } return self::$instances[$id]; }
Initialize toc element @param string $id @param string $label @return mixed
entailment
function formatField($exclude = array('2')) { if ($this->isControlField()) { return $this->getData(); } else { $out = ''; foreach ($this->getSubfields() as $subfield) { if (substr($this->getTag(), 0, 1) == '6' and (in_array($subfield->getCode(), array('v','x','y','z')))) { $out .= ' -- ' . $subfield->getData(); } elseif (!in_array($subfield->getCode(), $exclude)) { $out .= ' ' . $subfield->getData(); } } return trim($out); } }
Pretty print a MARC_Field object without tags, indicators, etc. @param array $exclude Subfields to exclude from formatted output @return string Returns the formatted field data
entailment
private function getHeader($name, $headers) { $headers = array_change_key_case($headers); $name = strtolower($name); return isset($headers[$name]) ? (string) $headers[$name] : false; }
Returns the case insensitive header from the list of headers. @param string $name name of the header @param string[] $headers List of headers @return string|false Contents of the header or false if it does not exist
entailment
function insertField(File_MARC_Field $new_field, File_MARC_Field $existing_field, $before = false) { $this->fields->insertNode($new_field, $existing_field, $before); return $new_field; }
Inserts a field in the MARC record relative to an existing field Inserts a {@link File_MARC_Control_Field} or {@link File_MARC_Data_Field} object before or after a specified existing field. <code> // Example: Insert a new field before the first 650 field // Create the new field $subfields[] = new File_MARC_Subfield('a', 'Scott, Daniel.'); $new_field = new File_MARC_Data_Field('100', $subfields, 0, null); // Retrieve the target field for our insertion point $subject = $record->getFields('650'); // Insert the new field if (is_array($subject)) { $record->insertField($new_field, $subject[0], true); } elseif ($subject) { $record->insertField($new_field, $subject, true); } </code> @param File_MARC_Field $new_field The field to add @param File_MARC_Field $existing_field The target field @param bool $before Insert the new field before the existing field if true, after the existing field if false @return File_MARC_Field The field that was added
entailment
private function _buildDirectory() { // Vars $fields = array(); $directory = array(); $data_end = 0; foreach ($this->fields as $field) { // No empty fields allowed if (!$field->isEmpty()) { // Get data in raw format $str = $field->toRaw(); $fields[] = $str; // Create directory entry $len = strlen($str); $direntry = sprintf("%03s%04d%05d", $field->getTag(), $len, $data_end); $directory[] = $direntry; $data_end += $len; } } /** * Rules from MARC::Record::USMARC */ $base_address = File_MARC::LEADER_LEN + // better be 24 (count($directory) * File_MARC::DIRECTORY_ENTRY_LEN) + // all the directory entries 1; // end-of-field marker $total = $base_address + // stuff before first field $data_end + // Length of the fields 1; // End-of-record marker return array($fields, $directory, $total, $base_address); }
Build record directory Generate the directory of the record according to the current contents of the record. @return array Array ($fields, $directory, $total, $base_address)
entailment
function setLeaderLengths($record_length, $base_address) { if (!is_int($record_length)) { return false; } if (!is_int($base_address)) { return false; } // Set record length $this->setLeader(substr_replace($this->getLeader(), sprintf("%05d", $record_length), 0, 5)); $this->setLeader(substr_replace($this->getLeader(), sprintf("%05d", $base_address), File_MARC::DIRECTORY_ENTRY_LEN, 5)); $this->setLeader(substr_replace($this->getLeader(), '22', 10, 2)); $this->setLeader(substr_replace($this->getLeader(), '4500', 20, 4)); if (strlen($this->getLeader()) > File_MARC::LEADER_LEN) { // Avoid incoming leaders that are mangled to be overly long $this->setLeader(substr($this->getLeader(), 0, File_MARC::LEADER_LEN)); $this->addWarning("Input leader was too long; truncated to " . File_MARC::LEADER_LEN . " characters"); } return true; }
Set MARC record leader lengths Set the Leader lengths of the record according to defaults specified in {@link http://www.loc.gov/marc/bibliographic/ecbdldrd.html} @param int $record_length Record length @param int $base_address Base address of data @return bool Success or failure
entailment
function getField($spec = null, $pcre = null) { foreach ($this->fields as $field) { if (($pcre && preg_match("/$spec/", $field->getTag())) || (!$pcre && $spec == $field->getTag()) ) { return $field; } } return false; }
Return the first {@link File_MARC_Data_Field} or {@link File_MARC_Control_Field} object that matches the specified tag name. Returns false if no match is found. @param string $spec tag name @param bool $pcre if true, then match as a regular expression @return {@link File_MARC_Data_Field}|{@link File_MARC_Control_Field} first field that matches the requested tag name
entailment
function getFields($spec = null, $pcre = null) { if (!$spec) { return $this->fields; } // Okay, we're actually looking for something specific $matches = array(); foreach ($this->fields as $field) { if (($pcre && preg_match("/$spec/", $field->getTag())) || (!$pcre && $spec == $field->getTag()) ) { $matches[] = $field; } } return $matches; }
Return an array or {@link File_MARC_List} containing all {@link File_MARC_Data_Field} or {@link File_MARC_Control_Field} objects that match the specified tag name. If the tag name is omitted all fields are returned. @param string $spec tag name @param bool $pcre if true, then match as a regular expression @return File_MARC_List|array {@link File_MARC_Data_Field} or {@link File_MARC_Control_Field} objects that match the requested tag name
entailment
function deleteFields($tag, $pcre = null) { $cnt = 0; foreach ($this->getFields() as $field) { if (($pcre && preg_match("/$tag/", $field->getTag())) || (!$pcre && $tag == $field->getTag()) ) { $field->delete(); $cnt++; } } return $cnt; }
Delete all occurrences of a field matching a tag name from the record. @param string $tag tag for the fields to be deleted @param bool $pcre if true, then match as a regular expression @return int number of fields that were deleted
entailment
function toRaw() { list($fields, $directory, $record_length, $base_address) = $this->_buildDirectory(); $this->setLeaderLengths($record_length, $base_address); /** * Glue together all parts */ return $this->getLeader().implode("", $directory).File_MARC::END_OF_FIELD.implode("", $fields).File_MARC::END_OF_RECORD; }
Return the record in raw MARC format. If you have modified an existing MARC record or created a new MARC record, use this method to save the record for use in other programs that accept the MARC format -- for example, your integrated library system. <code> // Example: Modify a record and save the output to a file $record->deleteFields('650'); // Now that the record has no subject fields, save it to disk fopen($file, '/home/dan/no_subject.mrc', 'w'); fwrite($file, $record->toRaw()); fclose($file); </code> @return string Raw MARC data
entailment
function toJSON() { $json = new StdClass(); $json->leader = utf8_encode($this->getLeader()); /* Start fields */ $fields = array(); foreach ($this->fields as $field) { if (!$field->isEmpty()) { switch(get_class($field)) { case "File_MARC_Control_Field": $fields[] = array(utf8_encode($field->getTag()) => utf8_encode($field->getData())); break; case "File_MARC_Data_Field": $subs = array(); foreach ($field->getSubfields() as $sf) { $subs[] = array(utf8_encode($sf->getCode()) => utf8_encode($sf->getData())); } $contents = new StdClass(); $contents->ind1 = utf8_encode($field->getIndicator(1)); $contents->ind2 = utf8_encode($field->getIndicator(2)); $contents->subfields = $subs; $fields[] = array(utf8_encode($field->getTag()) => $contents); break; } } } /* End fields and record */ $json->fields = $fields; $json_rec = json_encode($json); // Required because json_encode() does not let us stringify integer keys return preg_replace('/("subfields":)(.*?)\["([^\"]+?)"\]/', '\1\2{"0":"\3"}', $json_rec); }
Return the MARC record in JSON format This method produces a JSON representation of a MARC record. The input encoding must be UTF8, otherwise the returned values will be corrupted. @return string representation of MARC record in JSON format @todo Fix encoding input / output issues (PHP 6.0 required?)
entailment
function toJSONHash() { $json = new StdClass(); $json->type = "marc-hash"; $json->version = array(1, 0); $json->leader = utf8_encode($this->getLeader()); /* Start fields */ $fields = array(); foreach ($this->fields as $field) { if (!$field->isEmpty()) { switch(get_class($field)) { case "File_MARC_Control_Field": $fields[] = array(utf8_encode($field->getTag()), utf8_encode($field->getData())); break; case "File_MARC_Data_Field": $subs = array(); foreach ($field->getSubfields() as $sf) { $subs[] = array(utf8_encode($sf->getCode()), utf8_encode($sf->getData())); } $contents = array( utf8_encode($field->getTag()), utf8_encode($field->getIndicator(1)), utf8_encode($field->getIndicator(2)), $subs ); $fields[] = $contents; break; } } } /* End fields and record */ $json->fields = $fields; return json_encode($json); }
Return the MARC record in Bill Dueber's MARC-HASH JSON format This method produces a JSON representation of a MARC record as defined at http://robotlibrarian.billdueber.com/new-interest-in-marc-hash-json/ The input * encoding must be UTF8, otherwise the returned values will be corrupted. @return string representation of MARC record in JSON format @todo Fix encoding input / output issues (PHP 6.0 required?)
entailment
function toXML($encoding = "UTF-8", $indent = true, $single = true) { $this->marcxml->setIndent($indent); if ($single) { $this->marcxml->startElement("collection"); $this->marcxml->writeAttribute("xmlns", "http://www.loc.gov/MARC21/slim"); $this->marcxml->startElement("record"); } else { $this->marcxml->startElement("record"); $this->marcxml->writeAttribute("xmlns", "http://www.loc.gov/MARC21/slim"); } // MARCXML schema has some strict requirements // We'll set reasonable defaults to avoid invalid MARCXML $xmlLeader = $this->getLeader(); // Record status if ($xmlLeader[5] == " ") { // Default to "n" (new record) $xmlLeader[5] = "n"; } // Type of record if ($xmlLeader[6] == " ") { // Default to "a" (language material) $xmlLeader[6] = "a"; } $this->marcxml->writeElement("leader", $xmlLeader); foreach ($this->fields as $field) { if (!$field->isEmpty()) { switch(get_class($field)) { case "File_MARC_Control_Field": $this->marcxml->startElement("controlfield"); $this->marcxml->writeAttribute("tag", $field->getTag()); $this->marcxml->text($field->getData()); $this->marcxml->endElement(); // end control field break; case "File_MARC_Data_Field": $this->marcxml->startElement("datafield"); $this->marcxml->writeAttribute("tag", $field->getTag()); $this->marcxml->writeAttribute("ind1", $field->getIndicator(1)); $this->marcxml->writeAttribute("ind2", $field->getIndicator(2)); foreach ($field->getSubfields() as $subfield) { $this->marcxml->startElement("subfield"); $this->marcxml->writeAttribute("code", $subfield->getCode()); $this->marcxml->text($subfield->getData()); $this->marcxml->endElement(); // end subfield } $this->marcxml->endElement(); // end data field break; } } } $this->marcxml->endElement(); // end record if ($single) { $this->marcxml->endElement(); // end collection $this->marcxml->endDocument(); } return $this->marcxml->outputMemory(); }
Return the MARC record in MARCXML format This method produces an XML representation of a MARC record that attempts to adhere to the MARCXML standard documented at http://www.loc.gov/standards/marcxml/ @param string $encoding output encoding for the MARCXML record @param bool $indent pretty-print the MARCXML record @param bool $single wrap the <record> element in a <collection> element @return string representation of MARC record in MARCXML format @todo Fix encoding input / output issues (PHP 6.0 required?)
entailment
public static function getUri($name_space){ $refl = new \ReflectionClass(get_called_class()); $name_space = strtoupper($name_space); return $refl->hasConstant($name_space) ? $refl->getConstant($name_space) : ''; }
Get name space URL @param string $name_space @return mixed|string
entailment
public function getXML(){ $doc = new \DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $doc->loadXML($this->dom->asXml()); return $doc->saveXML(); }
Get XML string in pretty format @return string
entailment
public function putXML(){ $xml = $this->getXML(); return $this->distributor->write($xml, $this->proper_path); }
Put XML file @return bool|string
entailment
public static function get($id, $temp_dir = ''){ if( !isset(static::$instances[$id]) ){ static::$instances[$id] = new static($id, $temp_dir); } return static::$instances[$id]; }
Get instance @param string $id @param string $temp_dir @return static @throws SettingException
entailment
public function copy($src, $rel_path){ $path = $this->setDir($rel_path); if( !($exist = file_exists($src)) ){ trigger_error(sprintf('File %s doesn\'t exist.', $src), E_USER_WARNING); } return $path && $exist && copy($src, $path) ? $path : false; }
Copy file @param string $src @param string $rel_path @return bool|string
entailment
public function write($file_content, $rel_path){ $path = $this->setDir($rel_path); return $path && file_put_contents($path, $file_content) ? $path : false; }
Write string to file @param string $file_content File contents. @param string $rel_path Relative path from temp directory. @return bool|string
entailment
private function setDir($rel_path){ $path = $this->temp_dir.DIRECTORY_SEPARATOR.ltrim($rel_path, DIRECTORY_SEPARATOR); $dir = dirname($path); if( !is_dir($dir) ){ if( !mkdir($dir, 0755, true) ){ return false; } } return $path; }
Ensure parent directory is ready and writable @param string $rel_path @return false|string
entailment
public function compile($to){ copy($this->path->skeleton, $to); $epub = new \ZipArchive(); if( true === $epub->open($to) ){ $this->deliver($epub, $this->temp_dir); } }
Compile ePub File @param string $to @throws CompileException
entailment
private function rm($dir_or_file){ if( is_dir($dir_or_file) ){ foreach( scandir($dir_or_file) as $file ){ if( false === array_search($file, ['.', '..']) ){ $this->rm( rtrim($dir_or_file, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file ); } } if( !rmdir($dir_or_file) ){ throw new \Exception(sprintf('Failed to delete %s. Please check permission', $dir_or_file), 403); } }elseif( is_file($dir_or_file) ){ if( !unlink($dir_or_file) ){ throw new \Exception(sprintf('Failed to delete %s. Please check permission', $dir_or_file), 403); } }else{ throw new \Exception(sprintf('%s is not file or directory.', $dir_or_file), 404); } }
Remove directory recursively @param string $dir_or_file @throws \Exception
entailment
private function deliver( \ZipArchive &$epub, $src, $dir = ''){ if( !$dir ){ $dir = $src; } if( is_dir($src) ){ $root = rtrim($src, DIRECTORY_SEPARATOR); foreach( scandir($src) as $file ){ if( !preg_match('/^\./', $file) ){ // Skip dot files $path = $root.DIRECTORY_SEPARATOR.$file; $this->deliver($epub, $path, $dir); } } }elseif( file_exists($src) ){ $relative_path = ltrim(str_replace($dir, '', $src), DIRECTORY_SEPARATOR); $epub->addFile($src, $relative_path); }else{ throw new CompileException(sprintf('Cannot copy file %s.', $src)); } }
Copy file into zip @param \ZipArchive $epub @param string $src @param string $dir @throws CompileException
entailment
function next() { if (isset($this->source->record[$this->counter])) { $record = $this->source->record[$this->counter++]; } elseif ($this->source->getName() == "record" && $this->counter == 0) { $record = $this->source; $this->counter++; } else { return false; } if ($record) { return $this->_decode($record); } else { return false; } }
Return next {@link File_MARC_Record} object Decodes the next MARCXML record and returns the {@link File_MARC_Record} object. <code> <?php // Retrieve a set of MARCXML records from a file $journals = new File_MARCXML('journals.xml', SOURCE_FILE); // Iterate through the retrieved records while ($record = $journals->next()) { print $record; print "\n"; } ?> </code> @return File_MARC_Record next record, or false if there are no more records
entailment
private function _decode($text) { $marc = new $this->record_class($this); // Store leader $marc->setLeader($text->leader); // go through all the control fields foreach ($text->controlfield as $controlfield) { $controlfieldattributes = $controlfield->attributes(); $marc->appendField(new File_MARC_Control_Field((string)$controlfieldattributes['tag'], $controlfield)); } // go through all the data fields foreach ($text->datafield as $datafield) { $datafieldattributes = $datafield->attributes(); $subfield_data = array(); foreach ($datafield->subfield as $subfield) { $subfieldattributes = $subfield->attributes(); $subfield_data[] = new File_MARC_Subfield((string)$subfieldattributes['code'], $subfield); } // If the data is invalid, let's just ignore the one field try { $new_field = new File_MARC_Data_Field((string)$datafieldattributes['tag'], $subfield_data, $datafieldattributes['ind1'], $datafieldattributes['ind2']); $marc->appendField($new_field); } catch (Exception $e) { $marc->addWarning($e->getMessage()); } } return $marc; }
Decode a given MARCXML record @param string $text MARCXML record element @return File_MARC_Record Decoded File_MARC_Record object
entailment
public function registerHTML($id, $html, $linear = 'yes', array $properties = []){ $dom = $this->parser->parseFromString($html); if( $dom ){ if( !isset($this->doms[$id]) ){ $this->opf->addIdref($id.'.xhtml', $linear, $properties); } $this->doms[$id] = $dom; return $dom; } return false; }
Register HTML string @param string $id @param string $html @param string $linear @param array $properties @return false|\DOMDocument
entailment
public function includeTemplate($id, $path, array $args = [], $linear = 'yes', array $properties = []){ if( !file_exists($path) ){ return false; } if( !empty($args) ){ extract($args); } ob_start(); include $path; $content = ob_get_contents(); ob_end_clean(); return $this->registerHTML($id, $content, $linear, $properties); }
Load from path @param string $path @param array $args @param string $linear @param array $properties @return \DomDocument|false
entailment
public function registerFromPath($id, $path){ if( !file_exists($path) ){ return false; } $dom = $this->parser->parseFromString(file_get_contents($path)); if( $dom ){ $this->doms[$id] = $dom; } return false; }
Register HTML from file path @param string $id @param string $path @return bool
entailment
public function registerFromUrl($id, $url, array $context = []){ $response = $this->parser->getRemoteFile($url, $context); if( $response && ($dom = $this->parser->parseFromString($response)) ){ $this->doms[$id] = $dom; } return false; }
Get remote file @param string $id @param string $url @param array $context @return bool
entailment
public function addCover($src, $dest = '', $id = 'cover'){ if( file_exists($src) ){ if( !$dest ){ $dest = 'Image'.DIRECTORY_SEPARATOR.basename($src); } $this->distributor->copy($src, 'OEBPS'.DIRECTORY_SEPARATOR.$dest); $this->opf->addItem($dest, $id, ['cover-image']); $this->opf->addMeta('meta', '', [ 'name' => 'cover', 'content' => $id ]); } }
Add Cover image @param string $src @param string $dest @param string $id
entailment
public function copy($id, $src, $dist_name = ''){ if( !file_exists($src) ){ throw new CompileException(sprintf('%s doesn\'t exist.', $src)); } if( !$dist_name ){ $dist_name = basename($src); } if( !isset(static::$ids[$id]) ){ static::$ids[$id] = []; } if( false !== array_search($dist_name, static::$ids[$id]) ){ throw new DuplicateException(sprintf('%s is not unique for ePub(%s).', $dist_name, $id)); } static::$ids[$id][] = $dist_name; $distributor = Distributor::get($id); // Move file $rel_path = $this->directory.DIRECTORY_SEPARATOR.$dist_name; $distributor->copy($src, $rel_path); // Return ID return $rel_path; }
Copy file @param string $id @param string $src @param string $dist_name @return string item's relative path @throws DuplicateException @throws CompileException
entailment
public function main() { $email = $this->in('E-mailaddress:'); $password = $this->in('Password: [WILL BE VISIBLE]'); $this->loadModel('CakeAdmin.Administrators'); $entity = $this->Administrators->newEntity([ 'email' => $email, 'password' => $password ]); if ($this->Administrators->save($entity)) { $this->out('<info>Administrator has been saved</info>'); } else { $this->out('<error>Administrator could not be saved. Run $ bin/cake admin to create an admin.</error>'); $this->hr(); foreach ($entity->errors() as $field => $errors) { foreach ($errors as $error) { $this->out('<warning>For field `' . $field . '`: ' . $error . ' </warning>'); } } $this->hr(); } }
main() method. @return void
entailment
public static function get( array $settings = [] ){ $class_name = get_called_class(); if( !isset(self::$instances[$class_name]) ){ self::$instances[$class_name] = new $class_name($settings); } return self::$instances[$class_name]; }
Get instance @param array $settings @return static
entailment
public function beforeFilter(Event $event) { $slug = lcfirst($this->request->params['type']); $this->type = $this->PostTypes->getOption($slug); if (!$this->type) { throw new Exception("The PostType is not registered"); } $this->Model = TableRegistry::get($this->type['model']); // making the current item active $this->Menu->active($this->type['alias']); parent::beforeFilter($event); }
beforeFilter event. @param \Cake\Event\Event $event Event. @return void
entailment
public function beforeRender(Event $event) { parent::beforeRender($event); $this->set('type', $this->type); $this->set('title', $this->type['name']); }
beforeRender event. @param \Cake\Event\Event $event Event. @return void
entailment
public function index($type = null) { $this->_validateActionIsEnabled('index'); $this->_event('beforeIndex'); $this->paginate = [ 'limit' => 25, 'order' => [ ucfirst($this->Model->alias()) . '.id' => 'asc' ] ]; foreach ($this->type['filters'] as $key => $value) { if (is_array($value)) { $this->Search->addFilter($key, $value); } else { $this->Search->addFilter($value); } } $query = $this->_callQuery($this->Model->find('all')); $query = $this->Search->search($query); $this->set('data', $this->paginate($query)); $this->_event('afterIndex'); }
Index method @param string $type The requested PostType. @return void
entailment
public function view($type = null, $id = null) { $this->_validateActionIsEnabled('view'); $this->_event('beforeView', [ 'id' => $id ]); $data = $this->Model->get($id, [ 'contain' => $this->type['contain'] ]); $this->set('data', $data); $this->_event('afterView', [ 'id' => $id ]); }
View method @param string $type The requested PostType. @param string|null $id Post Type id @return void
entailment
public function add($type = null) { $this->_validateActionIsEnabled('add'); $this->_event('beforeAdd'); $entity = $this->Model->newEntity()->accessible('*', true); if ($this->request->is('post')) { $entity = $this->Model->patchEntity($entity, $this->request->data()); if ($this->Model->save($entity)) { $this->Flash->success(__d('CakeAdmin', 'The {0} has been saved.', [$this->type['singularAliasLc']])); return $this->redirect(['action' => 'index', 'type' => $this->type['name']]); } else { $this->Flash->error(__d('CakeAdmin', 'The {0} could not be saved. Please, try again.', [$this->type['singularAliasLc']])); } } $this->_loadAssociations(); $this->set(compact('type', 'entity')); $this->_event('afterAdd'); }
Add method @param string $type The requested PostType. @return void|\Cake\Network\Response
entailment
public function edit($type = null, $id = null) { $this->_validateActionIsEnabled('edit'); $this->_event('beforeEdit', [ 'id' => $id ]); $query = $this->_callQuery($this->Model->findById($id)); $entity = $query->first(); if ($this->request->is(['patch', 'post', 'put'])) { $entity->accessible('*', true); $entity = $this->Model->patchEntity($entity, $this->request->data()); if ($this->Model->save($entity)) { $this->Flash->success(__d('CakeAdmin', 'The {0} has been edited.', [$this->type['singularAliasLc']])); return $this->redirect(['action' => 'index', 'type' => $this->type['name']]); } else { $this->Flash->error(__d('CakeAdmin', 'The {0} could not be edited. Please, try again.', [$this->type['singularAliasLc']])); } } $this->_loadAssociations(); $this->set(compact('type', 'entity')); $this->_event('afterEdit', [ 'id' => $id ]); }
Edit method @param string $type The requested PostType. @param string|null $id Post Type id @return void|\Cake\Network\Response @throws \Cake\Network\Exception\NotFoundException
entailment
public function delete($type = null, $id = null) { $this->_validateActionIsEnabled('delete'); $this->_event('beforeDelete', [ 'id' => $id ]); $entity = $this->Model->get($id); $this->request->allowMethod(['post', 'delete']); if ($this->Model->delete($entity)) { $this->Flash->success(__d('CakeAdmin', 'The {0} has been deleted.', [$this->type['singularAliasLc']])); } else { $this->Flash->error(__d('CakeAdmin', 'The {0} could not be deleted. Please, try again.', [$this->type['singularAliasLc']])); } $this->_event('afterDelete', [ 'id' => $id ]); return $this->redirect(['action' => 'index', 'type' => $this->type['name']]); }
Delete method @param string $type The requested PostType. @param string|null $id Post Type id @return void|\Cake\Network\Response
entailment
protected function _callQuery($query) { $query->contain($this->type['contain']); $extQuery = $this->type['query']; return $extQuery($query); }
Uses the query-callable from the PostType. @param Query $query Query object. @return Query Query object.
entailment
protected function _loadAssociations() { foreach ($this->Model->associations()->getIterator() as $association => $assocData) { $this->set(Inflector::variable($assocData->alias()), $this->Model->{$association}->find('list')->toArray()); } }
Dynamically loads all associations of the model. @return void
entailment
protected function _actionIsEnabled($action) { $actions = $this->type['actions']; if (array_key_exists($action, $actions)) { return $actions[$action]; } return true; }
Checks if the action is enabled. @param string $action Chosen action to check on. @return bool
entailment
protected function _event($action, $data = []) { $_event = new Event('Controller.PostTypes.' . $this->type['name'] . '.' . $action, $this, $data); $this->eventManager()->dispatch($_event); }
Fires an event with the PostType-prefix. @param string $action Current action. @param array $data data that should be sent with the event. @return void
entailment
public static function get($id){ $class_name = get_called_class(); if( !isset(self::$instances[$class_name]) ){ self::$instances[$class_name] = []; } if( !isset(self::$instances[$class_name][$id]) ){ self::$instances[$class_name][$id] = new $class_name($id); } return self::$instances[$class_name][$id]; }
Get instance @param string $id @return static
entailment
public static function formatError($message, $errorValues) { foreach ($errorValues as $token => $value) { $message = preg_replace("/\%$token\%/", $value, $message); } return $message; }
Replaces placeholder tokens in an error message with actual values. This method enables you to internationalize the messages for the File_MARC class by simply replacing the File_MARC_Exception::$messages array with translated values for the messages. @param string $message Error message containing placeholders @param array $errorValues Actual values to substitute for placeholders @return string Formatted message
entailment
public function main() { // CakeAdmin Migration $this->out('Migrating CakeAdmin Tables...'); $this->migrate('CakeAdmin'); $this->out('<info>Migrating CakeAdmin Tables completed!</info>'); $this->hr(); // Notifier Migration $this->out('Migrating Notifier Tables...'); $this->migrate('Notifier'); $this->out('<info>Migrating Notifier Tables completed!</info>'); $this->hr(); // Settings Migration $this->out('Migrating Settings Tables...'); $this->migrate('Settings'); $this->out('<info>Migrating Settings Tables completed!</info>'); $this->hr(); $createAdmin = $this->in('Do you want to create your first administrator?', ['Y', 'n'], 'Y'); if ($createAdmin === 'Y') { $this->out('Generating a new administrator...'); $this->dispatchShell('admin'); } }
main() method. @return void
entailment
protected function _tableExists($table) { $db = ConnectionManager::get('default'); $tables = $db->schemaCollection()->listTables(); return in_array($table, $tables); }
Checks if the table exists. @param string $table Plugin name. @return bool
entailment
public function resetPassword($user) { $from = Configure::read('CA.email.from'); $fullBaseUrl = Setting::read('App.BaseUrl'); $this->domain($fullBaseUrl); $this->viewVars([ 'user' => $user, 'resetUrl' => $fullBaseUrl . '/admin/users/reset/' . $user['email'] . '/' . $user['request_key'], 'baseUrl' => $fullBaseUrl, 'loginUrl' => $fullBaseUrl . '/admin', 'from' => reset($from), ]); $this->template('CakeAdmin.resetPassword', 'CakeAdmin.default'); $this->emailFormat('both'); $this->from($from); $this->to($user['email']); $this->subject(__d('CakeAdmin', 'Forgot Password')); $this->transport(Configure::read('CA.email.transport')); }
resetPassword Sends mail if an user requested a new password. @param \CakeAdmin\Model\Entity\Administrator $user User entity. @return void
entailment
private function _validateIndicator($indicator) { if ($indicator == null) { $indicator = ' '; } elseif (strlen($indicator) > 1) { $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATOR], array("tag" => $this->getTag(), "indicator" => $indicator)); throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_INDICATOR); } return $indicator; }
Validates an indicator field Validates the value passed in for an indicator. This routine ensures that an indicator is a single character. If the indicator value is null, then this method returns a single character. If the indicator value contains more than a single character, this throws an exception. @param string $indicator Value of the indicator to be validated @return string Returns the indicator, or space if the indicator was null
entailment
function insertSubfield(File_MARC_Subfield $new_field, File_MARC_Subfield $existing_field, $before = false) { $this->subfields->insertNode($new_field, $existing_field, $before); return $new_field; }
Inserts a field in the MARC record relative to an existing field Inserts a {@link File_MARC_Subfield} object before or after an existing subfield. @param File_MARC_Subfield $new_field The subfield to add @param File_MARC_Subfield $existing_field The target subfield @param bool $before Insert the subfield before the existing subfield if true; after the existing subfield if false @return File_MARC_Subfield The new subfield
entailment
function addSubfields(array $subfields) { /* * Just in case someone passes in a single File_MARC_Subfield * instead of an array */ if ($subfields instanceof File_MARC_Subfield) { $this->appendSubfield($subfields); return 1; } // Add subfields $cnt = 0; foreach ($subfields as $subfield) { $this->appendSubfield($subfield); $cnt++; } return $cnt; }
Adds an array of subfields to a {@link File_MARC_Data_Field} object Appends subfields to existing subfields in the order in which they appear in the array. For finer grained control of the subfield order, use {@link appendSubfield()}, {@link prependSubfield()}, or {@link insertSubfield()} to add each subfield individually. @param array $subfields array of {@link File_MARC_Subfield} objects @return int returns the number of subfields that were added
entailment
function getIndicator($ind) { if ($ind == 1) { return (string)$this->ind1; } elseif ($ind == 2) { return (string)$this->ind2; } else { $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST], array("indicator" => $indicator)); throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST); } return false; }
Get the value of an indicator @param int $ind number of the indicator (1 or 2) @return string returns indicator value if it exists, otherwise false
entailment
function setIndicator($ind, $value) { switch ($ind) { case 1: $this->ind1 = $this->_validateIndicator($value); break; case 2: $this->ind2 = $this->_validateIndicator($value); break; default: $errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST], array("indicator" => $ind)); throw new File_MARC_Exception($errorMessage, File_MARC_Exception::ERROR_INVALID_INDICATOR_REQUEST); return false; } return $this->getIndicator($ind); }
Set the value of an indicator @param int $ind number of the indicator (1 or 2) @param string $value value of the indicator @return string returns indicator value if it exists, otherwise false
entailment
function getSubfield($code = null, $pcre = null) { // iterate merrily through the subfields looking for the requested code foreach ($this->subfields as $sf) { if (($pcre && preg_match("/$code/", $sf->getCode())) || (!$pcre && $code == $sf->getCode()) ) { return $sf; } } // No matches were found return false; }
Returns the first subfield that matches a requested code. @param string $code subfield code for which the {@link File_MARC_Subfield} is retrieved @param bool $pcre if true, then match as a regular expression @return File_MARC_Subfield returns the first subfield that matches $code, or false if no codes match $code
entailment
function getSubfields($code = null, $pcre = null) { $results = array(); // return all subfields if no specific subfields were requested if ($code === null) { $results = $this->subfields; return $results; } // iterate merrily through the subfields looking for the requested code foreach ($this->subfields as $sf) { if (($pcre && preg_match("/$code/", $sf->getCode())) || (!$pcre && $code == $sf->getCode()) ) { $results[] = $sf; } } return $results; }
Returns an array of subfields that match a requested code, or a {@link File_MARC_List} that contains all of the subfields if the requested code is null. @param string $code subfield code for which the {@link File_MARC_Subfield} is retrieved @param bool $pcre if true, then match as a regular expression @return File_MARC_List|array returns a linked list of all subfields if $code is null, an array of {@link File_MARC_Subfield} objects if one or more subfields match, or an empty array if no codes match $code
entailment
function isEmpty() { // If $this->subfields is null, we must have deleted it if (!$this->subfields) { return true; } // Iterate through the subfields looking for some data foreach ($this->subfields as $subfield) { // Check if subfield has data if (!$subfield->isEmpty()) { return false; } } // It is empty return true; }
Checks if the field is empty. Checks if the field is empty. If the field has at least one subfield with data, it is not empty. @return bool Returns true if the field is empty, otherwise false
entailment
function toRaw() { $subfields = array(); foreach ($this->subfields as $subfield) { if (!$subfield->isEmpty()) { $subfields[] = $subfield->toRaw(); } } return (string)$this->ind1.$this->ind2.implode("", $subfields).File_MARC::END_OF_FIELD; }
Return Field in Raw MARC Return the Field formatted in Raw MARC for saving into MARC files @return string Raw MARC
entailment
function getContents($joinChar = '') { $contents = array(); foreach($this->subfields as $subfield) { $contents[] = $subfield->getData(); } return implode($joinChar, $contents); }
Return fields data content as joined string Return all the fields data content as a joined string @param string $joinChar A string used to join the data conntent. Default is an empty string @return string Joined string
entailment
function next() { if ($this->text) { $marc = $this->_decode($this->text); $this->text = null; return $marc; } else { return false; } }
Return next {@link File_MARC_Record} object Decodes a MARCJSON record and returns the {@link File_MARC_Record} object. There can only be one MARCJSON record per string but we use the next() approach to maintain a unified API with XML and MARC21 readers. <code> <?php // Retrieve a MARC-in-JSON record from a string $json = '{"leader":"01850 2200517 4500","fields":[...]'; $journals = new File_MARCJSON($json); // Iterate through the retrieved records while ($record = $journals->next()) { print $record; print "\n"; } ?> </code> @return File_MARC_Record next record, or false if there are no more records
entailment
private function _decode($text) { $marc = new $this->record_class($this); // Store leader $marc->setLeader($text->leader); // go through all fields foreach ($text->fields as $field) { foreach ($field as $tag => $values) { // is it a control field? if (strpos($tag, '00') === 0) { $marc->appendField(new File_MARC_Control_Field($tag, $values)); } else { // it's a data field -- get the subfields $subfield_data = array(); foreach ($values->subfields as $subfield) { foreach ($subfield as $sf_code => $sf_value) { $subfield_data[] = new File_MARC_Subfield($sf_code, $sf_value); } } // If the data is invalid, let's just ignore the one field try { $new_field = new File_MARC_Data_Field($tag, $subfield_data, $values->ind1, $values->ind2); $marc->appendField($new_field); } catch (Exception $e) { $marc->addWarning($e->getMessage()); } } } } return $marc; }
Decode a given MARC-in-JSON record @param string $text MARC-in-JSON record element @return File_MARC_Record Decoded File_MARC_Record object
entailment
protected function printDbBuildVersion(OutputInterface $output) : void { $output->writeln( sprintf( '<info>Reference Database Version</info> => %s%s', $this->getApplication()->getDbVersions()['build.version'], PHP_EOL ) ); }
Prints the database current build version @param OutputInterface $output Console Output concrete instance @return void
entailment
protected function tableHelper(OutputInterface $output, array $headers, array $rows, string $style = 'compact') : void { $table = new Table($output); $table->setStyle($style) ->setHeaders($headers) ->setRows($rows) ->render() ; }
Helper that convert analyser results to a console table @param OutputInterface $output Console Output concrete instance @param array $headers All table headers @param array $rows All table rows @param string $style The default style name to render tables @return void
entailment
public function execute(OperationInterface $op) { try { if ($op instanceof DeleteOperationInterface) { $response = $this->httpClient->delete($op->getEndpoint(), [ 'headers' => $op->getHeaders(), ]); } elseif ($op instanceof PostOperationInterface) { $response = $this->httpClient->post($op->getEndpoint(), [ 'headers' => $op->getHeaders(), 'body' => $op->getData(), ]); } elseif ($op instanceof PatchOperationInterface) { $response = $this->httpClient->patch($op->getEndpoint(), [ 'headers' => $op->getHeaders(), 'body' => $op->getData(), ]); } elseif ($op instanceof PutOperationInterface) { $response = $this->httpClient->put($op->getEndpoint(), [ 'headers' => $op->getHeaders(), 'body' => $op->getData(), ]); } else { $response = $this->httpClient->get($op->getEndpoint()); } } catch (GuzzleHttp\Exception\ClientException $e) { throw new Exception\ClientException('ClientException occurred in request to Orchestrate: ' . $e->getMessage(), $e->getCode(), $e); } catch (GuzzleHttp\Exception\ServerException $e) { throw new Exception\ServerException('ServerException occurred in request to Orchestrate: ' . $e->getMessage(), $e->getCode(), $e); } $refLink = null; $location = null; if ($response->hasHeader('ETag')) { $refLink = str_replace('"', '', $response->getHeaderLine('ETag')); } elseif ($response->hasHeader('Link')) { $refLink = str_replace( ['<', '>; rel="next"'], ['', ''], $response->getHeaderLine('Link') ); } if ($response->hasHeader('Location')) { $location = $response->getHeaderLine('Location'); } $rawValue = $response->getBody(true); $value = json_decode($rawValue, true); return $op->getObjectFromResponse($refLink, $location, $value, $rawValue); }
Execute an operaction A successful operation will return result as an array. An unsuccessful operation will return null. @param OperationInterface $op @return array|null
entailment
protected function setCookie($value, array $params) { if (headers_sent()) { throw new TokenStorageException('Cannot store CSRF token, headers already sent'); } return setcookie( $params['name'], $value, $params['expire'], $params['path'], $params['domain'], $params['secure'], $params['httpOnly'] ); }
Sets the cookie that stores the secret CSRF token. @param string $value The value for the cookie @param array $params Parameters for the cookie @return bool True if the cookie was set successfully, false if not @throws TokenStorageException If the headers have already been sent @codeCoverageIgnore
entailment
public function initialize(array $config) { $this->setController($this->_registry->getController()); $this->_registerPostTypesFromConfigure(); $this->_addMenuItems(); }
Initialize component. @param array $config Configuration. @return void
entailment
public function register($model, $options = []) { $postTypes = Configure::read('CA.PostTypes'); $_defaults = [ 'model' => $model, 'menu' => true, 'menuWeight' => 20, 'slug' => lcfirst(Inflector::slug(pluginSplit($model)[1])), 'name' => ucfirst(Inflector::slug(pluginSplit($model)[1])), 'alias' => ucfirst(Inflector::humanize(pluginSplit($model)[1])), 'aliasLc' => lcfirst(Inflector::humanize(pluginSplit($model)[1])), 'singularAlias' => ucfirst(Inflector::singularize(Inflector::humanize(pluginSplit($model)[1]))), 'singularAliasLc' => lcfirst(Inflector::singularize(Inflector::humanize(pluginSplit($model)[1]))), 'description' => null, 'actions' => [ 'index' => true, 'add' => true, 'edit' => true, 'view' => true, 'delete' => true, ], 'filters' => [], 'contain' => [], 'query' => function ($query) { return $query; }, 'tableColumns' => false, 'formFields' => false, ]; $options = array_merge($_defaults, $options); if (!$options['tableColumns']) { $options['tableColumns'] = $this->_generateTableColumns($model); } if (!$options['formFields']) { $options['formFields'] = $this->_generateFormFields($model); } # model is able to disable the PostType to register by returning false $modelOptions = $this->_getOptionsFromModel($options['model']); if ($modelOptions === false) { return; } $options = array_merge($options, $modelOptions); if ($options['formFields']) { $options['formFields'] = $this->_normalizeFormFields($options['formFields']); } if ($options['tableColumns']) { $options['tableColumns'] = $this->_normalizeTableColumns($options['tableColumns']); } $postTypes[$options['slug']] = $options; Configure::write('CA.PostTypes', $postTypes); }
register Registers a new PostType. The default options will be merged with the given options. After that, the type will be saved in the Configure-class. @param string $model Model to make a PostType off. @param array $options Options. @return void
entailment
public function getOption($name, $option = null) { $postTypes = Configure::read('CA.PostTypes'); if (array_key_exists($name, $postTypes)) { if ($option) { if (array_key_exists($option, $postTypes[$name])) { return $postTypes[$name][$option]; } } return $postTypes[$name]; } return false; }
getOption Return single option, or all options per PostType. @param string $name Name of the PostType. @param string $option String of the named option. @return array|bool
entailment
protected function _addMenuItems() { $postTypes = Configure::read('CA.PostTypes'); $this->Controller->Menu->area('main'); foreach ($postTypes as $name => $options) { if ($options['menu']) { $this->Controller->Menu->add($options['alias'], [ 'url' => [ 'prefix' => 'admin', 'plugin' => 'CakeAdmin', 'controller' => 'PostTypes', 'action' => 'index', 'type' => $options['slug'] ], 'weight' => $options['menuWeight'] ]); } } }
_addMenuItems Adds menu-items of every PostType to the 'main' menu. @return void
entailment
protected function _getOptionsFromModel($model) { $model = TableRegistry::get($model); if (method_exists($model, 'postType')) { $result = $model->postType(); if ($result) { $result['table'] = $model->table(); } return $result; } if (property_exists($model, 'postType')) { $result = $model->postType; if ($result) { $result['table'] = $model->table(); } return $result; } return []; }
_getOptionsFromModel Returns a list of options token from the model. @param string $model The model to use. @return array|null|bool
entailment
protected function _registerPostTypesFromConfigure() { $configure = Configure::read('CA.Models'); foreach ($configure as $name => $model) { $this->register($model); } }
_registerPostTypesFromConfigure Registers the PostTypes added via the Configure-class. The PostType should be added via `CA.Models`. @return void
entailment