Laravel How can I have if statements in a factory? - laravel

Currently trying to have my factory only fill in certain columns based on the product type. Is it even possible to do this in the first place? Thanks in advance.
Here is my code:
class ProductFactory extends Factory
{
protected $model = Product::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
$productType = ProductType::all();
$products = [[
'type_id'=>$productType->random()->id,
'name'=>$this->faker->catchPhrase,
'description'=>$this->faker->paragraph (2, true),
'price'=>$this->faker->randomFloat(2,5,20),
'stock'=>$this->faker->numberBetween(1,100),
]];
foreach($products as $key=>$product){
if($product['type_id'] = 1){
$product[$key]['pagelength'] = $this->faker->randomFloat(3,100,500);
}
elseif($product['type_id'] = 2){
$product[$key]['playlength']=$this->faker->randomFloat(2,40,140);
}
if($product['type_id'] = 3){
$product[$key]['pegi']=$this->faker->randomFloat(1,1,10);
}
}
}
}

The definition method in a factory is responsible to create a single record/instance/array of the model. So the definition shouldn't have a collection $products
Try the below which I guess will help you achieve what you want
class ProductFactory extends Factory
{
protected $model = Product::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
$productTypes = ProductType::all();
$productType = $productTypes->random()->id;
$product = [
'type_id'=>$productType,
'name'=>$this->faker->catchPhrase,
'description'=>$this->faker->paragraph (2, true),
'price'=>$this->faker->randomFloat(2,5,20),
'stock'=>$this->faker->numberBetween(1,100),
];
if($productType === 1) {
$product['pagelength'] = $this->faker->randomFloat(3,100,500);
}
if($productType === 2) {
$product['playlength'] = $this->faker->randomFloat(2,40,140);
}
if($productType === 3) {
$product['pegi'] = $this->faker->randomFloat(1,1,10);
}
return $product;
}
}

Related

Laravel Eloquent, "inheritance" override fields from parent

Is there any way in Eloquent to have a model which has some sort of parent model, where both have an identical field, nullable on the child. And if I get the value $child->field I get the childs value if it's not null, otherwise I get the parent value? Something like this:
$parent = new Parent();
$parent->info = 'parent';
$parent->save();
$child = new Child();
$child->info = 'child';
$child->parent()->associate($parent);
$child->save();
echo $child->info
Prints 'child'
And opposite:
$parent = new Parent();
$parent->info = 'parent';
$parent->save();
$child = new Child();
$child->parent()->associate($parent);
$child->info = null;
$child->save();
echo $child->info
Prints 'parent'
It must be a pattern somewhere to have one table rows values 'overrule' another, I just can't seem to find what to search for.
You simply need a custom accessor on the model of your choice:
class Child
{
public function getInfoAttribute($value)
{
if ($value === null) {
return $this->parent->info;
}
return $value;
}
}
This will allow you to still access the property via $child->info.
Please be aware that this will not cast the attribute value according to the $casts array. If you need this casting logic as well, you should use a custom getter method instead of the magic accessor:
class Child
{
public function getInfo()
{
$info = $this->info;
if ($info === null) {
$info = $this->parent->info;
}
return $info;
}
}
If you need to multiple properties, you can either duplicate the code and put it into a trait to remove the clutter from your model. Or instead, you can try overriding the magic __get($key) method:
class Child
{
$parentInheritedAttributes = ['info', 'description'];
// solution 1: using normal model properties like $child->info
public function __get($key)
{
if (in_array($key, $this->parentInheritedAttributes)) {
$value = parent::__get($key);
if ($value === null) {
// this will implicitely use __get($key) of parent
$value = $this->parent->$key;
}
return $value;
}
return parent::__get($key);
}
// solution 2: using getters like $child->getInfo()
public function __call($method, $parameters)
{
if (\Illuminate\Support\Str::startsWith($method, 'get')) {
$attribute = \Illuminate\Support\Str::snake(lcfirst(substr($method, 3)));
in_array($attribute, $this->parentInheritedAttributes)) {
$value = $this->$attribute;
if ($value === null) {
$value = $this->parent->$attribute;
}
return $value;
}
}
}
}

Get someone else's User ID for Message

I'm unable to get someone's user ID from their Kunena profile to open a new private message with the recipient name already inserted. The closest I got was the following code, which inserts my own username...
defined('_JEXEC') or die ();
class KunenaPrivateUddeIM extends KunenaPrivate
{
protected $uddeim = null;
protected $params = null;
/**
* #param $params
*/
public function __construct($params)
{
$this->params = $params;
if (!class_exists('uddeIMAPI'))
{
return;
}
$this->uddeim = new uddeIMAPI();
if ($this->uddeim->version() < 1)
{
return;
}
}
/**
* #param $userid
*
* #return string
*/
protected function getURL($userid)
{
static $itemid = false;
if ($itemid === false)
{
$itemid = 0;
if (method_exists($this->uddeim, 'getItemid'))
{
$itemid = $this->uddeim->getItemid();
}
if ($itemid)
{
$itemid = '&Itemid=' . (int) $itemid;
}
else
{
$itemid = '';
}
}
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . (int) $userid . $itemid);
}
/**
* #param $userid
*
* #return mixed
*/
public function getUnreadCount($userid)
{
return $this->uddeim->getInboxUnreadMessages($userid);
}
/**
* #param $text
*
* #return string
*/
public function getInboxLink($text)
{
if (!$text)
{
$text = JText::_('COM_KUNENA_PMS_INBOX');
}
return '' . $text . '';
}
/**
* #return string
*/
public function getInboxURL()
{
$user = JFactory::getUser($userid);
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . ($user ->id));
}
}
Change this line:
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . (JFactory::getUser()->id));
to the following 2 lines:
$user = JFactory::getUser($userid);
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . ($user ->id));
You can check this post that we have written some time ago (it was written for Joomla 2.5, but it still works, except that you have to remove the &) on how to retrieve non-cached users in Joomla: http://www.itoctopus.com/how-to-retrieve-the-non-cached-user-information-from-joomla
Ok kunena developer has a hotfix on github for the upcomming release update. Here is the commit link https://github.com/Kunena/Kunena-Forum/pull/3547

Event dispatcher in silex

I need to replace my notifyService, with the event dispatcher of Symphony.
Here is the original service:
<?php
class VmService
{
/**
* #var VmManager|null
*/
protected $vmManager = null;
/**
* #var ProvisionerInterface[]
*/
protected $provisionners = array();
/**
* #var NotifyService|null
*/
protected $notifyService = null;
public function setVmManager(VmManager $vmManager)
{
$this->vmManager = $vmManager;
}
public function getVmManager()
{
return $this->vmManager;
}
/**
* #param $type
* #param ProvisionerInterface $provisionner
*/
public function setProvisionner($type, ProvisionerInterface $provisionner)
{
$this->provisionners[$type] = $provisionner;
}
/**
* #param $type
* #return ProvisionerInterface
*/
public function getProvisionner(Vm $vm)
{
return $this->provisionners[$vm->getType()];
}
/**
* #param NotifyService $notifyService
*/
public function setNotifyService(NotifyService $notifyService)
{
$this->notifyService = $notifyService;
}
/**
* #return NotifyService|null
*/
public function getNotifyService()
{
return $this->notifyService;
}
public function initialise(Vm $vm)
{
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->initialise($vm);
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
}
public function delete(Vm $vm, $force = false)
{
$now = new \DateTime();
$day = $now->format('w');
if ( ($day == 0 || $day == 6) && ! $force) {
throw new \Exception('Cannot delete a VM on weekend unless you force it');
}
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->delete($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
}
private function deleteLogFile(Vm $vm)
{
$filename = VmLogger::getLogFile($vm->getIdVm());
if (file_exists($filename)) {
#unlink("$filename");
}
}
public function prepare(Vm $vm)
{
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
//$provisionner->start($vm, true, 'integ.lafourchette.local');
$provisionner->stop($vm);
}
public function start(Vm $vm, $provisionEnable = true)
{
$vmManager = $this->getVmManager();
$notify = $this->getNotifyService();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(VM::STARTED);
$vmManager->flush($vm);
try {
$provisionner->start($vm, $provisionEnable);
$vm->setStatus(VM::RUNNING);
$vmManager->flush($vm);
$notify->send('ready', $vm);
} catch (UnableToStartException $e) {
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
$notify->send('unable_to_start', $vm);
throw $e;
}
}
public function getStatus(Vm $vm)
{
return $this->getProvisionner($vm)->getStatus($vm);
}
public function stop(Vm $vm)
{
$vmManager = $this->getVmManager();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
$provisionner->stop($vm);
}
public function archived(Vm $vm)
{
$vmManager = $this->getVmManager();
$this->delete($vm);
$vm->setStatus(VM::EXPIRED);
$this->deleteLogFile($vm);
$vmManager->flush($vm);
$this->prepare($vm);
}
}
And here is what I've changed:
<?php
class VmService
{
/**
* #var VmManager|null
*/
protected $vmManager = null;
/**
* #var ProvisionerInterface[]
*/
protected $provisionners = array();
/**
* #var NotifyService|null
*/
protected $notifyService = null;
public function setVmManager(VmManager $vmManager)
{
$this->vmManager = $vmManager;
}
public function getVmManager()
{
return $this->vmManager;
}
/**
* #param $type
* #param ProvisionerInterface $provisionner
*/
public function setProvisionner($type, ProvisionerInterface $provisionner)
{
$this->provisionners[$type] = $provisionner;
}
/**
* #param $type
* #return ProvisionerInterface
*/
public function getProvisionner(Vm $vm)
{
return $this->provisionners[$vm->getType()];
}
/**
* #param NotifyService $notifyService
*/
public function setNotifyService(NotifyService $notifyService)
{
$this->notifyService = $notifyService;
}
/**
* #return NotifyService|null
*/
public function getNotifyService()
{
return $this->notifyService;
}
public function initialise(Vm $vm)
{
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->initialise($vm);
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
}
public function delete(Vm $vm, $force = false)
{
$now = new \DateTime();
$day = $now->format('w');
if ( ($day == 0 || $day == 6) && ! $force) {
throw new \Exception('Cannot delete a VM on weekend unless you force it');
}
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->delete($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
}
private function deleteLogFile(Vm $vm)
{
$filename = VmLogger::getLogFile($vm->getIdVm());
if (file_exists($filename)) {
#unlink("$filename");
}
}
public function prepare(Vm $vm)
{
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
//$provisionner->start($vm, true, 'integ.lafourchette.local');
$provisionner->stop($vm);
}
public function start(Vm $vm, $provisionEnable = true)
{
$vmManager = $this->getVmManager();
$dispatcher = new EventDispatcher();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(VM::STARTED);
$vmManager->flush($vm);
try {
$provisionner->start($vm, $provisionEnable);
$vm->setStatus(VM::RUNNING);
$vmManager->flush($vm);
$event = new NotifyEvent($vm);
$dispatcher->addListener('notify.action', $event);
$dispatcher->dispatch('notify.action');
} catch (UnableToStartException $e) {
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
$event = new NotifyEvent($vm);
$dispatcher->addListener('notify.action', $event);
$dispatcher->dispatch('notify.action');
throw $e;
}
}
public function getStatus(Vm $vm)
{
return $this->getProvisionner($vm)->getStatus($vm);
}
public function stop(Vm $vm)
{
$vmManager = $this->getVmManager();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
$provisionner->stop($vm);
}
public function archived(Vm $vm)
{
$vmManager = $this->getVmManager();
$this->delete($vm);
$vm->setStatus(VM::EXPIRED);
$this->deleteLogFile($vm);
$vmManager->flush($vm);
$this->prepare($vm);
}
}
However as I see with the documentation, I need a listener but I can't figure out how to relate it, and how to make it to work.
You need to refactor your code. As stated in the documentation, in order to dispatch an event, you have to create the event and call the dispatch method on the EventDispatcher instance, so in your code instead of what you are doing currently:
<?php
// this is the start method of your service
// ...
$event = new NotifyEvent($vm);
$dispatcher->addListener('notify.action', $event);
$dispatcher->dispatch('notify.action');
// ...
you have to create the event and dispatch it directly:
<?php
// this is the start method of your service
// ...
$event = new NotifyEvent($vm);
$dispatcher->dispatch('notify.action', $event);
// ...
You also are sending the same event ('notify.action') now but previously you had 2 different events: 'ready' and 'unable_to_start', so you have to create 2 listeners for 2 differents events ('notify.success' and 'notify.unable_to_start' for example).
Now you have 2 more problems:
No listeners are configured for your 'notify.action' event, so you have to add listeners somewhere (you've tried but you've failed, see the documentation for the EventDispatcher component for more details about how to properly configure a listener)
You're creating the dispatcher every time the start method is created, so you have to configure it every time also (configure means add the listeners)
You can tackle both if you refactor a little bit by creating another service based on the Symfony EventDispatcher:
<?php
// somewhere in your config file
// ...
$app['notifyService'] = $app->share(function() use ($app) {
$dispatcher = new Symfony\Component\EventDispatcher\EventDispatcher();
$dispatcher->addListener('notify.success', $callable1);
$dispatcher->addListener('notify.unable_to_start', $callable2);
return $dispatcher;
});
Notice that $callable1 and $callable2 are there to give you an idea, again check the documentation to see how to add listeners properly (you can create a clousure or a method in a class that handles the events, it's completely up to you).
Now you've defined a notifyService based on the Event Dispatcher (another one completely different from the EventDispatcher used by Silex so you have a clean Event Dispatcher for your domain events), you can use it as a notify service on your class. You'd do it like before: using the setNotifyService method and in your code you just need to create the event and call the dispatch method (assuming you've already called the setNotifyService):
<?php
// class VmService
// method start
// when you've to dispatch the success event
$event = new NotifySuccessEvent($vm);
$this->notifyService->dispatch('notify.success', $event);
// if you have to dispatch the notify.unable_to_start event
$event = new NotifyUnableToStartEvent($vm);
$this->notifyService->dispatch('notify.unable_to_start', $event);
I hope that this will put you on the right track.
PS: You'll have to code the 2 event classes by yourself, again, check the docs for details.

Varien_Data_Collection pagination not working

I have been created a Varien_Data_Collection from scratch:
$myCollection = new Varien_Data_Collection();
after add some items into it, $myCollection->addItem($fooItem);, I tried to paginate it with:
$myCollection->setPageSize(3)->setCurPage(1);
but when I display the collection, it shows all items in the collection instead the first, second o N page.
$myItems = $myCollection->getItems();
foreach ($myItems as $item) {
echo $item->getData('bar');
}
The (non-abstract) base-class Varien_Data_Collection - although it does have the setPageSize and setCurPage methods, those are not reflected within the aggregation of the Iterator:
class Varien_Data_Collection implements IteratorAggregate, Countable
{
...
/**
* Implementation of IteratorAggregate::getIterator()
*/
public function getIterator()
{
$this->load();
return new ArrayIterator($this->_items);
}
...
It will in any case return an ArrayIteator that has all objects. The load method doesn't change a thing here btw:
...
/**
* Load data
*
* #return Varien_Data_Collection
*/
public function loadData($printQuery = false, $logQuery = false)
{
return $this;
}
...
/**
* Load data
*
* #return Varien_Data_Collection
*/
public function load($printQuery = false, $logQuery = false)
{
return $this->loadData($printQuery, $logQuery);
}
...
I'd say this qualifies as a bug, as the public interface makes one assume that the magent collection object Varien_Data_Collection provides pagination while it does not.
I have not searched for a bug-report regarding this issue. The solution is to use another iterator for pagination, for example like outlined in an answer to How to Paginate lines in a foreach loop with PHP with PHP's LimitIterator:
/**
* Class Varien_Data_Collection_Pagination
*
* Aggregates missing Pagination on Collection on getting the Iterator
*
* #author hakre <http://hakre.wordpress.com/>
*/
class Varien_Data_Collection_Pagination implements IteratorAggregate
{
/**
* #var Varien_Data_Collection
*/
private $collection;
public function __construct(Varien_Data_Collection $collection)
{
$this->collection = $collection;
}
public function getIterator()
{
$collection = $this->collection;
if (FALSE === $size = $collection->getPageSize()) {
return $collection;
}
$page = $collection->getCurPage();
if ($page < 1) {
return $collection;
}
$offset = $size * $page - $size;
return new LimitIterator(new IteratorIterator($collection), $offset, $size);
}
}
Usage Example:
$collection = new Varien_Data_Collection();
$collectionIterator = new Varien_Data_Collection_Pagination($collection);
# [...] fill collection
# set pagination:
$collection->setPageSize(3);
$collection->setCurPage(1);
echo iterator_count($collectionIterator); # 3 (int)
Keep in mind that this is mainly an example. IMHO this should be fixed upstream within the Magento codebase, so it's perhaps worth you do some search work in the Magento Bug-Tracker.
As explained in previous post Varien_Data_collection does not support pagination. One solution would be to extend this class and overwrite its loadData() method. Here is practical example of paginating array of stdClass objects. Can be used with any array of data
class YourNamespace_YourModule_Model_History_Collection extends Varien_Data_Collection{
//array of stdClass objects. Can be array of any objects/subarrays
protected $_history = array();
public function loadData($printQuery = false, $logQuery = false){
if ($this->isLoaded()) {
return $this;
}
$this->_totalRecords = count($this->_history);
$this->_setIsLoaded();
// paginate and add items
$from = ($this->getCurPage() - 1) * $this->getPageSize();
$to = $from + $this->getPageSize() ;
$isPaginated = $this->getPageSize() > 0;
$cnt = 0;
$sub_history = array_slice($this->_history, $from, $to-$from);
foreach ( $sub_history as $entry) {
$cnt++;
$item = new $this->_itemObjectClass();
//build here your Varien Object
$item->setDate($entry->Date);
//.......
$this->addItem($item);
if (!$item->hasId()) {
$item->setId($cnt);
}
}
return $this;
}
public function setRecords($records){
if(is_array($records)){
$this->_history = $records;
}
return;
}
}
//Your block class
class YourNamespace_YourModule_Block_History extends Mage_Core_Block_Template{
public function __construct(){
$collection_prepared = new YourNamespace_YourModule_Model_History_Collection();
//get your data here
//$records is array of stdClass objects
$collection_prepared->setRecords($records);
$this->setCollection($collection_prepared);
}
protected function _prepareLayout(){
parent::_prepareLayout();
$pager = $this->getLayout()->createBlock('page/html_pager', 'history.pager');
$pager->setAvailableLimit(array(20=>20,40=>40,80=>80,'all'=>'all'));
$pager->setCollection($this->getCollection());
$this->setChild('pager', $pager);
$this->getCollection()->load();
return $this;
}
public function getPagerHtml()
{
return $this->getChildHtml('pager');
}
}
Hope this helps!
class Pageable_Varien_Data_Collection extends Varien_Data_Collection
{
/**
* Load data
*
* #param bool $printQuery
* #param bool $logQuery
*
* #return Pageable_Varien_Data_Collection
*/
public function load($printQuery = false, $logQuery = false)
{
if ($this->isLoaded()) {
return $this;
}
$this->_renderLimit();
$this->_setIsLoaded();
return $this;
}
/**
* #return Pageable_Varien_Data_Collection
*/
protected function _renderLimit()
{
if ($this->_pageSize) {
$currentPage = $this->getCurPage();
$pageSize = $this->_pageSize;
$firstItem = (($currentPage - 1) * $pageSize + 1);
$lastItem = $firstItem + $pageSize;
$iterator = 1;
foreach ($this->getItems() as $key => $item) {
$pos = $iterator;
$iterator++;
if ($pos >= $firstItem && $pos <= $lastItem) {
continue;
}
$this->removeItemByKey($key);
}
}
return $this;
}
/**
* Retrieve collection all items count
*
* #return int
*/
public function getSize()
{
if (is_null($this->_totalRecords)) {
$this->_totalRecords = count($this->getItems());
}
return intval($this->_totalRecords);
}
/**
* Retrieve collection items
*
* #return array
*/
public function getItems()
{
return $this->_items;
}
}

Why is my Magento module not being loaded? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I just wrote a Magento module, but it's not being loaded and I'd like to debug it.
Here are a couple of classes and the methods that are responsible for various stages of loading.
Mage_Core_Model_Config
Called for each module (returns a Mage_Core_Model_Config representing the module's XML block in the main config directory (enabled, version, etc..)):
/**
* Get module config node
*
* #param string $moduleName
* #return Varien_Simplexml_Object
*/
function getModuleConfig($moduleName='')
{
$modules = $this->getNode('modules');
if (''===$moduleName) {
return $modules;
} else {
return $modules->$moduleName;
}
}
Called for each module, but just builds a structure still without including the individual module configs:
/**
* Load declared modules configuration
*
* #param null $mergeConfig depricated
* #return Mage_Core_Model_Config
*/
protected function _loadDeclaredModules($mergeConfig = null)
{
$moduleFiles = $this->_getDeclaredModuleFiles();
if (!$moduleFiles) {
return ;
}
Varien_Profiler::start('config/load-modules-declaration');
$unsortedConfig = new Mage_Core_Model_Config_Base();
$unsortedConfig->loadString('<config/>');
$fileConfig = new Mage_Core_Model_Config_Base();
// load modules declarations
foreach ($moduleFiles as $file) {
$fileConfig->loadFile($file);
$unsortedConfig->extend($fileConfig);
}
$moduleDepends = array();
foreach ($unsortedConfig->getNode('modules')->children() as $moduleName => $moduleNode) {
if (!$this->_isAllowedModule($moduleName)) {
continue;
}
$depends = array();
if ($moduleNode->depends) {
foreach ($moduleNode->depends->children() as $depend) {
$depends[$depend->getName()] = true;
}
}
$moduleDepends[$moduleName] = array(
'module' => $moduleName,
'depends' => $depends,
'active' => ('true' === (string)$moduleNode->active ? true : false),
);
}
// check and sort module dependence
$moduleDepends = $this->_sortModuleDepends($moduleDepends);
// create sorted config
$sortedConfig = new Mage_Core_Model_Config_Base();
$sortedConfig->loadString('<config><modules/></config>');
foreach ($unsortedConfig->getNode()->children() as $nodeName => $node) {
if ($nodeName != 'modules') {
$sortedConfig->getNode()->appendChild($node);
}
}
foreach ($moduleDepends as $moduleProp) {
$node = $unsortedConfig->getNode('modules/'.$moduleProp['module']);
$sortedConfig->getNode('modules')->appendChild($node);
}
$this->extend($sortedConfig);
Varien_Profiler::stop('config/load-modules-declaration');
return $this;
}
Loads config.xml, enterprise.xml, local.xml, etc..:
/**
* Load base system configuration (config.xml and local.xml files)
*
* #return Mage_Core_Model_Config
*/
public function loadBase()
{
$etcDir = $this->getOptions()->getEtcDir();
$files = glob($etcDir.DS.'*.xml');
$this->loadFile(current($files));
while ($file = next($files)) {
$merge = clone $this->_prototype;
$merge->loadFile($file);
$this->extend($merge);
}
if (in_array($etcDir.DS.'local.xml', $files)) {
$this->_isLocalConfigLoaded = true;
}
return $this;
}
Loads the individual module configs:
/**
* Iterate all active modules "etc" folders and combine data from
* specidied xml file name to one object
*
* #param string $fileName
* #param null|Mage_Core_Model_Config_Base $mergeToObject
* #return Mage_Core_Model_Config_Base
*/
public function loadModulesConfiguration($fileName, $mergeToObject = null, $mergeModel=null)
{
$disableLocalModules = !$this->_canUseLocalModules();
if ($mergeToObject === null) {
$mergeToObject = clone $this->_prototype;
$mergeToObject->loadString('<config/>');
}
if ($mergeModel === null) {
$mergeModel = clone $this->_prototype;
}
$modules = $this->getNode('modules')->children();
foreach ($modules as $modName=>$module) {
if ($module->is('active')) {
if ($disableLocalModules && ('local' === (string)$module->codePool)) {
continue;
}
$configFile = $this->getModuleDir('etc', $modName).DS.$fileName;
if ($mergeModel->loadFile($configFile)) {
$mergeToObject->extend($mergeModel, true);
}
}
}
return $mergeToObject;
}
Varien_Simplexml_Config (lib/Varien/Simplexml/Config.php)
What actually reads the individual module configs:
/**
* Imports XML file
*
* #param string $filePath
* #return boolean
*/
public function loadFile($filePath)
{
if (!is_readable($filePath)) {
//throw new Exception('Can not read xml file '.$filePath);
return false;
}
$fileData = file_get_contents($filePath);
$fileData = $this->processFileData($fileData);
return $this->loadString($fileData, $this->_elementClass);
}
Dustin Oprea

Resources