Generate cover
Yields an estimated percentage slice of: 20 - 100

@see pressbooks/templates/admin/generator.php

@param string $format

@return \Generator
@throws \Exception
168621
public static function formGenerator( $format ) : \Generator {
		wp_cache_delete( 'pressbooks_cg_options', 'options' ); // WordPress Core caches this key in the "options" group
		wp_cache_delete( 'alloptions', 'options' );
		$cg_options = get_option( 'pressbooks_cg_options' );

		yield 20 => __( 'Calculating spine width', 'pressbooks' );
		if ( isset( $cg_options['pdf_pagecount'] ) ) {
			$pages = $cg_options['pdf_pagecount'];
		} else {
			$spine = new Spine;
			$pages = $spine->countPagesInMostRecentPdf();
		}
		if ( isset( $cg_options['ppi'] ) ) {
			$ppi = $cg_options['ppi'];
		} else {
			$ppi = 444;
		}
		$spine = new Spine();
		$spine_width = $spine->spineWidthCalculator( $pages, $ppi );
		$spine_width = "{$spine_width}in"; // Inches, float to CSS string

		yield 30 => __( 'Creating barcode', 'pressbooks' );
		// Either ISBN or SKU, not both
		if ( isset( $cg_options['pb_print_isbn'] ) && '' !== trim( $cg_options['pb_print_isbn'] ) ) {
			$isbn_url = ( new Isbn() )->createBarcode( $cg_options['pb_print_isbn'] );
		} elseif ( isset( $cg_options['pb_print_sku'] ) && '' !== trim( $cg_options['pb_print_sku'] ) ) {
			$isbn_url = ( new Sku() )->createBarcode( $cg_options['pb_print_sku'] );
		}

		yield 40 => __( 'Loading metadata', 'pressbooks' );
		$input = new Input();
		$input->setTitle( $cg_options['pb_title'] );
		if ( $pages >= 48 ) {
			if ( isset( $cg_options['pb_title_spine'] ) && '' !== $cg_options['pb_title_spine'] ) {
				$input->setSpineTitle( $cg_options['pb_title_spine'] );
			} else {
				$input->setSpineTitle( $cg_options['pb_title'] );
			}
		}
		if ( isset( $cg_options['pb_subtitle'] ) && '' !== $cg_options['pb_subtitle'] ) {
			$input->setSubtitle( $cg_options['pb_subtitle'] );
		}
		$input->setAuthor( $cg_options['pb_author'] );
		if ( $pages >= 48 ) {
			if ( isset( $cg_options['pb_author_spine'] ) && '' !== $cg_options['pb_author_spine'] ) {
				$input->setSpineAuthor( $cg_options['pb_author_spine'] );
			} else {
				$input->setSpineAuthor( $cg_options['pb_author'] );
			}
		}
		if ( isset( $cg_options['pb_about_unlimited'] ) && '' !== $cg_options['pb_about_unlimited'] ) {
			$input->setAbout( $cg_options['pb_about_unlimited'] );
		}
		if ( isset( $cg_options['text_transform'] ) && '' !== $cg_options['text_transform'] ) {
			$input->setTextTransform( $cg_options['text_transform'] );
		}

		$pdf_options = get_option( 'pressbooks_theme_options_pdf' );

		$input->setTrimHeight( $pdf_options['pdf_page_height'] );
		$input->setTrimWidth( $pdf_options['pdf_page_width'] );
		$input->setSpineWidth( $spine_width );
		if ( isset( $cg_options['front_cover_text'] ) ) {
			$input->setFrontFontColor( $cg_options['front_cover_text'] );
		}
		if ( isset( $cg_options['front_cover_background'] ) ) {
			$input->setFrontBackgroundColor( $cg_options['front_cover_background'] );
		}
		if ( isset( $cg_options['spine_text'] ) ) {
			$input->setSpineFontColor( $cg_options['spine_text'] );
		}
		if ( isset( $cg_options['spine_background'] ) ) {
			$input->setSpineBackgroundColor( $cg_options['spine_background'] );
		}
		if ( isset( $cg_options['back_cover_text'] ) ) {
			$input->setBackFontColor( $cg_options['back_cover_text'] );
		}
		if ( isset( $cg_options['back_cover_background'] ) ) {
			$input->setBackBackgroundColor( $cg_options['back_cover_background'] );
		}
		if ( isset( $cg_options['front_background_image'] ) ) {
			$input->setFrontBackgroundImage( \Pressbooks\Sanitize\maybe_https( $cg_options['front_background_image'] ) );
		}
		if ( isset( $isbn_url ) ) {
			$input->setIsbnImage( $isbn_url );
		}

		yield 50 => __( 'Generating cover', 'pressbooks' );
		if ( 'pdf' === $format && defined( 'DOCRAPTOR_API_KEY' ) ) {
			$pdf = new DocraptorPdf( $input );
			$pdf->generate();
		} elseif ( 'pdf' === $format ) {
			$pdf = new PrincePdf( $input );
			$pdf->generate();
		} elseif ( 'jpg' === $format && defined( 'DOCRAPTOR_API_KEY' ) ) {
			$jpg = new DocraptorJpg( $input );
			$jpg->generate();
		} elseif ( 'jpg' === $format ) {
			$jpg = new PrinceJpg( $input );
			$jpg->generate();
		}

		yield 100 => __( 'Finishing up', 'pressbooks' );
	}
513393
public function parseFormat($format)
  {
    $this->keys = array();

    $regex = '';
    $curr = '';
    $beforeGroup = '';
    $afterGroup = '';

    $split = str_split($format);
    $count = count($split);
    for ($i=0; $i<$count; $i++) {
      $c = $split[$i];
      if ($c == '{') {
        $regex .= preg_quote($curr, '/');
        $curr = '';
        if ($i+1 < $count && $split[$i+1] == '{') {
          $beforeGroup = $i != 0 ? $split[$i-1] : '';
          $i++;
          continue;
        }
      } else if ($c == '}' && ($i+1 < $count && $split[$i+1] == '}')) {
        $afterGroup = $i+2 < $count ? $split[$i+2] : '';
        $regex .= $this->parseCapturingGroup(trim($curr), $beforeGroup, $afterGroup);
        $curr = '';
        $i++;
        continue;
      }
      $curr .= $c;
    }

    if (empty($this->keys)) {
      throw new \InvalidArgumentException('$format must have at least one capturing group');
    }

    # use /s flag so that wildcard char also matches "\n"
    $this->regex = '/^' . $regex . preg_quote($curr, '/') . '$/s';
  }
335222
public function timeRange(string $format = TimeOfDay::DEFAULT_FORMAT) : FieldBuilderBase
    {
        return $this->field->type(new TimeRangeType($format));
    }
368651
protected function getTemplate($format)
    {
        if (!isset($this->formatFilePaths[$format])) {
            throw new \Exception(sprintf('No format "%s" configured for Snippet export', $format));
        }

        $templatePath = $this->formatFilePaths[$format];

        if (!$this->templating->exists($templatePath)) {
            throw new \Exception(sprintf('No template file "%s" found for Snippet export', $format));
        }

        return $templatePath;
    }
1072339
protected function colorizeCoverage($coverage, $format)
    {
        if ($coverage >= 90) {
            return sprintf('<info>%s</info>', $format);
        }

        if ($coverage >= 80) {
            return sprintf('<comment>%s</comment>', $format);
        }

        return sprintf('<fg=red>%s</fg=red>', $format);
    }
1111948
protected function stashCustomFormatOptions(&$format) {
		$format = str_replace($this->formatOptionsNames, $this->formatOptionsPlaceholders, $format, $count);
		return (bool)$count;
	}
950305
private function getException($format, $args = [])
    {
        /** @var FormatterHelper $formatter */
        $formatter = $this->getHelperSet()->get('formatter');
        return new \InvalidArgumentException($formatter->formatBlock(vsprintf($format, $args), 'bg=red', true));
    }
466065
public static function create(string $format = SerializerBuilder::DEFAULT_FORMAT) : SerializerInterface
    {
        return SerializerBuilder::instance()->setFormat($format)->build();
    }
1201140
public function setJsonFormat($format) {
        if (!is_string($format)) throw new \Exception("JsonFormat must be a valid json string or a path to a file");

        if (file_exists($format)) {
            $handler = fopen($format, 'r');
            $contents = fread($handler, filesize($format));
            fclose($handler);

            $format = $contents;
        }
        $format = trim($format);

        $arrayFormatCandidate = json_decode($format, true, 1024);

        $error = json_last_error();
        if ($error === JSON_ERROR_NONE) {
            $this->setFormat($arrayFormatCandidate);
            return true;
        }

        throw new \Exception("Invalid Json format or file");
    }
683439
public function getProgressBarFormat($format)
    {
        return $this->displayBelow(function () use (&$format) {
            $tree = $this->getTree().$this->getFork();

            $format = explode(PHP_EOL, $format);
            $format = $tree.implode(PHP_EOL.$tree.' ', $format);

            return $format;
        }, 2);
    }
756018
public function format($format)
    {
        $pad    = false;
        $rChar  = 'hmsfHMS';
        $string = $this->format = $format;
        $string = static::encode($string, $rChar);

        // Perform rounding.
        $this->round = static::maxRound($format);

        // Decimal years, weeks, days, hours, minutes, and seconds
        static::fmtRep('Y', $string, $this->years);
        static::fmtRep('W', $string, $this->weeks);
        static::fmtRep('D', $string, $this->days);
        static::fmtRep('H', $string, $this->hours);
        static::fmtRep('M', $string, $this->min);
        static::fmtRep('S', $string, $this->sec);

        // Leading zeros h m s
        $string = str_replace('0h', sprintf('%02d', $this->h), $string);
        $string = str_replace('0m', sprintf('%02d', $this->m), $string);
        $string = str_replace('0s', sprintf('%02d', $this->s), $string);

        // No leading zeros, h m s
        $string = str_replace('h', $this->h, $string);
        $string = str_replace('m', $this->m, $string);
        $string = str_replace('s', $this->s, $string);

        // Fractional seconds.
        if (preg_match_all('/([0-9])f/', $string, $m)) {
            for ($i = 0; $i < count($m[0]); $i++) {
                $f = substr($this->f, 0, $m[1][$i]);

                if ($pad) {
                    $f      = str_pad($f, $m[1][$i], '0');
                    $string = str_replace($m[0][$i], $f, $string);
                } else {
                    if ($f == 0) {
                        $string = str_replace('.' . $m[0][$i], '', $string);
                        $string = str_replace($m[0][$i], '', $string);
                    } else {
                        $string = str_replace($m[0][$i], $f, $string);
                    }
                }
            }
        }

        return static::decode($string, $rChar);
    }
994203
public function format(string $format) : self
    {
        if (! in_array($format, self::VALID_FORMATS)) {
            throw new Exception('Invalid format provided to path.');
        }

        $this->format = $format;

        return $this;
    }
71623
public function format($format = 'EAN')
    {
        if (!$this->isValid()) {
            throw new \Exception('Cannot format invalid ISBN: '.$this->getErrors());
        }

        $this->calculateChecksum($format);

        $A = $this->getProduct();
        $B = $this->getCountry();
        $C = $this->getPublisher();
        $D = $this->getPublication();
        $E = $this->getChecksum();

        if ($format == 'ISBN-10') {
            return $B.'-'.$C.'-'.$D.'-'.$E;
        } elseif ($format == 'ISBN-13' || $format == 'ISBN') {
            return $A.'-'.$B.'-'.$C.'-'.$D.'-'.$E;
        } else {
            return $A.$B.$C.$D.$E;
        }
    }
847785
public function getCachedAt(string $format): ?int
    {
        $cachedAt = $this->cachedState[$format] ?? null;
        if ($cachedAt <= 0) {
            $cachedAt = null;
        }

        return $cachedAt;
    }
525208
public function setFormat($format)
    {
        switch ($format) {
            case self::FORMAT_BASE32:
                $this->encoder = new Base32Encoder();
                break;
            case self::FORMAT_HEX:
                $this->encoder = new HexEncoder();
                break;
            case self::FORMAT_RAW:
            default:
                $this->encoder = new RawEncoder();
        }

        return $this;
    }
190186
public function getTime(?int $format = null): float
    {
        $result = $this->endTime - $this->startTime;

        return $this->formatTime($result, $format);
    }
905167
public function getDateTimeFormat(string $format='Y-m-d H:i:s')
    {
        $this->setDateTimeZone()->setDateTime();

        return $this->dateTime->format($format);
    }