/** * @test * @covers ::getSignal * @covers \Hamdrew\AdventOfCode\Day7\CircuitComponent::getSignal * @covers \Hamdrew\AdventOfCode\Day7\CircuitComponent::setSignal */ public function returnsCachedSignal() { $signal = 123; $source = \Mockery::mock('\\Hamdrew\\AdventOfCode\\Day7\\CircuitComponent')->shouldReceive('getSignal')->andReturn($signal)->once()->getMock(); $wire = new Wire('test', $source); $wire->getSignal(); $this->assertSame($signal, $wire->getSignal()); }
/** * Get hooks debug info for the given Wire object * * @param Wire $obj * @return array * */ public function getHooksInfo(Wire $obj) { $hooks = array(); foreach ($obj->getHooks() as $hook) { list($class, $priority) = explode(':', $hook['id']); $key = ''; $value = ''; if ($hook['options']['before']) { $key .= "before "; } if ($hook['options']['type'] == 'property') { $key .= "property "; } else { if ($hook['options']['after']) { if (method_exists($class, $hook['method']) || method_exists($class, '___' . $hook['method'])) { $key .= "after "; } } } if ($hook['options']['type'] == 'property' || !$hook['options']['allInstances']) { $key .= "{$class}" . '->' . "{$hook['method']}"; } else { $key .= "{$class}::{$hook['method']}"; } $filename = ''; if (!empty($hook['toObject'])) { $value .= $hook['toObject']->className() . "->"; $ref = new ReflectionClass($hook['toObject']); $filename = $ref->getFileName(); } if (!empty($hook['toMethod'])) { if (is_string($hook['toMethod'])) { $value .= "{$hook['toMethod']}()"; } else { if (is_callable($hook['toMethod'])) { $ref = new ReflectionFunction($hook['toMethod']); $filename = $ref->getFileName(); $value = "anonymous function()"; } } } if ($filename) { $value .= " in " . basename($filename); } if (!isset($hooks[$key])) { $hooks[$key] = $value; } else { if (!is_array($hooks[$key])) { $hooks[$key] = array($hooks[$key]); } $hooks[$key][] = $value; } } return $hooks; }
/** * @inheritDoc */ public function getSignal() { $signal = parent::getSignal(); if (is_null($signal)) { $input = $this->source->getSignal(); if (!is_null($input)) { $signal = SixteenBitMask::mask(~$input); $this->setSignal($signal); } } return $signal; }
/** * Return all Fuel, or specified ProcessWire API variable, or NULL if it doesn't exist. * * Same as Wire::getFuel($name) and Wire::getAllFuel(); * When a $name is specified, this function is identical to the wire() function. * Both functions exist more for consistent naming depending on usage. * * @param string $name If ommitted, returns a Fuel object with references to all the fuel. * @return mixed Fuel value if available, NULL if not. * */ function fuel($name = '') { if (!$name) { return Wire::getAllFuel(); } return Wire::getFuel($name); }
/** * Perform a language translation * * @param string $text Text for translation. * @param string $textdomain Textdomain for the text, may be class name, filename, or something made up by you. If ommitted, a debug backtrace will attempt to determine it automatically. * @param string $context Name of context - DO NOT USE with this function for translation as it won't be parsed for translation. Use only with the _x() function, which will be parsed. * @return string Translated text or original text if translation not available. * * */ function __($text, $textdomain = null, $context = '') { if (!Wire::getFuel('languages')) { return $text; } if (!($language = Wire::getFuel('user')->language)) { return $text; } if (!$language->id) { return $text; } if (is_null($textdomain)) { $traces = @debug_backtrace(defined('DEBUG_BACKTRACE_IGNORE_ARGS') ? DEBUG_BACKTRACE_IGNORE_ARGS : false); if (isset($traces[0]) && $traces[0]['file'] != __FILE__) { $textdomain = $traces[0]['file']; } else { if (isset($traces[1]) && $traces[1]['file'] != __FILE__) { $textdomain = $traces[1]['file']; } } if (is_null($textdomain)) { $textdomain = 'site'; } } return htmlspecialchars($language->translator()->getTranslation($textdomain, $text, $context), ENT_QUOTES, 'UTF-8'); }
/** * Add fuel to all classes descending from Wire * * @param string $name * @param mixed $value * */ public static function setFuel($name, $value) { if (is_null(self::$fuel)) { self::$fuel = new Fuel(); } self::$fuel->set($name, $value); }
public function __get($key) { if ($key == 'delimiter') { return $this->delimeter; } // @todo learn how to spell return parent::__get($key); }
public function setCurrentUser(User $user) { if (!$user->roles->has("id=" . $this->fuel('config')->guestUserRolePageID)) { $guestRole = $this->fuel('roles')->getGuestRole(); $user->roles->add($guestRole); } $this->currentUser = $user; Wire::setFuel('user', $user); }
/** * Perform a language translation * * If no context provided then a global context is assumed * */ function __($context, $text = null) { if (is_null($text)) { $text = $context; $context = null; } if (!Wire::getFuel('languages')) { return $text; } if (!($language = Wire::getFuel('user')->language)) { return $text; } return $language->translator()->getTranslation($context, $text); }
/** * Set the current system user (the $user API variable) * * @param User $user * */ public function setCurrentUser(User $user) { $hasGuest = false; $guestRoleID = $this->wire('config')->guestUserRolePageID; if ($user->roles) { foreach ($user->roles as $role) { if ($role->id == $guestRoleID) { $hasGuest = true; break; } } } if (!$hasGuest && $user->roles) { $guestRole = $this->wire('roles')->getGuestRole(); $user->roles->add($guestRole); } $this->currentUser = $user; Wire::setFuel('user', $user); }
/** * Returns true if the method/property hooked, false if it isn't. * * This is for optimization use. It does not distinguish about class instance. * It only distinguishes about class if you provide a class with the $method argument (i.e. Class::). * As a result, a true return value indicates something "might" be hooked, as opposed to be * being definitely hooked. * * If checking for a hooked method, it should be in the form "Class::method()" or "method()". * If checking for a hooked property, it should be in the form "Class::property" or "property". * * @param string $method Method or property name in one of the following formats: * Class::method() * Class::property * method() * property * @param Wire|null $instance Optional instance to check against (see isThisHooked method for details) * Note that if specifying an $instance, you may not use the Class::method() or Class::property options for $method argument. * @return bool * */ public static function isHooked($method, Wire $instance = null) { if ($instance) { return $instance->hasHook($method); } $hooked = false; if (strpos($method, ':') !== false) { if (array_key_exists($method, self::$hookMethodCache)) { $hooked = true; } // fromClass::method() or fromClass::property } else { if (in_array($method, self::$hookMethodCache)) { $hooked = true; } // method() or property } return $hooked; }
/** * Render an object to a string * * @param Wire|object $value * @return string * */ protected function objectToString($value) { if ($value instanceof WireArray && !$value->count()) { return ''; } if ($value instanceof Page) { return $value->get('title|name'); } if ($value instanceof Pagefiles || $value instanceof Pagefile) { $out = $this->renderInputfieldValue($value); } else { $className = get_class($value); $out = (string) $value; if ($out === $className) { // just the class name probably isn't useful here, see if we can do do something else with it $this->renderIsUseless = true; } } return $out; }
public function __get($key) { if ($key == 'pdo') { return $this->pdo; } return parent::__get($key); }
public function error($text, $flags = 0) { $this->errors[] = $text; parent::error($text, $flags); }
/** * Save the template to database * * @return $this|bool Returns Template if successful, or false if not * */ public function save() { $result = Wire::getFuel('templates')->save($this); return $result ? $this : false; }
/** * Initialize the given API var * * @param string $name * @param Wire $value * */ protected function initVar($name, $value) { if ($this->debug) { Debug::timer("boot.load.{$name}"); } $value->init(); if ($this->debug) { Debug::saveTimer("boot.load.{$name}"); } }
public function testCanSetAndGetSignal() { $wire = new Wire('a'); $wire->setSignal(123); $this->assertEquals(123, $wire->getSignal()); }
/** * Sets the current users * * @param User $user * @return this * */ public function setCurrentUser(User $user) { $this->currentUser = $user; Wire::setFuel('user', $user); return $this; }
public function __debugInfo() { $info = parent::__debugInfo(); foreach ($this->wire('languages') as $language) { $info[$language->name] = isset($this->data[$language->id]) ? $this->data[$language->id] : ''; } return $info; }
/** * Save to pages activity log, if enabled in config * * @param $str * @param Page|null Page to log * @return WireLog * */ public function log($str, Page $page) { if (!in_array('pages', $this->wire('config')->logs)) { return parent::___log(); } if ($this->wire('process') != 'ProcessPageEdit') { $str .= " [From URL: " . $this->wire('input')->url() . "]"; } $options = array('name' => 'pages', 'url' => $page->path); return parent::___log($str, $options); }
/** * Get or inject a ProcessWire API variable * * 1. As a getter (option 1): * ========================== * Usage: $this->wire('name'); // name is an API variable name * If 'name' does not exist, a WireException will be thrown. * Specify '*' or 'all' for name to retrieve all API vars (as a Fuel object) * * 2. As a getter (option 2): * ========================== * Usage: $this->wire()->name; // name is an API variable name * Null will be returned if API var does not exist (no Exception thrown). * * 3. As a setter: * =============== * $this->wire('name', $value); * $this->wire('name', $value, true); // lock the API variable so nothing else can overwrite it * $this->wire()->set('name', $value); * $this->wire()->set('name', $value, true); // lock the API variable so nothing else can overwrite it * * 4. As a dependency injector (PW 3.0 only) * ========================================= * $this->wire(new Page()); * When creating a new object, this makes it inject the current PW instance into that object. * * @param string|object $name Name of API variable to retrieve, set, or omit to retrieve the master ProcessWire object * @param null|mixed $value Value to set if using this as a setter, otherwise omit. * @param bool $lock When using as a setter, specify true if you want to lock the value from future changes (default=false) * @return ProcessWire|Wire|Session|Page|Pages|Modules|User|Users|Roles|Permissions|Templates|Fields|Fieldtypes|Sanitizer|Config|Notices|WireDatabasePDO|WireInput|string|mixed * @throws WireException * * */ public function wire($name = '', $value = null, $lock = false) { if (is_null(self::$fuel)) { self::$fuel = new Fuel(); } if ($value !== null) { // setting a fuel value return self::$fuel->set($name, $value, $lock); } if (empty($name)) { // return ProcessWire instance return self::$fuel->wire; } else { if ($name === '*' || $name === 'all') { // return Fuel instance return self::$fuel; } } /* TBA PW3 if(is_object($name)) { // injecting ProcessWire instance to object if($name instanceof Wire) return $name->setWire($this->_wire); // inject fuel, PW 3.0 throw new WireException("Expected Wire instance"); } */ // get API variable $value = self::$fuel->{$name}; return $value; }
public function __call($method, $arguments) { if (method_exists($this, "___{$method}")) { return parent::__call($method, $arguments); } $value = $this->__get($method); if (is_object($value)) { return call_user_func_array(array($value, '__invoke'), $arguments); } return parent::__call($method, $arguments); }
public function __get($key) { $value = $this->get($key); if (is_null($value)) { $value = parent::__get($key); } return $value; }
/** * Include a PHP file passing it all API variables and optionally your own specified variables * * This is the same as PHP's include() function except for the following: * - It receives all API variables and optionally your custom variables * - If your filename is not absolute, it doesn't look in PHP's include path, only in the current dir. * - It only allows including files that are part of the PW installation: templates, core modules or site modules * - It will assume a ".php" extension if filename has no extension. * * Note this function produced direct output. To retrieve output as a return value, use the * wireTemplateFile function instead. * * @param $filename * @param array $vars Optional variables you want to hand to the include (associative array) * @param array $options Array of options to modify behavior: * - func: Function to use: include, include_once, require or require_once (default=include) * - autoExtension: Extension to assume when no ext in filename, make blank for no auto assumption (default=php) * - allowedPaths: Array of paths include files are allowed from. Note current dir is always allowed. * @return bool Returns true * @throws WireException if file doesn't exist or is not allowed * */ function wireIncludeFile($filename, array $vars = array(), array $options = array()) { $paths = wire('config')->paths; $defaults = array('func' => 'include', 'autoExtension' => 'php', 'allowedPaths' => array($paths->templates, $paths->adminTemplates, $paths->modules, $paths->siteModules)); $options = array_merge($defaults, $options); $filename = trim($filename); if (DIRECTORY_SEPARATOR != '/') { $filename = str_replace(DIRECTORY_SEPARATOR, '/', $filename); } // add .php extension if filename doesn't already have an extension if ($options['autoExtension'] && !strrpos(basename($filename), '.')) { $filename .= "." . $options['autoExtension']; } if (strpos($filename, '..') !== false) { // if backtrack/relative components, convert to real path $_filename = $filename; $filename = realpath($filename); if ($filename === false) { throw new WireException("File does not exist: {$_filename}"); } } if (strpos($filename, '//') !== false) { throw new WireException("File is not allowed (double-slash): {$filename}"); } if (strpos($filename, './') !== 0) { // file does not specify "current directory" $slashPos = strpos($filename, '/'); // If no absolute path specified, ensure it only looks in current directory if ($slashPos !== 0 && strpos($filename, ':/') === false) { $filename = "./{$filename}"; } } if (strpos($filename, '/') === 0 || strpos($filename, ':/') !== false) { // absolute path, make sure it's part of PW's installation $allowed = false; foreach ($options['allowedPaths'] as $path) { if (strpos($filename, $path) === 0) { $allowed = true; } } if (!$allowed) { throw new WireException("File is not in an allowed path: {$filename}"); } } if (!file_exists($filename)) { throw new WireException("File does not exist: {$filename}"); } // extract all API vars $fuel = array_merge(Wire::getAllFuel()->getArray(), $vars); extract($fuel); // include the file $func = $options['func']; if ($func == 'require') { require $filename; } else { if ($func == 'require_once') { require_once $filename; } else { if ($func == 'include_once') { include_once $filename; } else { include $filename; } } } return true; }
/** * Get the value of $property from $item * * Used by the WireArray::sort method to retrieve a value from a Wire object. * If output formatting is on, we turn it off to ensure that the sorting * is performed without output formatting. * * @param Wire $item * @param string $property * @return mixed * */ protected function getItemPropertyValue(Wire $item, $property) { if ($item instanceof Page) { $value = $item->getUnformatted($property); } else { if (strpos($property, '.') !== false) { $value = WireData::_getDot($property, $item); } else { if ($item instanceof WireArray) { $value = $item->getProperty($property); if (is_null($value)) { $value = $item->first(); $value = $this->getItemPropertyValue($value, $property); } } else { $value = $item->{$property}; } } } if (is_array($value)) { $value = implode('|', $value); } return $value; }
/** * Handle non-function versions of some properties * */ public function __get($key) { if ($key == 'path') { return $this->path(); } if ($key == 'url') { return $this->url(); } if ($key == 'page') { return $this->page; } return parent::__get($key); }
/** * Record an error message in the error log (errors.txt) * * Note: Fatal errors should instead throw a WireException. * * @param string $text * @param int|bool $flags Specify boolean true to also display the error interactively (admin only). * @return $this * */ public function error($text, $flags = 0) { $flags = $flags === true ? Notice::log : $flags | Notice::logOnly; return parent::error($text, $flags); }
/** * Record a warning message in the warnings log (warnings.txt) * * @param string $text * @param int|bool $flags Specify boolean true to also display the warning interactively (admin only). * @return $this * */ public function warning($text, $flags = 0) { $flags = $flags === true ? Notice::log : $flags | Notice::logOnly; return parent::warning($text, $flags); }
$event->arguments(0, $url); } } // ensure core jQuery modules are loaded before others $modules->get("JqueryCore"); $modules->get("JqueryUI"); // tell ProcessWire that any pages loaded from this point forward should have their outputFormatting turned off $pages->setOutputFormatting(false); // setup breadcrumbs to current page, and the Process may modify, add to or replace them as needed $breadcrumbs = new Breadcrumbs(); foreach ($page->parents() as $p) { if ($p->id > 1) { $breadcrumbs->add(new Breadcrumb($p->url, $p->get("title|name"))); } } Wire::setFuel('breadcrumbs', $breadcrumbs); $controller = null; $content = ''; // enable modules to output their own ajax responses if they choose to if ($config->ajax) { ob_start(); } if ($page->process && $page->process != 'ProcessPageView') { try { if ($config->demo && !in_array($page->process, array('ProcessLogin'))) { if (count($_POST)) { $this->error("Saving is disabled in this demo"); } foreach ($_POST as $k => $v) { unset($_POST[$k]); }
/** * Clears out any tracked changes and turns change tracking ON or OFF * * @param bool $trackChanges True to turn change tracking ON, or false to turn OFF. Default of true is assumed. * @return this * */ public function resetTrackChanges($trackChanges = true) { $this->itemsAdded = array(); $this->itemsRemoved = array(); return parent::resetTrackChanges($trackChanges); }